diff --git a/docs/clickhouse-baselines.md b/docs/clickhouse-baselines.md new file mode 100644 index 00000000..8df41b02 --- /dev/null +++ b/docs/clickhouse-baselines.md @@ -0,0 +1,60 @@ +# ClickHouse baseline variants + +The `clickhouse` engine of `approxbench benchmark-external run` runs plans the planner made (`clickhouse.equivalent-only`, `clickhouse.with-substitutes`). +The baseline variants are SQL written the way ClickHouse users write it today, run by the same engine, so one report compares them: + +| Variant | What | Answers | +|---|---|---| +| `clickhouse.native` | the raw table only; every query in plain SQL at query time | exact | +| `clickhouse.hand-mv` | one materialized view per query, `-State` in the view and `-Merge` at query time; no view shared between queries | exact | +| `clickhouse.sketch-functions` | `clickhouse.native`, with quantiles by `quantileTDigest(q)` | approximate | +| `clickhouse.sketch-functions-dd` | `clickhouse.native`, with quantiles by `quantileDD(0.01, q)` | approximate | +| `clickhouse.sketch-mv` | `clickhouse.hand-mv`, with quantiles kept as `quantileTDigestState(q)` | approximate | + +`scripts/clickhouse_baselines.py ` writes them from the run directory's workloads, next to the planner's variants: + +```sh +ASAP_PLANNER=... scripts/plan-suite.sh suites/showcase-1m /data/run-1 +python3 scripts/clickhouse_baselines.py /data/run-1 +``` + +Each `plans//.plan.json` is a hand-written deployment (`{"clickhouse_hand_written": {...}}`, read by [clickhouse_hand_written](../system-bench/src/engines_external/clickhouse_hand_written.rs)): source tables and views, then one query per workload query, with the rule that wrote it and, for a sketch function, the approximation. +The engine reports each approximation as a substitution, so the report's `substitutions` column names it, and the exact variants allow none. +A sketch variant writes `.no-plan.json` for a workload with no quantile query, since its SQL would equal the exact variant's. +A query no rule covers is a `no-plan.json` with the reason, in every variant. + +## Rules + +PromQL shapes with a rule: `F_over_time(m[w])` (F in sum, count, min, max, avg), `quantile_over_time(q, m[w])`, `rate(m[w])`, `increase(m[w])`, each optionally under `A by (labels) (...)` (A in sum, min, max, avg, count). +Windows are `(t − w, t]`, as in PromQL and the planner. +Per-series answers group by every label of the metric (PromQL drops `__name__` under a function). + +| Inner function | `clickhouse.native` (query time) | `clickhouse.hand-mv` (one view per query) | +|---|---|---| +| sum / count / min / max / avg | `sum(value)`, `count()`, ... per series over `(t − w, t]`; `sum by` of sum or count, `min by` of min and `max by` of max are one `GROUP BY` of the kept labels | `sumState`, `countState`, ... per bucket, by the series' labels (by the kept labels for the one-`GROUP BY` pairs); `-Merge` over the buckets in `(t − w, t]` | +| quantile | `quantileExactInclusive(q)`: PromQL's interpolation at rank q·(n − 1) | `quantileExactInclusiveState(q)` per series and bucket (every value is kept) | +| rate / increase | Prometheus `extrapolatedRate` (v3.15.1) over each series' samples sorted by time, with reset correction | per insert, series and bucket, one row: count, first and last time and value, and the reset-corrected increase inside it (a MergeTree, not states); the query joins a series' rows in time order, then `extrapolatedRate` | +| `A by (labels)` | `A(value)` grouped by the labels, over the per-series result | the same, over the per-series result read from the view | + +| Sketch variant | Quantile rule | Error parameters | +|---|---|---| +| `clickhouse.sketch-functions` | `quantileTDigest(q)(value)` | t-digest with ClickHouse's fixed parameters: epsilon 0.01, at most 2,048 centroids, Float32 centroids ([`QuantileTDigest.h`](https://github.com/ClickHouse/ClickHouse/blob/ed6dc0f3556499bed6bb0c41bf48eeb01f7293fe/src/AggregateFunctions/QuantileTDigest.h#L85-L87)); no stated error bound | +| `clickhouse.sketch-functions-dd` | `quantileDD(0.01, q)(value)` | DDSketch, relative accuracy 0.01 at rank q·(n − 1) | +| `clickhouse.sketch-mv` | `quantileTDigestState(q)` per series and bucket, `quantileTDigestMerge(q)` over the window | as `quantileTDigest`, after merging one digest per bucket | + +No showcase query asks for a distinct count or top-k, so there is no rule for them yet; the functions for them would be `uniqCombined` (HyperLogLog, precision 17 by default) and `topK(k)` (Space-Saving). +The accuracy of every sketch variant is measured by the report (`--truth clickhouse/clickhouse.native`), not assumed. + +Physical choices: +- The raw table of `clickhouse.native` and the sketch-function variants has the planner lane's layout: a MergeTree sorted by the labels and `ts`, with a `minmax` index on `ts`. +- The raw table of `clickhouse.hand-mv` and `clickhouse.sketch-mv` is `ENGINE = Null`, ClickHouse's pre-aggregation pattern: its views see every insert, and no raw row is kept. +- A bucket is gcd(window, evaluation interval) wide (10 s for a 1 m window every 10 s, 1 min for a 1 h window every minute), keyed `(intDiv(ts_ms − 1, b) + 1) · b`, so a bucket is `(end − b, end]`. A view table is sorted by bucket end, then the labels. A query that reads buckets fails (`throwIf`) at an evaluation time that is not a bucket end. + +Where ClickHouse cannot match PromQL the way users write it: +- Counter resets: no built-in aggregate state merges PromQL's reset rule. `deltaSumTimestamp`, the usual choice, adds 0 for the step across a reset, where PromQL adds the value after it. `clickhouse.hand-mv` therefore keeps one row per insert, series and bucket and joins them in time order at query time; this needs each series inserted in time order, as the harness does, and two overlapping rows are an error. +- Floating-point sums run in another order than PromQL's, so they agree to rounding, not bit for bit. + +## Conformance + +`system-bench/tests/clickhouse_baselines_conformance.rs` runs every variant on a real server (`#[ignore]`; the same environment as `clickhouse_conformance`) and compares each evaluation with an oracle written in the test from PromQL's semantics: the showcase-1m workloads at full size, the showcase-1h workloads with 100 series, and a counter with resets inside and across buckets. +The exact variants must answer the oracle's series to 1e-9 relative; the sketch variants must answer the oracle's series, and the test prints their errors. diff --git a/docs/system-bench.md b/docs/system-bench.md index 6956a78f..aba388d8 100644 --- a/docs/system-bench.md +++ b/docs/system-bench.md @@ -36,7 +36,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/plan-suite.sh` prepares a run directory from a suite, and `scripts/clickhouse_baselines.py` adds the ClickHouse baseline variants to it. `scripts/one-shot-workload.sh` and `scripts/one-shot-clickbench.sh` prepare one and run every system for one-shot queries. `scripts/write-throughput-asapquery-precompute-engine.sh` measures the write throughput of an ASAPQuery precompute engine. @@ -80,6 +80,9 @@ DuckDB and PilotDB are installed by `scripts/install-*.sh`. A plan step the translator has no rule for is refused, so the translator is also the check of what the system can run. What each system can run is written down for the planner in [capabilities](../system-bench/capabilities/README.md). +The ClickHouse engine also runs hand-written deployments: `scripts/clickhouse_baselines.py` writes the ClickHouse baseline variants (`clickhouse.native`, `clickhouse.hand-mv` and three sketch variants), SQL written as ClickHouse users write it today, next to the planner's variants. +Their rules are in [ClickHouse baselines](./clickhouse-baselines.md). + ### planeval `planeval` plans each query of a workload with ASAPPlanner and runs the plan with ASAPPlanner's executor, in the same process. diff --git a/scripts/clickhouse_baselines.py b/scripts/clickhouse_baselines.py new file mode 100644 index 00000000..0574d457 --- /dev/null +++ b/scripts/clickhouse_baselines.py @@ -0,0 +1,456 @@ +#!/usr/bin/env python3 +"""Write the ClickHouse baseline variants of a benchmark-external run directory. + + scripts/clickhouse_baselines.py + +For each workload in /workloads/, writes hand-written ClickHouse +SQL, the way a ClickHouse user would write it today, as one variant each: + + plans/clickhouse.native/ raw MergeTree table, every query at query time, exact + plans/clickhouse.hand-mv/ one materialized view per query (no sharing), -State/-Merge, exact + plans/clickhouse.sketch-functions/ native, quantiles by quantileTDigest(q) + plans/clickhouse.sketch-functions-dd/ native, quantiles by quantileDD(0.01, q) + plans/clickhouse.sketch-mv/ hand-mv, quantiles kept as quantileTDigestState(q) + +Each .plan.json is a hand-written deployment the `clickhouse` engine +installs (`{"clickhouse_hand_written": {...}}`): source tables, statements, +then one SQL query per workload query with the parameter {t:Int64}. A +workload with a query no rule covers gets .no-plan.json with the +reason; a sketch variant over a workload with no quantile query too (its SQL +would equal the exact variant's). docs/clickhouse-baselines.md has the rule +table. +""" + +import json +import math +import os +import re +import shutil +import sys +from dataclasses import dataclass, field +from typing import List, Optional + +# Variant -> whether it approximates (its variant.json's substitutions_allowed). +VARIANTS = { + "clickhouse.native": False, + "clickhouse.hand-mv": False, + "clickhouse.sketch-functions": True, + "clickhouse.sketch-functions-dd": True, + "clickhouse.sketch-mv": True, +} + +# Per variant: is the query answered by a view per query, and which quantile. +LAYOUT = { + "clickhouse.native": ("native", "exact"), + "clickhouse.hand-mv": ("hand-mv", "exact"), + "clickhouse.sketch-functions": ("native", "tdigest"), + "clickhouse.sketch-functions-dd": ("native", "dd"), + "clickhouse.sketch-mv": ("hand-mv", "tdigest"), +} + +# quantileDD's relative accuracy: the one the ClickHouse docs' examples use. +DD_RELATIVE_ACCURACY = 0.01 + +APPROXIMATIONS = { + "tdigest": "quantileTDigest({q}): ClickHouse's t-digest (Float32 centroids, epsilon 0.01, " + "at most 2,048 centroids, src/AggregateFunctions/QuantileTDigest.h); no stated error bound", + "dd": "quantileDD(" + str(DD_RELATIVE_ACCURACY) + ", {q}): DDSketch with relative accuracy " + + str(DD_RELATIVE_ACCURACY) + " at rank q*(n-1)", +} + +OVER_TIME = {"sum", "count", "min", "max", "avg"} +OUTER = {"sum", "min", "max", "avg", "count"} +# (outer, inner) pairs a user writes as one GROUP BY over the samples: the +# outer aggregation of per-series values equals it over the samples. +COLLAPSED = {("sum", "sum"), ("sum", "count"), ("min", "min"), ("max", "max")} + +NOTES = { + "native": [ + "Raw samples in a MergeTree table sorted by the labels and ts, with a minmax index on ts " + "(the planner lane's raw-table layout); every query reads (t - w, t] at query time.", + "Float sums run in another order than PromQL's; they agree to rounding, not bit for bit.", + ], + "hand-mv": [ + "One materialized view per query, written for that query alone: queries never share a view, " + "even when two read the same per-series state.", + "The raw table is ENGINE = Null (ClickHouse's pre-aggregation pattern): no raw rows are kept.", + "Buckets are gcd(window, evaluation interval) wide, keyed (intDiv(ts_ms - 1, b) + 1) * b, so a " + "bucket is (end - b, end]; a query merges the buckets in (t - w, t] and fails (throwIf) at a t " + "that is not a bucket end.", + "rate/increase: no built-in state merges PromQL's counter-reset rule (deltaSumTimestamp drops " + "the first value after a reset), so the view stores one row per insert, series and bucket: " + "count, first and last time and value, and the reset-corrected increase inside it, in a " + "MergeTree; the query joins a series' rows in time order (an overlap is an error) and applies " + "Prometheus extrapolatedRate. Each series must be inserted in time order, as the harness does.", + "Float sums run in another order than PromQL's; they agree to rounding, not bit for bit.", + ], +} + + +class NoRule(Exception): + pass + + +@dataclass +class Shape: + text: str + outer: Optional[str] + by: List[str] + inner: str # sum, count, min, max, avg, quantile, rate, increase + metric: str + range_ms: int + level: Optional[float] = None + + +IDENT = r"[a-zA-Z_][a-zA-Z0-9_]*" +DURATION = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": 86_400_000} + + +def _range_ms(text): + match = re.fullmatch(r"(\d+)(ms|s|m|h|d)", text) + if not match: + raise NoRule(f"range [{text}]") + return int(match.group(1)) * DURATION[match.group(2)] + + +def parse_query(text): + """The rule shape of PromQL `text`; NoRule when no rule covers it.""" + body = text.strip() + outer, by = None, [] + match = re.fullmatch(rf"({IDENT})\s+by\s*\(([^)]*)\)\s*\((.*)\)", body) + if match: + outer = match.group(1) + by = [label.strip() for label in match.group(2).split(",") if label.strip()] + body = match.group(3).strip() + if outer not in OUTER or not by or not all(re.fullmatch(IDENT, label) for label in by): + raise NoRule(f"no rule for {text}") + match = re.fullmatch(rf"({IDENT})\((?:\s*([0-9.]+)\s*,)?\s*({IDENT})\[([^\]]+)\]\s*\)", body) + if not match: + raise NoRule(f"no rule for {text}") + function, level, metric, range_text = match.groups() + level = float(level) if level is not None else None + if function.endswith("_over_time") and function[:-len("_over_time")] in OVER_TIME and level is None: + inner = function[:-len("_over_time")] + elif function == "quantile_over_time" and level is not None and 0.0 <= level <= 1.0: + inner = "quantile" + elif function in ("rate", "increase") and level is None: + inner = function + else: + raise NoRule(f"no rule for {text}") + return Shape(text, outer, by, inner, metric, _range_ms(range_text), level) + + +def bucket_ms(window_ms, interval_ms): + return math.gcd(window_ms, interval_ms) + + +def quoted(name): + return "`" + name.replace("\\", "\\\\").replace("`", "\\`") + "`" + + +def columns(labels): + return ", ".join(quoted(label) for label in labels) + + +def table_name(metric): + return "src_" + re.sub(r"[^A-Za-z0-9_]", "_", metric) + + +def level_text(q): + return repr(float(q)).rstrip("0").rstrip(".") if q not in (0.0, 1.0) else str(int(q)) + + +def window_sql(range_ms): + return (f"ts > fromUnixTimestamp64Milli({{t:Int64}} - {range_ms}) " + f"AND ts <= fromUnixTimestamp64Milli({{t:Int64}})") + + +def grouped(labels, value, source): + """SELECT labels, value FROM source GROUP BY labels; without labels, one + row only when the input has one (PromQL gives no series for no input).""" + if not labels: + return f"SELECT {value} AS value FROM {source} HAVING count() > 0" + return f"SELECT {columns(labels)}, {value} AS value FROM {source} GROUP BY {columns(labels)}" + + +def outer_function(outer): + return "count()" if outer == "count" else f"{outer}(value)" + + +def quantile_function(kind, q, combinator=""): + q = level_text(q) + if kind == "exact": + return f"quantileExactInclusive{combinator}({q})" + if kind == "tdigest": + return f"quantileTDigest{combinator}({q})" + return f"quantileDD{combinator}({DD_RELATIVE_ACCURACY}, {q})" + + +def aggregate_function(inner, quantile_kind, level, combinator=""): + """The ClickHouse aggregate of an over_time or quantile inner function.""" + if inner == "quantile": + return quantile_function(quantile_kind, level, combinator) + return inner + combinator + + +def extrapolated(labels, inner_sql, range_ms, kind): + """Prometheus extrapolatedRate (promql/functions.go, v3.15.1) over inner_sql, + which gives per series n, first_ms, last_ms, v_first and the reset-corrected + increase of the samples in (t - range, t].""" + per_second = f" / {range_ms / 1000:g}" if kind == "rate" else "" + group = columns(labels) + start = f"(first_ms - ({{t:Int64}} - {range_ms})) / 1000" + end = "({t:Int64} - last_ms) / 1000" + return (f"SELECT {group}, increase * (sampled + least(d_start, d_zero) + d_end) / sampled{per_second} " + f"AS value FROM (SELECT {group}, increase, (last_ms - first_ms) / 1000 AS sampled, " + f"sampled / (n - 1) AS avg_gap, " + f"if({start} >= 1.1 * avg_gap, avg_gap / 2, {start}) AS d_start, " + f"if(increase > 0 AND v_first >= 0, sampled * v_first / increase, d_start) AS d_zero, " + f"if({end} >= 1.1 * avg_gap, avg_gap / 2, {end}) AS d_end " + f"FROM ({inner_sql}))") + + +# Reset-corrected increase of a time-sorted array `vals`: a drop means the +# counter restarted from 0, so the step adds the new value (PromQL). +INCREASE_OF_VALS = "arraySum(arrayMap((c, p) -> if(c < p, c, c - p), arrayPopFront(vals), arrayPopBack(vals)))" +SORTED_POINTS = ("arraySort(groupArray((toUnixTimestamp64Milli(ts), value))) AS pts, " + "arrayMap(p -> p.2, pts) AS vals, length(pts) AS n") + + +@dataclass +class Workload: + name: str + queries: list + labels: dict # metric -> label names in the data description's order + interval_ms: int + + +@dataclass +class Deployment: + sources: list = field(default_factory=list) + statements: list = field(default_factory=list) + stored_tables: list = field(default_factory=list) + queries: list = field(default_factory=list) + + +def read_workload(path): + with open(path) as file: + spec = json.load(file) + labels = {} + for record in spec.get("data", []): + labels[record["metric"]] = [label["name"] for label in record["description"]["labels"]] + if spec.get("metrics"): + raise NoRule("workload metrics given as metric specs: no rule (data descriptions only)") + intervals = {query["evaluation_interval_ms"] for query in spec["queries"]} + return Workload(spec["name"], spec["queries"], labels, intervals.pop() if len(intervals) == 1 else 0) + + +def query_text(query): + texts = [t["text"] for t in query["texts"] if t["language"] == "PromQl"] + if not texts: + raise NoRule(f"query {query['id']} has no PromQL text") + return texts[0] + + +def native_query(shape, labels, quantile_kind): + """(rule, sql) of one query at query time over the raw table.""" + source = f"{table_name(shape.metric)} WHERE {window_sql(shape.range_ms)}" + if shape.outer and (shape.outer, shape.inner) in COLLAPSED: + value = "count()" if shape.inner == "count" else f"{shape.inner}(value)" + return (f"{shape.outer} by of {shape.inner}_over_time: one GROUP BY over the samples", + grouped(shape.by, value, source)) + if shape.inner in ("rate", "increase"): + inner = (f"SELECT {columns(labels)}, {SORTED_POINTS}, pts[1].1 AS first_ms, pts[n].1 AS last_ms, " + f"vals[1] AS v_first, {INCREASE_OF_VALS} AS increase " + f"FROM {source} GROUP BY {columns(labels)} HAVING n >= 2") + per_series = extrapolated(labels, inner, shape.range_ms, shape.inner) + rule = f"{shape.inner}: extrapolatedRate over the sorted samples per series" + else: + function = aggregate_function(shape.inner, quantile_kind, shape.level) + value = "count()" if shape.inner == "count" else f"{function}(value)" + per_series = grouped(labels, value, source) + rule = f"{shape.inner}{'_over_time' if shape.inner != 'quantile' else ''} per series: {function}" + if shape.outer: + return (f"{shape.outer} by over ({rule})", grouped(shape.by, outer_function(shape.outer), f"({per_series})")) + return rule, per_series + + +def hand_mv_query(shape, labels, quantile_kind, number, bucket, deployment): + """(rule, sql) of one query over its own view; adds the view's statements.""" + src = table_name(shape.metric) + state_table, view = f"q{number}_state", f"q{number}_view" + window_end = f"(intDiv(toUnixTimestamp64Milli(ts) - 1, {bucket}) + 1) * {bucket} AS window_end_ms" + buckets = (f"window_end_ms > {{t:Int64}} - {shape.range_ms} AND window_end_ms <= {{t:Int64}} " + f"AND (SELECT throwIf({{t:Int64}} % {bucket} != 0, " + f"'the evaluation time is not a multiple of the bucket width, {bucket} ms')) = 0") + if shape.inner in ("rate", "increase"): + state_table = f"q{number}_segments" + deployment.statements.append( + f"CREATE TABLE {state_table} ({', '.join(quoted(l) + ' LowCardinality(String)' for l in labels)}, " + f"window_end_ms Int64, n UInt64, first_ms Int64, last_ms Int64, first_value Float64, " + f"last_value Float64, increase Float64) ENGINE = MergeTree " + f"ORDER BY (window_end_ms, {columns(labels)}, first_ms)") + deployment.statements.append( + f"CREATE MATERIALIZED VIEW {view} TO {state_table} AS SELECT {columns(labels)}, window_end_ms, n, " + f"first_ms, last_ms, first_value, last_value, increase FROM (SELECT {columns(labels)}, {window_end}, " + f"{SORTED_POINTS}, pts[1].1 AS first_ms, pts[n].1 AS last_ms, vals[1] AS first_value, " + f"vals[n] AS last_value, {INCREASE_OF_VALS} AS increase " + f"FROM {src} GROUP BY {columns(labels)}, window_end_ms)") + deployment.stored_tables.append(state_table) + group = columns(labels) + # The segments are read one row each, never merged as states: the + # step into a segment comes from the series' previous segment. + joined = (f"SELECT {group}, sum(seg_n) AS n, min(seg_first_ms) AS first_ms, max(seg_last_ms) AS last_ms, " + f"argMin(seg_first_value, seg_first_ms) AS v_first, " + f"sum(seg_increase) + sum(step_in) AS increase " + f"FROM (SELECT {group}, seg_n, seg_first_ms, seg_last_ms, seg_first_value, seg_increase, " + f"if(prev_last_ms < 0, 0, if(seg_first_value < prev_last_value, seg_first_value, " + f"seg_first_value - prev_last_value)) AS step_in, " + f"throwIf(prev_last_ms >= seg_first_ms, 'segments of a series overlap in time: insert each " + f"series in time order') AS overlap " + f"FROM (SELECT {group}, n AS seg_n, first_ms AS seg_first_ms, last_ms AS seg_last_ms, " + f"first_value AS seg_first_value, increase AS seg_increase, " + f"lagInFrame(last_value, 1, 0.) OVER w AS prev_last_value, " + f"lagInFrame(last_ms, 1, toInt64(-1)) OVER w AS prev_last_ms " + f"FROM {state_table} WHERE {buckets} " + f"WINDOW w AS (PARTITION BY {group} ORDER BY first_ms " + f"ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW))) " + f"GROUP BY {group} HAVING n >= 2 AND max(overlap) = 0") + per_series = extrapolated(labels, joined, shape.range_ms, shape.inner) + rule = f"{shape.inner}: per-insert segments in a view, joined in time order, extrapolatedRate" + if shape.outer: + return (f"{shape.outer} by over ({rule})", + grouped(shape.by, outer_function(shape.outer), f"({per_series})")) + return rule, per_series + + collapsed = shape.outer is not None and (shape.outer, shape.inner) in COLLAPSED + keys = shape.by if collapsed else labels + function = aggregate_function(shape.inner, quantile_kind, shape.level) + state_type = ("AggregateFunction(count)" if shape.inner == "count" + else f"AggregateFunction({function}, Float64)") + state = ("countState()" if shape.inner == "count" + else f"{aggregate_function(shape.inner, quantile_kind, shape.level, 'State')}(value)") + merge = f"{aggregate_function(shape.inner, quantile_kind, shape.level, 'Merge')}(state)" + key_columns = "".join(f"{quoted(k)} LowCardinality(String), " for k in keys) + deployment.statements.append( + f"CREATE TABLE {state_table} ({key_columns}window_end_ms Int64, state {state_type}) " + f"ENGINE = AggregatingMergeTree ORDER BY (window_end_ms{''.join(', ' + quoted(k) for k in keys)})") + select_keys = "".join(f"{quoted(k)}, " for k in keys) + deployment.statements.append( + f"CREATE MATERIALIZED VIEW {view} TO {state_table} AS SELECT {select_keys}{window_end}, " + f"{state} AS state FROM {src} GROUP BY {select_keys}window_end_ms") + deployment.stored_tables.append(state_table) + merged = grouped(keys, merge, f"{state_table} WHERE {buckets}") + if collapsed: + return f"{shape.outer} by of {shape.inner}_over_time: {state} by the kept labels", merged + rule = f"{shape.inner} per series: {state} per bucket, {merge} over the window" + if shape.outer: + return f"{shape.outer} by over ({rule})", grouped(shape.by, outer_function(shape.outer), f"({merged})") + return rule, merged + + +def deployment_of(workload, shapes, variant): + layout, quantile_kind = LAYOUT[variant] + deployment = Deployment() + metrics = [] + for shape in shapes: + if shape.metric not in workload.labels: + raise NoRule(f"metric {shape.metric} has no data description in the workload") + if shape.metric not in metrics: + metrics.append(shape.metric) + for metric in metrics: + labels = workload.labels[metric] + if {"ts", "value"} & set(labels): + raise NoRule(f"metric {metric} has a label named ts or value") + label_columns = "".join(f", {quoted(l)} LowCardinality(String)" for l in labels) + if layout == "native": + statement = (f"CREATE TABLE {table_name(metric)} (ts DateTime64(3, 'UTC'), value Float64{label_columns}, " + f"INDEX ts_minmax ts TYPE minmax GRANULARITY 1) " + f"ENGINE = MergeTree ORDER BY ({columns(labels)}, ts)") + else: + statement = (f"CREATE TABLE {table_name(metric)} (ts DateTime64(3, 'UTC'), value Float64{label_columns}) " + f"ENGINE = Null") + deployment.statements.append(statement) + deployment.sources.append({"metric": metric, "table": table_name(metric), "label_columns": labels}) + for number, (query, shape) in enumerate(zip(workload.queries, shapes), start=1): + labels = workload.labels[shape.metric] + if layout == "native": + rule, sql = native_query(shape, labels, quantile_kind) + step = 1 + else: + if shape.range_ms != query["window_ms"]: + raise NoRule(f"query {query['id']}: range {shape.range_ms} ms is not its window {query['window_ms']} ms") + step = bucket_ms(shape.range_ms, workload.interval_ms) + rule, sql = hand_mv_query(shape, labels, quantile_kind, number, step, deployment) + approximation = None + if shape.inner == "quantile" and quantile_kind != "exact": + approximation = APPROXIMATIONS[quantile_kind].format(q=level_text(shape.level)) + deployment.queries.append({"query_text": shape.text, "rule": f"{rule} ({variant})", "sql": sql, + "step_ms": step, "approximation": approximation}) + return deployment + + +def write_json(path, value): + with open(path, "w") as file: + json.dump(value, file, indent=1) + file.write("\n") + + +def generate(run): + """Writes the variants into run/plans/. Each variant is written in a + directory beside plans/ and then renamed into it, so an engine run that + reads plans/ meanwhile sees a variant whole or not at all.""" + plans = os.path.join(run, "plans") + existing = [v for v in VARIANTS if os.path.exists(os.path.join(plans, v))] + if existing: + sys.exit(f"{', '.join(existing)} exist under {plans}; runs are never overwritten") + staging = os.path.join(run, "clickhouse-baselines.partial") + if os.path.exists(staging): + shutil.rmtree(staging) + workloads_dir = os.path.join(run, "workloads") + names = sorted(f[:-len(".json")] for f in os.listdir(workloads_dir) if f.endswith(".json")) + for variant, approximate in VARIANTS.items(): + os.makedirs(os.path.join(staging, variant)) + write_json(os.path.join(staging, variant, "variant.json"), {"substitutions_allowed": approximate}) + for name in names: + try: + workload = read_workload(os.path.join(workloads_dir, f"{name}.json")) + if not workload.interval_ms: + raise NoRule("queries with different evaluation intervals") + shapes = [parse_query(query_text(query)) for query in workload.queries] + error = None + except NoRule as no_rule: + error = str(no_rule) + for variant in VARIANTS: + directory = os.path.join(staging, variant) + reason = error + if reason is None and LAYOUT[variant][1] != "exact" and not any(s.inner == "quantile" for s in shapes): + exact = "clickhouse.native" if LAYOUT[variant][0] == "native" else "clickhouse.hand-mv" + reason = f"no quantile query: the SQL of {variant} would equal {exact}'s" + if reason is None: + try: + deployment = deployment_of(workload, shapes, variant) + except NoRule as no_rule: + reason = str(no_rule) + if reason is not None: + write_json(os.path.join(directory, f"{name}.no-plan.json"), {"reason": reason}) + print(f"{name} {variant}: no plan ({reason})") + continue + write_json(os.path.join(directory, f"{name}.plan.json"), {"clickhouse_hand_written": { + "sources": deployment.sources, + "statements": deployment.statements, + "stored_tables": deployment.stored_tables, + "queries": deployment.queries, + "notes": NOTES[LAYOUT[variant][0]], + }}) + print(f"{name} {variant}: plan") + os.makedirs(plans, exist_ok=True) + for variant in VARIANTS: + os.rename(os.path.join(staging, variant), os.path.join(plans, variant)) + os.rmdir(staging) + + +if __name__ == "__main__": + if len(sys.argv) != 2: + sys.exit(__doc__) + generate(sys.argv[1]) diff --git a/scripts/test_clickhouse_baselines.py b/scripts/test_clickhouse_baselines.py new file mode 100644 index 00000000..7480a8ed --- /dev/null +++ b/scripts/test_clickhouse_baselines.py @@ -0,0 +1,150 @@ +import json +import os +import shutil +import sys +import tempfile +import unittest + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import clickhouse_baselines as cb # noqa: E402 + +REPO = os.path.dirname(HERE) +SUITES = os.path.join(REPO, "suites") + + +def run_directory(suite): + """A run directory holding `suite`'s workloads, as plan-suite.sh copies them.""" + run = tempfile.mkdtemp() + os.makedirs(os.path.join(run, "workloads")) + for name in sorted(os.listdir(os.path.join(SUITES, suite))): + if name.endswith(".workload.json"): + shutil.copy(os.path.join(SUITES, suite, name), + os.path.join(run, "workloads", name.replace(".workload.json", ".json"))) + return run + + +def read(path): + with open(path) as file: + return json.load(file) + + +class ParseTests(unittest.TestCase): + def test_showcase_shapes(self): + shape = cb.parse_query("sum by (job) (rate(requests_total[1m]))") + self.assertEqual((shape.outer, shape.by, shape.inner, shape.metric, shape.range_ms), + ("sum", ["job"], "rate", "requests_total", 60_000)) + shape = cb.parse_query("quantile_over_time(0.99, latency[1h])") + self.assertEqual((shape.outer, shape.inner, shape.level, shape.range_ms), + (None, "quantile", 0.99, 3_600_000)) + shape = cb.parse_query("avg by (job) (quantile_over_time(0.9, latency[1m]))") + self.assertEqual((shape.outer, shape.by, shape.inner, shape.level), ("avg", ["job"], "quantile", 0.9)) + self.assertEqual(cb.parse_query("max_over_time(latency[1m])").inner, "max") + self.assertEqual(cb.parse_query("sum by (job) (count_over_time(latency[1m]))").inner, "count") + + def test_unknown_shape_has_no_rule(self): + for text in ["topk(5, latency)", "irate(x[1m])", "sum without (job) (rate(x[1m]))", + "quantile_over_time(1.5, latency[1m])", "latency"]: + with self.assertRaises(cb.NoRule, msg=text): + cb.parse_query(text) + + def test_bucket_is_gcd_of_window_and_interval(self): + self.assertEqual(cb.bucket_ms(60_000, 10_000), 10_000) + self.assertEqual(cb.bucket_ms(3_600_000, 60_000), 60_000) + self.assertEqual(cb.bucket_ms(90_000, 60_000), 30_000) + + +class GenerateTests(unittest.TestCase): + def setUp(self): + self.run = run_directory("showcase-1m") + cb.generate(self.run) + + def tearDown(self): + shutil.rmtree(self.run) + + def variant(self, name): + return os.path.join(self.run, "plans", name) + + def test_five_variants_with_their_flags(self): + self.assertEqual(sorted(os.listdir(os.path.join(self.run, "plans"))), sorted(cb.VARIANTS)) + for name, approximate in cb.VARIANTS.items(): + self.assertEqual(read(os.path.join(self.variant(name), "variant.json")), + {"substitutions_allowed": approximate}) + + def test_every_workload_has_a_plan_or_a_no_plan(self): + workloads = sorted(n[:-5] for n in os.listdir(os.path.join(self.run, "workloads"))) + for name in cb.VARIANTS: + files = os.listdir(self.variant(name)) + for workload in workloads: + has = [f"{workload}.plan.json" in files, f"{workload}.no-plan.json" in files] + self.assertEqual(sum(has), 1, (name, workload, files)) + + def test_exact_variants_plan_every_workload(self): + for name in ["clickhouse.native", "clickhouse.hand-mv"]: + self.assertFalse([f for f in os.listdir(self.variant(name)) if f.endswith(".no-plan.json")], name) + + def test_sketch_variants_skip_workloads_without_a_quantile(self): + for name in ["clickhouse.sketch-functions", "clickhouse.sketch-functions-dd", "clickhouse.sketch-mv"]: + planned = sorted(f[:-10] for f in os.listdir(self.variant(name)) if f.endswith(".plan.json")) + self.assertEqual(planned, ["avg_quantile", "joint", "quantile", "quantile_rank"], name) + reason = read(os.path.join(self.variant(name), "sum_rate.no-plan.json"))["reason"] + self.assertIn("no quantile", reason) + + def test_plan_file_answers_the_workload_queries_in_order(self): + workload = read(os.path.join(self.run, "workloads", "joint.json")) + plan = read(os.path.join(self.variant("clickhouse.native"), "joint.plan.json"))["clickhouse_hand_written"] + self.assertEqual([q["query_text"] for q in plan["queries"]], + [q["texts"][0]["text"] for q in workload["queries"]]) + self.assertTrue(all(q["step_ms"] == 1 for q in plan["queries"])) + self.assertEqual(plan["stored_tables"], []) + self.assertEqual([s["metric"] for s in plan["sources"]], ["latency", "requests_total"]) + self.assertEqual(plan["sources"][0]["label_columns"], ["job", "instance"]) + + def test_hand_mv_has_one_view_per_query_and_a_null_source(self): + plan = read(os.path.join(self.variant("clickhouse.hand-mv"), "joint.plan.json"))["clickhouse_hand_written"] + views = [s for s in plan["statements"] if s.startswith("CREATE MATERIALIZED VIEW")] + self.assertEqual(len(views), 5) + self.assertEqual(len(plan["stored_tables"]), 5) + self.assertTrue(all("ENGINE = Null" in s for s in plan["statements"] if s.startswith("CREATE TABLE src_"))) + self.assertTrue(all(q["step_ms"] == 10_000 for q in plan["queries"])) + # q1 and q2 both keep per-series quantile states: no sharing across queries. + self.assertIn("quantileExactInclusiveState(0.99)", views[0]) + self.assertIn("quantileExactInclusiveState(0.5)", views[1]) + + def test_exact_variants_have_no_approximation_and_sketch_variants_name_theirs(self): + for name in ["clickhouse.native", "clickhouse.hand-mv"]: + plan = read(os.path.join(self.variant(name), "joint.plan.json"))["clickhouse_hand_written"] + self.assertTrue(all(q["approximation"] is None for q in plan["queries"]), name) + for name, function in [("clickhouse.sketch-functions", "quantileTDigest(0.99)"), + ("clickhouse.sketch-functions-dd", "quantileDD(0.01, 0.99)"), + ("clickhouse.sketch-mv", "quantileTDigestMerge(0.99)")]: + plan = read(os.path.join(self.variant(name), "joint.plan.json"))["clickhouse_hand_written"] + approximated = [q["query_text"] for q in plan["queries"] if q["approximation"]] + self.assertEqual(len(approximated), 3, name) + self.assertIn(function, plan["queries"][0]["sql"], name) + self.assertIsNone(plan["queries"][3]["approximation"], name) + + def test_rules_are_named(self): + plan = read(os.path.join(self.variant("clickhouse.hand-mv"), "sum_rate.plan.json"))["clickhouse_hand_written"] + self.assertIn("rate", plan["queries"][0]["rule"]) + self.assertTrue(plan["notes"]) + + def test_an_existing_variant_is_never_overwritten(self): + with self.assertRaises(SystemExit): + cb.generate(self.run) + + +class OneHourSuite(unittest.TestCase): + def test_buckets_of_the_hour_suite_are_a_minute(self): + run = run_directory("showcase-1h") + try: + cb.generate(run) + plan = read(os.path.join(run, "plans", "clickhouse.hand-mv", "joint.plan.json"))["clickhouse_hand_written"] + self.assertTrue(all(q["step_ms"] == 60_000 for q in plan["queries"])) + self.assertIn("3600000", plan["queries"][0]["sql"]) + finally: + shutil.rmtree(run) + + +if __name__ == "__main__": + unittest.main() diff --git a/system-bench/src/engines_external/clickhouse_hand_written.rs b/system-bench/src/engines_external/clickhouse_hand_written.rs new file mode 100644 index 00000000..d3a069a6 --- /dev/null +++ b/system-bench/src/engines_external/clickhouse_hand_written.rs @@ -0,0 +1,205 @@ +//! A hand-written ClickHouse deployment: SQL a person wrote for a workload, +//! installed by the `clickhouse` engine in place of a translated plan file. +//! `scripts/clickhouse_baselines.py` writes one per workload for the +//! ClickHouse baseline variants (`clickhouse.native`, `clickhouse.hand-mv`, +//! the sketch variants); `docs/clickhouse-baselines.md` has their rules. +//! +//! Example (`plans/clickhouse.native/max.plan.json`): +//! +//! ```json +//! {"clickhouse_hand_written": { +//! "sources": [{"metric": "latency", "table": "src_latency", "label_columns": ["job", "instance"]}], +//! "statements": ["CREATE TABLE src_latency (ts DateTime64(3, 'UTC'), value Float64, ...) ENGINE = MergeTree ..."], +//! "stored_tables": [], +//! "queries": [{"query_text": "max_over_time(latency[1m])", "rule": "max_over_time per series: max", +//! "sql": "SELECT `job`, `instance`, max(value) AS value FROM src_latency WHERE ... GROUP BY `job`, `instance`", +//! "step_ms": 1, "approximation": null}], +//! "notes": ["..."]}} +//! ``` +//! +//! Query i answers workload query i. Each query's SQL gives the label +//! columns, then `value`, at the parameter `{t:Int64}` (epoch ms); `t` must +//! be a multiple of its `step_ms` (the width of the buckets it reads; 1 when +//! it reads raw rows). An `approximation` is reported as a substitution. + +use serde::Deserialize; + +use aqpbm_core::harness::engine::WorkloadSpec; + +use super::clickhouse::SourceTable; + +/// The file's one top-level key. +const KEY: &str = "clickhouse_hand_written"; + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +struct HandWrittenFile { + clickhouse_hand_written: HandWrittenDeployment, +} + +/// A hand-written deployment; see the module docs. +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HandWrittenDeployment { + sources: Vec, + /// Run in order at install: source tables, view tables, views. + statements: Vec, + /// The tables views write: their bytes are the arm's view bytes. + stored_tables: Vec, + queries: Vec, + /// Where the SQL differs from how it could have been written, e.g. "the + /// raw table is Null". Shown in the plan summary only. + notes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +struct HandWrittenSource { + metric: String, + table: String, + label_columns: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Deserialize)] +#[serde(deny_unknown_fields)] +struct HandWrittenQuery { + query_text: String, + /// The generator's rule that wrote `sql`. + rule: String, + sql: String, + step_ms: u64, + /// How the answer differs from the exact one, e.g. "quantileTDigest(0.99): ...". + approximation: Option, +} + +/// What [`HandWrittenDeployment::check`] found for a workload. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CheckedQueries { + /// Per query, the workload query id it answers. + pub query_ids: Vec, + /// Per query, the step its evaluation time must be a multiple of. + pub steps_ms: Vec, +} + +/// The hand-written deployment in `text`; `None` when `text` is another +/// file (an ASAPPlanner plan file). +pub fn read(text: &str) -> Result, String> { + let value: serde_json::Value = serde_json::from_str(text).map_err(|e| e.to_string())?; + if value.get(KEY).is_none() { + return Ok(None); + } + let file: HandWrittenFile = serde_json::from_value(value).map_err(|e| e.to_string())?; + Ok(Some(file.clickhouse_hand_written)) +} + +impl HandWrittenDeployment { + /// Checks the deployment against `workload`: one query per workload + /// query, in order, each with one of that query's texts; no label + /// named like a sample column; every step at least 1 ms. + pub fn check(&self, workload: &WorkloadSpec) -> Result { + if self.queries.len() != workload.queries.len() { + return Err(format!( + "the hand-written deployment has {} queries but workload {} has {}", + self.queries.len(), + workload.name, + workload.queries.len() + )); + } + if let Some(source) = self.sources.iter().find(|source| { + source + .label_columns + .iter() + .any(|label| label == "ts" || label == "value") + }) { + return Err(format!( + "metric {} has a label named ts or value, the names of its sample columns", + source.metric + )); + } + let mut checked = CheckedQueries { + query_ids: Vec::new(), + steps_ms: Vec::new(), + }; + for (query, workload_query) in self.queries.iter().zip(&workload.queries) { + if !workload_query + .texts + .iter() + .any(|text| text.text == query.query_text) + { + let texts: Vec<&str> = workload_query + .texts + .iter() + .map(|t| t.text.as_str()) + .collect(); + return Err(format!( + "query {}: the hand-written SQL answers '{}', but the workload's texts are {texts:?}", + workload_query.id, query.query_text + )); + } + if query.step_ms == 0 { + return Err(format!("query {}: step_ms is 0", workload_query.id)); + } + checked.query_ids.push(workload_query.id.clone()); + checked.steps_ms.push(query.step_ms); + } + Ok(checked) + } + + pub fn sources(&self) -> Vec { + self.sources + .iter() + .map(|source| SourceTable { + metric: source.metric.clone(), + table: source.table.clone(), + label_columns: source.label_columns.clone(), + }) + .collect() + } + + pub fn statements(&self) -> &[String] { + &self.statements + } + + pub fn stored_tables(&self) -> &[String] { + &self.stored_tables + } + + /// Per query, its SQL. + pub fn query_sql(&self) -> Vec { + self.queries.iter().map(|query| query.sql.clone()).collect() + } + + /// One line per approximating query, e.g. `query 1 (): quantileTDigest(0.99): ...`. + pub fn approximations(&self) -> Vec { + self.queries + .iter() + .enumerate() + .filter_map(|(i, query)| { + let approximation = query.approximation.as_ref()?; + Some(format!("query {} ({}): {approximation}", i + 1, query.rule)) + }) + .collect() + } + + /// The notes as SQL comments, then every statement and query, each + /// ending with `;`. + pub fn script(&self) -> String { + let notes: String = self + .notes + .iter() + .map(|note| format!("-- {note}\n")) + .collect(); + let queries = self + .queries + .iter() + .map(|query| format!("-- {}\n{}", query.rule, query.sql)); + let statements: String = self + .statements + .iter() + .cloned() + .chain(queries) + .map(|statement| format!("{statement};\n\n")) + .collect(); + format!("{notes}\n{statements}") + } +} diff --git a/system-bench/src/engines_external/clickhouse_server.rs b/system-bench/src/engines_external/clickhouse_server.rs index 24818bff..fc07ff55 100644 --- a/system-bench/src/engines_external/clickhouse_server.rs +++ b/system-bench/src/engines_external/clickhouse_server.rs @@ -1,6 +1,7 @@ //! A ClickHouse server as an engine under test: each arm is a plan file -//! translated by [`super::clickhouse::translate`] and installed in a fresh -//! database of the server over HTTP. +//! translated by [`super::clickhouse::translate`], or a hand-written +//! deployment ([`super::clickhouse_hand_written`], the ClickHouse baseline +//! variants), installed in a fresh database of the server over HTTP. //! //! Example: an arm whose `engine_options` are `{"plan_file": "sum_over_time.plan.json"}` //! installs `src_latency` in database `bench_4711_0`. Each refresh chunk is @@ -32,6 +33,7 @@ use aqpbm_core::harness::engine::{ use super::clickhouse::{quoted, translate, SourceTable, INSERT_SETTINGS, SERIES_IDENTITY}; use super::clickhouse_connection::ClickHouseConnectionOptions; use super::clickhouse_connection::{ClickHouseConnection, Http}; +use super::clickhouse_hand_written::{read as read_hand_written, HandWrittenDeployment}; use super::plan_file::{PlanFile, PlanOperator, RangeKind}; use super::server_cgroup::ServerCgroupOptions; use aqpbm_core::harness::protocol::Protocol; @@ -123,13 +125,16 @@ impl EngineUnderTest for ClickHouseEngine { .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 = PlanFile::from_json(&text) - .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; - let query_ids = query_ids_of(&plan, workload)?; - let deployment = - translate(&plan).map_err(|error| EngineError(format!("plan file {path}: {error}")))?; - check_evaluation_times(workload, &deployment.query_time_steps_ms)?; - if let Some(source) = deployment.sources.iter().find(|source| { + let parts = match read_hand_written(&text) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))? + { + Some(hand_written) => hand_written_parts(&hand_written, workload) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?, + None => plan_parts(&text, workload) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?, + }; + check_evaluation_times(workload, &parts.steps_ms)?; + if let Some(source) = parts.sources.iter().find(|source| { source .label_columns .iter() @@ -153,7 +158,7 @@ impl EngineUnderTest for ClickHouseEngine { http: self.http.clone(), database, max_threads: self.server.max_threads, - sources: deployment + sources: parts .sources .iter() .map(|source| SourceInsert { @@ -161,41 +166,111 @@ impl EngineUnderTest for ClickHouseEngine { source: source.clone(), }) .collect(), - queries: query_ids + queries: parts + .queries .into_iter() - .zip(&deployment.queries) - .zip(&plan.roots) - .map(|((id, sql), &root)| RootQuery { + .map(|query| RootQuery { asked_from_ms: workload - .query(&id) - .and_then(|query| workload.asked_from_ms(query)), - id, - sql: sql.clone(), - keeps_metric_name: matches!( - plan.nodes[root].operator, - PlanOperator::TimeRange { - kind: RangeKind::Instant, - .. - } - ), + .query(&query.id) + .and_then(|q| workload.asked_from_ms(q)), + ..query }) .collect(), - stored_tables: deployment.stored_tables.clone(), - summary: plan_summary(&plan, &deployment), + stored_tables: parts.stored_tables, + summary: parts.summary, }; // TTL statements are never applied: the harness replays data, and a // TTL deletes by wall-clock time. - for statement in deployment - .tables - .iter() - .chain(&deployment.materialized_views) - { + for statement in &parts.statements { installed.run(statement, &[], None)?; } Ok(Box::new(installed)) } } +/// What an arm installs and runs, from a plan file or a hand-written +/// deployment. +struct ArmParts { + sources: Vec, + /// Run in order at install. + statements: Vec, + /// Per workload query, in order (`asked_from_ms` not yet set). + queries: Vec, + /// Per query, the step its evaluation time must be a multiple of. + steps_ms: Vec, + stored_tables: Vec, + summary: PlanSummary, +} + +/// An ASAPPlanner plan file, translated. +fn plan_parts(text: &str, workload: &WorkloadSpec) -> Result { + let plan = PlanFile::from_json(text).map_err(|error| error.to_string())?; + let query_ids = query_ids_of(&plan, workload).map_err(|EngineError(error)| error)?; + let deployment = translate(&plan).map_err(|error| error.to_string())?; + Ok(ArmParts { + sources: deployment.sources.clone(), + statements: deployment + .tables + .iter() + .chain(&deployment.materialized_views) + .cloned() + .collect(), + queries: query_ids + .into_iter() + .zip(&deployment.queries) + .zip(&plan.roots) + .map(|((id, sql), &root)| RootQuery { + id, + sql: sql.clone(), + keeps_metric_name: matches!( + plan.nodes[root].operator, + PlanOperator::TimeRange { + kind: RangeKind::Instant, + .. + } + ), + asked_from_ms: None, + }) + .collect(), + steps_ms: deployment.query_time_steps_ms.clone(), + stored_tables: deployment.stored_tables.clone(), + summary: plan_summary(&plan, &deployment), + }) +} + +/// A hand-written deployment. Its queries are functions or aggregations of +/// range selectors, so none keeps `__name__`. +fn hand_written_parts( + hand_written: &HandWrittenDeployment, + workload: &WorkloadSpec, +) -> Result { + let checked = hand_written.check(workload)?; + Ok(ArmParts { + sources: hand_written.sources(), + statements: hand_written.statements().to_vec(), + queries: checked + .query_ids + .into_iter() + .zip(hand_written.query_sql()) + .map(|(id, sql)| RootQuery { + id, + sql, + keeps_metric_name: false, + asked_from_ms: None, + }) + .collect(), + steps_ms: checked.steps_ms, + stored_tables: hand_written.stored_tables().to_vec(), + summary: PlanSummary { + text: hand_written.script(), + node_kinds: Vec::new(), + stored_outputs: hand_written.stored_tables().to_vec(), + substitutions: hand_written.approximations(), + sharing_lost: Vec::new(), + }, + }) +} + /// Every evaluation time is a multiple of the evaluation interval from an /// aligned data start ([`aqpbm_core::harness::arm_run::ArmSchedule`]), so a query /// that reads stored windows answers right only when its step divides the diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 6bf0b9b2..702b66b6 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -17,6 +17,7 @@ pub mod asapquery_backend_server; pub mod asapquery_precompute_engine_server; pub mod clickhouse; pub mod clickhouse_connection; +pub mod clickhouse_hand_written; pub mod clickhouse_query_text; pub mod clickhouse_server; pub mod druid_sql; diff --git a/system-bench/tests/clickhouse_baselines_conformance.rs b/system-bench/tests/clickhouse_baselines_conformance.rs new file mode 100644 index 00000000..f980020d --- /dev/null +++ b/system-bench/tests/clickhouse_baselines_conformance.rs @@ -0,0 +1,527 @@ +//! Conformance of the ClickHouse baseline variants (`scripts/clickhouse_baselines.py`) +//! on a real server (`#[ignore]`: set `AQPBM_CLICKHOUSE_URL`, +//! `AQPBM_SERVER_CGROUP_DIRECTORY` and, for a server on another host, +//! `AQPBM_SERVER_SSH_HOST`, as for `clickhouse_conformance`). +//! +//! Each case generates the variants for suite workloads, installs every +//! variant through the `clickhouse` engine, feeds the harness's chunks and +//! compares every evaluation with an oracle written here from PromQL's +//! semantics: windows `(t − w, t]`, `quantile_over_time` interpolating at rank +//! q·(n − 1), and Prometheus `extrapolatedRate` with reset correction. The +//! exact variants must give the oracle's series, each to 1e-9 relative; the +//! sketch variants must give the oracle's series, and their errors are +//! printed (measured, not assumed). Run with `--test-threads 1 --nocapture`. + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::Arc; +use std::time::Duration; + +use aqpbm_core::harness::arm_run::ArmSchedule; +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::data::{workload_sample_chunks, Sample}; +use aqpbm_core::harness::engine::{ + ArmSpec, EngineUnderTest, InstalledArm, SampleChunk, SeriesLabels, WorkloadSpec, +}; +use serde_json::{json, Value}; +use system_bench::engines_external::clickhouse_connection::ClickHouseConnection; +use system_bench::engines_external::clickhouse_server::{ClickHouseEngine, ClickHouseServer}; + +const EXACT: [&str; 2] = ["clickhouse.native", "clickhouse.hand-mv"]; +const SKETCH: [&str; 3] = [ + "clickhouse.sketch-functions", + "clickhouse.sketch-functions-dd", + "clickhouse.sketch-mv", +]; + +fn engine() -> ClickHouseEngine { + let cgroup_directory: PathBuf = std::env::var("AQPBM_SERVER_CGROUP_DIRECTORY") + .expect("AQPBM_SERVER_CGROUP_DIRECTORY") + .into(); + ClickHouseEngine::new(ClickHouseServer { + connection: ClickHouseConnection { + url: std::env::var("AQPBM_CLICKHOUSE_URL").expect("AQPBM_CLICKHOUSE_URL"), + statement_timeout: Duration::from_secs(600), + }, + 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), + }, + max_threads: 1, + }) + .expect("the server answers") +} + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .unwrap() + .into() +} + +/// A run directory with `workloads` (each changed by `shrink`), and the +/// baseline variants generated by the script. +fn generated(name: &str, workloads: Vec) -> PathBuf { + let run = std::env::temp_dir().join(format!("ch-baselines-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&run); + std::fs::create_dir_all(run.join("workloads")).unwrap(); + for workload in workloads { + let file = run.join(format!( + "workloads/{}.json", + workload["name"].as_str().unwrap() + )); + std::fs::write(file, workload.to_string()).unwrap(); + } + let status = Command::new("python3") + .arg(repo().join("scripts/clickhouse_baselines.py")) + .arg(&run) + .status() + .expect("python3 runs"); + assert!(status.success(), "the generator failed"); + run +} + +fn suite_workloads(suite: &str, shrink: impl Fn(&mut Value)) -> Vec { + let dir = repo().join("suites").join(suite); + let mut names: Vec<_> = std::fs::read_dir(&dir) + .unwrap() + .map(|e| e.unwrap().file_name().into_string().unwrap()) + .filter(|n| n.ends_with(".workload.json")) + .collect(); + names.sort(); + names + .iter() + .map(|n| { + let mut w: Value = + serde_json::from_str(&std::fs::read_to_string(dir.join(n)).unwrap()).unwrap(); + shrink(&mut w); + w + }) + .collect() +} + +/// One query's PromQL shape, parsed as the generator's rule table names it. +#[derive(Debug, Clone)] +struct Shape { + outer: Option<(String, Vec)>, + inner: String, + level: f64, + metric: String, + range_ms: i64, +} + +fn parse(text: &str) -> Shape { + let text = text.trim(); + let (outer, rest) = match text.split_once(" by (") { + Some((aggregation, rest)) => { + let (labels, rest) = rest.split_once(") (").unwrap(); + let labels = labels.split(',').map(|l| l.trim().to_string()).collect(); + ( + Some((aggregation.trim().to_string(), labels)), + rest.strip_suffix(')').unwrap(), + ) + } + None => (None, text), + }; + let (function, args) = rest.split_once('(').unwrap(); + let args = args.strip_suffix(')').unwrap(); + let (level, selector) = match args.split_once(',') { + Some((q, s)) => (q.trim().parse().unwrap(), s.trim()), + None => (0.0, args.trim()), + }; + let (metric, range) = selector.split_once('[').unwrap(); + let range = range.strip_suffix(']').unwrap(); + let range_ms = match range.split_at(range.len() - 1) { + (n, "m") => n.parse::().unwrap() * 60_000, + (n, "h") => n.parse::().unwrap() * 3_600_000, + (n, "s") => n.parse::().unwrap() * 1_000, + _ => panic!("range {range}"), + }; + Shape { + outer, + inner: function.trim_end_matches("_over_time").to_string(), + level, + metric: metric.trim().to_string(), + range_ms, + } +} + +/// The samples seen so far, per metric, per series (labels without `__name__`). +#[derive(Default)] +struct Store(BTreeMap>>); + +impl Store { + fn add(&mut self, sample: &Sample) { + let mut labels = (*sample.labels).clone(); + let metric = labels.remove("__name__").unwrap(); + self.0 + .entry(metric) + .or_default() + .entry(labels) + .or_default() + .push((sample.ts_ms, sample.value)); + } +} + +fn quantile(mut values: Vec, q: f64) -> f64 { + values.sort_by(f64::total_cmp); + let rank = q * (values.len() - 1) as f64; + let lower = rank.floor() as usize; + let upper = (lower + 1).min(values.len() - 1); + let weight = rank - lower as f64; + values[lower] * (1.0 - weight) + values[upper] * weight +} + +/// Prometheus `extrapolatedRate` (v3.15.1) over `points` in `(t − range, t]`. +fn extrapolated(points: &[(i64, f64)], t: i64, range_ms: i64, rate: bool) -> Option { + if points.len() < 2 { + return None; + } + let (first_ms, first) = points[0]; + let (last_ms, _) = points[points.len() - 1]; + let mut increase = points[points.len() - 1].1 - first; + for pair in points.windows(2) { + if pair[1].1 < pair[0].1 { + increase += pair[0].1; + } + } + let sampled = (last_ms - first_ms) as f64 / 1000.0; + let average = sampled / (points.len() - 1) as f64; + let mut to_start = (first_ms - (t - range_ms)) as f64 / 1000.0; + let mut to_end = (t - last_ms) as f64 / 1000.0; + if to_start >= 1.1 * average { + to_start = average / 2.0; + } + if increase > 0.0 && first >= 0.0 { + to_start = to_start.min(sampled * first / increase); + } + if to_end >= 1.1 * average { + to_end = average / 2.0; + } + let mut value = increase * (sampled + to_start + to_end) / sampled; + if rate { + value /= range_ms as f64 / 1000.0; + } + Some(value) +} + +/// The oracle's answer of `shape` at `t`. +fn oracle(shape: &Shape, store: &Store, t: i64) -> BTreeMap { + let mut per_series = BTreeMap::new(); + for (labels, points) in store.0.get(&shape.metric).into_iter().flatten() { + let from = points.partition_point(|&(ts, _)| ts <= t - shape.range_ms); + let to = points.partition_point(|&(ts, _)| ts <= t); + let window = &points[from..to]; + if window.is_empty() { + continue; + } + let values: Vec = window.iter().map(|&(_, v)| v).collect(); + let value = match shape.inner.as_str() { + "sum" => values.iter().sum(), + "count" => values.len() as f64, + "min" => values.iter().copied().fold(f64::INFINITY, f64::min), + "max" => values.iter().copied().fold(f64::NEG_INFINITY, f64::max), + "avg" => values.iter().sum::() / values.len() as f64, + "quantile" => quantile(values, shape.level), + "rate" | "increase" => { + match extrapolated(window, t, shape.range_ms, shape.inner == "rate") { + Some(value) => value, + None => continue, + } + } + other => panic!("no oracle for {other}"), + }; + per_series.insert(labels.clone(), value); + } + let Some((aggregation, 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, value)| by.contains(name) && !value.is_empty()) + .collect(); + groups.entry(key).or_default().push(value); + } + groups + .into_iter() + .map(|(key, values)| { + let value = match aggregation.as_str() { + "sum" => values.iter().sum(), + "avg" => values.iter().sum::() / values.len() as f64, + "min" => values.iter().copied().fold(f64::INFINITY, f64::min), + "max" => values.iter().copied().fold(f64::NEG_INFINITY, f64::max), + "count" => values.len() as f64, + other => panic!("no oracle for {other}"), + }; + (key, value) + }) + .collect() +} + +/// Errors of one (variant, query) over every evaluation. +#[derive(Default, Debug)] +struct Errors { + points: usize, + missing: usize, + extra: usize, + not_finite: usize, + relative: Vec, +} + +impl Errors { + fn compare( + &mut self, + got: &BTreeMap, + expected: &BTreeMap, + ) { + for (labels, &want) in expected { + self.points += 1; + match got.get(labels) { + None => self.missing += 1, + Some(&value) if !value.is_finite() => self.not_finite += 1, + Some(&value) => self.relative.push(if want == 0.0 { + value.abs() + } else { + ((value - want) / want).abs() + }), + } + } + self.extra += got.keys().filter(|l| !expected.contains_key(*l)).count(); + } + + fn max(&self) -> f64 { + self.relative.iter().copied().fold(0.0, f64::max) + } + + fn median(&self) -> f64 { + let mut sorted = self.relative.clone(); + sorted.sort_by(f64::total_cmp); + sorted.get(sorted.len() / 2).copied().unwrap_or(0.0) + } +} + +/// Runs every variant that has a plan for `workload` side by side over its +/// chunks (or `chunks` when given) and checks them against the oracle. +fn check_workload( + engine: &ClickHouseEngine, + run: &Path, + workload: &str, + chunks: Option>, +) -> BTreeMap<(String, String), Errors> { + let spec: WorkloadSpec = serde_json::from_str( + &std::fs::read_to_string(run.join(format!("workloads/{workload}.json"))).unwrap(), + ) + .unwrap(); + let schedule = ArmSchedule::for_workload(&spec).unwrap(); + let mut arms: Vec<(String, Box)> = Vec::new(); + for variant in EXACT.iter().chain(&SKETCH) { + let plan = run.join(format!("plans/{variant}/{workload}.plan.json")); + if !plan.exists() { + assert!( + SKETCH.contains(variant), + "{variant} has no plan for {workload}" + ); + continue; + } + let arm = ArmSpec { + name: variant.to_string(), + raw_data_retained: true, + engine_options: json!({ "plan_file": plan }), + }; + let installed = engine + .install(&spec, &arm) + .unwrap_or_else(|e| panic!("{workload} {variant}: {e}")); + arms.push((variant.to_string(), installed)); + } + let shapes: Vec<(String, Shape)> = spec + .queries + .iter() + .map(|q| (q.id.clone(), parse(&q.texts[0].text))) + .collect(); + let chunks: Vec = match chunks { + Some(chunks) => chunks, + None => workload_sample_chunks(&spec, Path::new("."), schedule.refresh_ms) + .unwrap() + .map(Result::unwrap) + .collect(), + }; + let mut store = Store::default(); + let mut errors: BTreeMap<(String, String), Errors> = BTreeMap::new(); + for chunk in &chunks { + for sample in &chunk.samples { + store.add(sample); + } + for (_, arm) in &mut arms { + arm.ingest(chunk).unwrap(); + } + if !schedule.evaluate_at_ms.contains(&chunk.end_ms) { + continue; + } + let expected: Vec<_> = shapes + .iter() + .map(|(id, shape)| (id.clone(), oracle(shape, &store, chunk.end_ms))) + .collect(); + for (variant, arm) in &mut arms { + let (answers, _) = arm + .evaluate(chunk.end_ms) + .unwrap_or_else(|e| panic!("{workload} {variant} at {}: {e}", chunk.end_ms)); + for (id, want) in &expected { + errors + .entry((variant.clone(), id.clone())) + .or_default() + .compare(&answers.0[id], want); + } + } + } + for ((variant, query), e) in &errors { + println!( + "{workload} {query} {variant}: points {}, missing {}, extra {}, not finite {}, \ + max relative error {:.3e}, median {:.3e}", + e.points, + e.missing, + e.extra, + e.not_finite, + e.max(), + e.median() + ); + } + errors +} + +fn assert_conformance(errors: &BTreeMap<(String, String), Errors>) { + for ((variant, query), e) in errors { + assert!(e.points > 0, "{variant} {query}: no points"); + assert_eq!( + (e.missing, e.extra, e.not_finite), + (0, 0, 0), + "{variant} {query}: {e:?}" + ); + if EXACT.contains(&variant.as_str()) { + assert!( + e.max() <= 1e-9, + "{variant} {query}: max relative error {}", + e.max() + ); + } + } +} + +#[test] +#[ignore = "needs a ClickHouse server"] +fn showcase_1m_variants_answer_promql() { + let run = generated("1m", suite_workloads("showcase-1m", |_| {})); + let engine = engine(); + for workload in [ + "avg_quantile", + "count", + "joint", + "max", + "quantile", + "quantile_rank", + "sum_over_time", + "sum_rate", + ] { + assert_conformance(&check_workload(&engine, &run, workload, None)); + } +} + +#[test] +#[ignore = "needs a ClickHouse server"] +fn showcase_1h_variants_answer_promql() { + // 100 series instead of 1,000: the hour windows and the one-minute + // buckets are the suite's. + let run = generated( + "1h", + suite_workloads("showcase-1h", |w| { + for record in w["data"].as_array_mut().unwrap() { + record["description"]["series_num"] = json!(100); + } + }), + ); + let engine = engine(); + for workload in ["joint", "sum_rate", "quantile", "sum_over_time"] { + assert_conformance(&check_workload(&engine, &run, workload, None)); + } +} + +/// Counter resets inside a bucket and across buckets: the hand-written +/// views answer PromQL's increase, where `deltaSumTimestamp` would drop the +/// first value after each reset. +#[test] +#[ignore = "needs a ClickHouse server"] +fn rate_and_increase_with_counter_resets() { + let workload = json!({ + "name": "resets", + "queries": [ + {"id": "q1", "texts": [{"language": "PromQl", "text": "rate(c[1m])"}], + "window_ms": 60000, "evaluation_interval_ms": 10000}, + {"id": "q2", "texts": [{"language": "PromQl", "text": "sum by (job) (increase(c[1m]))"}], + "window_ms": 60000, "evaluation_interval_ms": 10000} + ], + "data": [{"metric": "c", "description": { + "labels": [{"name": "job", "cardinality": 1}, {"name": "instance", "cardinality": 3}], + "series_num": 3, "start_ms": 1_700_000_040_000_i64, "sample_interval_ms": 1000, + "duration_ms": 180000, + "value_distribution": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 10.0, "seed": 1}, + "counter": true, "seed": 2}}] + }); + let run = generated("resets", vec![workload]); + // Three series every 2 s; x resets at 15 s (inside a bucket) and at + // 20 s (on a bucket edge), y every 25 s, z never. + let start = 1_700_000_040_000_i64; + let series = |instance: &str| { + Arc::new(SeriesLabels::from([ + ("__name__".to_string(), "c".to_string()), + ("job".to_string(), "a".to_string()), + ("instance".to_string(), instance.to_string()), + ])) + }; + let mut samples = Vec::new(); + let (mut x, mut y, mut z) = (100.0, 5.0, 0.0); + for step in 1..=90_i64 { + let ts = start + step * 2_000; + let second = step * 2; + x = if second == 16 || second == 20 { + 3.0 + } else { + x + 7.0 + }; + y = if second % 26 == 0 { 1.0 } else { y + 2.5 }; + z += 1.5; + for (name, value) in [("x", x), ("y", y), ("z", z)] { + samples.push(Sample { + labels: series(name), + ts_ms: ts, + value, + }); + } + } + let mut chunks: Vec = Vec::new(); + for sample in samples { + let end_ms = (sample.ts_ms - start + 9_999) / 10_000 * 10_000 + start; + match chunks.last_mut() { + Some(chunk) if chunk.end_ms == end_ms => chunk.samples.push(sample), + _ => chunks.push(SampleChunk { + end_ms, + samples: vec![sample], + }), + } + } + let engine = engine(); + let errors = check_workload(&engine, &run, "resets", Some(chunks)); + assert_eq!( + errors + .keys() + .map(|(v, _)| v.as_str()) + .collect::>(), + EXACT.into_iter().collect() + ); + assert_conformance(&errors); +} diff --git a/system-bench/tests/clickhouse_hand_written.rs b/system-bench/tests/clickhouse_hand_written.rs new file mode 100644 index 00000000..fa8fb48a --- /dev/null +++ b/system-bench/tests/clickhouse_hand_written.rs @@ -0,0 +1,138 @@ +//! The hand-written ClickHouse deployment file (`scripts/clickhouse_baselines.py` +//! writes one per workload and baseline variant), as the `clickhouse` engine +//! reads it. No server needed. + +use aqpbm_core::harness::engine::{QueryLanguage, QueryText, WorkloadQuery, WorkloadSpec}; +use serde_json::json; +use system_bench::engines_external::clickhouse_hand_written::{read, HandWrittenDeployment}; + +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![], + ) +} + +fn file(label_columns: &[&str], approximation: Option<&str>) -> serde_json::Value { + json!({"clickhouse_hand_written": { + "sources": [{"metric": "latency", "table": "src_latency", "label_columns": label_columns}], + "statements": [ + "CREATE TABLE src_latency (ts DateTime64(3, 'UTC'), value Float64, `job` LowCardinality(String)) ENGINE = Null", + "CREATE TABLE q1_state (window_end_ms Int64, `job` LowCardinality(String), state AggregateFunction(sum, Float64)) ENGINE = AggregatingMergeTree ORDER BY (window_end_ms, `job`)", + "CREATE MATERIALIZED VIEW q1_view TO q1_state AS SELECT 1" + ], + "stored_tables": ["q1_state"], + "queries": [{ + "query_text": "sum by (job) (sum_over_time(latency[1m]))", + "rule": "sum by of sum_over_time / hand-mv", + "sql": "SELECT `job`, sumMerge(state) AS value FROM q1_state GROUP BY `job`", + "step_ms": 10000, + "approximation": approximation + }], + "notes": ["the raw table is Null"] + }}) +} + +fn deployment(value: serde_json::Value) -> HandWrittenDeployment { + read(&value.to_string()) + .expect("reads") + .expect("a hand-written file") +} + +#[test] +fn a_planner_plan_file_is_not_hand_written() { + assert!(read(r#"{"wire_version": 15, "nodes": []}"#) + .expect("reads") + .is_none()); +} + +#[test] +fn reads_sources_statements_queries_and_steps() { + let deployment = deployment(file(&["job"], None)); + let checked = deployment + .check(&workload(&["sum by (job) (sum_over_time(latency[1m]))"])) + .expect("matches the workload"); + assert_eq!(checked.query_ids, vec!["q1".to_string()]); + assert_eq!(checked.steps_ms, vec![10_000]); + assert_eq!(deployment.sources()[0].table, "src_latency"); + assert_eq!( + deployment.sources()[0].label_columns, + vec!["job".to_string()] + ); + assert_eq!(deployment.statements().len(), 3); + assert_eq!(deployment.stored_tables(), &["q1_state".to_string()]); + assert!(deployment.approximations().is_empty()); + assert!(deployment.script().contains("sumMerge(state)")); +} + +#[test] +fn an_approximation_is_reported_as_a_substitution() { + let deployment = deployment(file(&["job"], Some("quantileTDigest(0.99): t-digest"))); + assert_eq!( + deployment.approximations(), + vec![ + "query 1 (sum by of sum_over_time / hand-mv): quantileTDigest(0.99): t-digest" + .to_string() + ] + ); +} + +#[test] +fn refuses_a_query_text_that_is_not_the_workloads() { + let error = deployment(file(&["job"], None)) + .check(&workload(&["max_over_time(latency[1m])"])) + .unwrap_err(); + assert!(error.contains("max_over_time(latency[1m])"), "{error}"); +} + +#[test] +fn refuses_a_different_number_of_queries() { + let error = deployment(file(&["job"], None)) + .check(&workload(&[ + "sum by (job) (sum_over_time(latency[1m]))", + "max_over_time(latency[1m])", + ])) + .unwrap_err(); + assert!( + error.contains("1 queries") && error.contains("2"), + "{error}" + ); +} + +#[test] +fn refuses_a_label_named_like_a_sample_column() { + let error = deployment(file(&["value"], None)) + .check(&workload(&["sum by (job) (sum_over_time(latency[1m]))"])) + .unwrap_err(); + assert!(error.contains("ts or value"), "{error}"); +} + +#[test] +fn refuses_a_zero_step_and_unknown_fields() { + let mut zero = file(&["job"], None); + zero["clickhouse_hand_written"]["queries"][0]["step_ms"] = json!(0); + assert!(deployment(zero) + .check(&workload(&["sum by (job) (sum_over_time(latency[1m]))"])) + .is_err()); + let mut unknown = file(&["job"], None); + unknown["clickhouse_hand_written"]["extra"] = json!(1); + assert!(read(&unknown.to_string()).is_err()); +}