diff --git a/docs/system-bench.md b/docs/system-bench.md index 6956a78f..cd98cf9c 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 | | | +| `questdb` | yes | | | | `asapquery-backend` | yes | | | | `asapquery-precompute-engine` | | | yes | | `fake` (for tests) | yes | | | @@ -38,6 +39,7 @@ approxbench benchmark-external write-throughput --help What to run comes from a run directory: the workloads, and the plans if a system runs planned queries. `scripts/plan-suite.sh` prepares a run directory from a suite. `scripts/one-shot-workload.sh` and `scripts/one-shot-clickbench.sh` prepare one and run every system for one-shot queries. +`scripts/questdb_variants.py` adds QuestDB's variants (native SQL, materialized views, approximate functions) to a run directory. `scripts/write-throughput-asapquery-precompute-engine.sh` measures the write throughput of an ASAPQuery precompute engine. ## Output diff --git a/scripts/extbench-up-questdb.sh b/scripts/extbench-up-questdb.sh new file mode 100755 index 00000000..3c7cbd71 --- /dev/null +++ b/scripts/extbench-up-questdb.sh @@ -0,0 +1,129 @@ +#!/usr/bin/env bash +# Start (or stop) a QuestDB server for +# `approxbench benchmark-external run --engine questdb` 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-questdb.sh up [] +# scripts/extbench-up-questdb.sh down [] +# +# Example: LISTEN_HOST=10.0.0.2 scripts/extbench-up-questdb.sh up /data/run-1/questdb 2,4,6,8 0 19000 +# +# 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 has no password +# IMAGE the image, pinned by digest (default: 10.2.0 below) +# QUESTDB_PARALLEL_SQL off (default): each query runs on one thread (parallel +# filter, GROUP BY, window join and Parquet read off), as +# ClickHouse runs with max_threads=1; on: QuestDB's defaults +# MEMORY_LIMIT a docker memory limit such as 32g (default: none) +# +# The server listens on HTTP (SQL `/exec`, ILP `/write`), and +# its PostgreSQL wire, ILP TCP and health ports are +1, +2 and +# +3 on LISTEN_HOST too. Queries may run 10 minutes (QuestDB's default is 1). +# +# 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. +set -euo pipefail + +marker=.extbench-data-dir +# questdb/questdb:10.2.0 (released 2026-11-10), multi-arch index digest. +default_image=questdb/questdb@sha256:bbf5b3cb0dfb08ad667a008dbcc48794bf942d18d1ad832cb6ecb7ff87314694 + +# 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 +} + +# "2,4-6" as "2 4 5 6". +expand_cores() { + local part + for part in ${1//,/ }; do + if [[ "$part" == *-* ]]; then seq "${part%-*}" "${part#*-}"; else echo "$part"; fi + done | tr '\n' ' ' +} + +action=${1:?up|down}; data_dir=$(realpath -m "${2:?data dir}") + +if [ "$action" = down ]; then + name=${3:-extbench-questdb} + 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 nodes}; http_port=${5:?http port} +name=${6:-extbench-questdb} +image=${IMAGE:-$default_image} +parallel=${QUESTDB_PARALLEL_SQL:-off} +: "${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; } +case "$parallel" in + off) sql_parallel=false ;; + on) sql_parallel=true ;; + *) echo "QUESTDB_PARALLEL_SQL is on or off, not $parallel" >&2; exit 2 ;; +esac + +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/root"; touch "$data_dir/$marker" + +memory=() +[ -n "${MEMORY_LIMIT:-}" ] && memory=(--memory "$MEMORY_LIMIT" --memory-swap "$MEMORY_LIMIT") +docker rm -f "$name" >/dev/null 2>&1 || true +docker run -d --name "$name" --network host \ + --cpuset-cpus "$cores" --cpuset-mems "$numa" --user "$(id -u):$(id -g)" "${memory[@]}" \ + -v "$data_dir/root:/var/lib/questdb" \ + -e QDB_HTTP_BIND_TO="$LISTEN_HOST:$http_port" \ + -e QDB_PG_NET_BIND_TO="$LISTEN_HOST:$((http_port + 1))" \ + -e QDB_LINE_TCP_NET_BIND_TO="$LISTEN_HOST:$((http_port + 2))" \ + -e QDB_HTTP_MIN_NET_BIND_TO="$LISTEN_HOST:$((http_port + 3))" \ + -e QDB_LINE_UDP_ENABLED=false \ + -e QDB_TELEMETRY_ENABLED=false \ + -e QDB_QUERY_TIMEOUT=10m \ + -e QDB_CAIRO_SQL_PARALLEL_FILTER_ENABLED=$sql_parallel \ + -e QDB_CAIRO_SQL_PARALLEL_GROUPBY_ENABLED=$sql_parallel \ + -e QDB_CAIRO_SQL_PARALLEL_WINDOW_JOIN_ENABLED=$sql_parallel \ + -e QDB_CAIRO_SQL_PARALLEL_READ_PARQUET_ENABLED=$sql_parallel \ + "$image" >/dev/null + +exec_sql() { curl -sf -G "http://$LISTEN_HOST:$http_port/exec" --data-urlencode "query=$1"; } +for _ in $(seq 1 60); do + exec_sql "SELECT 1" >/dev/null 2>&1 && break; sleep 1 +done +exec_sql "SELECT 1" >/dev/null || { echo "the server did not start" >&2; docker logs "$name" >&2; exit 1; } + +group="/sys/fs/cgroup/system.slice/docker-$(docker inspect -f '{{.Id}}' "$name").scope" +[ -d "$group" ] || { echo "no cgroup at $group (is docker on the systemd cgroup driver?)" >&2; exit 1; } + +siblings() { + for core in $(expand_cores "$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 $(exec_sql "SELECT build()" | sed -n 's/.*"dataset":\[\["\([^"]*\)"\]\].*/\1/p')" + echo "parallel_sql $parallel" + 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/questdb_variants.py b/scripts/questdb_variants.py new file mode 100755 index 00000000..bc58f17c --- /dev/null +++ b/scripts/questdb_variants.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Add the QuestDB variants to a benchmark-external run directory. + + scripts/questdb_variants.py + +For each workload in /workloads/, writes +plans//.plan.json, a file naming the variant that engine +`questdb` builds its SQL from (`{"questdb_variant": "native"}`), or +.no-plan.json when the variant's SQL would be the same as +questdb.native's, so identical SQL is not run twice: + + questdb.native every query at query time, exact + questdb.materialized-views a materialized view per query, quantiles at query time; + no plan when every query is a quantile + questdb.approximate approx_percentile for quantiles; no plan without a quantile + +Example: scripts/questdb_variants.py /data/run-1 +""" +import json +import pathlib +import re +import sys + +VARIANTS = { + # name: (questdb_variant, substitutions_allowed) + "questdb.native": ("native", False), + "questdb.materialized-views": ("materialized-views", True), + "questdb.approximate": ("approximate", True), +} + +QUANTILE = re.compile(r"\bquantile_over_time\s*\(") + + +def promql_texts(workload): + """The PromQL text of each query, e.g. ["quantile_over_time(0.99, latency[1m])"].""" + texts = [] + for query in workload["queries"]: + promql = [t["text"] for t in query["texts"] if t["language"] == "PromQl"] + texts.append(promql[0] if promql else "") + return texts + + +def no_plan_reason(variant, texts): + """Why `variant` has no plan for a workload of `texts`, or None.""" + quantiles = [bool(QUANTILE.search(text)) for text in texts] + if variant == "questdb.approximate" and not any(quantiles): + return "no quantile query: its SQL equals questdb.native's" + if variant == "questdb.materialized-views" and all(quantiles): + return "only quantile queries, which read the raw table: its SQL equals questdb.native's" + return None + + +def write_variants(run): + run = pathlib.Path(run) + workloads = sorted((run / "workloads").glob("*.json")) + if not workloads: + raise SystemExit(f"{run}/workloads holds no workload") + for variant, (name, substitutions) in VARIANTS.items(): + directory = run / "plans" / variant + if directory.exists(): + raise SystemExit(f"{directory} exists; runs are never overwritten") + for variant, (name, substitutions) in VARIANTS.items(): + directory = run / "plans" / variant + directory.mkdir(parents=True) + (directory / "variant.json").write_text( + json.dumps({"substitutions_allowed": substitutions}) + "\n") + for path in workloads: + texts = promql_texts(json.loads(path.read_text())) + reason = no_plan_reason(variant, texts) + if reason is None: + (directory / f"{path.stem}.plan.json").write_text( + json.dumps({"questdb_variant": name}) + "\n") + print(f"{path.stem} {variant}: plan") + else: + (directory / f"{path.stem}.no-plan.json").write_text( + json.dumps({"reason": reason}) + "\n") + print(f"{path.stem} {variant}: no plan ({reason})") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit(__doc__) + write_variants(sys.argv[1]) diff --git a/scripts/test_questdb_variants.py b/scripts/test_questdb_variants.py new file mode 100644 index 00000000..9d973cf0 --- /dev/null +++ b/scripts/test_questdb_variants.py @@ -0,0 +1,44 @@ +"""Tests of questdb_variants.py over the showcase suite: python3 -m unittest scripts/test_questdb_variants.py""" +import json +import pathlib +import shutil +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).parent)) +import questdb_variants # noqa: E402 + +SUITE = pathlib.Path(__file__).parent.parent / "suites" / "showcase-1m" + + +class QuestDbVariants(unittest.TestCase): + def test_showcase_cells(self): + with tempfile.TemporaryDirectory() as tmp: + run = pathlib.Path(tmp) + (run / "workloads").mkdir() + for spec in SUITE.glob("*.workload.json"): + shutil.copy(spec, run / "workloads" / spec.name.replace(".workload", "")) + questdb_variants.write_variants(run) + cells = {} + for variant in questdb_variants.VARIANTS: + for path in (run / "plans" / variant).iterdir(): + if path.name != "variant.json": + workload, kind = path.name.split(".", 1) + cells[(variant, workload)] = kind + planned = lambda v: sorted(w for (x, w), k in cells.items() if x == v and k == "plan.json") + self.assertEqual(len(planned("questdb.native")), 8) + self.assertEqual(planned("questdb.approximate"), + ["avg_quantile", "joint", "quantile", "quantile_rank"]) + self.assertEqual(planned("questdb.materialized-views"), + ["count", "joint", "max", "sum_over_time", "sum_rate"]) + plan = json.loads((run / "plans/questdb.approximate/joint.plan.json").read_text()) + self.assertEqual(plan, {"questdb_variant": "approximate"}) + native = json.loads((run / "plans/questdb.native/variant.json").read_text()) + self.assertEqual(native, {"substitutions_allowed": False}) + with self.assertRaises(SystemExit): + questdb_variants.write_variants(run) + + +if __name__ == "__main__": + unittest.main() diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 6bf0b9b2..972e5b2b 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -25,6 +25,8 @@ mod kept_process; pub mod pilotdb; pub mod plan_file; pub mod postgresql_command_line; +pub mod questdb; +pub mod questdb_server; mod restart_command; pub mod server_cgroup; pub mod victoriametrics; diff --git a/system-bench/src/engines_external/questdb.rs b/system-bench/src/engines_external/questdb.rs new file mode 100644 index 00000000..cf607bc4 --- /dev/null +++ b/system-bench/src/engines_external/questdb.rs @@ -0,0 +1,1055 @@ +//! QuestDB SQL for the periodic queries of a workload, written the way a +//! QuestDB user writes them, in one of three variants: +//! +//! - [`Variant::Native`]: one table per metric; every query computed at query +//! time over `ts > T - w AND ts <= T`, exact. +//! - [`Variant::MaterializedViews`]: one hand-written materialized view per +//! query (`SAMPLE BY b`, `b = gcd(window, evaluation interval)`, refreshed +//! incrementally after each commit), merged over the window's buckets at +//! query time. A quantile has no mergeable per-bucket state, so a quantile +//! query reads the raw table at query time. +//! - [`Variant::Approximate`]: native, with `approx_percentile` for quantiles. +//! +//! Each SQL text holds `{lo}` and `{hi}`, the window's start `T - w` and end +//! `T` in microseconds, replaced at each evaluation. +//! +//! Example: `sum by (job) (sum_over_time(latency[1m]))`, native: +//! `SELECT "job", sum(value) value FROM bench_1_0_latency WHERE ts > {lo} AND ts <= {hi}`. +//! +//! Windows: PromQL's window is `(T - w, T]`. A `SAMPLE BY` bucket is +//! `[s, s + b)`, so an arm with views stores each sample at its time minus +//! 1 µs ([`QuestDbDeployment::timestamp_shift_us`]); with whole-millisecond +//! data, `(T - w, T]` is then exactly the buckets that start in `[T - w, T)`, +//! and that arm's raw reads use `ts >= {lo} AND ts < {hi}`. +//! +//! Rate and increase follow Prometheus `extrapolatedRate` (v3, the formula +//! of the ClickHouse translator): the increase is last − first plus the +//! value before each counter reset (found with `lag`/`lead`), extrapolated +//! to the window's edges. + +use std::fmt::Write as _; + +use aqpbm_core::harness::engine::{QueryLanguage, WorkloadSpec}; + +/// How QuestDB computes the queries of an arm. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Variant { + Native, + MaterializedViews, + Approximate, +} + +impl Variant { + /// The name in a plan file's `questdb_variant`, e.g. `native`. + pub fn parse(name: &str) -> Option { + match name { + "native" => Some(Variant::Native), + "materialized-views" => Some(Variant::MaterializedViews), + "approximate" => Some(Variant::Approximate), + _ => None, + } + } + + pub fn name(self) -> &'static str { + match self { + Variant::Native => "native", + Variant::MaterializedViews => "materialized-views", + Variant::Approximate => "approximate", + } + } +} + +/// `approx_percentile`'s precision: significant decimal digits the +/// HdrHistogram keeps, 2 = values resolved to 1 %, the 1 % relative error +/// the suites' quantile queries ask for. +pub const APPROX_PERCENTILE_PRECISION: u32 = 2; + +/// An aggregation over series, `sum by (job) (…)`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Aggregation { + Sum, + Min, + Max, + Avg, + Count, +} + +impl Aggregation { + fn parse(name: &str) -> Option { + match name { + "sum" => Some(Aggregation::Sum), + "min" => Some(Aggregation::Min), + "max" => Some(Aggregation::Max), + "avg" => Some(Aggregation::Avg), + "count" => Some(Aggregation::Count), + _ => None, + } + } + + /// QuestDB's aggregate of a `value` column. + fn of_values(self) -> &'static str { + match self { + Aggregation::Sum => "sum(value)", + Aggregation::Min => "min(value)", + Aggregation::Max => "max(value)", + Aggregation::Avg => "avg(value)", + Aggregation::Count => "count()", + } + } +} + +/// A range function of one series. +#[derive(Debug, Clone, PartialEq)] +pub enum RangeFunction { + /// `_over_time`, f one of sum, min, max, avg, count. + OverTime(Aggregation), + /// `quantile_over_time(q, …)`. + Quantile(f64), + Rate, + Increase, +} + +/// A query the rules cover: a range function of one metric, optionally +/// aggregated over series. +#[derive(Debug, Clone, PartialEq)] +pub struct QueryShape { + pub function: RangeFunction, + pub metric: String, + pub range_ms: u64, + /// `sum by (job) (…)`: the aggregation and the labels kept. + pub outer: Option<(Aggregation, Vec)>, +} + +impl QueryShape { + /// Parses `sum by (job) (rate(requests_total[1m]))` and the like; any + /// other text is refused with the reason. + pub fn parse(text: &str) -> Result { + let mut parser = Parser { text, at: 0 }; + let shape = parser.expression()?; + parser.skip_space(); + if parser.at != text.len() { + return Err(format!( + "no rule for '{text}': unexpected '{}'", + &text[parser.at..] + )); + } + Ok(shape) + } +} + +struct Parser<'a> { + text: &'a str, + at: usize, +} + +impl Parser<'_> { + fn skip_space(&mut self) { + while self.rest().starts_with(char::is_whitespace) { + self.at += self.rest().chars().next().map_or(1, char::len_utf8); + } + } + + fn rest(&self) -> &str { + &self.text[self.at..] + } + + fn refuse(&self, what: &str) -> String { + format!("no rule for '{}': {what} at '{}'", self.text, self.rest()) + } + + fn expect(&mut self, token: &str) -> Result<(), String> { + self.skip_space(); + if self.rest().starts_with(token) { + self.at += token.len(); + Ok(()) + } else { + Err(self.refuse(&format!("expected '{token}'"))) + } + } + + /// A PromQL metric or label name. + fn name(&mut self) -> Result { + self.skip_space(); + let length = self + .rest() + .char_indices() + .find(|&(i, c)| { + !(c.is_ascii_alphabetic() || c == '_' || c == ':' || (i > 0 && c.is_ascii_digit())) + }) + .map_or(self.rest().len(), |(i, _)| i); + if length == 0 { + return Err(self.refuse("expected a name")); + } + let name = self.rest()[..length].to_string(); + self.at += length; + Ok(name) + } + + fn number(&mut self) -> Result { + self.skip_space(); + let length = self + .rest() + .find(|c: char| !(c.is_ascii_digit() || c == '.')) + .unwrap_or(self.rest().len()); + let number = self.rest()[..length] + .parse() + .map_err(|_| self.refuse("expected a number"))?; + self.at += length; + Ok(number) + } + + fn expression(&mut self) -> Result { + let start = self.at; + let name = self.name()?; + if let Some(aggregation) = Aggregation::parse(&name) { + self.skip_space(); + let mut labels = Vec::new(); + if self.rest().starts_with("by") { + self.expect("by")?; + self.expect("(")?; + loop { + labels.push(self.name()?); + self.skip_space(); + if self.rest().starts_with(',') { + self.at += 1; + } else { + break; + } + } + self.expect(")")?; + } else if self.rest().starts_with("without") { + return Err(self.refuse("'without'")); + } + self.expect("(")?; + let mut inner = self.expression()?; + self.expect(")")?; + if inner.outer.is_some() { + return Err(self.refuse("an aggregation of an aggregation")); + } + inner.outer = Some((aggregation, labels)); + return Ok(inner); + } + let function = match name.as_str() { + "rate" => RangeFunction::Rate, + "increase" => RangeFunction::Increase, + "quantile_over_time" => { + self.expect("(")?; + let q = self.number()?; + self.expect(",")?; + return self.selector_range(RangeFunction::Quantile(q)); + } + other => match other + .strip_suffix("_over_time") + .and_then(Aggregation::parse) + { + Some(aggregation) => RangeFunction::OverTime(aggregation), + None => { + self.at = start; + return Err(self.refuse("an unknown function")); + } + }, + }; + self.expect("(")?; + self.selector_range(function) + } + + /// `[])`, after the function's `(` (and a quantile's `q,`). + fn selector_range(&mut self, function: RangeFunction) -> Result { + let metric = self.name()?; + self.skip_space(); + if self.rest().starts_with('{') { + return Err(self.refuse("label matchers")); + } + self.expect("[")?; + let end = self + .rest() + .find(']') + .ok_or_else(|| self.refuse("expected ']'"))?; + let range = self.rest()[..end].trim().to_string(); + let range_ms = duration_ms(&range).ok_or_else(|| self.refuse("a range"))?; + self.at += end; + self.expect("]")?; + self.expect(")")?; + Ok(QueryShape { + function, + metric, + range_ms, + outer: None, + }) + } +} + +/// A PromQL duration such as `1m`, `1h30m` or `500ms`, in ms. +fn duration_ms(text: &str) -> Option { + let mut total = 0u64; + let mut rest = text; + if rest.is_empty() { + return None; + } + while !rest.is_empty() { + let digits = rest.find(|c: char| !c.is_ascii_digit())?; + if digits == 0 { + return None; + } + let number: u64 = rest[..digits].parse().ok()?; + rest = &rest[digits..]; + let (unit_ms, length) = if rest.starts_with("ms") { + (1, 2) + } else { + let unit = match rest.chars().next()? { + 's' => 1_000, + 'm' => 60_000, + 'h' => 3_600_000, + 'd' => 86_400_000, + 'w' => 604_800_000, + 'y' => 31_536_000_000, + _ => return None, + }; + (unit, 1) + }; + total = total.checked_add(number.checked_mul(unit_ms)?)?; + rest = &rest[length..]; + } + Some(total) +} + +/// A metric's table: where its samples are written. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SourceTable { + pub metric: String, + pub table: String, + /// One `SYMBOL` column per label, in the data record's order. + pub label_columns: Vec, +} + +/// A workload query as the arm runs it. +#[derive(Debug, Clone, PartialEq)] +pub struct QuestDbQuery { + pub id: String, + /// SQL with `{lo}` and `{hi}` (µs). + pub sql: String, + pub window_ms: u64, + /// Evaluation times must be multiples of this (a view's bucket); 1 for + /// a query over the raw table. + pub step_ms: u64, + pub rule: String, +} + +/// A materialized view and the table it reads. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MaterializedView { + pub name: String, + pub base_table: String, +} + +/// What an arm installs on QuestDB. +#[derive(Debug, Clone, PartialEq)] +pub struct QuestDbDeployment { + pub variant: Variant, + pub sources: Vec, + /// `CREATE TABLE` then `CREATE MATERIALIZED VIEW` statements, in order. + pub statements: Vec, + pub views: Vec, + pub queries: Vec, + /// Each sample is stored at its time minus this many µs (1 with views, + /// see the module docs). + pub timestamp_shift_us: i64, + /// Rules whose answers differ from PromQL's, e.g. an approximate quantile. + pub substitutions: Vec, +} + +impl QuestDbDeployment { + /// Every statement and query, for the arm's plan text. + pub fn script(&self) -> String { + let mut text = format!("-- QuestDB variant {}\n", self.variant.name()); + for statement in &self.statements { + let _ = writeln!(text, "{statement};"); + } + for query in &self.queries { + let _ = writeln!(text, "-- {} ({})\n{};", query.id, query.rule, query.sql); + } + text + } +} + +/// A QuestDB identifier in double quotes. +pub fn quoted(identifier: &str) -> String { + format!("\"{}\"", identifier.replace('"', "\"\"")) +} + +fn table_name(prefix: &str, metric: &str) -> String { + let name: String = metric + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || c == '_' { + c + } else { + '_' + } + }) + .collect(); + format!("{prefix}_{name}") +} + +fn greatest_common_divisor(a: u64, b: u64) -> u64 { + let (mut x, mut y) = (a, b); + while y != 0 { + (x, y) = (y, x % y); + } + x +} + +/// `10000` ms as QuestDB's `10s`, or `T` (ms) when not whole seconds. +fn sample_by(bucket_ms: u64) -> String { + if bucket_ms.is_multiple_of(1000) { + format!("{}s", bucket_ms / 1000) + } else { + format!("{bucket_ms}T") + } +} + +/// The SQL of every query of `workload` in `variant`, with tables named +/// `_` and views `_`. Refused: a query +/// with no PromQL text the rules cover, a metric without a data record (its +/// labels are unknown), a label named `ts` or `value`, and, with views, a +/// bucket that does not divide the data start. +pub fn deploy( + workload: &WorkloadSpec, + variant: Variant, + prefix: &str, +) -> Result { + let shift: i64 = i64::from(variant == Variant::MaterializedViews); + let mut deployment = QuestDbDeployment { + variant, + sources: Vec::new(), + statements: Vec::new(), + views: Vec::new(), + queries: Vec::new(), + timestamp_shift_us: shift, + substitutions: Vec::new(), + }; + let mut shapes = Vec::new(); + for query in &workload.queries { + let mut reasons = Vec::new(); + let shape = query + .texts + .iter() + .filter(|text| text.language == QueryLanguage::PromQl) + .find_map(|text| { + QueryShape::parse(&text.text) + .map_err(|reason| reasons.push(reason)) + .ok() + }) + .ok_or_else(|| { + if reasons.is_empty() { + format!("query {} has no PromQL text", query.id) + } else { + format!("query {}: {}", query.id, reasons.join("; ")) + } + })?; + if shape.range_ms != query.window_ms { + return Err(format!( + "query {}: range {} ms differs from the workload window {} ms", + query.id, shape.range_ms, query.window_ms + )); + } + if !deployment.sources.iter().any(|s| s.metric == shape.metric) { + let record = workload + .data + .iter() + .find(|record| record.metric == shape.metric) + .ok_or_else(|| { + format!( + "query {}: metric {} has no data record, so its labels are unknown", + query.id, shape.metric + ) + })?; + let label_columns: Vec = record + .description + .labels + .iter() + .map(|label| label.name.clone()) + .filter(|name| name != "__name__") + .collect(); + if let Some(clash) = label_columns.iter().find(|l| *l == "ts" || *l == "value") { + return Err(format!( + "metric {} has a label named {clash}, the name of a sample column", + shape.metric + )); + } + deployment.sources.push(SourceTable { + metric: shape.metric.clone(), + table: table_name(prefix, &shape.metric), + label_columns, + }); + } + if let Some((_, by)) = &shape.outer { + let source = deployment.sources.iter().find(|s| s.metric == shape.metric); + if let Some(missing) = by + .iter() + .find(|l| !source.is_some_and(|s| s.label_columns.contains(l))) + { + return Err(format!( + "query {}: label {missing} is not a label of {}", + query.id, shape.metric + )); + } + } + shapes.push(shape); + } + for source in &deployment.sources { + let mut columns: Vec = source + .label_columns + .iter() + .map(|label| format!("{} SYMBOL", quoted(label))) + .collect(); + columns.push("value DOUBLE".into()); + columns.push("ts TIMESTAMP".into()); + deployment.statements.push(format!( + "CREATE TABLE {} ({}) TIMESTAMP(ts) PARTITION BY DAY WAL", + source.table, + columns.join(", ") + )); + } + let data_start_ms = workload.data_start_ms().unwrap_or(0); + for (query, shape) in workload.queries.iter().zip(&shapes) { + let source = deployment + .sources + .iter() + .find(|s| s.metric == shape.metric) + .expect("added above") + .clone(); + let rule = Rule { + shape, + source: &source, + variant, + }; + let (sql, step_ms, rule_text) = if variant == Variant::MaterializedViews && rule.has_view() + { + let bucket_ms = greatest_common_divisor(query.window_ms, query.evaluation_interval_ms); + if data_start_ms.rem_euclid(bucket_ms as i64) != 0 { + return Err(format!( + "query {}: the view's buckets of {bucket_ms} ms do not divide the data start ({data_start_ms} ms)", + query.id + )); + } + let view = format!("{prefix}_{}", query.id); + let (create, sql) = rule.view(&view, bucket_ms); + deployment.statements.push(create); + deployment.views.push(MaterializedView { + name: view, + base_table: source.table.clone(), + }); + if matches!( + shape.function, + RangeFunction::Rate | RangeFunction::Increase + ) { + deployment.substitutions.push(format!( + "query {}: rate over materialized-view buckets of {bucket_ms} ms misses a counter reset inside one bucket", + query.id + )); + } + ( + sql, + bucket_ms, + format!("materialized view SAMPLE BY {}", sample_by(bucket_ms)), + ) + } else { + if let (Variant::Approximate, RangeFunction::Quantile(q)) = (variant, &shape.function) { + deployment.substitutions.push(format!( + "query {}: approx_percentile(value, {q}, {APPROX_PERCENTILE_PRECISION}) for quantile_over_time", + query.id + )); + } + let text = match (variant, &shape.function) { + (Variant::MaterializedViews, RangeFunction::Quantile(_)) => { + "raw table at query time (no mergeable quantile state)" + } + _ => "raw table at query time", + }; + (rule.raw(shift), 1, text.to_string()) + }; + deployment.queries.push(QuestDbQuery { + id: query.id.clone(), + sql, + window_ms: query.window_ms, + step_ms, + rule: rule_text, + }); + } + Ok(deployment) +} + +/// The SQL of one query. +struct Rule<'a> { + shape: &'a QueryShape, + source: &'a SourceTable, + variant: Variant, +} + +impl Rule<'_> { + fn labels(&self) -> String { + column_list(&self.source.label_columns) + } + + /// The labels the answer keeps without an aggregation over series + /// (direct grouping), e.g. `sum by (job) (sum_over_time(…))` groups by + /// `job` right away: a sum of per-series sums is the sum of the samples. + fn direct_group(&self) -> Option<&[String]> { + let (outer, by) = self.shape.outer.as_ref()?; + let RangeFunction::OverTime(inner) = self.shape.function else { + return None; + }; + matches!( + (outer, inner), + (Aggregation::Sum, Aggregation::Sum) + | (Aggregation::Sum, Aggregation::Count) + | (Aggregation::Max, Aggregation::Max) + | (Aggregation::Min, Aggregation::Min) + ) + .then_some(by.as_slice()) + } + + fn has_view(&self) -> bool { + !matches!(self.shape.function, RangeFunction::Quantile(_)) + } + + /// `labels` then `rest`, comma-separated, with no leading comma when + /// there are no labels. + fn select(labels: &[String], rest: &str) -> String { + if labels.is_empty() { + rest.to_string() + } else { + format!("{}, {rest}", column_list(labels)) + } + } + + /// `sum by (job) (…)` over a per-series relation `inner`. + fn outer(&self, inner: String) -> String { + match &self.shape.outer { + Some((aggregation, by)) => format!( + "SELECT {} FROM ({inner})", + Self::select(by, &format!("{} value", aggregation.of_values())) + ), + None => inner, + } + } + + /// The query over the raw table; samples stored `shift` µs early. + fn raw(&self, shift: i64) -> String { + let table = &self.source.table; + let window = if shift == 0 { + "ts > {lo} AND ts <= {hi}" + } else { + "ts >= {lo} AND ts < {hi}" + }; + if let Some(by) = self.direct_group() { + let RangeFunction::OverTime(inner) = self.shape.function else { + unreachable!("direct grouping is of an _over_time"); + }; + return format!( + "SELECT {} FROM {table} WHERE {window}", + Self::select(by, &format!("{} value", inner.of_values())) + ); + } + let labels = &self.source.label_columns; + let per_series = match &self.shape.function { + RangeFunction::OverTime(f) => format!( + "SELECT {} FROM {table} WHERE {window}", + Self::select(labels, &format!("{} value", f.of_values())) + ), + RangeFunction::Quantile(q) => { + let function = match self.variant { + Variant::Approximate => { + format!("approx_percentile(value, {q}, {APPROX_PERCENTILE_PRECISION})") + } + _ => format!("percentile_cont(value, {q})"), + }; + format!( + "SELECT {} FROM {table} WHERE {window}", + Self::select(labels, &format!("{function} value")) + ) + } + RangeFunction::Rate | RangeFunction::Increase => { + let partition = self.partition(); + let counter = format!( + "SELECT {}, count() n, cast(min(ts) AS LONG) + {shift} first_us, \ + cast(max(ts) AS LONG) + {shift} last_us, \ + max(CASE WHEN prev IS NULL THEN value END) v_first, \ + max(CASE WHEN nxt IS NULL THEN value END) - max(CASE WHEN prev IS NULL THEN value END) \ + + sum(CASE WHEN value < prev THEN prev ELSE 0.0 END) increase \ + FROM (SELECT {}, ts, value, \ + lag(value) OVER ({partition}) prev, lead(value) OVER ({partition}) nxt \ + FROM {table} WHERE {window})", + self.labels(), + self.labels(), + ); + self.extrapolated(counter) + } + }; + self.outer(per_series) + } + + fn partition(&self) -> String { + if self.source.label_columns.is_empty() { + "ORDER BY ts".into() + } else { + format!("PARTITION BY {} ORDER BY ts", self.labels()) + } + } + + /// Prometheus `extrapolatedRate` over per-series rows of `n`, + /// `first_us`, `last_us`, `v_first` and `increase`. + fn extrapolated(&self, counter: String) -> String { + let labels = &self.source.label_columns; + let per_second = if self.shape.function == RangeFunction::Rate { + format!(" / {}", self.shape.range_ms as f64 / 1000.0) + } else { + String::new() + }; + format!( + "SELECT {} FROM (\ + SELECT {}, CASE WHEN increase > 0 AND v_first >= 0 THEN sampled * v_first / increase ELSE d_start END d_zero FROM (\ + SELECT {}, CASE WHEN raw_start >= 1.1 * gap THEN gap / 2 ELSE raw_start END d_start, \ + CASE WHEN raw_end >= 1.1 * gap THEN gap / 2 ELSE raw_end END d_end FROM (\ + SELECT {}, (last_us - first_us) / 1000000.0 sampled, \ + (last_us - first_us) / 1000000.0 / (n - 1) gap, \ + (first_us - {{lo}}) / 1000000.0 raw_start, ({{hi}} - last_us) / 1000000.0 raw_end \ + FROM ({counter}) WHERE n >= 2)))", + Self::select( + labels, + &format!("increase * (sampled + least(d_start, d_zero) + d_end) / sampled{per_second} value") + ), + Self::select(labels, "increase, sampled, d_start, d_end"), + Self::select(labels, "increase, v_first, sampled, raw_start, raw_end"), + Self::select(labels, "n, increase, v_first"), + ) + } + + /// The `CREATE MATERIALIZED VIEW` of this query and the query over it. + fn view(&self, view: &str, bucket_ms: u64) -> (String, String) { + let table = &self.source.table; + let window = "ts >= {lo} AND ts < {hi}"; + let every = sample_by(bucket_ms); + let (group, state, merged): (&[String], &str, &str) = match (&self.shape.function, self.direct_group()) { + (RangeFunction::OverTime(f), direct) => { + let group = direct.unwrap_or(&self.source.label_columns); + let (state, merged) = match f { + Aggregation::Sum => ("sum(value) s", "sum(s)"), + Aggregation::Count => ("count() c", "sum(c)"), + Aggregation::Min => ("min(value) m", "min(m)"), + Aggregation::Max => ("max(value) m", "max(m)"), + Aggregation::Avg => ("sum(value) s, count() c", "sum(s) / sum(c)"), + }; + (group, state, merged) + } + (RangeFunction::Rate | RangeFunction::Increase, _) => ( + &self.source.label_columns, + "count() n, min(ts) first_ts, max(ts) last_ts, first(value) v_first, last(value) v_last", + "", + ), + (RangeFunction::Quantile(_), _) => unreachable!("no view for a quantile"), + }; + let create = format!( + "CREATE MATERIALIZED VIEW {view} REFRESH IMMEDIATE AS (SELECT ts, {} FROM {table} SAMPLE BY {every})", + Self::select(group, state) + ); + let query = if merged.is_empty() { + let partition = self.partition(); + let counter = format!( + "SELECT {}, sum(n) n, cast(min(first_ts) AS LONG) + 1 first_us, \ + cast(max(last_ts) AS LONG) + 1 last_us, \ + max(CASE WHEN prev IS NULL THEN v_first END) v_first, \ + max(CASE WHEN nxt IS NULL THEN v_last END) - max(CASE WHEN prev IS NULL THEN v_first END) \ + + sum(CASE WHEN v_first < prev THEN prev ELSE 0.0 END) increase \ + FROM (SELECT {}, ts, n, first_ts, last_ts, v_first, v_last, \ + lag(v_last) OVER ({partition}) prev, lead(v_first) OVER ({partition}) nxt \ + FROM {view} WHERE {window})", + self.labels(), + self.labels(), + ); + self.outer(self.extrapolated(counter)) + } else { + let per_group = format!( + "SELECT {} FROM {view} WHERE {window}", + Self::select(group, &format!("{merged} value")) + ); + if self.direct_group().is_some() { + per_group + } else { + self.outer(per_group) + } + }; + (create, query) + } +} + +fn column_list(labels: &[String]) -> String { + labels + .iter() + .map(|l| quoted(l)) + .collect::>() + .join(", ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn durations() { + assert_eq!(duration_ms("1m"), Some(60_000)); + assert_eq!(duration_ms("1h30m"), Some(5_400_000)); + assert_eq!(duration_ms("500ms"), Some(500)); + assert_eq!(duration_ms("m"), None); + assert_eq!(duration_ms(""), None); + } + + fn shape(text: &str) -> QueryShape { + QueryShape::parse(text).unwrap_or_else(|e| panic!("{e}")) + } + + #[test] + fn every_showcase_text_parses() { + let job = Some((Aggregation::Avg, vec!["job".to_string()])); + assert_eq!( + shape("avg by (job) (quantile_over_time(0.9, latency[1h]))"), + QueryShape { + function: RangeFunction::Quantile(0.9), + metric: "latency".into(), + range_ms: 3_600_000, + outer: job, + } + ); + assert_eq!( + shape("quantile_over_time(0.99, latency[1m])").function, + RangeFunction::Quantile(0.99) + ); + assert_eq!( + shape("max_over_time(latency[1m])").function, + RangeFunction::OverTime(Aggregation::Max) + ); + let rate = shape("sum by (job) (rate(requests_total[1m]))"); + assert_eq!(rate.function, RangeFunction::Rate); + assert_eq!(rate.metric, "requests_total"); + assert_eq!(rate.outer, Some((Aggregation::Sum, vec!["job".into()]))); + assert_eq!( + shape("sum by (job) (count_over_time(latency[1m]))").function, + RangeFunction::OverTime(Aggregation::Count) + ); + assert_eq!( + shape("sum by(job, instance)(sum_over_time(latency[5m]))").outer, + Some((Aggregation::Sum, vec!["job".into(), "instance".into()])) + ); + assert_eq!(shape("increase(x[30s])").function, RangeFunction::Increase); + } + + #[test] + fn other_texts_are_refused_with_the_reason() { + for (text, reason) in [ + ("latency", "unknown function"), + ("rate(latency{job=\"a\"}[1m])", "label matchers"), + ("sum without (job) (rate(x[1m]))", "'without'"), + ("irate(x[1m])", "unknown function"), + ("sum(sum(rate(x[1m])))", "aggregation of an aggregation"), + ("rate(x[1m]) * 2", "unexpected"), + ] { + let error = QueryShape::parse(text).unwrap_err(); + assert!(error.contains(reason), "{text}: {error}"); + } + } + + fn workload(texts: &[&str], interval_ms: u64, start_ms: i64) -> WorkloadSpec { + use aqpbm_core::harness::engine::{QueryText, WorkloadQuery}; + let record = |metric: &str| -> aqpbm_core::harness::data::DataRecord { + serde_json::from_value(serde_json::json!({ + "metric": metric, + "description": { + "labels": [{"name": "job", "cardinality": 2}, {"name": "instance", "cardinality": 2}], + "series_num": 4, "start_ms": start_ms, "sample_interval_ms": 1000, + "duration_ms": 600000, + "value_distribution": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1.0, "seed": 0}, + "counter": metric.ends_with("_total"), "seed": 1 + } + })) + .unwrap() + }; + 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: QueryShape::parse(text).unwrap().range_ms, + evaluation_interval_ms: interval_ms, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![record("latency"), record("requests_total")], + ) + } + + const JOINT: &[&str] = &[ + "quantile_over_time(0.99, 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]))", + ]; + + #[test] + fn native_reads_the_left_open_window_at_query_time() { + let d = deploy(&workload(JOINT, 10_000, 0), Variant::Native, "p").unwrap(); + assert_eq!(d.timestamp_shift_us, 0); + assert!(d.views.is_empty() && d.substitutions.is_empty()); + assert_eq!( + d.statements, + vec![ + "CREATE TABLE p_latency (\"job\" SYMBOL, \"instance\" SYMBOL, value DOUBLE, ts TIMESTAMP) TIMESTAMP(ts) PARTITION BY DAY WAL", + "CREATE TABLE p_requests_total (\"job\" SYMBOL, \"instance\" SYMBOL, value DOUBLE, ts TIMESTAMP) TIMESTAMP(ts) PARTITION BY DAY WAL", + ] + ); + let sql: Vec<&str> = d.queries.iter().map(|q| q.sql.as_str()).collect(); + assert_eq!( + sql[0], + "SELECT \"job\", \"instance\", percentile_cont(value, 0.99) value FROM p_latency WHERE ts > {lo} AND ts <= {hi}" + ); + assert_eq!( + sql[1], + "SELECT \"job\", avg(value) value FROM (SELECT \"job\", \"instance\", percentile_cont(value, 0.9) value FROM p_latency WHERE ts > {lo} AND ts <= {hi})" + ); + assert_eq!( + sql[4], + "SELECT \"job\", sum(value) value FROM p_latency WHERE ts > {lo} AND ts <= {hi}" + ); + assert_eq!( + sql[5], + "SELECT \"job\", count() value FROM p_latency WHERE ts > {lo} AND ts <= {hi}" + ); + assert!(sql[3] + .contains("lag(value) OVER (PARTITION BY \"job\", \"instance\" ORDER BY ts) prev")); + assert!(sql[3].contains("/ 60 value"), "{}", sql[3]); + assert!(sql[3].contains("WHERE n >= 2")); + assert!(d.queries.iter().all(|q| q.step_ms == 1)); + } + + #[test] + fn approximate_differs_from_native_only_in_quantiles() { + let native = deploy(&workload(JOINT, 10_000, 0), Variant::Native, "p").unwrap(); + let approx = deploy(&workload(JOINT, 10_000, 0), Variant::Approximate, "p").unwrap(); + for (n, a) in native.queries.iter().zip(&approx.queries) { + assert_eq!( + n.sql + .replace( + "percentile_cont(value, 0.99)", + "approx_percentile(value, 0.99, 2)" + ) + .replace( + "percentile_cont(value, 0.9)", + "approx_percentile(value, 0.9, 2)" + ), + a.sql + ); + } + assert_eq!(approx.substitutions.len(), 2); + } + + #[test] + fn views_are_per_query_except_quantiles() { + let d = deploy(&workload(JOINT, 10_000, 0), Variant::MaterializedViews, "p").unwrap(); + assert_eq!(d.timestamp_shift_us, 1); + let names: Vec<&str> = d.views.iter().map(|v| v.name.as_str()).collect(); + assert_eq!(names, vec!["p_q3", "p_q4", "p_q5", "p_q6"]); + let steps: Vec = d.queries.iter().map(|q| q.step_ms).collect(); + assert_eq!(steps, vec![1, 1, 10_000, 10_000, 10_000, 10_000]); + assert_eq!( + d.queries[0].sql, + "SELECT \"job\", \"instance\", percentile_cont(value, 0.99) value FROM p_latency WHERE ts >= {lo} AND ts < {hi}" + ); + assert_eq!( + d.statements[2], + "CREATE MATERIALIZED VIEW p_q3 REFRESH IMMEDIATE AS (SELECT ts, \"job\", \"instance\", max(value) m FROM p_latency SAMPLE BY 10s)" + ); + assert_eq!( + d.queries[2].sql, + "SELECT \"job\", \"instance\", max(m) value FROM p_q3 WHERE ts >= {lo} AND ts < {hi}" + ); + // sum of sums: grouped by job in the view itself. + assert_eq!( + d.statements[4], + "CREATE MATERIALIZED VIEW p_q5 REFRESH IMMEDIATE AS (SELECT ts, \"job\", sum(value) s FROM p_latency SAMPLE BY 10s)" + ); + assert_eq!( + d.queries[5].sql, + "SELECT \"job\", sum(c) value FROM p_q6 WHERE ts >= {lo} AND ts < {hi}" + ); + assert!(d.statements[3].contains("first(value) v_first, last(value) v_last")); + assert!(d.queries[3] + .sql + .contains("cast(min(first_ts) AS LONG) + 1 first_us")); + assert_eq!(d.substitutions.len(), 1, "{:?}", d.substitutions); + assert!(d.substitutions[0].contains("reset inside one bucket")); + } + + #[test] + fn view_buckets_are_the_gcd_and_must_divide_the_data_start() { + let hour = &["max_over_time(latency[1h])"]; + let d = deploy( + &workload(hour, 60_000, 1_700_000_040_000), + Variant::MaterializedViews, + "p", + ) + .unwrap(); + assert!( + d.statements[1].ends_with("SAMPLE BY 60s)"), + "{}", + d.statements[1] + ); + let error = deploy( + &workload(hour, 60_000, 1_700_000_001_000), + Variant::MaterializedViews, + "p", + ) + .unwrap_err(); + assert!(error.contains("do not divide the data start"), "{error}"); + // Native reads raw rows and takes any start. + deploy( + &workload(hour, 60_000, 1_700_000_001_000), + Variant::Native, + "p", + ) + .unwrap(); + } + + #[test] + fn unknown_metrics_and_sample_column_labels_are_refused() { + let error = deploy( + &workload(&["max_over_time(other[1m])"], 10_000, 0), + Variant::Native, + "p", + ) + .unwrap_err(); + assert!(error.contains("no data record"), "{error}"); + let mut w = workload(&["max_over_time(latency[1m])"], 10_000, 0); + w.data[0].description.labels[0].name = "ts".into(); + let error = deploy(&w, Variant::Native, "p").unwrap_err(); + assert!(error.contains("label named ts"), "{error}"); + let error = deploy( + &workload(&["sum by (zone) (max_over_time(latency[1m]))"], 10_000, 0), + Variant::Native, + "p", + ) + .unwrap_err(); + assert!(error.contains("label zone"), "{error}"); + } +} diff --git a/system-bench/src/engines_external/questdb_server.rs b/system-bench/src/engines_external/questdb_server.rs new file mode 100644 index 00000000..9250d5f2 --- /dev/null +++ b/system-bench/src/engines_external/questdb_server.rs @@ -0,0 +1,659 @@ +//! A QuestDB server as an engine under test. Each arm's plan file names a +//! variant, `{"questdb_variant": "native"}` (`native`, `materialized-views` +//! or `approximate`); [`super::questdb::deploy`] writes the arm's tables, +//! views and SQL from the workload's PromQL texts. +//! +//! Example: an arm of variant `materialized-views` over `max_over_time(latency[1m])` +//! creates table `bench_4711_0_latency` and view `bench_4711_0_q1` +//! (`SAMPLE BY 10s`, refreshed incrementally); each refresh chunk is one +//! InfluxDB Line Protocol request over HTTP to `/write`, and each evaluation +//! at `t` runs `SELECT … FROM bench_4711_0_q1 WHERE ts >= t - 60 s AND ts < t` +//! over `/exec`. +//! +//! Ingest waits until the server applied the chunk's WAL transactions to each +//! table and every view refreshed up to them, so that work is ingest CPU and +//! an evaluation runs only its queries. +//! +//! NaN: QuestDB stores a NaN `DOUBLE` as NULL, so a NaN sample is refused at +//! ingest; an answer row whose value is NULL (an aggregate of no rows) is +//! left out, as PromQL returns no series. +//! +//! CPU and memory: the server runs in its own cgroup, read over SSH or on +//! this host. QuestDB keeps no per-query CPU counter; [`StepReport`] carries +//! each query request's wall time as the client saw it. + +use std::collections::BTreeMap; +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, SampleChunk, SeriesLabels, StepReport, WorkloadSpec, +}; +use aqpbm_core::harness::protocol::Protocol; +use serde_json::Value; + +use super::questdb::{deploy, QuestDbDeployment, SourceTable, Variant}; +use super::server_cgroup::ServerCgroupOptions; + +/// How to reach the server. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct QuestDbServer { + /// The HTTP interface, e.g. `http://10.0.0.1:9000`. + pub url: String, + /// Where the server's cgroup is read, e.g. over SSH from `bench@10.0.0.1`. + pub cgroup: CgroupSource, + /// How long one request, or one ingest's wait for the server to apply + /// it, may take, e.g. 600 s. + pub request_timeout: Duration, +} + +/// The server's HTTP interface: `/exec` for SQL, `/write` for ILP. +#[derive(Clone)] +pub struct QuestDbHttp { + agent: ureq::Agent, + url: String, +} + +impl QuestDbHttp { + pub fn new(url: &str, request_timeout: Duration) -> QuestDbHttp { + QuestDbHttp { + agent: ureq::AgentBuilder::new() + .timeout_connect(Duration::from_secs(5)) + .timeout(request_timeout) + .build(), + url: url.trim_end_matches('/').to_string(), + } + } + + /// Runs `sql`; the answer's JSON (`columns`, `dataset`, or `ddl`). + pub fn exec(&self, sql: &str) -> Result { + let response = self + .agent + .get(&format!("{}/exec", self.url)) + .query("query", sql) + .call(); + let text = match response { + Ok(response) => response.into_string(), + Err(ureq::Error::Status(_, response)) => response.into_string(), + Err(error) => return Err(EngineError(format!("{sql}: {error}"))), + } + .map_err(|error| EngineError(format!("{sql}: {error}")))?; + let body: Value = serde_json::from_str(&text) + .map_err(|error| EngineError(format!("{sql}: {error}: {text}")))?; + if let Some(error) = body.get("error") { + return Err(EngineError(format!("{sql}: {error}"))); + } + Ok(body) + } + + /// The rows of `sql`'s answer. + pub fn rows(&self, sql: &str) -> Result>, EngineError> { + let body = self.exec(sql)?; + Ok(body["dataset"] + .as_array() + .map(|rows| { + rows.iter() + .map(|row| row.as_array().cloned().unwrap_or_default()) + .collect() + }) + .unwrap_or_default()) + } + + /// Writes ILP `lines` with microsecond timestamps. + pub fn write(&self, lines: &str) -> Result<(), EngineError> { + let response = self + .agent + .post(&format!("{}/write", self.url)) + .query("precision", "u") + .send_string(lines); + match response { + Ok(_) => Ok(()), + Err(ureq::Error::Status(status, response)) => Err(EngineError(format!( + "ILP write: status {status}: {}", + response.into_string().unwrap_or_default() + ))), + Err(error) => Err(EngineError(format!("ILP write: {error}"))), + } + } +} + +/// A QuestDB server; see the module docs. +pub struct QuestDbEngine { + server: QuestDbServer, + http: QuestDbHttp, + description: EngineDescription, + /// Each install's tables and views start with `__`. + prefix: String, +} + +/// Installs made by this process: numbers each install's tables. +static INSTALL_COUNT: AtomicU64 = AtomicU64::new(0); + +/// The server settings recorded in the build profile: whether a query runs +/// on one thread or several, and the worker pools. +const PROFILE_PARAMETERS: &[&str] = &[ + "cairo.sql.parallel.filter.enabled", + "cairo.sql.parallel.groupby.enabled", + "cairo.sql.parallel.window.join.enabled", + "cairo.sql.parallel.read.parquet.enabled", + "shared.query.worker.count", + "shared.network.worker.count", + "shared.write.worker.count", + "query.timeout", +]; + +/// How often an ingest polls whether the server applied its writes. +const APPLY_POLL_INTERVAL: Duration = Duration::from_millis(5); + +impl QuestDbEngine { + /// Connects to the server and reads its version and settings. Tables of + /// an earlier run (`bench_*`) are refused: dropping them, or their WAL + /// apply and view refresh, would be charged to this run. + pub fn new(server: QuestDbServer) -> Result { + let http = QuestDbHttp::new(&server.url, server.request_timeout); + let leftovers: Vec = http + .rows("SELECT table_name FROM tables() WHERE table_name LIKE 'bench_%'")? + .iter() + .filter_map(|row| row.first()?.as_str().map(String::from)) + .collect(); + if !leftovers.is_empty() { + return Err(EngineError(format!( + "the server holds tables of an earlier run: {}; start it from an empty data dir", + leftovers.join(", ") + ))); + } + let build = http + .rows("SELECT build()")? + .first() + .and_then(|row| row.first()?.as_str().map(String::from)) + .ok_or_else(|| EngineError("no answer to build()".into()))?; + // "Build Information: QuestDB 10.2.0, JDK 25.0.2, Commit Hash 14d5…" + let version = build + .strip_prefix("Build Information: QuestDB ") + .unwrap_or(&build) + .to_string(); + let mut settings = Vec::new(); + for row in http.rows("SHOW PARAMETERS")? { + let name = row.first().and_then(Value::as_str).unwrap_or_default(); + if PROFILE_PARAMETERS.contains(&name) { + let value = row.get(2).and_then(Value::as_str).unwrap_or("null"); + settings.push(format!("{name}={value}")); + } + } + settings.sort(); + Ok(QuestDbEngine { + description: EngineDescription { + id: "questdb".into(), + version, + version_dirty: false, + build_profile: settings.join(" "), + }, + prefix: format!("bench_{}", std::process::id()), + server, + http, + }) + } +} + +impl EngineUnderTest for QuestDbEngine { + fn description(&self) -> EngineDescription { + self.description.clone() + } + + fn cpu_accounting(&self) -> CpuAccounting { + CpuAccounting::Cgroup(self.server.cgroup.clone()) + } + + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + let variant = variant_of(arm)?; + let prefix = format!( + "{}_{}", + self.prefix, + INSTALL_COUNT.fetch_add(1, Ordering::Relaxed) + ); + let deployment = deploy(workload, variant, &prefix).map_err(EngineError)?; + check_evaluation_times(workload, &deployment)?; + let installed = QuestDbArm { + http: self.http.clone(), + timeout: self.server.request_timeout, + asked_from_ms: workload + .queries + .iter() + .map(|query| workload.asked_from_ms(query)) + .collect(), + summary: PlanSummary { + text: deployment.script(), + node_kinds: deployment + .queries + .iter() + .map(|query| query.rule.clone()) + .collect(), + stored_outputs: deployment + .views + .iter() + .map(|view| view.name.clone()) + .collect(), + substitutions: deployment.substitutions.clone(), + sharing_lost: Vec::new(), + }, + deployment, + }; + // From here on, dropping the arm drops what it created. + for statement in &installed.deployment.statements { + installed.http.exec(statement)?; + } + Ok(Box::new(installed)) + } +} + +/// The variant a plan file names: `{"questdb_variant": "native"}`. +fn variant_of(arm: &ArmSpec) -> Result { + let path = arm + .engine_options + .get("plan_file") + .and_then(|p| p.as_str()) + .ok_or_else(|| EngineError("engine_options has no plan_file".into()))?; + let text = std::fs::read_to_string(path) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; + let plan: Value = serde_json::from_str(&text) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; + let name = plan + .get("questdb_variant") + .and_then(Value::as_str) + .ok_or_else(|| { + EngineError(format!( + "plan file {path} is not a QuestDB variant file ({{\"questdb_variant\": \"native\"}})" + )) + })?; + Variant::parse(name).ok_or_else(|| { + EngineError(format!( + "plan file {path}: unknown QuestDB variant {name}; known: native, materialized-views, approximate" + )) + }) +} + +/// Every evaluation time is a multiple of the evaluation interval from an +/// aligned data start, so a query over a view's buckets answers right only +/// when its bucket divides the interval and the data start. Refused at +/// install. +fn check_evaluation_times( + workload: &WorkloadSpec, + deployment: &QuestDbDeployment, +) -> Result<(), EngineError> { + let data_start_ms = workload.data_start_ms().unwrap_or(0); + for (query, sql) in workload.queries.iter().zip(&deployment.queries) { + let step = sql.step_ms as i64; + if (query.evaluation_interval_ms as i64) % step != 0 || data_start_ms % step != 0 { + return Err(EngineError(format!( + "query {} reads buckets of {step} ms, which do not divide its evaluation \ + interval ({} ms) and the data start ({data_start_ms} ms)", + query.id, query.evaluation_interval_ms + ))); + } + } + Ok(()) +} + +/// One installed arm: its tables, views and queries. +struct QuestDbArm { + http: QuestDbHttp, + timeout: Duration, + deployment: QuestDbDeployment, + /// Per query: the first evaluation that asks it, when not every one does. + asked_from_ms: Vec>, + summary: PlanSummary, +} + +impl Drop for QuestDbArm { + fn drop(&mut self) { + // Best effort: a server that is gone keeps nothing anyway. + for view in &self.deployment.views { + let _ = self + .http + .exec(&format!("DROP MATERIALIZED VIEW IF EXISTS {}", view.name)); + } + for source in &self.deployment.sources { + let _ = self + .http + .exec(&format!("DROP TABLE IF EXISTS {}", source.table)); + } + } +} + +impl QuestDbArm { + /// Waits until the server applied every WAL transaction of `tables` and + /// every view refreshed up to its base table's newest transaction. + fn wait_applied(&self, tables: &[&str]) -> Result<(), EngineError> { + let started = Instant::now(); + let names: Vec = tables + .iter() + .copied() + .chain(self.deployment.views.iter().map(|view| view.name.as_str())) + .map(|name| format!("'{name}'")) + .collect(); + let wal = format!( + "SELECT name, suspended, writerTxn, sequencerTxn, errorMessage FROM wal_tables() \ + WHERE name IN ({})", + names.join(", ") + ); + let views = format!( + "SELECT view_name, view_status, refresh_base_table_txn, base_table_txn, \ + invalidation_reason FROM materialized_views() WHERE view_name IN ({})", + names.join(", ") + ); + loop { + let mut pending = Vec::new(); + let mut base_txn: BTreeMap = BTreeMap::new(); + for row in self.http.rows(&wal)? { + let name = row[0].as_str().unwrap_or_default().to_string(); + if row[1].as_bool() == Some(true) { + return Err(EngineError(format!( + "table {name}'s WAL apply is suspended: {}", + row[4] + ))); + } + let (writer, sequencer) = (row[2].as_i64(), row[3].as_i64()); + if writer != sequencer { + pending.push(format!("table {name} at {writer:?} of {sequencer:?}")); + } + base_txn.insert(name, sequencer.unwrap_or(0)); + } + for row in self.http.rows(&views)? { + let name = row[0].as_str().unwrap_or_default(); + let status = row[1].as_str().unwrap_or_default(); + if status == "invalid" { + return Err(EngineError(format!("view {name} is invalid: {}", row[4]))); + } + let refreshed = row[2].as_i64().unwrap_or(-1); + let base = self + .deployment + .views + .iter() + .find(|view| view.name == name) + .and_then(|view| base_txn.get(&view.base_table).copied()); + let target = base.unwrap_or_else(|| row[3].as_i64().unwrap_or(0)); + if status != "valid" || refreshed < target { + pending.push(format!("view {name} {status} at {refreshed} of {target}")); + } + } + if pending.is_empty() { + return Ok(()); + } + if started.elapsed() > self.timeout { + return Err(EngineError(format!( + "the server did not apply the chunk in {:?}: {}", + self.timeout, + pending.join(", ") + ))); + } + std::thread::sleep(APPLY_POLL_INTERVAL); + } + } +} + +impl InstalledArm for QuestDbArm { + fn plan_summary(&self) -> PlanSummary { + self.summary.clone() + } + + fn ingest(&mut self, chunk: &SampleChunk) -> Result { + let shift = self.deployment.timestamp_shift_us; + let mut lines: Vec = vec![String::new(); self.deployment.sources.len()]; + for sample in &chunk.samples { + let Some(at) = sample.labels.get("__name__").and_then(|metric| { + self.deployment + .sources + .iter() + .position(|source| &source.metric == metric) + }) else { + continue; + }; + if !sample.value.is_finite() { + return Err(EngineError(format!( + "a sample of {:?} at {} ms is {}: QuestDB stores NaN as NULL and the \ + Line Protocol has no infinity", + sample.labels, sample.ts_ms, sample.value + ))); + } + push_line( + &mut lines[at], + &self.deployment.sources[at], + &sample.labels, + sample.value, + sample.ts_ms * 1000 - shift, + ); + } + let mut written = Vec::new(); + for (source, lines) in self.deployment.sources.iter().zip(&lines) { + if lines.is_empty() { + continue; + } + self.http.write(lines)?; + written.push(source.table.as_str()); + } + if !written.is_empty() { + self.wait_applied(&written)?; + } + 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, asked_from_ms) in self.deployment.queries.iter().zip(&self.asked_from_ms) { + if asked_from_ms.is_some_and(|from_ms| at_ms < from_ms) { + continue; + } + let sql = query + .sql + .replace( + "{lo}", + &((at_ms - query.window_ms as i64) * 1000).to_string(), + ) + .replace("{hi}", &(at_ms * 1000).to_string()); + let started = Instant::now(); + let body = self.http.exec(&sql)?; + report + .query_wall_ns + .insert(query.id.clone(), started.elapsed().as_nanos() as u64); + answers.insert( + query.id.clone(), + parse_answer(&body).map_err(|e| EngineError(format!("query {}: {e}", query.id)))?, + ); + } + Ok((Answers(answers), report)) + } + + fn footprint(&self) -> Result { + let mut footprint = Footprint::default(); + for row in self + .http + .rows("SELECT tableName, diskSize FROM table_storage()")? + { + let name = row[0].as_str().unwrap_or_default(); + let bytes = row[1].as_u64().unwrap_or(0); + if self.deployment.views.iter().any(|view| view.name == name) { + footprint.view_bytes += bytes; + } else if self.deployment.sources.iter().any(|s| s.table == name) { + footprint.raw_retained_bytes += bytes; + } + } + Ok(footprint) + } +} + +/// One InfluxDB Line Protocol line: `table,job=a,instance=i1 value=1.5 <µs>`. +/// An empty label is left out (a NULL symbol), as PromQL has no empty label. +pub fn push_line( + out: &mut String, + source: &SourceTable, + labels: &SeriesLabels, + value: f64, + ts_us: i64, +) { + out.push_str(&source.table); + for label in &source.label_columns { + let Some(text) = labels.get(label).filter(|text| !text.is_empty()) else { + continue; + }; + out.push(','); + push_escaped(out, label); + out.push('='); + push_escaped(out, text); + } + out.push_str(" value="); + // Rust prints the shortest text that reads back exactly; ILP reads a + // field without a suffix as a double. + out.push_str(&value.to_string()); + out.push(' '); + out.push_str(&ts_us.to_string()); + out.push('\n'); +} + +/// A tag key or value: space, comma, equals sign and backslash escaped; a +/// line break, which ILP cannot carry, as a space. +fn push_escaped(out: &mut String, text: &str) { + for c in text.chars() { + match c { + ' ' | ',' | '=' | '\\' => { + out.push('\\'); + out.push(c); + } + '\n' | '\r' => out.push(' '), + c => out.push(c), + } + } +} + +/// An `/exec` answer (label columns, then the value column last) as series +/// and values. NULL labels are left out; a row whose value is NULL is +/// skipped. +pub fn parse_answer(body: &Value) -> Result, String> { + let names: Vec<&str> = body["columns"] + .as_array() + .ok_or("the answer has no columns")? + .iter() + .map(|column| column["name"].as_str().unwrap_or_default()) + .collect(); + let mut series = BTreeMap::new(); + for row in body["dataset"] + .as_array() + .ok_or("the answer has no dataset")? + { + let row = row.as_array().ok_or("a row is not an array")?; + if row.len() != names.len() { + return Err(format!("row {row:?} does not match the columns {names:?}")); + } + let (value, labels) = row.split_last().ok_or("a row without a value")?; + let value = match value { + Value::Null => continue, + Value::Number(number) => number.as_f64().ok_or("a value out of range")?, + other => return Err(format!("value {other} is not a number")), + }; + let key: SeriesLabels = names + .iter() + .zip(labels) + .filter_map(|(name, label)| match label { + Value::String(text) if !text.is_empty() => Some((name.to_string(), text.clone())), + _ => None, + }) + .collect(); + 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 QuestDbOptions { + /// The QuestDB server's HTTP interface (engine `questdb`), e.g. + /// `http://10.0.0.1:9000`. + #[arg(long)] + pub questdb_url: Option, + /// How long one QuestDB request, or one ingest's wait for the server to + /// apply its chunk, may take, in seconds. + #[arg(long, default_value_t = 600)] + pub questdb_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"), + ("clickhouse_url", "--clickhouse-url"), + ("victoriametrics_url", "--victoriametrics-url"), + ("asapquery_backend_url", "--asapquery-backend-url"), + ] { + if matches!(matches.try_get_raw(id), Ok(Some(_))) { + anyhow::bail!("{flag} is not an option of engine questdb"); + } + } + let options = ::from_arg_matches(matches)?; + let (Some(url), Some(cgroup)) = (options.questdb_url, options.cgroup.source()) else { + anyhow::bail!("engine questdb needs --questdb-url and --server-cgroup-directory"); + }; + Ok(Box::new(QuestDbEngine::new(QuestDbServer { + url, + cgroup, + request_timeout: Duration::from_secs(options.questdb_request_timeout_seconds), + })?)) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn a_line_escapes_tags_and_leaves_out_empty_labels() { + let source = SourceTable { + metric: "latency".into(), + table: "p_latency".into(), + label_columns: vec!["job".into(), "instance".into(), "zone".into()], + }; + let labels: SeriesLabels = [("__name__", "latency"), ("job", "a b,c=d\\"), ("zone", "")] + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + let mut out = String::new(); + push_line(&mut out, &source, &labels, 7.0, 1_700_000_041_000_000 - 1); + push_line(&mut out, &source, &labels, 0.1, 5); + assert_eq!( + out, + "p_latency,job=a\\ b\\,c\\=d\\\\ value=7 1700000040999999\n\ + p_latency,job=a\\ b\\,c\\=d\\\\ value=0.1 5\n" + ); + } + + #[test] + fn an_answer_drops_null_labels_and_null_values() { + let body = json!({ + "columns": [{"name": "job", "type": "SYMBOL"}, {"name": "instance", "type": "SYMBOL"}, + {"name": "value", "type": "DOUBLE"}], + "dataset": [["a", "i1", 1.5], ["a", null, 2], ["b", "i1", null]] + }); + let answer = parse_answer(&body).unwrap(); + let key = |pairs: &[(&str, &str)]| -> SeriesLabels { + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }; + assert_eq!(answer.len(), 2); + assert_eq!(answer[&key(&[("job", "a"), ("instance", "i1")])], 1.5); + assert_eq!(answer[&key(&[("job", "a")])], 2.0); + let twice = json!({"columns": [{"name": "value"}], "dataset": [[1.0], [2.0]]}); + assert!(parse_answer(&twice).unwrap_err().contains("two rows")); + } +} diff --git a/system-bench/src/registry.rs b/system-bench/src/registry.rs index a83822b4..78924501 100644 --- a/system-bench/src/registry.rs +++ b/system-bench/src/registry.rs @@ -17,6 +17,7 @@ use crate::engines_external::druid_sql::{self, DruidOptions}; use crate::engines_external::duckdb_command_line::{self, DuckDbOptions}; use crate::engines_external::pilotdb::{self, PilotDbOptions}; use crate::engines_external::postgresql_command_line::{self, PostgreSqlOptions}; +use crate::engines_external::questdb_server::{self, QuestDbOptions}; use crate::engines_external::victoriametrics_server::{self, VictoriaMetricsOptions}; pub struct System { @@ -122,6 +123,15 @@ pub const SYSTEMS: &[System] = &[ build: postgresql_command_line::one_shot_queries, }), }, + System { + name: "questdb", + periodic_queries: Some(PeriodicQueries { + options: QuestDbOptions::augment_args, + build: questdb_server::periodic_queries, + }), + write_throughput: None, + one_shot_queries: None, + }, System { name: "druid", periodic_queries: None, @@ -248,6 +258,7 @@ fn fake_engine(matches: &ArgMatches, _: &Protocol) -> Result QuestDbEngine { + let cgroup_directory = std::env::var("AQPBM_SERVER_CGROUP_DIRECTORY") + .expect("AQPBM_SERVER_CGROUP_DIRECTORY") + .into(); + QuestDbEngine::new(QuestDbServer { + url: std::env::var("AQPBM_QUESTDB_URL").expect("AQPBM_QUESTDB_URL"), + cgroup: match std::env::var("AQPBM_SERVER_SSH_HOST") { + Ok(host) => CgroupSource::Remote { + ssh_program: "ssh".into(), + host, + cgroup_directory, + }, + Err(_) => CgroupSource::Local(cgroup_directory), + }, + request_timeout: Duration::from_secs(600), + }) + .expect("the server answers") +} + +/// The arm of `variant`, its plan file written to a temporary directory. +fn arm(variant: &str) -> ArmSpec { + let dir = std::env::temp_dir().join(format!("questdb-conformance-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path: PathBuf = dir.join(format!("{variant}.plan.json")); + std::fs::write(&path, json!({ "questdb_variant": variant }).to_string()).unwrap(); + ArmSpec { + name: format!("questdb.{variant}"), + raw_data_retained: true, + engine_options: json!({ "plan_file": path }), + } +} + +/// A data record that only declares `metric`'s labels; the cases ingest +/// their own samples. +fn record(metric: &str, labels: &[&str], start_ms: i64) -> DataRecord { + serde_json::from_value(json!({ + "metric": metric, + "description": { + "labels": labels.iter().map(|name| json!({"name": name, "cardinality": 2})).collect::>(), + "series_num": 2, "start_ms": start_ms, "sample_interval_ms": 1000, + "duration_ms": 600000, + "value_distribution": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1.0, "seed": 0}, + "counter": false, "seed": 1 + } + })) + .unwrap() +} + +/// A workload of `texts` (ids `q0`, `q1`, …) evaluated every `interval_ms`. +fn workload(texts: &[&str], interval_ms: u64, data: Vec) -> WorkloadSpec { + WorkloadSpec::periodic( + "conformance".into(), + texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + dialect: None, + }], + window_ms: QueryShape::parse(text).unwrap().range_ms, + evaluation_interval_ms: interval_ms, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + data, + ) +} + +fn series(pairs: &[(&str, &str)]) -> Arc { + Arc::new( + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ) +} + +/// `samples` cut into time-ordered chunks of `chunk_ms`, ending at +/// multiples of it, as the harness's chunks are. +fn chunks(mut samples: Vec, chunk_ms: i64) -> Vec { + samples.sort_by_key(|s| s.ts_ms); + let mut out: Vec = Vec::new(); + for sample in samples { + let end_ms = (sample.ts_ms + chunk_ms - 1).div_euclid(chunk_ms) * chunk_ms; + match out.last_mut() { + Some(chunk) if chunk.end_ms == end_ms => chunk.samples.push(sample), + _ => out.push(SampleChunk { + end_ms, + samples: vec![sample], + }), + } + } + out +} + +/// PromQL's answer to `text` at `at_ms` over `samples`: the window +/// `(at − range, at]`, `quantile_over_time` by linear interpolation, and +/// `rate` / `increase` by Prometheus v3 `extrapolatedRate`. +fn reference(text: &str, samples: &[Sample], at_ms: i64) -> BTreeMap { + reference_with(text, samples, at_ms, false) +} + +/// [`reference`], with quantiles by nearest rank (the `ceil(q · n)`-th +/// smallest value) when `nearest_rank`: the value HdrHistogram's +/// `approx_percentile` approximates, to its precision (1 % at 2 digits). Its +/// error against PromQL's interpolated quantile is what the report measures. +fn reference_with( + text: &str, + samples: &[Sample], + at_ms: i64, + nearest_rank: bool, +) -> BTreeMap { + let shape = QueryShape::parse(text).unwrap(); + let start_ms = at_ms - shape.range_ms as i64; + let mut windows: BTreeMap> = BTreeMap::new(); + for sample in samples { + if sample.labels.get("__name__") == Some(&shape.metric) + && sample.ts_ms > start_ms + && sample.ts_ms <= at_ms + { + let mut labels = (*sample.labels).clone(); + labels.remove("__name__"); + windows + .entry(labels) + .or_default() + .push((sample.ts_ms, sample.value)); + } + } + let mut per_series = BTreeMap::new(); + for (labels, mut points) in windows { + points.sort_by_key(|p| p.0); + let values: Vec = points.iter().map(|p| p.1).collect(); + let value = match &shape.function { + RangeFunction::OverTime(f) => aggregate(*f, &values), + RangeFunction::Quantile(q) => { + let mut sorted = values.clone(); + sorted.sort_by(f64::total_cmp); + if nearest_rank { + let rank = (q * sorted.len() as f64).ceil().max(1.0) as usize; + per_series.insert(labels, sorted[rank - 1]); + continue; + } + let rank = q * (sorted.len() - 1) as f64; + let (low, high) = (rank.floor() as usize, rank.ceil() as usize); + sorted[low] + (sorted[high] - sorted[low]) * (rank - low as f64) + } + RangeFunction::Rate | RangeFunction::Increase => { + if points.len() < 2 { + continue; + } + let mut increase = values[values.len() - 1] - values[0]; + for pair in values.windows(2) { + if pair[1] < pair[0] { + increase += pair[0]; + } + } + let (first_ms, last_ms) = (points[0].0, points[points.len() - 1].0); + let sampled = (last_ms - first_ms) as f64 / 1000.0; + let gap = sampled / (points.len() - 1) as f64; + let mut to_start = (first_ms - start_ms) as f64 / 1000.0; + let mut to_end = (at_ms - last_ms) as f64 / 1000.0; + if to_start >= 1.1 * gap { + to_start = gap / 2.0; + } + if increase > 0.0 && values[0] >= 0.0 { + to_start = to_start.min(sampled * values[0] / increase); + } + if to_end >= 1.1 * gap { + to_end = gap / 2.0; + } + let extrapolated = increase * (sampled + to_start + to_end) / sampled; + if shape.function == RangeFunction::Rate { + extrapolated / (shape.range_ms as f64 / 1000.0) + } else { + extrapolated + } + } + }; + per_series.insert(labels, value); + } + let Some((outer, by)) = shape.outer else { + return per_series; + }; + let mut groups: BTreeMap> = BTreeMap::new(); + for (labels, value) in per_series { + let key = labels + .into_iter() + .filter(|(name, _)| by.contains(name)) + .collect(); + groups.entry(key).or_default().push(value); + } + groups + .into_iter() + .map(|(key, values)| (key, aggregate(outer, &values))) + .collect() +} + +fn aggregate(f: Aggregation, values: &[f64]) -> f64 { + match f { + Aggregation::Sum => values.iter().sum(), + Aggregation::Count => values.len() as f64, + Aggregation::Min => values.iter().copied().fold(f64::INFINITY, f64::min), + Aggregation::Max => values.iter().copied().fold(f64::NEG_INFINITY, f64::max), + Aggregation::Avg => values.iter().sum::() / values.len() as f64, + } +} + +/// `got` equals `want` series by series, each value to `relative`. +fn assert_close( + what: &str, + got: &BTreeMap, + want: &BTreeMap, + relative: f64, +) { + assert_eq!( + got.keys().collect::>(), + want.keys().collect::>(), + "{what}: series differ" + ); + for (key, w) in want { + let g = got[key]; + assert!( + (g - w).abs() <= relative * w.abs().max(1.0), + "{what} {key:?}: {g} vs {w}" + ); + } +} + +fn answer(answers: &Answers, id: &str) -> BTreeMap { + answers.0.get(id).cloned().unwrap_or_default() +} + +fn key(pairs: &[(&str, &str)]) -> SeriesLabels { + (*series(pairs)).clone() +} + +#[test] +#[ignore = "needs a QuestDB server"] +fn the_server_is_the_pinned_version_with_one_thread_queries() { + let description: EngineDescription = engine().description(); + println!("{description:?}"); + assert_eq!( + description.version, + "10.2.0, JDK 25.0.2, Commit Hash 14d560b27e6911828f7315496e90d0209aec8831" + ); + assert!(description + .build_profile + .contains("cairo.sql.parallel.groupby.enabled=false")); + assert!(description + .build_profile + .contains("cairo.sql.parallel.filter.enabled=false")); +} + +/// The counter data of the ClickHouse conformance cases (x, y, z, w), each +/// series in its own job, over 600 s: resets, a reset to a lower nonzero +/// value, and a sparse series. +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 +} + +/// rate over 5 m at 600 s: native and approximate answer PromQL's rates +/// (x 1, y 417/299, z 642/299, w 1, the ClickHouse case's values). The views +/// keep per-bucket first and last values, so a reset inside one 10 s +/// bucket is not seen: z resets at 400 s and 500 s, each the last sample of +/// its bucket (391..400, 491..500), so z's increase loses the values before +/// them (399 and 494): (642 − 893) / 299. x and y reset on a bucket's first +/// sample, and the view sees those. +#[test] +#[ignore = "needs a QuestDB server"] +fn rate_is_promql_and_views_miss_resets_inside_a_bucket() { + let engine = engine(); + let samples = counter_samples(); + let spec = workload( + &["sum by (job) (rate(requests_total[5m]))"], + 10_000, + vec![record("requests_total", &["job"], 0)], + ); + for variant in VARIANTS { + let mut installed = engine.install(&spec, &arm(variant)).unwrap(); + for chunk in chunks(samples.clone(), 10_000) { + installed.ingest(&chunk).unwrap(); + } + let got = answer(&installed.evaluate(600_000).unwrap().0, "q0"); + let mut want = reference(&spec.queries[0].texts[0].text, &samples, 600_000); + assert_close( + "reference", + &want, + &[ + (key(&[("job", "x")]), 1.0), + (key(&[("job", "y")]), 417.0 / 299.0), + (key(&[("job", "z")]), 642.0 / 299.0), + (key(&[("job", "w")]), 1.0), + ] + .into_iter() + .collect(), + 1e-12, + ); + if variant == "materialized-views" { + want.insert(key(&[("job", "z")]), -251.0 / 299.0); + assert_eq!(installed.plan_summary().substitutions.len(), 1); + } + assert_close(variant, &got, &want, 1e-9); + } +} + +/// Every shape, evaluated with samples on both window edges: series a/i1 +/// value s, a/i2 2 s, b/i1 10 + s at each second s in 1..=180; windows of +/// 60 s evaluated every 10 s from 60 s. A sample on T − 60 s must be left +/// out and one on T counted; the ClickHouse case's values are checked by +/// hand at 120 s. +#[test] +#[ignore = "needs a QuestDB server"] +fn every_shape_reads_the_left_open_window() { + let texts = [ + "quantile_over_time(0.99, latency[1m])", + "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "max_over_time(latency[1m])", + "min_over_time(latency[1m])", + "avg_over_time(latency[1m])", + "sum by (job) (sum_over_time(latency[1m]))", + "sum by (job) (count_over_time(latency[1m]))", + "count_over_time(latency[1m])", + "max by (job) (max_over_time(latency[1m]))", + "sum by (job) (increase(requests_total[1m]))", + ]; + let mut samples = Vec::new(); + for s in 1..=180i64 { + for (job, instance, value) in [ + ("a", "i1", s as f64), + ("a", "i2", 2.0 * s as f64), + ("b", "i1", 10.0 + s as f64), + ] { + for metric in ["latency", "requests_total"] { + samples.push(Sample { + labels: series(&[("__name__", metric), ("job", job), ("instance", instance)]), + ts_ms: s * 1000, + value, + }); + } + } + } + let spec = workload( + &texts, + 10_000, + vec![ + record("latency", &["job", "instance"], 0), + record("requests_total", &["job", "instance"], 0), + ], + ); + // Hand values at 120 s (window 61..120): quantile 0.99 of a/i1 is + // 61 + 0.99 · 59; min of a/i1 61 (60 left out), max 120 (counted). + let at_120 = |i: usize| reference(texts[i], &samples, 120_000); + assert_eq!( + at_120(0)[&key(&[("job", "a"), ("instance", "i1")])], + 61.0 + 0.99 * 59.0 + ); + assert_eq!(at_120(3)[&key(&[("job", "a"), ("instance", "i1")])], 61.0); + assert_eq!(at_120(2)[&key(&[("job", "a"), ("instance", "i1")])], 120.0); + assert_eq!(at_120(6)[&key(&[("job", "a")])], 120.0); + let engine = engine(); + for variant in VARIANTS { + let mut installed = engine.install(&spec, &arm(variant)).unwrap(); + for chunk in chunks(samples.clone(), 10_000) { + let end_ms = chunk.end_ms; + installed.ingest(&chunk).unwrap(); + if end_ms < 60_000 { + continue; + } + let (answers, _) = installed.evaluate(end_ms).unwrap(); + for (i, text) in texts.iter().enumerate() { + let approximate = variant == "approximate" && text.contains("quantile"); + assert_close( + &format!("{variant} {text} at {end_ms}"), + &answer(&answers, &format!("q{i}")), + &reference_with(text, &samples, end_ms, approximate), + if approximate { 0.01 } else { 1e-9 }, + ); + } + } + } +} + +/// The harness's kit (`sum_over_time(probe[10s])`, +/// `count_over_time(probe[10s])`): answers are deterministic and windows +/// left-open, in every variant. +#[test] +#[ignore = "needs a QuestDB server"] +fn the_harness_conformance_kit_passes() { + struct WithVariant(QuestDbEngine, &'static str); + impl EngineUnderTest for WithVariant { + fn description(&self) -> EngineDescription { + self.0.description() + } + fn cpu_accounting(&self) -> CpuAccounting { + self.0.cpu_accounting() + } + fn install( + &self, + workload: &WorkloadSpec, + _: &ArmSpec, + ) -> Result, EngineError> { + self.0.install(workload, &arm(self.1)) + } + } + for variant in VARIANTS { + let mut engine = WithVariant(engine(), variant); + 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!("{variant}: {report:?}"); + let passed = report.expect("the kit passes").passed; + use aqpbm_core::harness::conformance::ConformanceCheck; + assert!(passed.contains(&ConformanceCheck::DeterministicAnswers)); + assert!(passed.contains(&ConformanceCheck::LeftOpenWindow)); + } +} + +/// Suite size, the showcase `joint` workload at 1 m: 1,000 series of +/// `latency` and 1,000 of `requests_total` in 10 jobs, 1 s samples for +/// 10 min, the five showcase queries evaluated every 10 s. Every +/// evaluation's answers equal the reference (approximate quantiles to 1 %). +/// The server cgroup's CPU grows and is never throttled; only the views +/// variant holds view bytes. +#[test] +#[ignore = "needs a QuestDB server"] +fn suite_sized_joint_workload() { + let path = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../suites/showcase-1m/joint.workload.json"); + let spec: WorkloadSpec = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let all: Vec = workload_chunks(&spec.data, 10_000) + .unwrap() + .map(|chunk| chunk.unwrap()) + .collect(); + let mut samples: Vec = Vec::new(); + let engine = engine(); + let CpuAccounting::Cgroup(source) = engine.cpu_accounting() else { + panic!("cgroup accounting"); + }; + for variant in VARIANTS { + samples.clear(); + let mut installed = engine.install(&spec, &arm(variant)).unwrap(); + let cpu_before = source.cpu().expect("the server's cgroup reads"); + let started = std::time::Instant::now(); + let (mut ingest, mut evaluate) = (Duration::ZERO, Duration::ZERO); + let mut evaluations = 0; + for chunk in &all { + samples.extend(chunk.samples.iter().cloned()); + let at = std::time::Instant::now(); + installed.ingest(chunk).unwrap(); + ingest += at.elapsed(); + let first_ms = spec.data_start_ms().unwrap() + 60_000; + if chunk.end_ms < first_ms { + continue; + } + let at = std::time::Instant::now(); + let (answers, _) = installed.evaluate(chunk.end_ms).unwrap(); + evaluate += at.elapsed(); + evaluations += 1; + // The reference at every 6th evaluation (each costs a scan of + // every sample in the test). + if evaluations % 6 != 1 && chunk.end_ms != all.last().unwrap().end_ms { + continue; + } + let recent: Vec = samples + .iter() + .filter(|s| s.ts_ms > chunk.end_ms - 60_000) + .cloned() + .collect(); + for query in &spec.queries { + let text = &query.texts[0].text; + let approximate = variant == "approximate" && text.contains("quantile"); + assert_close( + &format!("{variant} {} at {}", query.id, chunk.end_ms), + &answer(&answers, &query.id), + &reference_with(text, &recent, chunk.end_ms, approximate), + if approximate { 0.01 } else { 1e-9 }, + ); + } + } + let cpu_after = source.cpu().unwrap(); + let footprint = installed.footprint().unwrap(); + println!( + "{variant}: {evaluations} evaluations; wall {:.1} s (ingest {:.1} s, evaluate {:.1} s); \ + server cgroup CPU {:.1} s; footprint {footprint:?}", + started.elapsed().as_secs_f64(), + ingest.as_secs_f64(), + evaluate.as_secs_f64(), + (cpu_after.usage_ns - cpu_before.usage_ns) as f64 / 1e9 + ); + assert!(cpu_after.usage_ns > cpu_before.usage_ns); + assert_eq!(cpu_after.nr_throttled, cpu_before.nr_throttled); + assert!(footprint.raw_retained_bytes > 0); + assert_eq!(footprint.view_bytes > 0, variant == "materialized-views"); + } +}