diff --git a/docs/influxdb3.md b/docs/influxdb3.md new file mode 100644 index 00000000..9077a426 --- /dev/null +++ b/docs/influxdb3.md @@ -0,0 +1,95 @@ +# InfluxDB 3 as a periodic-query system + +`approxbench benchmark-external run --engine influxdb3` runs the periodic suites (`suites/showcase-1m`, `suites/showcase-1h`) on an InfluxDB 3 Core server, used the way an InfluxDB user would run those queries. +The adapter is [influxdb3_server](../system-bench/src/engines_external/influxdb3_server.rs); its PromQL-to-SQL rules are in [influxdb3_query](../system-bench/src/engines_external/influxdb3_query.rs). + +## Version + +InfluxDB 3 Core 3.12.3 (revision 51f4ac865b, DataFusion 52.5), image `influxdb@sha256:f8cd424eff20b584ce41b1ee72959261c4d1b700d2a97c0d21ff1b173b9b1b81` (`influxdb:3.12.3-core`), pinned in `scripts/extbench-up-influxdb3.sh`. + +Core is the free single-node server. Enterprise needs a license key and adds compaction and clustering, which these queries do not use. +Core holds at most 5 databases, so the engine holds one install at a time: each repetition of a cell writes all the data again into a fresh database, which is deleted before the next. + +## Data + +One table per metric, one tag per label (`__name__` is the table), one float field `value`. +Samples are written as line protocol with millisecond timestamps to `/api/v3/write_lp`. +A write returns after the server's write-ahead log flush (every 1 s by default), so the rows can be queried when the ingest step ends. +Queries are SQL sent to `/api/v3/query_sql`, answered as CSV. + +## Variants + +`scripts/influxdb3-variants.sh ` adds three variants to a run directory. +They have no plan files, and run only when `--variant` names them: + +| Variant | How each query runs | Exact | +|---|---|---| +| `influxdb3.native` | SQL over the raw rows at query time | yes | +| `influxdb3.downsampled` | the processing engine writes a downsampled table per query at ingest, and the query reads it; a quantile runs as in native | yes | +| `influxdb3.approximate` | quantiles with `approx_percentile_cont` (t-digest, 100 centroids) at query time; the other queries run as in native | quantiles no (recorded as substitutions) | + +A downsampled or approximate cell in which every query would run as in native is refused (`NotRun`), since it would repeat the native cell: + +| Workload | native | downsampled | approximate | +|---|---|---|---| +| sum_over_time, count, max, sum_rate | runs | runs | refused: no approximate function | +| quantile, quantile_rank, avg_quantile | runs | refused: no exact downsample | runs | +| joint | runs | q4 and q5 downsampled, q1 to q3 native | q1 to q3 approximate, q4 and q5 native | + +### Queries + +The adapter translates each query's PromQL text: `[sum|count|min|max|avg [by (labels)]] (f(m[w]))`, with `f` one of `sum_over_time`, `count_over_time`, `min_over_time`, `max_over_time`, `avg_over_time`, `quantile_over_time(φ, …)`, `rate` and `increase`. +Any other text is refused at install. +A query at `T` reads `time > T − w AND time <= T`, as PromQL's range `(T − w, T]`. + +- `quantile_over_time(φ)` is `percentile_cont(φ) WITHIN GROUP (ORDER BY value)` per series: rank φ·(n − 1) with linear interpolation, as PromQL, except that InfluxDB rounds the interpolation fraction to 6 decimals (the 0.99 quantile of 1..60 is 59.409999, not 59.41). The answer is off by at most 10⁻⁶ of the gap between the two neighbouring values. +- `rate` and `increase` are Prometheus `extrapolatedRate` written in SQL: each step where the counter goes down adds the new value, then the increase is extrapolated to the range's ends (the 1.1 × average-gap threshold and the clamp at zero), and divided by the range for a rate. These are the same rules as ClickHouse's query-time rate. +- `sum by (job)` of `sum_over_time` or `count_over_time` is one grouped aggregate over the rows; other aggregations over per-series values are nested queries. + +### Downsampling + +InfluxDB 3 has no materialized views or continuous queries. Its documented way to precompute is the processing engine: a Python plugin, usually behind a scheduled trigger (`every:10s`), queries the last interval and writes aggregates into another table. +A scheduled trigger runs on wall-clock time, and the harness replays data time faster than that. +So the adapter installs the plugin ([influxdb3_downsample.py](../system-bench/src/engines_external/influxdb3_downsample.py)) behind a request trigger, and calls it after each chunk is written, with the SQL that downsamples that chunk. +The plugin's work is therefore measured as ingest work. + +Buckets are `gcd(window, evaluation interval)` wide, right-closed, and stored at their end time: + +- `sum`, `count`, `min`, `max` over time: one row per bucket and series, or per bucket and group when the outer aggregation can read rows directly (`sum` of sums or counts, `max` of maxima, `min` of minima). `avg_over_time` stores sum and count. +- `rate` and `increase`: per bucket and series, the sample count, first and last time and value, and the increase inside the bucket. The query adds the step between adjacent buckets, with the same rule for a counter that goes down, then extrapolates as at query time. +- `quantile_over_time`: no exact downsample. A quantile cannot be combined from per-bucket values, and InfluxDB has no mergeable quantile state. + +The last value cache (at most 10 newest values per series) and the distinct value cache (distinct tag values) do not answer aggregates over a window, so no variant uses them. + +### Approximate functions + +DataFusion's `approx_percentile_cont` (t-digest) is the only approximate function that fits these suites. `approx_distinct` (HyperLogLog) exists, but no suite query counts distinct values. + +## Where InfluxDB differs from the truth + +- Exact quantiles differ by at most 10⁻⁶ of the gap between the two neighbouring values (`percentile_cont` rounds its interpolation fraction to 6 decimals). +- `approx_percentile_cont` does not interpolate as PromQL. On 60 values per series it answered within two ranks of the exact quantile in the conformance tests (the 0.99 quantile of 1..60: 59.9 instead of 59.41). +- Every other shape is exact, except in the last bits of a floating-point sum (summation order). +- Line protocol cannot carry NaN or infinite values: a chunk with one fails. +- A label named `time` or `value` collides with a column of the table: refused. +- Timestamps must be after 0. + +## Measurement + +- CPU and memory: the container's cgroup (`--server-cgroup-directory`, `--server-ssh-host`). +- Query wall time per request is recorded; InfluxDB reports no CPU per query. +- An ingest step's wall time is mostly the wait for the write-ahead log flush (1 s by default): a write is acknowledged after the flush. A downsampled arm waits twice per chunk, for its raw rows and for the plugin's rows. This is idle time, not CPU. +- Stored bytes: the database's Parquet files (`system.parquet_files`). The server writes Parquet only when it snapshots its write-ahead log (by default every 600 flushes, about 10 minutes of wall-clock writing). A replay of the suites is shorter than that, so the rows stay in the write-ahead log files and in memory, and the stored bytes are 0. The server's memory (cgroup) is the number to compare; the run commands also record the size of the data directory after each run. + +## Commands + +```sh +LISTEN_HOST=10.0.0.2 scripts/extbench-up-influxdb3.sh up /data/influxdb3 2,4,6,8 0 18181 # prints the cgroup +scripts/influxdb3-variants.sh +approxbench benchmark-external run --run-directory --engine influxdb3 \ + --variant influxdb3.native --variant influxdb3.downsampled --variant influxdb3.approximate \ + --influxdb3-url http://10.0.0.2:18181 --server-cgroup-directory --server-ssh-host 10.0.0.2 +scripts/extbench-up-influxdb3.sh down /data/influxdb3 +``` + +Conformance tests against a real server: `AQPBM_INFLUXDB3_URL=http://10.0.0.2:18181 cargo test -p system-bench --test influxdb3_conformance -- --ignored --test-threads 1`. diff --git a/docs/system-bench.md b/docs/system-bench.md index 6956a78f..77ea7c8d 100644 --- a/docs/system-bench.md +++ b/docs/system-bench.md @@ -20,6 +20,7 @@ Not every system supports every measurement: | `druid` | | yes | | | `pilotdb` (over DuckDB) | | yes | | | `victoriametrics` | yes | | | +| `influxdb3` ([details](./influxdb3.md)) | yes | | | | `asapquery-backend` | yes | | | | `asapquery-precompute-engine` | | | yes | | `fake` (for tests) | yes | | | diff --git a/scripts/extbench-up-influxdb3.sh b/scripts/extbench-up-influxdb3.sh new file mode 100755 index 00000000..b3157931 --- /dev/null +++ b/scripts/extbench-up-influxdb3.sh @@ -0,0 +1,113 @@ +#!/usr/bin/env bash +# Start (or stop) an InfluxDB 3 Core server for +# `approxbench benchmark-external run --engine influxdb3` on this host: a +# docker container pinned to given cores. The harness reads its cgroup over +# SSH (`--server-ssh-host`, `--server-cgroup-directory`). +# +# scripts/extbench-up-influxdb3.sh up [] +# scripts/extbench-up-influxdb3.sh down [] +# +# Example: LISTEN_HOST=10.0.0.2 scripts/extbench-up-influxdb3.sh up /data/run-1/influxdb3 2,22 0 18181 +# +# Environment: +# LISTEN_HOST address the server listens on (required): a private +# (10/8, 172.16/12, 192.168/16) or loopback address, never +# 0.0.0.0 or a public one: the server runs without auth +# IMAGE the image, pinned by digest (default: InfluxDB 3 Core +# 3.12.3 below) +# MEMORY_LIMIT a docker --memory limit, e.g. 32g (default: none) +# +# Every start begins from an empty data dir. The script only deletes a data +# dir it created (it holds the marker file .extbench-data-dir). The +# container runs as the invoking user, with no CPU quota. The server keeps +# its default settings (WAL flush every 1 s, Parquet files of 10 min, file +# cache, query memory pool), with a local file object store, and the +# processing engine's plugin directory holding the adapter's downsampling +# plugin. Telemetry upload is off. +set -euo pipefail + +marker=.extbench-data-dir +# influxdb:3.12.3-core, InfluxDB 3 Core 3.12.3 (revision 51f4ac865b). +default_image=influxdb@sha256:f8cd424eff20b584ce41b1ee72959261c4d1b700d2a97c0d21ff1b173b9b1b81 +plugin_source=$(cd "$(dirname "$0")/.." && pwd)/system-bench/src/engines_external/influxdb3_downsample.py +plugin_file=sketch_bench_downsample.py + +# Exit 0 when $1 is a private or loopback IPv4 address. +private_address() { + local a b c d + IFS=. read -r a b c d <<<"$1" || return 1 + for octet in "$a" "$b" "$c" "$d"; do + [[ "$octet" =~ ^[0-9]+$ ]] && [ "$octet" -le 255 ] || return 1 + done + [ "$a" = 10 ] && return 0 + [ "$a" = 127 ] && return 0 + [ "$a" = 172 ] && [ "$b" -ge 16 ] && [ "$b" -le 31 ] && return 0 + [ "$a" = 192 ] && [ "$b" = 168 ] && return 0 + return 1 +} + +if [ "${1:-}" = check-listen-host ]; then + private_address "${2:?address}" || { echo "refused: ${2} is not a private address" >&2; exit 1; } + exit 0 +fi + +action=${1:?up|down}; data_dir=$(realpath -m "${2:?data dir}") + +if [ "$action" = down ]; then + name=${3:-extbench-influxdb3} + docker rm -f "$name" >/dev/null 2>&1 || true + exit 0 +fi +[ "$action" = up ] || { echo "unknown action $action" >&2; exit 2; } + +cores=${3:?cores}; numa=${4:?numa node}; http_port=${5:?http port} +name=${6:-extbench-influxdb3} +image=${IMAGE:-$default_image} +: "${LISTEN_HOST:?set LISTEN_HOST to a private address}" +private_address "$LISTEN_HOST" || { echo "refused: LISTEN_HOST $LISTEN_HOST is not a private address" >&2; exit 1; } +[[ "$image" == *@sha256:* ]] || { echo "refused: IMAGE must be pinned by digest" >&2; exit 1; } +[ -f "$plugin_source" ] || { echo "no plugin at $plugin_source" >&2; exit 1; } + +if [ -e "$data_dir" ]; then + [ -f "$data_dir/$marker" ] || { echo "refused: $data_dir exists and was not made by this script" >&2; exit 1; } + docker rm -f "$name" >/dev/null 2>&1 || true + rm -rf "$data_dir" +fi +mkdir -p "$data_dir/data" "$data_dir/plugins"; touch "$data_dir/$marker" +cp "$plugin_source" "$data_dir/plugins/$plugin_file" + +memory=(); [ -n "${MEMORY_LIMIT:-}" ] && memory=(--memory "$MEMORY_LIMIT") +docker rm -f "$name" >/dev/null 2>&1 || true +docker run -d --name "$name" --network host \ + --cpuset-cpus "$cores" --cpuset-mems "$numa" "${memory[@]}" --user "$(id -u):$(id -g)" \ + -v "$data_dir/data:/var/lib/influxdb3/data" -v "$data_dir/plugins:/var/lib/influxdb3/plugins" \ + -e HOME=/tmp \ + --entrypoint influxdb3 "$image" serve \ + --node-id extbench --object-store file --data-dir /var/lib/influxdb3/data \ + --plugin-dir /var/lib/influxdb3/plugins --http-bind "$LISTEN_HOST:$http_port" \ + --without-auth --disable-telemetry-upload --log-filter warn >/dev/null +for _ in $(seq 1 90); do + curl -sf "http://$LISTEN_HOST:$http_port/health" >/dev/null && break; sleep 1 +done +curl -sf "http://$LISTEN_HOST:$http_port/health" >/dev/null || { echo "the server did not start" >&2; docker logs "$name" >&2; exit 1; } + +id=$(docker inspect -f '{{.Id}}' "$name") +group="/sys/fs/cgroup/system.slice/docker-$id.scope" +[ -d "$group" ] || { echo "no cgroup at $group (is docker on the systemd cgroup driver?)" >&2; exit 1; } + +siblings() { + for core in ${cores//,/ }; do + printf '%s:%s ' "$core" "$(cat "/sys/devices/system/cpu/cpu$core/topology/thread_siblings_list")" + done +} +{ echo "image $image" + echo "image_id $(docker inspect -f '{{.Image}}' "$name")" + echo "version $(curl -sf "http://$LISTEN_HOST:$http_port/ping")" + echo "plugin_sha256 $(sha256sum "$data_dir/plugins/$plugin_file" | cut -d' ' -f1)" + echo "memory_limit ${MEMORY_LIMIT:-none}" + echo "cpuset $cores mems $numa" + echo "thread_siblings $(siblings)" + echo "cpu_model $(lscpu | sed -n 's/^Model name: *//p')" + echo "cgroup $group" + echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" +cat "$data_dir/versions.txt" diff --git a/scripts/influxdb3-variants.sh b/scripts/influxdb3-variants.sh new file mode 100755 index 00000000..9156c2bb --- /dev/null +++ b/scripts/influxdb3-variants.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Add the InfluxDB 3 variants to a benchmark-external run directory (one +# `scripts/plan-suite.sh` made, or any with workloads/): three variants with +# no plan files, which no engine runs unless `--variant` names them. +# +# scripts/influxdb3-variants.sh +# +# Variants (plans//variant.json): +# influxdb3.native every query in SQL at query time, exact +# influxdb3.downsampled processing-engine downsampled tables where exact, else as native +# influxdb3.approximate approx_percentile_cont for quantiles (substitutions), else as native +# +# Example: scripts/influxdb3-variants.sh /data/run-1, then +# approxbench benchmark-external run --run-directory /data/run-1 --engine influxdb3 \ +# --variant influxdb3.native --influxdb3-url http://10.0.0.2:18181 ... +set -euo pipefail + +run=${1:?run directory} +[ -d "$run/workloads" ] || { echo "$run has no workloads/" >&2; exit 1; } +for variant in native downsampled approximate; do + dir="$run/plans/influxdb3.$variant" + [ -e "$dir" ] && { echo "$dir exists; left as it is" >&2; continue; } + mkdir -p "$dir" + substitutions=false; [ "$variant" = approximate ] && substitutions=true + printf '{"substitutions_allowed": %s, "plans": false, "run_by_default": false}\n' "$substitutions" \ + > "$dir/variant.json" + echo "influxdb3.$variant" +done diff --git a/system-bench/src/engines_external/influxdb3_downsample.py b/system-bench/src/engines_external/influxdb3_downsample.py new file mode 100644 index 00000000..f3048e4c --- /dev/null +++ b/system-bench/src/engines_external/influxdb3_downsample.py @@ -0,0 +1,45 @@ +# InfluxDB 3 processing-engine plugin of sketch-bench's InfluxDB 3 adapter +# (`influxdb3.downsampled` arms): runs each downsampling query it is given +# over the database's raw tables and writes the rows into a downsampled table, +# as the downsampling plugins of the InfluxDB 3 docs do from a scheduled +# trigger. The adapter calls it through a request trigger at each data-time +# boundary, after the rows up to that boundary were written. +# +# Request body (JSON): +# {"jobs": [{"sql": "SELECT job, bucket_ms, sum(value) AS v FROM ...", +# "table": "downsampled_q1", +# "keys": ["job"], +# "fields": [["v", false]]}]} +# Each row of `sql` becomes one line of `table`: its `keys` as tags (a null +# key is left out), its `fields` (name, integer?) as fields, at time +# `bucket_ms`. Answers {"tables": {"downsampled_q1": {"rows": 10, +# "tags": ["job"]}}}: the rows written and the tags any row carried. +# +# The writes are buffered and flushed when the call returns, before the +# HTTP answer, so the rows are queryable when the adapter's call ends. +import json + + +def process_request(influxdb3_local, query_parameters, request_headers, request_body, args=None): + body = json.loads(request_body) + tables = {} + for job in body["jobs"]: + rows = influxdb3_local.query(job["sql"]) + written = tables.setdefault(job["table"], {"rows": 0, "tags": []}) + for row in rows: + line = LineBuilder(job["table"]) + for key in job["keys"]: + value = row.get(key) + if value is not None and value != "": + line.tag(key, str(value)) + if key not in written["tags"]: + written["tags"].append(key) + for name, integer in job["fields"]: + if integer: + line.int64_field(name, int(row[name])) + else: + line.float64_field(name, float(row[name])) + line.time_ns(int(row["bucket_ms"]) * 1000000) + influxdb3_local.write(line) + written["rows"] += 1 + return {"tables": tables} diff --git a/system-bench/src/engines_external/influxdb3_query.rs b/system-bench/src/engines_external/influxdb3_query.rs new file mode 100644 index 00000000..cfb83ced --- /dev/null +++ b/system-bench/src/engines_external/influxdb3_query.rs @@ -0,0 +1,984 @@ +//! The PromQL shapes the InfluxDB 3 adapter runs, and the InfluxDB SQL of +//! each shape in each way of running it ([`Mode`]). +//! +//! A query is `[AGG [by (l, …)]] (RANGE(m[w]))`, `RANGE` one of +//! `sum/count/min/max/avg_over_time`, `quantile_over_time(φ, …)`, `rate` and +//! `increase`, `AGG` one of `sum/count/min/max/avg`. Anything else is refused. +//! +//! Data model: one table per metric, one tag column per label, one float +//! field `value`, and `time`. A query at `T` reads `(T − w, T]`: +//! `time > to_timestamp_millis(T − w) AND time <= to_timestamp_millis(T)`. +//! +//! Example: `sum by (job) (rate(requests_total[1m]))` at `T` = +//! 1,700,000,100,000 ms over tags `instance` and `job` is, natively, +//! Prometheus `extrapolatedRate` per (`instance`, `job`) series over the raw +//! rows, summed per `job`. + +use std::fmt::Write as _; + +/// How an arm runs its queries. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + /// Every query computed at query time from the raw rows, exactly. + Native, + /// Queries with an exact downsample read a table a processing-engine + /// plugin fills at ingest; the others run as in [`Mode::Native`]. + Downsampled, + /// Quantiles with `approx_percentile_cont` at query time; the others run + /// as in [`Mode::Native`]. + Approximate, +} + +impl Mode { + /// The mode a run-directory variant names, e.g. `influxdb3.native`. + pub fn of_variant(name: &str) -> Option { + match name { + "influxdb3.native" => Some(Mode::Native), + "influxdb3.downsampled" => Some(Mode::Downsampled), + "influxdb3.approximate" => Some(Mode::Approximate), + _ => None, + } + } +} + +/// A function over a range of one series. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum RangeFunction { + Sum, + Count, + Min, + Max, + Avg, + Quantile(f64), + Rate, + Increase, +} + +/// An aggregation across series. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Aggregation { + Sum, + Count, + Min, + Max, + Avg, +} + +/// One accepted query. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryShape { + /// The aggregation across series and its `by` labels (empty: one group). + pub outer: Option<(Aggregation, Vec)>, + pub function: RangeFunction, + pub metric: String, + pub range_ms: u64, +} + +/// Parses `text`; the error says what is not accepted. +pub fn parse(text: &str) -> Result { + let tokens = tokenize(text)?; + let mut parser = Parser { tokens, at: 0 }; + let shape = parser.query()?; + if parser.at != parser.tokens.len() { + return Err(format!("'{text}': unexpected text after the query")); + } + Ok(shape) +} + +#[derive(Debug, Clone, PartialEq)] +enum Token { + Word(String), + Number(f64), + Duration(u64), + Open, + Close, + OpenBracket, + CloseBracket, + Comma, +} + +fn tokenize(text: &str) -> Result, String> { + let chars: Vec = text.chars().collect(); + let mut tokens = Vec::new(); + let mut i = 0; + let mut in_brackets = false; + while i < chars.len() { + let c = chars[i]; + match c { + ' ' | '\t' | '\n' => i += 1, + '(' => { + tokens.push(Token::Open); + i += 1 + } + ')' => { + tokens.push(Token::Close); + i += 1 + } + '[' => { + tokens.push(Token::OpenBracket); + in_brackets = true; + i += 1 + } + ']' => { + tokens.push(Token::CloseBracket); + in_brackets = false; + i += 1 + } + ',' => { + tokens.push(Token::Comma); + i += 1 + } + _ if in_brackets => { + let start = i; + while i < chars.len() && chars[i] != ']' { + i += 1; + } + let duration: String = chars[start..i].iter().collect(); + tokens.push(Token::Duration(parse_duration(duration.trim())?)); + } + c if c.is_ascii_digit() || c == '.' => { + let start = i; + while i < chars.len() + && (chars[i].is_ascii_digit() || matches!(chars[i], '.' | 'e' | 'E')) + { + i += 1; + } + let number: String = chars[start..i].iter().collect(); + tokens.push(Token::Number( + number + .parse() + .map_err(|_| format!("'{number}' is not a number"))?, + )); + } + c if c.is_ascii_alphabetic() || c == '_' || c == ':' => { + let start = i; + while i < chars.len() + && (chars[i].is_ascii_alphanumeric() || matches!(chars[i], '_' | ':')) + { + i += 1; + } + tokens.push(Token::Word(chars[start..i].iter().collect())); + } + other => return Err(format!("'{text}': '{other}' is not accepted")), + } + } + Ok(tokens) +} + +/// A PromQL duration such as `1m`, `90s`, `1h30m` or `500ms`, in ms. +fn parse_duration(text: &str) -> Result { + let mut total = 0u64; + let mut rest = text; + if rest.is_empty() { + return Err("an empty range".into()); + } + while !rest.is_empty() { + let digits = rest.chars().take_while(|c| c.is_ascii_digit()).count(); + if digits == 0 { + return Err(format!("range '{text}' is not a duration")); + } + let number: u64 = rest[..digits] + .parse() + .map_err(|_| format!("range '{text}' is not a duration"))?; + rest = &rest[digits..]; + let unit = rest.chars().take_while(|c| c.is_ascii_alphabetic()).count(); + let factor = match &rest[..unit] { + "ms" => 1, + "s" => 1_000, + "m" => 60_000, + "h" => 3_600_000, + "d" => 86_400_000, + "w" => 604_800_000, + "y" => 31_536_000_000, + other => return Err(format!("range '{text}': unit '{other}'")), + }; + rest = &rest[unit..]; + total += number * factor; + } + Ok(total) +} + +struct Parser { + tokens: Vec, + at: usize, +} + +impl Parser { + fn next(&mut self) -> Option { + let token = self.tokens.get(self.at).cloned(); + self.at += 1; + token + } + + fn peek(&self) -> Option<&Token> { + self.tokens.get(self.at) + } + + fn expect(&mut self, wanted: Token) -> Result<(), String> { + match self.next() { + Some(token) if token == wanted => Ok(()), + other => Err(format!("expected {wanted:?}, found {other:?}")), + } + } + + fn word(&mut self) -> Result { + match self.next() { + Some(Token::Word(word)) => Ok(word), + other => Err(format!("expected a name, found {other:?}")), + } + } + + fn query(&mut self) -> Result { + let name = self.word()?; + let aggregation = match name.as_str() { + "sum" => Some(Aggregation::Sum), + "count" => Some(Aggregation::Count), + "min" => Some(Aggregation::Min), + "max" => Some(Aggregation::Max), + "avg" => Some(Aggregation::Avg), + _ => None, + }; + let Some(aggregation) = aggregation else { + return self.range_call(&name); + }; + let mut by = Vec::new(); + let mut by_given = false; + if let Some(Token::Word(word)) = self.peek() { + if word == "by" { + self.next(); + by = self.labels()?; + by_given = true; + } else { + return Err(format!("'{word}' after {name}: only 'by' is accepted")); + } + } + self.expect(Token::Open)?; + let inner_name = self.word()?; + let mut shape = self.range_call(&inner_name)?; + self.expect(Token::Close)?; + if !by_given { + if let Some(Token::Word(word)) = self.peek() { + if word == "by" { + self.next(); + by = self.labels()?; + } else { + return Err(format!("'{word}' after {name}(…): only 'by' is accepted")); + } + } + } + shape.outer = Some((aggregation, by)); + Ok(shape) + } + + fn labels(&mut self) -> Result, String> { + self.expect(Token::Open)?; + let mut labels = Vec::new(); + loop { + match self.next() { + Some(Token::Close) => break, + Some(Token::Word(word)) => { + labels.push(word); + match self.next() { + Some(Token::Comma) => continue, + Some(Token::Close) => break, + other => return Err(format!("in a label list: {other:?}")), + } + } + other => return Err(format!("in a label list: {other:?}")), + } + } + Ok(labels) + } + + fn range_call(&mut self, name: &str) -> Result { + let function = match name { + "sum_over_time" => RangeFunction::Sum, + "count_over_time" => RangeFunction::Count, + "min_over_time" => RangeFunction::Min, + "max_over_time" => RangeFunction::Max, + "avg_over_time" => RangeFunction::Avg, + "rate" => RangeFunction::Rate, + "increase" => RangeFunction::Increase, + "quantile_over_time" => RangeFunction::Quantile(f64::NAN), + other => return Err(format!("function '{other}' is not accepted")), + }; + self.expect(Token::Open)?; + let function = if let RangeFunction::Quantile(_) = function { + let phi = match self.next() { + Some(Token::Number(phi)) => phi, + other => return Err(format!("quantile level: {other:?}")), + }; + if !(0.0..=1.0).contains(&phi) { + return Err(format!("quantile level {phi} is outside [0, 1]")); + } + self.expect(Token::Comma)?; + RangeFunction::Quantile(phi) + } else { + function + }; + let metric = self.word()?; + if metric == "__name__" { + return Err("a selector by __name__ is not accepted".into()); + } + self.expect(Token::OpenBracket)?; + let range_ms = match self.next() { + Some(Token::Duration(ms)) => ms, + other => return Err(format!("range: {other:?}")), + }; + self.expect(Token::CloseBracket)?; + self.expect(Token::Close)?; + Ok(QueryShape { + outer: None, + function, + metric, + range_ms, + }) + } +} + +/// `identifier` as a SQL identifier: double-quoted, `"` doubled. +pub fn quoted(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +fn column_list(columns: &[String]) -> String { + columns + .iter() + .map(|c| quoted(c)) + .collect::>() + .join(", ") +} + +/// `a, b, ` (with the trailing separator) or nothing for no columns. +fn leading(columns: &[String]) -> String { + if columns.is_empty() { + String::new() + } else { + format!("{}, ", column_list(columns)) + } +} + +fn group_by(columns: &[String]) -> String { + if columns.is_empty() { + String::new() + } else { + format!(" GROUP BY {}", column_list(columns)) + } +} + +fn partition_by(columns: &[String]) -> String { + if columns.is_empty() { + String::new() + } else { + format!("PARTITION BY {} ", column_list(columns)) + } +} + +/// `(from_ms, to_ms]` on the `time` column. +pub fn window(from_ms: i64, to_ms: i64) -> String { + format!("time > to_timestamp_millis({from_ms}) AND time <= to_timestamp_millis({to_ms})") +} + +/// A sample's time in ms. +const TIME_MS: &str = "CAST(time AS BIGINT) / 1000000"; + +/// The `by` labels of `shape` that are tag columns; a label no series has +/// is empty in every group, so it is no column of the answer. +fn grouping(by: &[String], tags: &[String]) -> Vec { + by.iter() + .filter(|label| tags.contains(label)) + .cloned() + .collect() +} + +/// The aggregate over `value` that `function` is over one group's rows. +fn row_aggregate(function: RangeFunction, approximate: bool) -> String { + match function { + RangeFunction::Sum => "sum(value)".into(), + RangeFunction::Count => "CAST(count(value) AS DOUBLE)".into(), + RangeFunction::Min => "min(value)".into(), + RangeFunction::Max => "max(value)".into(), + RangeFunction::Avg => "avg(value)".into(), + RangeFunction::Quantile(phi) if approximate => { + format!("approx_percentile_cont({phi}) WITHIN GROUP (ORDER BY value)") + } + RangeFunction::Quantile(phi) => { + format!("percentile_cont({phi}) WITHIN GROUP (ORDER BY value)") + } + RangeFunction::Rate | RangeFunction::Increase => { + unreachable!("a counter function is no row aggregate") + } + } +} + +fn outer_aggregate(aggregation: Aggregation) -> &'static str { + match aggregation { + Aggregation::Sum => "sum(value)", + Aggregation::Count => "CAST(count(value) AS DOUBLE)", + Aggregation::Min => "min(value)", + Aggregation::Max => "max(value)", + Aggregation::Avg => "avg(value)", + } +} + +/// Whether `AGG by (G) (F(m[w]))` equals `F` over the rows of each group +/// `G` (a sum of sums or of counts, a max of maxima, a min of minima). +pub fn direct(shape: &QueryShape) -> bool { + matches!( + (shape.outer.as_ref().map(|(a, _)| *a), shape.function), + (Some(Aggregation::Sum), RangeFunction::Sum) + | (Some(Aggregation::Sum), RangeFunction::Count) + | (Some(Aggregation::Max), RangeFunction::Max) + | (Some(Aggregation::Min), RangeFunction::Min) + ) +} + +/// The outer aggregation over `per_series` (columns `tags…, value`), or +/// `per_series` itself when there is none. +fn with_outer(shape: &QueryShape, per_series: String, tags: &[String]) -> String { + match &shape.outer { + None => per_series, + Some((aggregation, by)) => { + let groups = grouping(by, tags); + format!( + "SELECT {}{} AS value FROM ({per_series}){} HAVING count(*) > 0", + leading(&groups), + outer_aggregate(*aggregation), + group_by(&groups) + ) + } + } +} + +/// Native (and approximate) SQL of `shape` at `t_ms` over table `metric` +/// with tag columns `tags`; answer columns are labels then `value`. +pub fn query_time_sql(shape: &QueryShape, tags: &[String], t_ms: i64, approximate: bool) -> String { + let table = quoted(&shape.metric); + let from_ms = t_ms - shape.range_ms as i64; + let rows = window(from_ms, t_ms); + match shape.function { + RangeFunction::Rate | RangeFunction::Increase => { + let stats = format!( + "SELECT {lead}count(*) AS n, min(t_ms) AS first_ms, max(t_ms) AS last_ms, \ + first_value(value ORDER BY t_ms) AS v_first, \ + sum(CASE WHEN prev IS NULL THEN 0.0 WHEN value < prev THEN value ELSE value - prev END) AS increase \ + FROM (SELECT {lead}value, {TIME_MS} AS t_ms, \ + LAG(value) OVER ({partition}ORDER BY time) AS prev FROM {table} WHERE {rows})\ + {group} HAVING count(*) >= 2", + lead = leading(tags), + partition = partition_by(tags), + group = group_by(tags), + ); + with_outer(shape, extrapolated(shape, tags, &stats, t_ms), tags) + } + function => { + if direct(shape) { + let (_, by) = shape.outer.as_ref().expect("direct has an outer"); + let groups = grouping(by, tags); + return format!( + "SELECT {}{} AS value FROM {table} WHERE {rows}{} HAVING count(value) > 0", + leading(&groups), + row_aggregate(function, approximate), + group_by(&groups) + ); + } + let per_series = format!( + "SELECT {}{} AS value FROM {table} WHERE {rows}{} HAVING count(value) > 0", + leading(tags), + row_aggregate(function, approximate), + group_by(tags) + ); + with_outer(shape, per_series, tags) + } + } +} + +/// Prometheus `extrapolatedRate` (`promql/functions.go`, v3.15.1) over +/// `stats`, which gives per series `n`, `first_ms`, `last_ms`, `v_first` and +/// the reset-corrected `increase` of its samples in `(t − range, t]` (at +/// least 2): the 1.1 × average-gap threshold first, then the zero-point +/// clamp; divided by the range in seconds for a rate. +fn extrapolated(shape: &QueryShape, tags: &[String], stats: &str, t_ms: i64) -> String { + let range_ms = shape.range_ms as i64; + let per_second = if shape.function == RangeFunction::Rate { + format!(" / {}", range_ms as f64 / 1000.0) + } else { + String::new() + }; + let lead = leading(tags); + format!( + "SELECT {lead}increase * (sampled + least(d_start, d_zero) + d_end) / sampled{per_second} AS value FROM (\ + SELECT {lead}increase, sampled, d_start, d_end, \ + CASE WHEN increase > 0 AND v_first >= 0 THEN sampled * v_first / increase ELSE d_start END AS d_zero FROM (\ + SELECT {lead}increase, v_first, sampled, \ + CASE WHEN start_gap >= 1.1 * avg_gap THEN avg_gap / 2 ELSE start_gap END AS d_start, \ + CASE WHEN end_gap >= 1.1 * avg_gap THEN avg_gap / 2 ELSE end_gap END AS d_end FROM (\ + SELECT {lead}increase, v_first, CAST(last_ms - first_ms AS DOUBLE) / 1000.0 AS sampled, \ + CAST(last_ms - first_ms AS DOUBLE) / 1000.0 / CAST(n - 1 AS DOUBLE) AS avg_gap, \ + CAST(first_ms - {from_ms} AS DOUBLE) / 1000.0 AS start_gap, \ + CAST({t_ms} - last_ms AS DOUBLE) / 1000.0 AS end_gap FROM ({stats}))))", + from_ms = t_ms - range_ms, + ) +} + +/// A downsampled table: what the plugin writes for one query, and how the +/// query reads it back. +#[derive(Debug, Clone, PartialEq)] +pub struct Downsample { + /// The table the plugin writes, e.g. `downsampled_q4`. + pub table: String, + /// Bucket width in ms: rows of `(e − b, e]` are stored at `e`. + pub bucket_ms: u64, + /// Whether buckets are kept per group `G` (the direct form) rather than + /// per series. + pub per_group: bool, +} + +/// The exact downsample of `shape` at buckets of `bucket_ms`, when InfluxDB +/// has one: none for a quantile (not decomposable into buckets). +pub fn downsample_of(shape: &QueryShape, query_id: &str, bucket_ms: u64) -> Option { + if let RangeFunction::Quantile(_) = shape.function { + return None; + } + Some(Downsample { + table: format!("downsampled_{query_id}"), + bucket_ms, + per_group: direct(shape), + }) +} + +/// The bucket columns the plugin writes for `function`: name and whether +/// it is an integer field. +pub fn bucket_fields(function: RangeFunction) -> Vec<(&'static str, bool)> { + match function { + RangeFunction::Sum | RangeFunction::Min | RangeFunction::Max => vec![("v", false)], + RangeFunction::Count => vec![("c", true)], + RangeFunction::Avg => vec![("s", false), ("c", true)], + RangeFunction::Rate | RangeFunction::Increase => vec![ + ("n", true), + ("first_ms", true), + ("last_ms", true), + ("first_v", false), + ("last_v", false), + ("inc", false), + ], + RangeFunction::Quantile(_) => Vec::new(), + } +} + +/// The key columns of `downsample`'s buckets: the groups of the direct form, +/// else the series' tags. +pub fn bucket_keys(shape: &QueryShape, downsample: &Downsample, tags: &[String]) -> Vec { + if downsample.per_group { + let (_, by) = shape.outer.as_ref().expect("per group has an outer"); + grouping(by, tags) + } else { + tags.to_vec() + } +} + +/// The SQL the plugin runs after rows of `(from_ms, to_ms]` were written: +/// one row per key and bucket, with `bucket_ms` and [`bucket_fields`]. +pub fn downsample_sql( + shape: &QueryShape, + downsample: &Downsample, + tags: &[String], + from_ms: i64, + to_ms: i64, +) -> String { + let table = quoted(&shape.metric); + let keys = bucket_keys(shape, downsample, tags); + let b = downsample.bucket_ms; + let bucketed = format!( + "SELECT {lead}value, time, {TIME_MS} AS t_ms, (({TIME_MS} - 1) / {b} + 1) * {b} AS bucket_ms \ + FROM {table} WHERE {rows}", + lead = leading(&keys), + rows = window(from_ms, to_ms), + ); + let mut key_and_bucket = keys.clone(); + key_and_bucket.push("bucket_ms".into()); + let fields = match shape.function { + RangeFunction::Sum => "sum(value) AS v".to_string(), + RangeFunction::Min => "min(value) AS v".to_string(), + RangeFunction::Max => "max(value) AS v".to_string(), + RangeFunction::Count => "count(value) AS c".to_string(), + RangeFunction::Avg => "sum(value) AS s, count(value) AS c".to_string(), + RangeFunction::Rate | RangeFunction::Increase => { + return format!( + "SELECT {lead}bucket_ms, count(*) AS n, min(t_ms) AS first_ms, max(t_ms) AS last_ms, \ + first_value(value ORDER BY t_ms) AS first_v, last_value(value ORDER BY t_ms) AS last_v, \ + sum(CASE WHEN prev IS NULL THEN 0.0 WHEN value < prev THEN value ELSE value - prev END) AS inc \ + FROM (SELECT {lead}bucket_ms, value, t_ms, \ + LAG(value) OVER ({partition}ORDER BY t_ms) AS prev FROM ({bucketed})){group}", + lead = leading(&keys), + partition = partition_by(&key_and_bucket), + group = group_by(&key_and_bucket), + ); + } + RangeFunction::Quantile(_) => unreachable!("no downsample of a quantile"), + }; + format!( + "SELECT {lead}bucket_ms, {fields} FROM ({bucketed}){group}", + lead = leading(&keys), + group = group_by(&key_and_bucket), + ) +} + +/// The SQL of `shape` at `t_ms` reading `downsample` (bucket rows at their +/// end time, key columns `keys`); answer columns are labels then `value`. +pub fn downsampled_sql( + shape: &QueryShape, + downsample: &Downsample, + keys: &[String], + t_ms: i64, +) -> String { + let table = quoted(&downsample.table); + let rows = window(t_ms - shape.range_ms as i64, t_ms); + let lead = leading(keys); + let group = group_by(keys); + match shape.function { + RangeFunction::Rate | RangeFunction::Increase => { + let stats = format!( + "SELECT {lead}sum(n) AS n, min(first_ms) AS first_ms, max(last_ms) AS last_ms, \ + first_value(first_v ORDER BY time) AS v_first, \ + sum(inc + CASE WHEN prev_last IS NULL THEN 0.0 WHEN first_v < prev_last THEN first_v \ + ELSE first_v - prev_last END) AS increase \ + FROM (SELECT {lead}time, n, first_ms, last_ms, first_v, inc, \ + LAG(last_v) OVER ({partition}ORDER BY time) AS prev_last FROM {table} WHERE {rows})\ + {group} HAVING sum(n) >= 2", + partition = partition_by(keys), + ); + with_outer(shape, extrapolated(shape, keys, &stats, t_ms), keys) + } + function => { + let combined = match function { + RangeFunction::Sum => "sum(v)", + RangeFunction::Min => "min(v)", + RangeFunction::Max => "max(v)", + RangeFunction::Count => "CAST(sum(c) AS DOUBLE)", + RangeFunction::Avg => "sum(s) / CAST(sum(c) AS DOUBLE)", + _ => unreachable!("handled above"), + }; + let per_key = + format!("SELECT {lead}{combined} AS value FROM {table} WHERE {rows}{group}"); + if downsample.per_group { + per_key + } else { + with_outer(shape, per_key, keys) + } + } + } +} + +/// A line-protocol key part (measurement, tag key or value) escaped: `,`, +/// `=`, ` ` and `\` take a backslash (`=` only matters in tags, and is +/// escaped everywhere for simplicity, which line protocol allows). +pub fn push_escaped(out: &mut String, text: &str) { + for c in text.chars() { + if matches!(c, ',' | '=' | ' ' | '\\') { + out.push('\\'); + } + out.push(c); + } +} + +/// One line of line protocol: `metric,tag=v,… value= `, tags with +/// an empty value left out. Refuses a value line protocol cannot carry. +pub fn push_line( + out: &mut String, + metric: &str, + tags: &[(&str, &str)], + value: f64, + ts_ms: i64, +) -> Result<(), String> { + if !value.is_finite() { + return Err(format!( + "value {value} at {ts_ms} ms of {metric}: line protocol has no NaN or infinity" + )); + } + push_escaped(out, metric); + for (key, tag_value) in tags { + if tag_value.is_empty() { + continue; + } + out.push(','); + push_escaped(out, key); + out.push('='); + push_escaped(out, tag_value); + } + // `{:?}` of an f64 always has a decimal point or an exponent, so the + // field is a float, never an integer. + let _ = writeln!(out, " value={value:?} {ts_ms}"); + Ok(()) +} + +/// Parses CSV (RFC 4180: quoted fields, doubled quotes) into rows. +pub fn parse_csv(text: &str) -> Result>, String> { + let mut rows = Vec::new(); + let mut row = Vec::new(); + let mut field = String::new(); + let mut chars = text.chars().peekable(); + let mut quoted_field = false; + let mut in_quotes = false; + let mut any = false; + while let Some(c) = chars.next() { + any = true; + if in_quotes { + if c == '"' { + if chars.peek() == Some(&'"') { + chars.next(); + field.push('"'); + } else { + in_quotes = false; + } + } else { + field.push(c); + } + continue; + } + match c { + '"' if field.is_empty() && !quoted_field => { + in_quotes = true; + quoted_field = true; + } + ',' => { + row.push(std::mem::take(&mut field)); + quoted_field = false; + } + '\r' => {} + '\n' => { + row.push(std::mem::take(&mut field)); + rows.push(std::mem::take(&mut row)); + quoted_field = false; + any = false; + } + c => field.push(c), + } + } + if in_quotes { + return Err("an unterminated quoted field".into()); + } + if any { + row.push(field); + rows.push(row); + } + Ok(rows) +} + +/// A CSV float as InfluxDB writes it: `NaN`, `inf`, `-inf` or a decimal. +pub fn parse_float(text: &str) -> Option { + match text { + "NaN" | "nan" => Some(f64::NAN), + "inf" | "+inf" | "Infinity" => Some(f64::INFINITY), + "-inf" | "-Infinity" => Some(f64::NEG_INFINITY), + _ => text.parse().ok(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn suite_texts_parse() { + let shape = parse("avg by (job) (quantile_over_time(0.9, latency[1m]))").unwrap(); + assert_eq!( + shape, + QueryShape { + outer: Some((Aggregation::Avg, vec!["job".into()])), + function: RangeFunction::Quantile(0.9), + metric: "latency".into(), + range_ms: 60_000, + } + ); + let shape = parse("sum by (job) (rate(requests_total[1h]))").unwrap(); + assert_eq!(shape.function, RangeFunction::Rate); + assert_eq!(shape.range_ms, 3_600_000); + let shape = parse("max_over_time(latency[1m])").unwrap(); + assert_eq!(shape.outer, None); + let shape = parse("sum(count_over_time(latency[90s])) by (job, instance)").unwrap(); + assert_eq!( + shape.outer, + Some((Aggregation::Sum, vec!["job".into(), "instance".into()])) + ); + assert_eq!(shape.range_ms, 90_000); + assert_eq!( + parse("sum(increase(x[1h30m]))").unwrap().range_ms, + 5_400_000 + ); + } + + #[test] + fn other_shapes_are_refused() { + for text in [ + "latency", + "latency[1m]", + "max_over_time(latency{job=\"a\"}[1m])", + "sum without (job) (rate(x[1m]))", + "quantile_over_time(1.5, latency[1m])", + "topk(3, rate(x[1m]))", + "rate(x[1m]) * 2", + "sum(sum(rate(x[1m])))", + "irate(x[1m])", + "max_over_time(latency[1m] offset 1m)", + ] { + assert!(parse(text).is_err(), "{text}"); + } + } + + #[test] + fn windows_are_left_open() { + let shape = parse("max_over_time(latency[1m])").unwrap(); + let sql = query_time_sql(&shape, &["instance".into(), "job".into()], 120_000, false); + assert!(sql + .contains("time > to_timestamp_millis(60000) AND time <= to_timestamp_millis(120000)")); + assert_eq!( + sql, + "SELECT \"instance\", \"job\", max(value) AS value FROM \"latency\" WHERE time > \ + to_timestamp_millis(60000) AND time <= to_timestamp_millis(120000) GROUP BY \ + \"instance\", \"job\" HAVING count(value) > 0" + ); + } + + #[test] + fn grouped_sums_read_rows_directly_and_quantiles_nest() { + let tags = vec!["instance".to_string(), "job".to_string()]; + let sql = query_time_sql( + &parse("sum by (job) (count_over_time(latency[1m]))").unwrap(), + &tags, + 60_000, + false, + ); + assert!(sql + .starts_with("SELECT \"job\", CAST(count(value) AS DOUBLE) AS value FROM \"latency\"")); + let sql = query_time_sql( + &parse("avg by (job) (quantile_over_time(0.9, latency[1m]))").unwrap(), + &tags, + 60_000, + false, + ); + assert!(sql.starts_with("SELECT \"job\", avg(value) AS value FROM (SELECT \"instance\", \"job\", percentile_cont(0.9) WITHIN GROUP (ORDER BY value)"), "{sql}"); + let approximate = query_time_sql( + &parse("quantile_over_time(0.99, latency[1m])").unwrap(), + &tags, + 60_000, + true, + ); + assert!(approximate.contains("approx_percentile_cont(0.99) WITHIN GROUP (ORDER BY value)")); + // A `by` label no series has is no column. + let sql = query_time_sql( + &parse("sum by (zone) (sum_over_time(latency[1m]))").unwrap(), + &tags, + 60_000, + false, + ); + assert!( + sql.starts_with("SELECT sum(value) AS value FROM \"latency\""), + "{sql}" + ); + } + + #[test] + fn rate_extrapolates_over_the_window() { + let sql = query_time_sql( + &parse("rate(requests_total[5m])").unwrap(), + &["job".to_string()], + 600_000, + false, + ); + assert!(sql.contains("CAST(first_ms - 300000 AS DOUBLE) / 1000.0 AS start_gap")); + assert!(sql.contains("CAST(600000 - last_ms AS DOUBLE) / 1000.0 AS end_gap")); + assert!(sql.contains("/ sampled / 300 AS value"), "{sql}"); + assert!(sql.contains("HAVING count(*) >= 2")); + let increase = query_time_sql( + &parse("increase(requests_total[5m])").unwrap(), + &["job".to_string()], + 600_000, + false, + ); + assert!(increase.contains("/ sampled AS value")); + } + + #[test] + fn downsamples_exist_except_for_quantiles() { + let quantile = parse("quantile_over_time(0.5, latency[1m])").unwrap(); + assert_eq!(downsample_of(&quantile, "q1", 10_000), None); + let sum = parse("sum by (job) (sum_over_time(latency[1m]))").unwrap(); + let downsample = downsample_of(&sum, "q1", 10_000).unwrap(); + assert!(downsample.per_group); + let tags = vec!["instance".to_string(), "job".to_string()]; + assert_eq!( + bucket_keys(&sum, &downsample, &tags), + vec!["job".to_string()] + ); + let sql = downsample_sql(&sum, &downsample, &tags, 0, 10_000); + assert!( + sql.contains("((CAST(time AS BIGINT) / 1000000 - 1) / 10000 + 1) * 10000 AS bucket_ms") + ); + assert!(sql.ends_with("GROUP BY \"job\", \"bucket_ms\""), "{sql}"); + let read = downsampled_sql(&sum, &downsample, &["job".to_string()], 60_000); + assert_eq!( + read, + "SELECT \"job\", sum(v) AS value FROM \"downsampled_q1\" WHERE time > \ + to_timestamp_millis(0) AND time <= to_timestamp_millis(60000) GROUP BY \"job\"" + ); + let rate = parse("sum by (job) (rate(requests_total[1m]))").unwrap(); + let downsample = downsample_of(&rate, "q5", 10_000).unwrap(); + assert!(!downsample.per_group); + let read = downsampled_sql(&rate, &downsample, &tags, 60_000); + assert!( + read.contains("LAG(last_v) OVER (PARTITION BY \"instance\", \"job\" ORDER BY time)") + ); + assert!(read.starts_with("SELECT \"job\", sum(value) AS value FROM (")); + } + + #[test] + fn line_protocol_escapes_and_refuses_non_finite_values() { + let mut out = String::new(); + push_line( + &mut out, + "my metric", + &[("job", "a,b=c d"), ("empty", ""), ("instance", "i\\1")], + 3.0, + 1_000, + ) + .unwrap(); + assert_eq!( + out, + "my\\ metric,job=a\\,b\\=c\\ d,instance=i\\\\1 value=3.0 1000\n" + ); + assert!(push_line(&mut out, "m", &[], f64::NAN, 1).is_err()); + assert!(push_line(&mut out, "m", &[], f64::INFINITY, 1).is_err()); + } + + #[test] + fn csv_answers_parse() { + let rows = parse_csv("job,value\n\"a,\"\"b\",1.5\n,NaN\nc,inf\n").unwrap(); + assert_eq!( + rows, + vec![ + vec!["job".to_string(), "value".into()], + vec!["a,\"b".into(), "1.5".into()], + vec!["".into(), "NaN".into()], + vec!["c".into(), "inf".into()], + ] + ); + assert!(parse_float("NaN").unwrap().is_nan()); + assert_eq!(parse_float("-inf"), Some(f64::NEG_INFINITY)); + assert_eq!(parse_csv("").unwrap(), Vec::>::new()); + } + + #[test] + fn variants_name_modes() { + assert_eq!(Mode::of_variant("influxdb3.native"), Some(Mode::Native)); + assert_eq!( + Mode::of_variant("influxdb3.downsampled"), + Some(Mode::Downsampled) + ); + assert_eq!( + Mode::of_variant("influxdb3.approximate"), + Some(Mode::Approximate) + ); + assert_eq!(Mode::of_variant("native"), None); + } +} diff --git a/system-bench/src/engines_external/influxdb3_server.rs b/system-bench/src/engines_external/influxdb3_server.rs new file mode 100644 index 00000000..a3e2b199 --- /dev/null +++ b/system-bench/src/engines_external/influxdb3_server.rs @@ -0,0 +1,852 @@ +//! An InfluxDB 3 Core server as an engine under test, used the way an +//! InfluxDB user runs periodic queries. An arm has no plan file: its +//! variant name says how its queries run ([`Mode`]): +//! +//! - `influxdb3.native`: each query's PromQL text is translated by +//! [`super::influxdb3_query`] into one InfluxDB SQL query over the raw rows, +//! computed at query time, exactly. +//! - `influxdb3.downsampled`: each query with an exact downsample reads a +//! table that the processing engine fills at ingest: the plugin +//! `influxdb3_downsample.py` (copied into the server's plugin directory by +//! `scripts/extbench-up-influxdb3.sh`) behind a request trigger, called +//! after each chunk is written with the SQL that downsamples it. A +//! scheduled trigger would run on wall-clock time, and the harness replays +//! data time faster than that, so the adapter calls the plugin at each data +//! time boundary instead; its work is ingest work. Quantiles have no exact +//! downsample and run as in native. +//! - `influxdb3.approximate`: quantiles with `approx_percentile_cont` +//! (t-digest) at query time, recorded as substitutions; the other queries +//! run as in native. +//! +//! A downsampled or approximate arm in which every query would run as in +//! native is refused at install: its cell would repeat the native one. +//! +//! Data: one table per metric, one tag per label, the float field `value`, +//! written as line protocol with ms timestamps; a write returns after the +//! server's WAL flush, so the rows are queryable when the ingest step ends. +//! Answers are keyed by their labels without `__name__` (every accepted +//! query is a function or an aggregation). +//! +//! Installs: InfluxDB 3 Core holds at most 5 databases, so the engine holds +//! one install at a time ([`EngineUnderTest::holds_one_install_at_a_time`]), +//! each in a fresh database `bench__`, deleted (hard, now) when the +//! arm is dropped. +//! +//! CPU and memory: the server's cgroup, read over SSH or on this host. +//! InfluxDB reports no per-query CPU, so [`StepReport`] carries each query +//! request's wall time only. Footprint: the Parquet files of the database +//! (`system.parquet_files`); rows still in the write buffer are not counted. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::engine::{ + Answers, ArmSpec, CpuAccounting, EngineDescription, EngineError, EngineUnderTest, Footprint, + InstalledArm, PlanSummary, QueryLanguage, SampleChunk, SeriesLabels, StepReport, WorkloadSpec, +}; +use aqpbm_core::harness::protocol::Protocol; +use serde_json::{json, Value}; + +use super::influxdb3_query::{ + bucket_fields, bucket_keys, downsample_of, downsample_sql, downsampled_sql, parse, parse_csv, + parse_float, push_line, query_time_sql, Downsample, Mode, QueryShape, RangeFunction, +}; +use super::server_cgroup::ServerCgroupOptions; + +/// The plugin file the downsampled arms' trigger runs, in the server's +/// plugin directory. +pub const PLUGIN_FILE: &str = "sketch_bench_downsample.py"; +/// Its source, which `scripts/extbench-up-influxdb3.sh` copies there. +pub const PLUGIN_SOURCE: &str = include_str!("influxdb3_downsample.py"); +/// At most this many lines in one write request (the server takes up to +/// 10 MB per request by default). +const LINES_PER_WRITE: usize = 50_000; + +/// How to reach the server. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InfluxDb3Server { + /// The HTTP interface, e.g. `http://10.0.0.1:8181`. + pub url: String, + /// Where the server's cgroup is read; `None`: no CPU or memory is read. + pub cgroup: Option, + /// How long one request may take, e.g. 600 s. + pub request_timeout: Duration, +} + +#[derive(Clone)] +struct Http { + agent: ureq::Agent, + url: String, +} + +impl Http { + fn new(server: &InfluxDb3Server) -> Http { + Http { + agent: ureq::AgentBuilder::new() + .timeout_connect(Duration::from_secs(5)) + .timeout(server.request_timeout) + .build(), + url: server.url.trim_end_matches('/').to_string(), + } + } + + fn answer( + &self, + what: &str, + sent: Result, + ) -> Result { + match sent { + Ok(response) => { + let mut text = String::new(); + std::io::Read::read_to_string(&mut response.into_reader(), &mut text) + .map_err(|error| EngineError(format!("{what}: reading the answer: {error}")))?; + Ok(text) + } + Err(ureq::Error::Status(code, response)) => { + let text = response.into_string().unwrap_or_default(); + Err(EngineError(format!( + "{what}: InfluxDB answered {code}: {}", + text.trim_end() + ))) + } + Err(error) => Err(EngineError(format!( + "{what}: InfluxDB at {}: {error}", + self.url + ))), + } + } + + fn get(&self, path: &str) -> Result { + let sent = self.agent.get(&format!("{}{path}", self.url)).call(); + self.answer(path, sent) + } + + fn post_json(&self, path: &str, body: &Value) -> Result { + let sent = self + .agent + .post(&format!("{}{path}", self.url)) + .set("Content-Type", "application/json") + .send_string(&body.to_string()); + self.answer(path, sent) + } + + fn delete(&self, path_and_query: &str) -> Result { + let sent = self + .agent + .delete(&format!("{}{path_and_query}", self.url)) + .call(); + self.answer(path_and_query, sent) + } + + /// Runs `sql` in `database`; its answer as CSV rows (a header first, + /// or nothing for no rows). + fn query(&self, database: &str, sql: &str) -> Result>, EngineError> { + let text = self.post_json( + "/api/v3/query_sql", + &json!({"db": database, "q": sql, "format": "csv"}), + )?; + parse_csv(&text).map_err(|error| EngineError(format!("answer of '{sql}': {error}"))) + } + + fn write(&self, database: &str, lines: &str) -> Result<(), EngineError> { + let sent = self + .agent + .post(&format!("{}/api/v3/write_lp", self.url)) + .query("db", database) + .query("precision", "millisecond") + .set("Content-Type", "text/plain; charset=utf-8") + .send_string(lines); + self.answer("write", sent).map(|_| ()) + } +} + +/// An InfluxDB 3 server; see the module docs. +pub struct InfluxDb3Engine { + server: InfluxDb3Server, + http: Http, + description: EngineDescription, + database_prefix: String, +} + +/// Installs made by this process: numbers each install's database. +static INSTALL_COUNT: AtomicU64 = AtomicU64::new(0); + +impl InfluxDb3Engine { + /// Connects to the server and reads its version. A database of an + /// earlier run (`bench_*`) is refused: its data and background work + /// would be charged to this run. + pub fn new(server: InfluxDb3Server) -> Result { + let http = Http::new(&server); + let ping: Value = serde_json::from_str(&http.get("/ping")?) + .map_err(|error| EngineError(format!("/ping: {error}")))?; + let field = |name: &str| ping[name].as_str().unwrap_or("?").to_string(); + let databases = http.get("/api/v3/configure/database?format=csv")?; + let leftovers: Vec<&str> = databases + .lines() + .skip(1) + .filter(|name| name.starts_with("bench_")) + .collect(); + if !leftovers.is_empty() { + return Err(EngineError(format!( + "the server holds databases of an earlier run: {}; start it from an empty data dir", + leftovers.join(", ") + ))); + } + let description = EngineDescription { + id: "influxdb3".into(), + version: format!( + "{} {} ({})", + field("product_name"), + field("version"), + field("revision") + ), + version_dirty: false, + build_profile: "default server settings".into(), + }; + Ok(InfluxDb3Engine { + database_prefix: format!("bench_{}", std::process::id()), + server, + http, + description, + }) + } +} + +/// How one query of an arm runs. +#[derive(Debug, Clone)] +enum Way { + QueryTime { approximate: bool }, + Downsampled(Downsample), +} + +#[derive(Debug, Clone)] +struct ArmQuery { + id: String, + text: String, + shape: QueryShape, + way: Way, + asked_from_ms: Option, +} + +fn gcd(a: u64, b: u64) -> u64 { + if b == 0 { + a + } else { + gcd(b, a % b) + } +} + +/// The arm's queries and how each runs in `mode`; refuses a query outside +/// the accepted shapes and an arm in which nothing differs from native. +fn arm_queries(workload: &WorkloadSpec, mode: Mode) -> Result, EngineError> { + let mut queries = Vec::new(); + for query in &workload.queries { + let text = query.text_in(QueryLanguage::PromQl).ok_or_else(|| { + EngineError(format!("query {}: no PromQL text to translate", query.id)) + })?; + let shape = parse(text).map_err(|error| { + EngineError(format!( + "query {}: no InfluxDB translation: {error}", + query.id + )) + })?; + if shape.range_ms != query.window_ms { + return Err(EngineError(format!( + "query {}: its range is {} ms but its window is {} ms", + query.id, shape.range_ms, query.window_ms + ))); + } + let quantile = matches!(shape.function, RangeFunction::Quantile(_)); + let way = match mode { + Mode::Native => Way::QueryTime { approximate: false }, + Mode::Approximate => Way::QueryTime { + approximate: quantile, + }, + Mode::Downsampled => { + let bucket_ms = gcd(query.window_ms, query.evaluation_interval_ms); + let data_start_ms = workload.data_start_ms().unwrap_or(0); + if data_start_ms.rem_euclid(bucket_ms as i64) != 0 { + return Err(EngineError(format!( + "query {}: buckets of {bucket_ms} ms do not divide the data start ({data_start_ms} ms)", + query.id + ))); + } + match downsample_of(&shape, &query.id, bucket_ms) { + Some(downsample) => Way::Downsampled(downsample), + None => Way::QueryTime { approximate: false }, + } + } + }; + queries.push(ArmQuery { + id: query.id.clone(), + text: text.to_string(), + shape, + way, + asked_from_ms: workload.asked_from_ms(query), + }); + } + let differs = |query: &ArmQuery| { + matches!( + query.way, + Way::Downsampled(_) | Way::QueryTime { approximate: true } + ) + }; + match mode { + Mode::Native => {} + Mode::Downsampled if !queries.iter().any(differs) => { + return Err(EngineError( + "no query of this workload has an exact InfluxDB downsample (quantiles are not \ + decomposable into buckets): every query would run as in influxdb3.native" + .into(), + )) + } + Mode::Approximate if !queries.iter().any(differs) => { + return Err(EngineError( + "no query of this workload has an approximate InfluxDB function (only quantiles \ + do: approx_percentile_cont): every query would run as in influxdb3.native" + .into(), + )) + } + _ => {} + } + Ok(queries) +} + +impl EngineUnderTest for InfluxDb3Engine { + fn description(&self) -> EngineDescription { + self.description.clone() + } + + fn cpu_accounting(&self) -> CpuAccounting { + match &self.server.cgroup { + Some(source) => CpuAccounting::Cgroup(source.clone()), + None => CpuAccounting::NotMeasured, + } + } + + fn holds_one_install_at_a_time(&self) -> bool { + true + } + + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + let mode = arm + .engine_options + .get("influxdb3_mode") + .and_then(Value::as_str) + .map(|name| format!("influxdb3.{name}")) + .as_deref() + .or(Some(arm.name.as_str())) + .and_then(Mode::of_variant) + .ok_or_else(|| { + EngineError(format!( + "arm {}: name one of influxdb3.native, influxdb3.downsampled and \ + influxdb3.approximate (or set engine_options.influxdb3_mode)", + arm.name + )) + })?; + let queries = arm_queries(workload, mode)?; + let metrics: BTreeSet = queries.iter().map(|q| q.shape.metric.clone()).collect(); + let database = format!( + "{}_{}", + self.database_prefix, + INSTALL_COUNT.fetch_add(1, Ordering::Relaxed) + ); + self.http + .post_json("/api/v3/configure/database", &json!({ "db": database }))?; + let mut installed = InfluxDb3Arm { + http: self.http.clone(), + trigger: None, + tags: metrics + .iter() + .map(|m| (m.clone(), BTreeSet::new())) + .collect(), + written_metrics: BTreeSet::new(), + downsampled_tags: BTreeMap::new(), + previous_chunk_end_ms: None, + summary: summary(&queries, mode), + queries, + database, + }; + if mode == Mode::Downsampled { + let trigger = format!("{}_downsample", installed.database); + self.http.post_json( + "/api/v3/configure/processing_engine_trigger", + &json!({ + "db": installed.database, + "plugin_filename": PLUGIN_FILE, + "trigger_name": trigger, + "trigger_specification": format!("request:{trigger}"), + "trigger_settings": {"run_async": false, "error_behavior": "log"}, + "disabled": false, + }), + )?; + installed.trigger = Some(trigger); + } + Ok(Box::new(installed)) + } +} + +fn summary(queries: &[ArmQuery], mode: Mode) -> PlanSummary { + let mut text = format!("InfluxDB 3, {mode:?}\n"); + let mut substitutions = Vec::new(); + let mut stored_outputs = Vec::new(); + let mut node_kinds = Vec::new(); + for query in queries { + let way = match &query.way { + Way::QueryTime { approximate: false } => "SQL at query time, exact".to_string(), + Way::QueryTime { approximate: true } => { + substitutions.push(format!( + "approx_percentile_cont (t-digest, 100 centroids) for quantile_over_time at query {}", + query.id + )); + "SQL at query time, approx_percentile_cont".to_string() + } + Way::Downsampled(downsample) => { + stored_outputs.push(downsample.table.clone()); + format!( + "processing-engine downsample into {} ({} ms buckets), exact", + downsample.table, downsample.bucket_ms + ) + } + }; + node_kinds.push( + match &query.way { + Way::QueryTime { approximate: false } => "QueryTime", + Way::QueryTime { approximate: true } => "QueryTimeApproximate", + Way::Downsampled(_) => "Downsampled", + } + .to_string(), + ); + let _ = std::fmt::Write::write_fmt( + &mut text, + format_args!("{}: {} -> {way}\n", query.id, query.text), + ); + } + PlanSummary { + text, + node_kinds, + stored_outputs, + substitutions, + sharing_lost: Vec::new(), + } +} + +/// One installed arm: its database and the queries it answers. +struct InfluxDb3Arm { + http: Http, + database: String, + trigger: Option, + queries: Vec, + /// Per metric the arm reads: the tag columns its rows carry so far. + tags: BTreeMap>, + /// The metrics with at least one row written (their table exists). + written_metrics: BTreeSet, + /// Per downsampled table written so far: the tags its rows carry. + downsampled_tags: BTreeMap>, + previous_chunk_end_ms: Option, + summary: PlanSummary, +} + +impl Drop for InfluxDb3Arm { + fn drop(&mut self) { + // Best effort: a server that is gone keeps nothing anyway. + if let Some(trigger) = &self.trigger { + let _ = self.http.delete(&format!( + "/api/v3/configure/processing_engine_trigger?db={}&trigger_name={trigger}&force=true", + self.database + )); + } + let _ = self.http.delete(&format!( + "/api/v3/configure/database?db={}&hard_delete_at=now", + self.database + )); + } +} + +impl InfluxDb3Arm { + fn tags_of(&self, metric: &str) -> Vec { + self.tags + .get(metric) + .map(|tags| tags.iter().cloned().collect()) + .unwrap_or_default() + } + + /// Calls the downsampling plugin for the rows of `(from_ms, to_ms]` of + /// the metrics in `written`. + fn downsample( + &mut self, + trigger: &str, + written: &BTreeSet, + from_ms: i64, + to_ms: i64, + ) -> Result<(), EngineError> { + let mut jobs = Vec::new(); + for query in &self.queries { + let Way::Downsampled(downsample) = &query.way else { + continue; + }; + if !written.contains(&query.shape.metric) { + continue; + } + if to_ms.rem_euclid(downsample.bucket_ms as i64) != 0 { + return Err(EngineError(format!( + "query {}: a chunk ends at {to_ms} ms, inside a bucket of {} ms", + query.id, downsample.bucket_ms + ))); + } + let tags = self.tags_of(&query.shape.metric); + let fields: Vec = bucket_fields(query.shape.function) + .into_iter() + .map(|(name, integer)| json!([name, integer])) + .collect(); + jobs.push(json!({ + "sql": downsample_sql(&query.shape, downsample, &tags, from_ms, to_ms), + "table": downsample.table, + "keys": bucket_keys(&query.shape, downsample, &tags), + "fields": fields, + })); + } + if jobs.is_empty() { + return Ok(()); + } + let answer = self.http.post_json( + &format!("/api/v3/engine/{trigger}"), + &json!({ "jobs": jobs }), + )?; + let answer: Value = serde_json::from_str(&answer).map_err(|error| { + EngineError(format!( + "the downsampling plugin answered '{answer}': {error}" + )) + })?; + let Some(tables) = answer["tables"].as_object() else { + return Err(EngineError(format!( + "the downsampling plugin failed: {answer}" + ))); + }; + for (table, written) in tables { + if written["rows"].as_u64().unwrap_or(0) == 0 { + continue; + } + let tags = self.downsampled_tags.entry(table.clone()).or_default(); + for tag in written["tags"].as_array().into_iter().flatten() { + if let Some(tag) = tag.as_str() { + tags.insert(tag.to_string()); + } + } + } + Ok(()) + } +} + +impl InstalledArm for InfluxDb3Arm { + fn plan_summary(&self) -> PlanSummary { + self.summary.clone() + } + + fn ingest(&mut self, chunk: &SampleChunk) -> Result { + // Every line is built (and every sample checked) before any write, + // so a refused chunk writes nothing. + let mut lines: BTreeMap<&str, (String, usize)> = BTreeMap::new(); + let mut first_ts_ms: Option = None; + for sample in &chunk.samples { + let Some(metric) = sample.labels.get("__name__") else { + continue; + }; + let Some(known) = self.tags.get_mut(metric) else { + continue; + }; + if sample.ts_ms <= 0 { + return Err(EngineError(format!( + "a sample at {} ms: timestamps must be after 0", + sample.ts_ms + ))); + } + first_ts_ms = Some(first_ts_ms.map_or(sample.ts_ms, |t| t.min(sample.ts_ms))); + let mut tags: Vec<(&str, &str)> = Vec::with_capacity(sample.labels.len()); + for (key, value) in sample.labels.iter() { + if key == "__name__" || value.is_empty() { + continue; + } + if key == "time" || key == "value" { + return Err(EngineError(format!( + "metric {metric} has a label named {key}, a column name of InfluxDB's table" + ))); + } + if !known.contains(key) { + known.insert(key.clone()); + } + tags.push((key, value)); + } + let (text, count) = lines.entry(metric.as_str()).or_default(); + push_line(text, metric, &tags, sample.value, sample.ts_ms).map_err(EngineError)?; + *count += 1; + } + let mut written = BTreeSet::new(); + for (metric, (text, count)) in &lines { + if *count <= LINES_PER_WRITE { + self.http.write(&self.database, text)?; + } else { + let all: Vec<&str> = text.lines().collect(); + for part in all.chunks(LINES_PER_WRITE) { + let mut body = part.join("\n"); + body.push('\n'); + self.http.write(&self.database, &body)?; + } + } + written.insert(metric.to_string()); + self.written_metrics.insert(metric.to_string()); + } + let from_ms = self + .previous_chunk_end_ms + .or(first_ts_ms.map(|t| t - 1)) + .unwrap_or(chunk.end_ms); + self.previous_chunk_end_ms = Some(chunk.end_ms); + if let Some(trigger) = self.trigger.clone() { + self.downsample(&trigger, &written, from_ms, chunk.end_ms)?; + } + Ok(StepReport::default()) + } + + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError> { + let mut answers = BTreeMap::new(); + let mut report = StepReport::default(); + for query in &self.queries { + if query.asked_from_ms.is_some_and(|from_ms| at_ms < from_ms) { + continue; + } + let sql = match &query.way { + Way::QueryTime { approximate } => { + if !self.written_metrics.contains(&query.shape.metric) { + answers.insert(query.id.clone(), BTreeMap::new()); + continue; + } + query_time_sql( + &query.shape, + &self.tags_of(&query.shape.metric), + at_ms, + *approximate, + ) + } + Way::Downsampled(downsample) => { + let Some(written_tags) = self.downsampled_tags.get(&downsample.table) else { + answers.insert(query.id.clone(), BTreeMap::new()); + continue; + }; + let keys: Vec = + bucket_keys(&query.shape, downsample, &self.tags_of(&query.shape.metric)) + .into_iter() + .filter(|key| written_tags.contains(key)) + .collect(); + downsampled_sql(&query.shape, downsample, &keys, at_ms) + } + }; + let started = Instant::now(); + let rows = self.http.query(&self.database, &sql)?; + report + .query_wall_ns + .insert(query.id.clone(), started.elapsed().as_nanos() as u64); + answers.insert( + query.id.clone(), + answer_of(&rows).map_err(|e| EngineError(format!("query {}: {e}", query.id)))?, + ); + } + Ok((Answers(answers), report)) + } + + fn footprint(&self) -> Result { + let rows = self.http.query( + &self.database, + "SELECT table_name, CAST(sum(size_bytes) AS BIGINT) AS bytes FROM system.parquet_files \ + GROUP BY table_name", + )?; + let mut footprint = Footprint::default(); + for row in rows.iter().skip(1) { + let [table, bytes] = row.as_slice() else { + return Err(EngineError(format!("unexpected parquet_files row {row:?}"))); + }; + let bytes: u64 = bytes + .parse() + .map_err(|_| EngineError(format!("unexpected parquet_files row {row:?}")))?; + if self.downsampled_tags.contains_key(table) { + footprint.view_bytes += bytes; + } else if self.tags.contains_key(table) { + footprint.raw_retained_bytes += bytes; + } + } + Ok(footprint) + } +} + +/// The rows of one answer (a header, label columns, `value` last) as series +/// and values; an empty label cell is no label. +fn answer_of(rows: &[Vec]) -> Result, String> { + let Some((header, rows)) = rows.split_first() else { + return Ok(BTreeMap::new()); + }; + if header.last().map(String::as_str) != Some("value") { + return Err(format!("the answer's last column is not value: {header:?}")); + } + let mut series = BTreeMap::new(); + for row in rows { + if row.len() != header.len() { + return Err(format!("row {row:?} does not match the header {header:?}")); + } + let (value, labels) = row.split_last().expect("at least the value"); + let key: SeriesLabels = header + .iter() + .zip(labels) + .filter(|(_, value)| !value.is_empty()) + .map(|(name, value)| (name.clone(), value.clone())) + .collect(); + let value = if value.is_empty() { + f64::NAN + } else { + parse_float(value).ok_or_else(|| format!("value '{value}' is not a number"))? + }; + if series.insert(key.clone(), value).is_some() { + return Err(format!("two rows for the series {key:?}")); + } + } + Ok(series) +} + +#[derive(clap::Args, Debug, Clone)] +pub struct InfluxDb3Options { + /// The InfluxDB 3 server's HTTP interface, e.g. `http://10.0.0.1:8181` + /// (engine `influxdb3`). + #[arg(long)] + pub influxdb3_url: Option, + /// How long one InfluxDB 3 request may take, in seconds. + #[arg(long, default_value_t = 600)] + pub influxdb3_request_timeout_seconds: u64, + #[command(flatten)] + pub cgroup: ServerCgroupOptions, +} + +pub fn periodic_queries( + matches: &clap::ArgMatches, + _: &Protocol, +) -> anyhow::Result> { + for (id, flag) in [ + ("speed", "--speed"), + ( + "victoriametrics_restart_command", + "--victoriametrics-restart-command", + ), + ( + "asapquery_backend_restart_command", + "--asapquery-backend-restart-command", + ), + ] { + if matches!(matches.try_get_raw(id), Ok(Some(_))) { + anyhow::bail!("{flag} is not for engine influxdb3"); + } + } + let options = ::from_arg_matches(matches)?; + let Some(url) = options.influxdb3_url else { + anyhow::bail!("engine influxdb3 needs --influxdb3-url"); + }; + Ok(Box::new(InfluxDb3Engine::new(InfluxDb3Server { + url, + cgroup: options.cgroup.source(), + request_timeout: Duration::from_secs(options.influxdb3_request_timeout_seconds), + })?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use aqpbm_core::harness::engine::{QueryText, WorkloadQuery}; + + fn workload(texts: &[&str]) -> WorkloadSpec { + WorkloadSpec::periodic( + "w".into(), + texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{}", i + 1), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + dialect: None, + }], + window_ms: 60_000, + evaluation_interval_ms: 10_000, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![], + ) + } + + #[test] + fn variants_that_change_nothing_are_refused() { + let quantiles = workload(&["quantile_over_time(0.99, latency[1m])"]); + assert!(arm_queries(&quantiles, Mode::Native).is_ok()); + assert!(arm_queries(&quantiles, Mode::Approximate).is_ok()); + let error = arm_queries(&quantiles, Mode::Downsampled).unwrap_err(); + assert!(error.0.contains("not decomposable"), "{error:?}"); + let rates = workload(&["sum by (job) (rate(requests_total[1m]))"]); + assert!(arm_queries(&rates, Mode::Downsampled).is_ok()); + let error = arm_queries(&rates, Mode::Approximate).unwrap_err(); + assert!(error.0.contains("approx_percentile_cont"), "{error:?}"); + } + + #[test] + fn joint_mixes_ways_and_records_substitutions() { + let joint = workload(&[ + "quantile_over_time(0.99, latency[1m])", + "max_over_time(latency[1m])", + "sum by (job) (rate(requests_total[1m]))", + ]); + let queries = arm_queries(&joint, Mode::Downsampled).unwrap(); + assert!(matches!( + queries[0].way, + Way::QueryTime { approximate: false } + )); + assert!(matches!(&queries[1].way, Way::Downsampled(d) if d.bucket_ms == 10_000)); + let downsampled = summary(&queries, Mode::Downsampled); + assert!(downsampled.substitutions.is_empty()); + assert_eq!( + downsampled.stored_outputs, + vec!["downsampled_q2", "downsampled_q3"] + ); + let queries = arm_queries(&joint, Mode::Approximate).unwrap(); + let approximate = summary(&queries, Mode::Approximate); + assert_eq!(approximate.substitutions.len(), 1); + assert!(approximate.substitutions[0].ends_with("query q1")); + } + + #[test] + fn a_range_other_than_the_window_is_refused() { + let error = + arm_queries(&workload(&["max_over_time(latency[2m])"]), Mode::Native).unwrap_err(); + assert!(error.0.contains("window"), "{error:?}"); + let error = arm_queries(&workload(&["irate(x[1m])"]), Mode::Native).unwrap_err(); + assert!(error.0.contains("no InfluxDB translation"), "{error:?}"); + } + + #[test] + fn answers_key_by_their_label_columns() { + let rows = parse_csv("instance,job,value\ni1,a,1.5\n,b,NaN\n").unwrap(); + let answer = answer_of(&rows).unwrap(); + let first: SeriesLabels = [("instance", "i1"), ("job", "a")] + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + assert_eq!(answer[&first], 1.5); + let second: SeriesLabels = [("job".to_string(), "b".to_string())].into_iter().collect(); + assert!(answer[&second].is_nan()); + assert!(answer_of(&[]).unwrap().is_empty()); + } +} diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 6bf0b9b2..92278296 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -21,6 +21,8 @@ pub mod clickhouse_query_text; pub mod clickhouse_server; pub mod druid_sql; pub mod duckdb_command_line; +pub mod influxdb3_query; +pub mod influxdb3_server; mod kept_process; pub mod pilotdb; pub mod plan_file; diff --git a/system-bench/src/registry.rs b/system-bench/src/registry.rs index a83822b4..4127b79c 100644 --- a/system-bench/src/registry.rs +++ b/system-bench/src/registry.rs @@ -15,6 +15,7 @@ use crate::engines_external::clickhouse_query_text::{self, ClickHouseQueryTextOp use crate::engines_external::clickhouse_server::{self, ClickHouseServerOptions}; use crate::engines_external::druid_sql::{self, DruidOptions}; use crate::engines_external::duckdb_command_line::{self, DuckDbOptions}; +use crate::engines_external::influxdb3_server::{self, InfluxDb3Options}; use crate::engines_external::pilotdb::{self, PilotDbOptions}; use crate::engines_external::postgresql_command_line::{self, PostgreSqlOptions}; use crate::engines_external::victoriametrics_server::{self, VictoriaMetricsOptions}; @@ -93,6 +94,15 @@ pub const SYSTEMS: &[System] = &[ write_throughput: None, one_shot_queries: None, }, + System { + name: "influxdb3", + periodic_queries: Some(PeriodicQueries { + options: InfluxDb3Options::augment_args, + build: influxdb3_server::periodic_queries, + }), + write_throughput: None, + one_shot_queries: None, + }, System { name: "asapquery-precompute-engine", periodic_queries: None, @@ -256,12 +266,13 @@ fn fake_engine(matches: &ArgMatches, _: &Protocol) -> Result InfluxDb3Server { + InfluxDb3Server { + url: std::env::var("AQPBM_INFLUXDB3_URL").expect("AQPBM_INFLUXDB3_URL"), + cgroup: std::env::var("AQPBM_SERVER_CGROUP_DIRECTORY") + .ok() + .map(|directory| match std::env::var("AQPBM_SERVER_SSH_HOST") { + Ok(host) => CgroupSource::Remote { + ssh_program: "ssh".into(), + host, + cgroup_directory: directory.into(), + }, + Err(_) => CgroupSource::Local(directory.into()), + }), + request_timeout: Duration::from_secs(120), + } +} + +fn engine() -> InfluxDb3Engine { + InfluxDb3Engine::new(server()).expect("the server answers") +} + +/// Queries `texts` (ids `q1`, `q2`, …) with window `window_ms`, evaluated +/// every `interval_ms`, data supplied by the test from 0 ms. +fn workload(texts: &[&str], window_ms: u64, interval_ms: u64) -> WorkloadSpec { + WorkloadSpec::periodic( + "conformance".into(), + texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{}", i + 1), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + dialect: None, + }], + window_ms, + evaluation_interval_ms: interval_ms, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![], + ) +} + +fn arm(mode: &str) -> ArmSpec { + ArmSpec { + name: format!("influxdb3.{mode}"), + raw_data_retained: true, + engine_options: json!({}), + } +} + +fn install(engine: &InfluxDb3Engine, mode: &str, spec: &WorkloadSpec) -> Box { + engine + .install(spec, &arm(mode)) + .unwrap_or_else(|e| panic!("{mode}: {e}")) +} + +fn series(pairs: &[(&str, &str)]) -> Arc { + Arc::new( + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ) +} + +/// `samples` cut into chunks ending at every multiple of `chunk_ms` from +/// `chunk_ms` to `end_ms` (empty ones included), time-major. +fn chunks(mut samples: Vec, chunk_ms: i64, end_ms: i64) -> Vec { + samples.sort_by_key(|s| s.ts_ms); + (1..=end_ms / chunk_ms) + .map(|k| SampleChunk { + end_ms: k * chunk_ms, + samples: samples + .iter() + .filter(|s| s.ts_ms > (k - 1) * chunk_ms && s.ts_ms <= k * chunk_ms) + .cloned() + .collect(), + }) + .collect() +} + +/// The answers of query `q` as (labels joined by `,`, value). +fn rows(answers: &Answers, index: usize) -> BTreeMap { + answers + .0 + .get(&format!("q{index}")) + .into_iter() + .flatten() + .map(|(labels, value)| (key(labels), *value)) + .collect() +} + +fn key(labels: &SeriesLabels) -> String { + labels + .iter() + .filter(|(name, _)| name.as_str() != "__name__") + .map(|(name, value)| format!("{name}={value}")) + .collect::>() + .join(",") +} + +fn assert_rows(what: &str, got: &BTreeMap, expected: &[(&str, f64)]) { + assert_rows_within(what, got, expected, 0.0); +} + +/// [`assert_rows`] with an absolute tolerance added to the relative one. +fn assert_rows_within( + what: &str, + got: &BTreeMap, + expected: &[(&str, f64)], + absolute: f64, +) { + assert_eq!(got.len(), expected.len(), "{what}: {got:?} vs {expected:?}"); + for (key, want) in expected { + let value = got + .get(*key) + .unwrap_or_else(|| panic!("{what}: no {key} in {got:?}")); + assert!( + (value - want).abs() <= 1e-9 * want.abs().max(1.0) + absolute, + "{what} {key}: {value} vs {want}" + ); + } +} + +/// Runs `texts` in `mode` over `samples` (10 s chunks up to `end_ms`) and +/// evaluates at `at_ms`. +fn answers_at( + engine: &InfluxDb3Engine, + mode: &str, + spec: &WorkloadSpec, + samples: &[Sample], + end_ms: i64, + at_ms: i64, +) -> Answers { + let mut installed = install(engine, mode, spec); + for chunk in chunks(samples.to_vec(), 10_000, end_ms) { + installed.ingest(&chunk).expect("ingest"); + } + installed.evaluate(at_ms).expect("evaluate").0 +} + +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn the_server_is_the_pinned_version() { + let description = engine().description(); + println!("{description:?}"); + assert_eq!(description.id, "influxdb3"); + assert!( + description.version.starts_with("InfluxDB 3 Core 3.12.3"), + "{}", + description.version + ); +} + +/// C1, C2: a sample at T − w is out of the window and one at T is in; sums, +/// counts and maxima, natively and downsampled. Job a: series 1 (1.0 each +/// second) and 2 (0.5), job b: series 1 (2.0), samples 1..120 s, plus +/// 1,000 at 60 s for a/1: at 120 s, sum a 90, b 120; count a 120, b 60; +/// max a/1 1, a/2 0.5, b/1 2. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn sums_counts_and_maxima_over_left_open_windows() { + let engine = engine(); + let mut samples: Vec = (1..=120) + .flat_map(|s: i64| { + [("a", "1", 1.0), ("a", "2", 0.5), ("b", "1", 2.0)] + .into_iter() + .map(move |(job, id, value)| Sample { + labels: series(&[("__name__", "latency"), ("job", job), ("id", id)]), + ts_ms: s * 1000, + value: if s == 60 && job == "a" && id == "1" { + 1000.0 + } else { + value + }, + }) + }) + .collect(); + samples.sort_by_key(|s| s.ts_ms); + let spec = workload( + &[ + "sum by (job) (sum_over_time(latency[1m]))", + "sum by (job) (count_over_time(latency[1m]))", + "max_over_time(latency[1m])", + "avg by (job) (max_over_time(latency[1m]))", + "avg_over_time(latency[1m])", + ], + 60_000, + 10_000, + ); + for mode in ["native", "downsampled"] { + let answers = answers_at(&engine, mode, &spec, &samples, 120_000, 120_000); + assert_rows( + mode, + &rows(&answers, 1), + &[("job=a", 90.0), ("job=b", 120.0)], + ); + assert_rows( + mode, + &rows(&answers, 2), + &[("job=a", 120.0), ("job=b", 60.0)], + ); + assert_rows( + mode, + &rows(&answers, 3), + &[ + ("id=1,job=a", 1.0), + ("id=2,job=a", 0.5), + ("id=1,job=b", 2.0), + ], + ); + assert_rows(mode, &rows(&answers, 4), &[("job=a", 0.75), ("job=b", 2.0)]); + assert_rows( + mode, + &rows(&answers, 5), + &[ + ("id=1,job=a", 1.0), + ("id=2,job=a", 0.5), + ("id=1,job=b", 2.0), + ], + ); + } + let refused = engine + .install(&spec, &arm("approximate")) + .err() + .expect("nothing to approximate"); + assert!(refused.0.contains("approx_percentile_cont"), "{refused:?}"); +} + +/// C3: values 1..60 over (60 s, 120 s] for a/1 and 2·(1..60) for a/2: the +/// 0.99 quantiles 59.41 and 118.82; avg by job of the 0.9 quantiles +/// (54.1 + 108.2) / 2 = 81.15. InfluxDB's `percentile_cont` rounds the +/// interpolation fraction to 6 decimals (0.41 -> 0.409999), so its answers +/// are within 1e-6 of the gap between the two neighbour values (here 1 and +/// 2). Approximate answers within 1% of these. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn quantiles_interpolate_as_promql() { + let engine = engine(); + let samples: Vec = (61..=120) + .flat_map(|s: i64| { + [("1", 1.0), ("2", 2.0)] + .into_iter() + .map(move |(id, m)| Sample { + labels: series(&[("__name__", "latency"), ("job", "a"), ("id", id)]), + ts_ms: s * 1000, + value: m * (s - 60) as f64, + }) + }) + .collect(); + let spec = workload( + &[ + "quantile_over_time(0.99, latency[1m])", + "avg by (job) (quantile_over_time(0.9, latency[1m]))", + ], + 60_000, + 10_000, + ); + let answers = answers_at(&engine, "native", &spec, &samples, 120_000, 120_000); + assert_rows_within( + "native", + &rows(&answers, 1), + &[("id=1,job=a", 59.41), ("id=2,job=a", 118.82)], + 2e-6, + ); + assert_rows_within("native", &rows(&answers, 2), &[("job=a", 81.15)], 2e-6); + let answers = answers_at(&engine, "approximate", &spec, &samples, 120_000, 120_000); + for (index, expected) in [ + (1, vec![("id=1,job=a", 59.41), ("id=2,job=a", 118.82)]), + (2, vec![("job=a", 81.15)]), + ] { + let got = rows(&answers, index); + assert_eq!(got.len(), expected.len()); + for (key, want) in expected { + let value = got[key]; + println!("approximate q{index} {key}: {value} vs exact {want}"); + assert!( + (value - want).abs() <= 0.01 * want, + "{key}: {value} vs {want}" + ); + } + } + let refused = engine + .install(&spec, &arm("downsampled")) + .err() + .expect("nothing to downsample"); + assert!(refused.0.contains("not decomposable"), "{refused:?}"); +} + +/// The counter data of the ClickHouse conformance case (x, y, z, w), each +/// series in its own job, over 600 s, with resets. +fn counter_samples() -> Vec { + let mut samples = Vec::new(); + for s in 1..=600i64 { + let x = if s <= 450 { s } else { s - 450 } as f64; + let y = if s <= 360 { 3 * s } else { s - 360 } as f64; + let z = if s < 400 { + s as f64 + } else if s < 500 { + (s - 5) as f64 + } else { + (s - 500) as f64 / 2.0 + }; + for (job, value) in [("x", x), ("y", y), ("z", z)] { + samples.push(Sample { + labels: series(&[("__name__", "requests_total"), ("job", job)]), + ts_ms: s * 1000, + value, + }); + } + if s % 10 == 5 { + samples.push(Sample { + labels: series(&[("__name__", "requests_total"), ("job", "w")]), + ts_ms: s * 1000, + value: s as f64, + }); + } + } + samples +} + +/// C4: PromQL's rates over 5 m at 600 s, resets included: x 1, y 417/299, +/// z 642/299, w 1 (the ClickHouse query-time case); increases are the +/// rates × 300; natively and from 10 s downsampled buckets alike. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn rates_and_increases_are_promql() { + let engine = engine(); + let spec = workload( + &[ + "rate(requests_total[5m])", + "sum by (job) (increase(requests_total[5m]))", + "sum(rate(requests_total[5m]))", + ], + 300_000, + 10_000, + ); + let rates = [ + ("job=x", 1.0), + ("job=y", 417.0 / 299.0), + ("job=z", 642.0 / 299.0), + ("job=w", 1.0), + ]; + let increases: Vec<(&str, f64)> = rates.iter().map(|(k, v)| (*k, v * 300.0)).collect(); + let total: f64 = rates.iter().map(|(_, v)| v).sum(); + for mode in ["native", "downsampled"] { + let answers = answers_at(&engine, mode, &spec, &counter_samples(), 600_000, 600_000); + assert_rows(mode, &rows(&answers, 1), &rates); + assert_rows(mode, &rows(&answers, 2), &increases); + assert_rows(mode, &rows(&answers, 3), &[("", total)]); + } +} + +/// A deterministic pseudo-random sequence (64-bit LCG), in [0, 1). +struct Lcg(u64); + +impl Lcg { + fn next(&mut self) -> f64 { + self.0 = self + .0 + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407); + (self.0 >> 11) as f64 / (1u64 << 53) as f64 + } +} + +/// Generated data: 20 latency series (jobs a, b, and one series with no +/// job) and 20 counters with resets, 1 s samples with random gaps, over +/// 180 s from 1,700,000,000,000 ms. +fn generated() -> (Vec, i64) { + let start_ms: i64 = 1_700_000_000_000; + let mut random = Lcg(42); + let mut samples = Vec::new(); + let mut counters = [0.0f64; 20]; + for s in 1..=180i64 { + for (i, counter) in counters.iter_mut().enumerate() { + let job = match i { + 19 => "", + i if i % 2 == 0 => "a", + _ => "b", + }; + let instance = format!("i{i}"); + if random.next() < 0.9 { + samples.push(Sample { + labels: series(&[ + ("__name__", "latency"), + ("job", job), + ("instance", &instance), + ]), + ts_ms: start_ms + s * 1000 - (random.next() * 500.0) as i64, + value: (random.next() * 1000.0).round() / 4.0, + }); + } + if random.next() < 0.8 { + *counter = if random.next() < 0.02 { + random.next() * 3.0 + } else { + *counter + random.next() * 10.0 + }; + samples.push(Sample { + labels: series(&[ + ("__name__", "requests_total"), + ("job", job), + ("instance", &instance), + ]), + ts_ms: start_ms + s * 1000, + value: *counter, + }); + } + } + } + (samples, start_ms) +} + +/// PromQL over `samples` of `metric` in `(t − range, t]`, per series. +fn per_series( + samples: &[Sample], + metric: &str, + t_ms: i64, + range_ms: i64, +) -> BTreeMap> { + let mut out: BTreeMap> = BTreeMap::new(); + for sample in samples { + if sample.labels["__name__"] != metric + || sample.ts_ms <= t_ms - range_ms + || sample.ts_ms > t_ms + { + continue; + } + let labels: SeriesLabels = sample + .labels + .iter() + .filter(|(k, v)| k.as_str() != "__name__" && !v.is_empty()) + .map(|(k, v)| (k.clone(), v.clone())) + .collect(); + out.entry(labels) + .or_default() + .push((sample.ts_ms, sample.value)); + } + for points in out.values_mut() { + points.sort_by_key(|p| p.0); + } + out +} + +fn quantile(phi: f64, points: &[(i64, f64)]) -> f64 { + let mut values: Vec = points.iter().map(|p| p.1).collect(); + values.sort_by(f64::total_cmp); + let rank = phi * (values.len() - 1) as f64; + let (lo, hi) = (rank.floor() as usize, rank.ceil() as usize); + values[lo] + (values[hi] - values[lo]) * (rank - lo as f64) +} + +/// Prometheus `extrapolatedRate` (promql/functions.go, v3). +fn extrapolated(points: &[(i64, f64)], t_ms: i64, range_ms: i64, rate: bool) -> Option { + if points.len() < 2 { + return None; + } + let (first_t, first) = points[0]; + let (last_t, last) = points[points.len() - 1]; + let mut increase = last - first; + for pair in points.windows(2) { + if pair[1].1 < pair[0].1 { + increase += pair[0].1; + } + } + let sampled = (last_t - first_t) as f64 / 1000.0; + let average = sampled / (points.len() - 1) as f64; + let mut to_start = (first_t - (t_ms - range_ms)) as f64 / 1000.0; + let mut to_end = (t_ms - last_t) as f64 / 1000.0; + if to_start >= average * 1.1 { + to_start = average / 2.0; + } + if to_end >= average * 1.1 { + to_end = average / 2.0; + } + if increase > 0.0 && first >= 0.0 { + to_start = to_start.min(sampled * first / increase); + } + let value = increase * (sampled + to_start + to_end) / sampled; + Some(if rate { + value / (range_ms as f64 / 1000.0) + } else { + value + }) +} + +fn by_job( + values: BTreeMap, + aggregate: fn(&[f64]) -> f64, +) -> BTreeMap { + let mut groups: BTreeMap> = BTreeMap::new(); + for (labels, value) in values { + let group = labels + .get("job") + .map(|job| format!("job={job}")) + .unwrap_or_default(); + groups.entry(group).or_default().push(value); + } + groups + .into_iter() + .map(|(k, v)| (k, aggregate(&v))) + .collect() +} + +fn sum(values: &[f64]) -> f64 { + values.iter().sum() +} + +fn avg(values: &[f64]) -> f64 { + sum(values) / values.len() as f64 +} + +/// The reference answers of the generated workload's queries at `t_ms`. +fn reference(samples: &[Sample], t_ms: i64) -> Vec> { + let range = 60_000; + let latency = per_series(samples, "latency", t_ms, range); + let counters = per_series(samples, "requests_total", t_ms, range); + type PerSeries<'a> = &'a dyn Fn(&[(i64, f64)]) -> f64; + let each = |f: PerSeries| -> BTreeMap { + latency.iter().map(|(k, p)| (k.clone(), f(p))).collect() + }; + let keyed = |m: BTreeMap| -> BTreeMap { + m.into_iter().map(|(k, v)| (key(&k), v)).collect() + }; + let rates: BTreeMap = counters + .iter() + .filter_map(|(k, p)| Some((k.clone(), extrapolated(p, t_ms, range, true)?))) + .collect(); + let increases: BTreeMap = counters + .iter() + .filter_map(|(k, p)| Some((k.clone(), extrapolated(p, t_ms, range, false)?))) + .collect(); + vec![ + keyed(each(&|p| quantile(0.99, p))), + keyed(each(&|p| quantile(0.5, p))), + by_job(each(&|p| quantile(0.9, p)), avg), + keyed(each(&|p| { + p.iter().map(|x| x.1).fold(f64::NEG_INFINITY, f64::max) + })), + by_job(rates.clone(), sum), + by_job(each(&|p| p.iter().map(|x| x.1).sum()), sum), + by_job(each(&|p| p.len() as f64), sum), + keyed(increases), + keyed(rates), + ] +} + +const GENERATED_QUERIES: [&str; 9] = [ + "quantile_over_time(0.99, latency[1m])", + "quantile_over_time(0.5, latency[1m])", + "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "max_over_time(latency[1m])", + "sum by (job) (rate(requests_total[1m]))", + "sum by (job) (sum_over_time(latency[1m]))", + "sum by (job) (count_over_time(latency[1m]))", + "increase(requests_total[1m])", + "rate(requests_total[1m])", +]; + +/// C5, C6: every query shape of the suites (and a few more) over generated +/// data, at every evaluation from 60 s to 180 s: native and downsampled +/// equal the reference to 1e-9 relative (quantiles: plus 1e-6 of the +/// values' range, `percentile_cont`'s rounded fraction); approximate +/// per-series quantiles lie within two ranks of the exact ones (t-digest +/// does not interpolate as PromQL), and every other approximate answer +/// equals the reference. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn generated_data_matches_the_reference_evaluator() { + let engine = engine(); + let (samples, start_ms) = generated(); + let spec = workload(&GENERATED_QUERIES, 60_000, 10_000); + let times: Vec = (6..=18).map(|k| start_ms + k * 10_000).collect(); + for mode in MODES { + let mut installed = install(&engine, mode, &spec); + let summary = installed.plan_summary(); + println!("{mode}: {}", summary.text); + let mut shifted = samples.clone(); + for sample in &mut shifted { + sample.ts_ms -= start_ms; + } + let mut evaluated = 0; + let mut largest_approximate_error: f64 = 0.0; + for chunk in chunks(shifted, 10_000, 180_000) { + let chunk = SampleChunk { + end_ms: chunk.end_ms + start_ms, + samples: chunk + .samples + .into_iter() + .map(|mut s| { + s.ts_ms += start_ms; + s + }) + .collect(), + }; + installed.ingest(&chunk).expect("ingest"); + if !times.contains(&chunk.end_ms) { + continue; + } + let answers = installed.evaluate(chunk.end_ms).expect("evaluate").0; + let expected = reference(&samples, chunk.end_ms); + for (index, want) in expected.iter().enumerate() { + let got = rows(&answers, index + 1); + let approximate_quantile = mode == "approximate" && index < 3; + assert_eq!( + got.keys().collect::>(), + want.keys().collect::>(), + "{mode} q{} at {}", + index + 1, + chunk.end_ms + ); + let latency = per_series(&samples, "latency", chunk.end_ms, 60_000); + for (key, want) in want { + let value = got[key]; + if approximate_quantile { + let error = (value - want).abs(); + largest_approximate_error = largest_approximate_error.max(error); + if index < 2 { + // Within two ranks of the exact quantile. + let phi = [0.99, 0.5][index]; + let points = latency + .iter() + .find(|(labels, _)| &self::key(labels) == key) + .map(|(_, points)| points) + .expect("the series"); + let mut values: Vec = points.iter().map(|p| p.1).collect(); + values.sort_by(f64::total_cmp); + let rank = phi * (values.len() - 1) as f64; + let low = values[(rank.floor() as usize).saturating_sub(2)]; + let high = values[(rank.ceil() as usize + 2).min(values.len() - 1)]; + assert!( + low <= value && value <= high, + "approximate q{} {key} at {}: {value} outside [{low}, {high}] (exact {want})", + index + 1, + chunk.end_ms + ); + } + continue; + } + let tolerance = if index < 3 { + 1e-9 * want.abs().max(1.0) + 1e-6 * 250.0 + } else { + 1e-9 * want.abs().max(1.0) + }; + assert!( + (value - want).abs() <= tolerance, + "{mode} q{} {key} at {}: {value} vs {want}", + index + 1, + chunk.end_ms + ); + } + } + evaluated += 1; + } + assert_eq!(evaluated, times.len()); + if mode == "approximate" { + println!( + "approximate: largest quantile error {largest_approximate_error} (values 0..250)" + ); + } + println!("{mode}: footprint {:?}", installed.footprint().unwrap()); + } +} + +/// C7: a text outside the accepted shapes is refused at install, and so is +/// a label named like a column, and a NaN value. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn unsupported_queries_and_samples_are_refused() { + let engine = engine(); + for text in [ + "topk(3, rate(x[1m]))", + "max_over_time(latency{job=\"a\"}[1m])", + ] { + assert!(engine + .install(&workload(&[text], 60_000, 10_000), &arm("native")) + .is_err()); + } + let spec = workload(&["max_over_time(latency[1m])"], 60_000, 10_000); + let refused_names = engine.install(&spec, &arm("exact")).err().unwrap(); + assert!( + refused_names.0.contains("influxdb3.native"), + "{refused_names:?}" + ); + let mut installed = install(&engine, "native", &spec); + for (labels, value) in [ + (series(&[("__name__", "latency"), ("value", "x")]), 1.0), + (series(&[("__name__", "latency")]), f64::NAN), + ] { + let chunk = SampleChunk { + end_ms: 10_000, + samples: vec![Sample { + labels, + ts_ms: 5_000, + value, + }], + }; + assert!(installed.ingest(&chunk).is_err()); + } + let (answers, _) = installed.evaluate(10_000).unwrap(); + assert!( + rows(&answers, 1).is_empty(), + "a refused chunk writes nothing" + ); +} + +/// C8: the harness's conformance kit (deterministic answers, left-open +/// windows) on the native arm. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn the_harness_conformance_kit_passes() { + struct Native(InfluxDb3Engine); + impl EngineUnderTest for Native { + fn description(&self) -> EngineDescription { + self.0.description() + } + fn cpu_accounting(&self) -> CpuAccounting { + self.0.cpu_accounting() + } + fn holds_one_install_at_a_time(&self) -> bool { + true + } + fn install( + &self, + workload: &WorkloadSpec, + arm_spec: &ArmSpec, + ) -> Result, EngineError> { + let mut native = arm("native"); + native.raw_data_retained = arm_spec.raw_data_retained; + self.0.install(workload, &native) + } + } + let mut engine = Native(engine()); + let clock = aqpbm_core::harness::protocol::OsCpuClock; + let clocks = aqpbm_core::harness::protocol::MeasurementClocks::with_calling_thread(&clock); + let report = aqpbm_core::harness::conformance::check(&mut engine, &clocks); + println!("harness kit: {report:?}"); + let passed = report.expect("the kit passes").passed; + assert!( + passed.contains(&aqpbm_core::harness::conformance::ConformanceCheck::DeterministicAnswers) + ); + assert!(passed.contains(&aqpbm_core::harness::conformance::ConformanceCheck::LeftOpenWindow)); +} + +/// C9: suite size: 1,000 series in 10 jobs, 1 s samples for 10 min, +/// `sum by (job) (sum_over_time(latency[1m]))` every 10 s, natively and +/// downsampled: at the last evaluation each job's answer is the sum of its +/// last minute; the server's CPU grows; wall times printed. +#[test] +#[ignore = "needs an InfluxDB 3 server"] +fn suite_sized_workload() { + let engine = engine(); + let start_ms: i64 = 1_700_000_040_000; + let mut random = Lcg(7); + let mut samples = Vec::new(); + let labels: Vec> = (0..1000) + .map(|i| { + series(&[ + ("__name__", "latency"), + ("job", &format!("j{}", i % 10)), + ("instance", &format!("i{i}")), + ]) + }) + .collect(); + for s in 1..=600i64 { + for l in &labels { + samples.push(Sample { + labels: l.clone(), + ts_ms: start_ms + s * 1000, + value: (random.next() * 1000.0).round(), + }); + } + } + let end_ms = start_ms + 600_000; + let mut last_minute: BTreeMap = BTreeMap::new(); + for sample in &samples { + if sample.ts_ms > end_ms - 60_000 { + *last_minute + .entry(format!("job={}", sample.labels["job"])) + .or_default() += sample.value; + } + } + let spec = workload( + &["sum by (job) (sum_over_time(latency[1m]))"], + 60_000, + 10_000, + ); + for mode in ["native", "downsampled"] { + let mut installed = install(&engine, mode, &spec); + let cpu = |engine: &InfluxDb3Engine| match engine.cpu_accounting() { + CpuAccounting::Cgroup(source) => Some(source.cpu().unwrap().usage_ns), + _ => None, + }; + let cpu_before = cpu(&engine); + let (mut ingest, mut evaluate) = (Duration::ZERO, Duration::ZERO); + let mut answers = Answers::default(); + for k in 1..=60i64 { + let chunk = SampleChunk { + end_ms: start_ms + k * 10_000, + samples: samples + .iter() + .filter(|s| { + s.ts_ms > start_ms + (k - 1) * 10_000 && s.ts_ms <= start_ms + k * 10_000 + }) + .cloned() + .collect(), + }; + assert_eq!(chunk.samples.len(), 10_000); + let started = std::time::Instant::now(); + installed.ingest(&chunk).unwrap(); + ingest += started.elapsed(); + if k >= 6 { + let started = std::time::Instant::now(); + answers = installed.evaluate(chunk.end_ms).unwrap().0; + evaluate += started.elapsed(); + } + } + let expected: Vec<(&str, f64)> = + last_minute.iter().map(|(k, v)| (k.as_str(), *v)).collect(); + assert_rows(mode, &rows(&answers, 1), &expected); + let cpu_after = cpu(&engine); + println!( + "{mode}: 60 chunks of 10,000 rows: ingest wall {:.1} s, 55 evaluations wall {:.2} s, server CPU {:?} s, footprint {:?}", + ingest.as_secs_f64(), + evaluate.as_secs_f64(), + cpu_before.zip(cpu_after).map(|(b, a)| (a - b) as f64 / 1e9), + installed.footprint().unwrap() + ); + if let (Some(before), Some(after)) = (cpu_before, cpu_after) { + assert!(after > before); + } + } +}