diff --git a/docs/system-bench.md b/docs/system-bench.md index 6956a78f..515d4ced 100644 --- a/docs/system-bench.md +++ b/docs/system-bench.md @@ -78,6 +78,7 @@ DuckDB and PilotDB are installed by `scripts/install-*.sh`. `plan_file.rs` reads an ASAPPlanner plan file. `clickhouse.rs` and `victoriametrics.rs` translate it into what that system can run. A plan step the translator has no rule for is refused, so the translator is also the check of what the system can run. +A hand-written baseline is a plan file as well: `scripts/victoriametrics-hand-written.py` writes `plans/victoriametrics.hand-written/` (one stream aggregation or vmalert recording rule per query, see [capabilities](../system-bench/capabilities/README.md#hand-written-variant)), which the VictoriaMetrics adapter installs as written. What each system can run is written down for the planner in [capabilities](../system-bench/capabilities/README.md). ### planeval diff --git a/scripts/extbench-up-victoriametrics.sh b/scripts/extbench-up-victoriametrics.sh index 18079f7c..18ede66c 100755 --- a/scripts/extbench-up-victoriametrics.sh +++ b/scripts/extbench-up-victoriametrics.sh @@ -18,6 +18,18 @@ # 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: v1.154.1 below) +# VMALERT_PORT also run a vmalert listening on this port, for hand-written +# arms' recording rules (`--victoriametrics-vmalert-url`, +# `--victoriametrics-vmalert-rules-file`): it runs inside the +# server's container (`docker exec`), so its CPU and memory are +# in the cgroup the harness reads, for every arm alike +# VMALERT_IMAGE the image vmalert's binary is copied from, pinned by digest +# (default: v1.154.1 below) +# +# vmalert evaluates against the server and writes back to it with +# -rule.evalDelay=0s (the server's -search.latencyOffset is 0), +# -group.maxStartDelay=1s (a group starts within 1 s of a reload, so the +# harness sets its phase) and -remoteWrite.flushInterval=100ms. # # 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 @@ -26,6 +38,7 @@ set -euo pipefail marker=.extbench-data-dir default_image=victoriametrics/victoria-metrics@sha256:c7884f32920dd45a9d86542a717227e63af03e060e53bbf8031e6e6fd0e1e05d +default_vmalert_image=victoriametrics/vmalert@sha256:aafb962b5a5713c71f0d697d629416f9cccf23aecb74f0ec5e829ddbf3f221f2 # Exit 0 when $1 is a private or loopback IPv4 address. private_address() { @@ -48,6 +61,22 @@ wait_healthy() { curl -sf "http://$1/health" >/dev/null || { echo "the server did not start" >&2; docker logs "$2" >&2; exit 1; } } +# Starts vmalert in container $1 (server at $2, vmalert at $3), when the +# data dir has its binary, and waits for it. +start_vmalert() { + [ -x "$data_dir/vmalert/vmalert-prod" ] || return 0 + echo "groups: []" > "$data_dir/config/rules.yaml" + docker exec -d --user "$(id -u):$(id -g)" "$1" /vmalert/vmalert-prod \ + -httpListenAddr="$3" -rule=/config/rules.yaml \ + -datasource.url="http://$2" -remoteWrite.url="http://$2" \ + -remoteWrite.flushInterval=100ms -rule.evalDelay=0s -group.maxStartDelay=1s \ + -loggerLevel=WARN + for _ in $(seq 1 30); do + curl -sf "http://$3/health" >/dev/null && return 0; sleep 1 + done + echo "vmalert did not start" >&2; exit 1 +} + cgroup_of() { echo "/sys/fs/cgroup/system.slice/docker-$(docker inspect -f '{{.Id}}' "$1").scope" } @@ -70,7 +99,10 @@ if [ "$action" = restart ]; then find "$data_dir/storage" -mindepth 1 -delete echo "[]" > "$data_dir/config/stream-aggregation.yaml" docker start "$name" >/dev/null - wait_healthy "$(docker inspect -f '{{range .Args}}{{println .}}{{end}}' "$name" | sed -n 's/^-httpListenAddr=//p')" "$name" + server=$(docker inspect -f '{{range .Args}}{{println .}}{{end}}' "$name" | sed -n 's/^-httpListenAddr=//p') + wait_healthy "$server" "$name" + vmalert_url=$(sed -n 's/^vmalert_url http:\/\///p' "$data_dir/versions.txt") + [ -z "$vmalert_url" ] || start_vmalert "$name" "$server" "$vmalert_url" group=$(cgroup_of "$name") [ "$group" = "$(sed -n 's/^cgroup //p' "$data_dir/versions.txt")" ] && [ -d "$group" ] \ || { echo "the server's cgroup is now $group, not the one in $data_dir/versions.txt" >&2; exit 1; } @@ -85,6 +117,8 @@ image=${IMAGE:-$default_image} : "${LISTEN_HOST:?set LISTEN_HOST to a private address}" private_address "$LISTEN_HOST" || { echo "refused: LISTEN_HOST $LISTEN_HOST is not a private address" >&2; exit 1; } [[ "$image" == *@sha256:* ]] || { echo "refused: IMAGE must be pinned by digest" >&2; exit 1; } +vmalert_image=${VMALERT_IMAGE:-$default_vmalert_image} +[[ "$vmalert_image" == *@sha256:* ]] || { echo "refused: VMALERT_IMAGE must be pinned by digest" >&2; exit 1; } if [ -e "$data_dir" ]; then [ -f "$data_dir/$marker" ] || { echo "refused: $data_dir exists and was not made by this script" >&2; exit 1; } @@ -95,17 +129,27 @@ mkdir -p "$data_dir/storage" "$data_dir/config"; touch "$data_dir/$marker" # The config directory is bind-mounted (not the file), so the harness's # temporary-file-and-rename replacement is seen by the server. echo "[]" > "$data_dir/config/stream-aggregation.yaml" +mkdir -p "$data_dir/vmalert" +if [ -n "${VMALERT_PORT:-}" ]; then + # vmalert's static binary, copied out of its pinned image. + docker pull -q "$vmalert_image" >/dev/null + copy=$(docker create "$vmalert_image") + docker cp "$copy:/vmalert-prod" "$data_dir/vmalert/vmalert-prod" >/dev/null + docker rm "$copy" >/dev/null +fi 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)" \ -v "$data_dir/storage:/storage" -v "$data_dir/config:/config:ro" \ + -v "$data_dir/vmalert:/vmalert:ro" \ "$image" \ -httpListenAddr="$LISTEN_HOST:$http_port" -storageDataPath=/storage \ -streamAggr.config=/config/stream-aggregation.yaml -streamAggr.keepInput=true \ -search.latencyOffset=0 -search.disableCache=true -retentionPeriod=100y \ -loggerLevel=WARN >/dev/null wait_healthy "$LISTEN_HOST:$http_port" "$name" +[ -z "${VMALERT_PORT:-}" ] || start_vmalert "$name" "$LISTEN_HOST:$http_port" "$LISTEN_HOST:$VMALERT_PORT" group=$(cgroup_of "$name") [ -d "$group" ] || { echo "no cgroup at $group (is docker on the systemd cgroup driver?)" >&2; exit 1; } @@ -123,5 +167,11 @@ siblings() { echo "cpu_model $(lscpu | sed -n 's/^Model name: *//p')" echo "cgroup $group" echo "stream_aggregation_config $(realpath "$data_dir")/config/stream-aggregation.yaml" + if [ -n "${VMALERT_PORT:-}" ]; then + echo "vmalert_image $vmalert_image" + echo "vmalert_version $(curl -sf "http://$LISTEN_HOST:$VMALERT_PORT/metrics" | sed -n 's/^vm_app_version{version="\([^"]*\)".*/\1/p')" + echo "vmalert_url http://$LISTEN_HOST:$VMALERT_PORT" + echo "vmalert_rules_file $(realpath "$data_dir")/config/rules.yaml" + fi echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" cat "$data_dir/versions.txt" diff --git a/scripts/test_victoriametrics_hand_written.py b/scripts/test_victoriametrics_hand_written.py new file mode 100644 index 00000000..f7d300e1 --- /dev/null +++ b/scripts/test_victoriametrics_hand_written.py @@ -0,0 +1,147 @@ +"""Tests of scripts/victoriametrics-hand-written.py (no server). + + python3 -m unittest scripts/test_victoriametrics_hand_written.py +""" + +import importlib.util +import json +import shutil +import tempfile +import unittest +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +SPEC = importlib.util.spec_from_file_location( + "victoriametrics_hand_written", REPO / "scripts" / "victoriametrics-hand-written.py" +) +hw = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(hw) + + +def workload(name, texts, window_ms=60_000, interval_ms=10_000): + return { + "name": name, + "queries": [ + { + "id": f"q{i + 1}", + "texts": [{"language": "PromQl", "text": text}], + "window_ms": window_ms, + "evaluation_interval_ms": interval_ms, + } + for i, text in enumerate(texts) + ], + "data": [], + } + + +def deployment(texts, **kw): + return hw.hand_written(workload("w", texts, **kw))["victoriametrics_hand_written"] + + +class Shapes(unittest.TestCase): + def test_grouped_sum_is_a_stream_aggregation_by_the_group(self): + d = deployment(["sum by (job) (sum_over_time(latency[1m]))"]) + self.assertEqual( + d["stream_aggregations"], + [{"query": "q1", "metric": "latency", "selector": "latency", "interval_ms": 10_000, + "by": ["job"], "outputs": ["sum_samples"]}], + ) + self.assertEqual(d["recording_rules"], []) + q = d["queries"][0] + self.assertEqual(q["expr"], "sum_over_time(latency:10s_by_job_sum_samples[60s] offset -4500ms)") + self.assertEqual(q["time_step_ms"], 10_000) + self.assertIsNone(q["difference"]) + + def test_grouped_count_sums_the_counts(self): + q = deployment(["sum by (job) (count_over_time(latency[1m]))"])["queries"][0] + self.assertEqual(q["expr"], "sum_over_time(latency:10s_by_job_count_samples[60s] offset -4500ms)") + self.assertIsNone(q["difference"]) + + def test_per_series_max_keeps_every_label(self): + d = deployment(["max_over_time(latency[1m])"]) + self.assertIsNone(d["stream_aggregations"][0]["by"]) + self.assertEqual(d["queries"][0]["expr"], "max_over_time(latency:10s_max[60s] offset -4500ms)") + + def test_other_outer_aggregate_runs_over_the_per_series_output(self): + d = deployment(['avg by (job) (max_over_time(latency{job="a"}[1m]))']) + self.assertEqual(d["stream_aggregations"][0]["selector"], 'latency{job="a"}') + self.assertIsNone(d["stream_aggregations"][0]["by"]) + self.assertEqual( + d["queries"][0]["expr"], "avg by (job) (max_over_time(latency:10s_max[60s] offset -4500ms))" + ) + + def test_pane_is_the_gcd_of_window_and_interval(self): + d = deployment(["max_over_time(latency[1h])"], window_ms=3_600_000, interval_ms=60_000) + self.assertEqual(d["stream_aggregations"][0]["interval_ms"], 60_000) + self.assertEqual(d["queries"][0]["expr"], "max_over_time(latency:60s_max[3600s] offset -29500ms)") + self.assertEqual(hw.stream_pane_ms(90_000, 60_000), 30_000) + self.assertIsNone(hw.stream_pane_ms(60_000, 1_500)) # 500 ms: not whole seconds + self.assertIsNone(hw.stream_pane_ms(7_000, 7_000)) # does not divide a day + + def test_quantile_rate_and_avg_of_quantile_are_recording_rules(self): + d = deployment([ + "quantile_over_time(0.99, latency[1m])", + "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "sum by (job) (rate(requests_total[1m]))", + ]) + self.assertEqual(d["stream_aggregations"], []) + records = [r["record"] for r in d["recording_rules"]] + self.assertEqual(records, [ + "series:latency:quantile_over_time_0_99_1m_q1", + "job:latency:avg_quantile_over_time_0_9_1m_q2", + "job:requests_total:sum_rate_1m_q3", + ]) + rate = d["recording_rules"][2] + self.assertEqual(rate["expr"], "sum by (job) (rate(requests_total[1m]))") + self.assertEqual(rate["interval_ms"], 10_000) + self.assertEqual(rate["group"], "w-q3") + self.assertTrue(rate["reads_counters"]) + self.assertEqual(rate["longest_range_ms"], 60_000) + self.assertFalse(d["recording_rules"][0]["reads_counters"]) + self.assertEqual([q["expr"] for q in d["queries"]], + [f"last_over_time({r}[10s])" for r in records]) + + def test_unknown_text_is_still_a_recording_rule(self): + d = deployment(["topk(3, max_over_time(latency[5m]))"]) + self.assertEqual(d["recording_rules"][0]["record"], "query:q1") + self.assertEqual(d["recording_rules"][0]["longest_range_ms"], 300_000) + + def test_same_query_twice_gets_two_rules(self): + d = deployment(["quantile_over_time(0.5, latency[1m])"] * 2) + self.assertEqual(len({r["record"] for r in d["recording_rules"]}), 2) + + def test_same_stream_output_twice_is_no_plan(self): + reason = hw.hand_written(workload("w", ["max_over_time(latency[1m])"] * 2)) + self.assertIsInstance(reason, str) + self.assertIn("latency:10s_max", reason) + + +class RunDirectory(unittest.TestCase): + def test_showcase_variants(self): + with tempfile.TemporaryDirectory() as tmp: + run = Path(tmp) / "run" + (run / "workloads").mkdir(parents=True) + for spec in (REPO / "suites" / "showcase-1m").glob("*.workload.json"): + shutil.copy(spec, run / "workloads" / spec.name.replace(".workload", "")) + hw.write_run_directory(run) + variant = run / "plans" / hw.VARIANT + self.assertEqual( + json.loads((variant / "variant.json").read_text()), + {"substitutions_allowed": True, "run_by_default": False}, + ) + self.assertEqual( + json.loads((run / "plans" / hw.NATIVE / "variant.json").read_text()), + {"substitutions_allowed": True, "plans": False, "run_by_default": False}, + ) + plans = {p.name.split(".")[0] for p in variant.glob("*.plan.json")} + self.assertEqual(plans, {"avg_quantile", "count", "joint", "max", "quantile", + "quantile_rank", "sum_over_time", "sum_rate"}) + joint = json.loads((variant / "joint.plan.json").read_text())["victoriametrics_hand_written"] + self.assertEqual([q["precompute"] for q in joint["queries"]], + ["recording rule"] * 3 + ["stream aggregation", "recording rule"]) + with self.assertRaises(SystemExit): + hw.write_run_directory(run) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/victoriametrics-hand-written.py b/scripts/victoriametrics-hand-written.py new file mode 100644 index 00000000..730cf5e7 --- /dev/null +++ b/scripts/victoriametrics-hand-written.py @@ -0,0 +1,295 @@ +#!/usr/bin/env python3 +"""Write the VictoriaMetrics hand-written baseline variant of a run directory. + + scripts/victoriametrics-hand-written.py + +For each workload in /workloads/, writes +plans/victoriametrics.hand-written/.plan.json: what an experienced +VictoriaMetrics user writes by hand for each query, one stream aggregation or +one vmalert recording rule per query (nothing shared between queries), and the +dashboard query that reads the recorded series. It also writes +plans/victoriametrics.native/variant.json (the query texts asked as written) +when that variant is missing, so one run of engine `victoriametrics` with +`--variant victoriametrics.native --variant victoriametrics.hand-written` +(and the planner's `victoriametrics.*` variants) fills one report. Both +variants run only when named (`run_by_default: false`). + +The rules, with pane p = gcd(window, evaluation interval) and read shift +h = (p - 1 s) / 2: + +* `F_over_time(m[W])`, F in sum, count, min, max: a stream aggregation of m + every p with the one output `sum_samples` / `count_samples` / `min` / `max` + (no `by`: every label kept), read by `G_over_time([W] offset -h)` + (G: sum for sum and count, min, max). Stream outputs are stamped at their + flush time, in [end - 1 s, end + lag], so an unshifted read counts one + window too many or too few; the shift reads exactly the windows ending in + (t - W, t]. +* `A by (L) (F_over_time(m[W]))` with (A, F) in (sum, sum), (sum, count), + (max, max), (min, min): the same with `by: [L]`, so the cardinality is + reduced at ingestion. With another A: the per-series aggregation and A in + the dashboard query. +* Anything else (quantile_over_time, rate, increase, an aggregation of them, + or a pane that is not whole seconds, at least 2 s and a divisor of a day): + one vmalert group per query, evaluated every evaluation interval with + `eval_alignment: true` and `eval_delay: 0s` (the server runs with + `-search.latencyOffset=0`), with one recording rule whose expression is the + query text; the dashboard query reads the latest evaluation of the + recorded series, `last_over_time([])` (a bare selector + would also answer series recorded up to 5 minutes earlier and no longer + written, such as another arm's). + +Example: `sum by (job) (rate(requests_total[1m]))` every 10 s becomes the rule +`job:requests_total:sum_rate_1m_q1` and the dashboard query +`last_over_time(job:requests_total:sum_rate_1m_q1[10s])`; `max_over_time(latency[1m])` becomes the +stream aggregation `latency` every 10 s with output `max` and the dashboard +query `max_over_time(latency:10s_max[60s] offset -4500ms)`. +""" + +import json +import math +import re +import sys +from pathlib import Path + +VARIANT = "victoriametrics.hand-written" +NATIVE = "victoriametrics.native" +DAY_MS = 86_400_000 + +DURATION_UNITS_MS = {"ms": 1, "s": 1000, "m": 60_000, "h": 3_600_000, "d": DAY_MS} +METRIC = r"[a-zA-Z_:][a-zA-Z0-9_:]*" +LABEL = r"[a-zA-Z_][a-zA-Z0-9_]*" +SELECTOR = rf"(?P{METRIC})(?P\{{[^{{}}]*\}})?" +RANGE = r"\[(?P[0-9a-z]+)\]" +OVER_TIME = re.compile(rf"^(?Psum|count|min|max)_over_time\(\s*{SELECTOR}\s*{RANGE}\s*\)$") +OUTER = re.compile(rf"^(?Psum|count|min|max|avg)\s*(?:by\s*\((?P[^()]*)\))?\s*\((?P.*)\)$") +COUNTER_FUNCTIONS = re.compile(r"\b(rate|increase|irate|resets|delta|idelta)\s*\(") +ANY_RANGE = re.compile(r"\[([0-9a-z]+)(?::[0-9a-z]*)?\]") + +# (outer aggregate, inner function) pairs a grouped stream output answers directly. +GROUPED_STREAM = {("sum", "sum"), ("sum", "count"), ("max", "max"), ("min", "min")} +OUTPUT_OF = {"sum": "sum_samples", "count": "count_samples", "min": "min", "max": "max"} +MERGE_OF = {"sum": "sum_over_time", "count": "sum_over_time", "min": "min_over_time", "max": "max_over_time"} + + + +def duration_ms(text): + """`1m` is 60000; `1h30m` is 5400000; None for anything else.""" + parts = re.findall(r"(\d+)(ms|s|m|h|d)", text) + if not parts or "".join(n + u for n, u in parts) != text: + return None + return sum(int(n) * DURATION_UNITS_MS[u] for n, u in parts) + + +def duration(ms): + """MetricsQL / YAML duration: 300000 is `300s`, 4500 is `4500ms`.""" + return f"{ms // 1000}s" if ms % 1000 == 0 else f"{ms}ms" + + +def short_duration(ms): + """A duration for a record name: 60000 is `1m`, 3600000 is `1h`.""" + for unit, size in (("d", DAY_MS), ("h", 3_600_000), ("m", 60_000), ("s", 1000)): + if ms % size == 0: + return f"{ms // size}{unit}" + return f"{ms}ms" + + +def query_text(query): + """The query's PromQL (or MetricsQL) text.""" + for language in ("PromQl", "MetricsQl"): + for text in query["texts"]: + if text["language"] == language: + return text["text"] + raise ValueError(f"query {query['id']} has no PromQL or MetricsQL text") + + +def stream_pane_ms(window_ms, interval_ms): + """The stream interval for a window read every interval, or None when + stream aggregation cannot hold it (whole seconds, at least 2 s, divides a day).""" + pane = math.gcd(window_ms, interval_ms) + if pane % 1000 or pane < 2000 or DAY_MS % pane: + return None + return pane + + +def stream_plan(text, interval_ms): + """The stream aggregation and dashboard query of `text`, or None when no + stream rule applies.""" + text = text.strip() + outer = None + inner = text + m = OUTER.match(text) + if m and not OVER_TIME.match(text): + by = [label.strip() for label in (m["by"] or "").split(",") if label.strip()] + if not all(re.fullmatch(LABEL, label) for label in by): + return None + outer = (m["a"], sorted(set(by))) + inner = m["inner"].strip() + m = OVER_TIME.match(inner) + if not m: + return None + window_ms = duration_ms(m["range"]) + if window_ms is None: + return None + pane = stream_pane_ms(window_ms, interval_ms) + if pane is None: + return None + f, metric = m["f"], m["metric"] + selector = metric + (m["matchers"] or "") + grouped = outer is not None and (outer[0], f) in GROUPED_STREAM and outer[1] + by = outer[1] if grouped else None + output = OUTPUT_OF[f] + name = f"{metric}:{duration(pane)}" + (f"_by_{'_'.join(by)}" if by else "") + f"_{output}" + shift = duration((pane - 1000) // 2) + read = f"{MERGE_OF[f]}({name}[{duration(window_ms)}] offset -{shift})" + if outer is not None and not grouped: + a, labels = outer + read = f"{a} by ({', '.join(labels)}) ({read})" if labels else f"{a}({read})" + return { + "aggregation": { + "metric": metric, + "selector": selector, + "interval_ms": pane, + "by": by, + "outputs": [output], + }, + "output_metric": name, + "expr": read, + "time_step_ms": pane, + # The translator pairs sum_samples with count_samples in case an + # empty window is written as 0; VictoriaMetrics v1.154.1 writes none + # (conformance test H1), so the hand-written read needs no pairing. + "difference": None, + } + + +def record_name(text, query_id): + """`level:metric:operations` for the recorded series of `text`, made + unique by the query id, e.g. `job:requests_total:sum_rate_1m_q1`.""" + text = text.strip() + level, outer_ops = "series", "" + inner = text + m = OUTER.match(text) + if m and not OVER_TIME.match(text): + by = [label.strip() for label in (m["by"] or "").split(",") if label.strip()] + level = "_".join(sorted(set(by))) or "all" + outer_ops = m["a"] + "_" + inner = m["inner"].strip() + m = re.match( + rf"^(?P[a-z_]+)\(\s*(?:(?P[0-9.]+)\s*,\s*)?{SELECTOR}\s*{RANGE}\s*\)$", inner + ) + if m and duration_ms(m["range"]) is not None: + q = "_" + m["q"].replace(".", "_") if m["q"] else "" + ops = f"{outer_ops}{m['f']}{q}_{short_duration(duration_ms(m['range']))}" + return f"{level}:{m['metric']}:{ops}_{query_id}" + return f"query:{query_id}" + + +def rule_plan(text, query_id, workload, interval_ms): + if interval_ms % 1000: + raise ValueError(f"query {query_id}: evaluation interval {interval_ms} ms is not whole seconds") + record = record_name(text, query_id) + ranges = [duration_ms(r) for r in ANY_RANGE.findall(text)] + return { + "rule": { + "query": query_id, + "group": f"{workload}-{query_id}", + "interval_ms": interval_ms, + "record": record, + "expr": text.strip(), + "reads_counters": bool(COUNTER_FUNCTIONS.search(text)), + "longest_range_ms": max([r for r in ranges if r is not None], default=0), + }, + # Only the latest evaluation: a bare selector would also answer the + # series other rules (or arms) recorded in the last 5 minutes + # (VictoriaMetrics' look-back of an instant query). + "expr": f"last_over_time({record}[{duration(interval_ms)}])", + "time_step_ms": interval_ms, + } + + +def hand_written(workload): + """The hand-written deployment of `workload` (a harness WorkloadSpec), or + a no-plan reason (str).""" + streams, rules, queries = [], [], [] + seen_names = {} + for query in workload["queries"]: + text = query_text(query) + qid = query["id"] + interval_ms = query["evaluation_interval_ms"] + stream = stream_plan(text, interval_ms) + if stream is not None: + name = stream["output_metric"] + if name in seen_names: + return ( + f"queries {seen_names[name]} and {qid} would write the same stream output {name}; " + "one aggregation per query cannot name them apart" + ) + seen_names[name] = qid + streams.append({"query": qid, **stream["aggregation"]}) + queries.append({ + "id": qid, + "query_text": text, + "precompute": "stream aggregation", + "expr": stream["expr"], + "time_step_ms": stream["time_step_ms"], + "difference": stream["difference"], + }) + else: + rule = rule_plan(text, qid, workload["name"], interval_ms) + name = rule["rule"]["record"] + if name in seen_names: + return f"queries {seen_names[name]} and {qid} would record the same series {name}" + seen_names[name] = qid + rules.append(rule["rule"]) + queries.append({ + "id": qid, + "query_text": text, + "precompute": "recording rule", + "expr": rule["expr"], + "time_step_ms": rule["time_step_ms"], + "difference": None, + }) + return { + "victoriametrics_hand_written": { + "stream_aggregations": streams, + "recording_rules": rules, + "queries": queries, + } + } + + +def write_run_directory(run): + run = Path(run) + workloads = sorted((run / "workloads").glob("*.json")) + if not workloads: + raise SystemExit(f"{run}/workloads has no workload") + out = run / "plans" / VARIANT + if out.exists(): + raise SystemExit(f"{out} exists; variants are never overwritten") + out.mkdir(parents=True) + (out / "variant.json").write_text( + json.dumps({"substitutions_allowed": True, "run_by_default": False}) + "\n" + ) + native = run / "plans" / NATIVE + if not native.exists(): + native.mkdir(parents=True) + (native / "variant.json").write_text( + json.dumps({"substitutions_allowed": True, "plans": False, "run_by_default": False}) + "\n" + ) + for path in workloads: + workload = json.loads(path.read_text()) + result = hand_written(workload) + name = path.stem + if isinstance(result, str): + (out / f"{name}.no-plan.json").write_text(json.dumps({"reason": result}) + "\n") + print(f"{name} {VARIANT}: no plan ({result})") + else: + (out / f"{name}.plan.json").write_text(json.dumps(result, indent=1) + "\n") + kinds = [q["precompute"] for q in result["victoriametrics_hand_written"]["queries"]] + print(f"{name} {VARIANT}: {', '.join(kinds)}") + + +if __name__ == "__main__": + if len(sys.argv) != 2: + raise SystemExit(__doc__) + write_run_directory(sys.argv[1]) diff --git a/system-bench/capabilities/README.md b/system-bench/capabilities/README.md index 9f0f6172..40c8a55a 100644 --- a/system-bench/capabilities/README.md +++ b/system-bench/capabilities/README.md @@ -63,3 +63,24 @@ One rule cannot be written in a capability file: VictoriaMetrics stores a stream | Raw samples retained | a | the raw series (`-streamAggr.keepInput`) | — | `app/vminsert/common/streamaggr.go` | In `victoriametrics.equivalent-only.json`, both counter semantics are `false`. The planner therefore excludes every Rate / Increase / IRate state and every `rate` / `increase` / `irate` / `resets` / `delta` measure. + +### Hand-written variant + +`victoriametrics.hand-written` is the baseline for the planner's plan on the same engine: what an experienced user writes by hand for each query, one stream aggregation or one vmalert recording rule per query (nothing shared between queries), with the dashboard query reading the recorded series. `scripts/victoriametrics-hand-written.py ` writes it (and `victoriametrics.native`, the query texts asked as written, when missing); both run only when `--variant` names them. With pane `p = gcd(window, evaluation interval)` and `h = (p − 1 s) / 2`: + +| Query | Hand-written | Dashboard query | +|---|---|---| +| `F_over_time(m[W])`, F in sum, count, min, max | stream aggregation of `m` every `p`, output `sum_samples` / `count_samples` / `min` / `max`, every label kept | `G_over_time([W] offset -h)` | +| `sum by (L) (sum_over_time…)`, `sum by (L) (count_over_time…)`, `max by (L) (max_over_time…)`, `min by (L) (min_over_time…)` | the same with `by: [L]` | the same | +| another aggregation of those | the per-series stream aggregation | the aggregation over the read | +| anything else (`quantile_over_time`, `rate`, `increase`, aggregations of them) | a vmalert group per query, `interval` = the evaluation interval, `eval_alignment: true`, `eval_delay: 0s`, one recording rule with the query as its expression | the latest evaluation: `last_over_time([])` | + +The adapter loads the rules into a vmalert that runs in the server's container (`VMALERT_PORT` of `scripts/extbench-up-victoriametrics.sh`), so its CPU and memory are measured with the server's, and it waits, as ingest work, until each rule's evaluation at the chunk end is written before the queries run. Where the answers can differ from the queries over raw samples: + +- the read shift: stream outputs are stamped at their flush time, in `[end − 1 s, end + lag]`, so a read without `offset -h` can count one window too many or too few (the conformance test prints how often); +- `sum_samples` alone: the translator pairs it with `count_samples` in case an empty window is written as 0 while the output is not stale; on v1.154.1 the conformance test sees no such 0 (grouped or per series, after the series stop), so the hand-written read has no companion. A file's `difference` per query is reported as the cell's substitution; the generator writes none today; +- vmalert's defaults: with `-rule.evalDelay=30s` the record at `t` holds the window ending 30 s earlier (rounded down to the interval), and a dashboard that reads before the group ran for `t` gets the previous interval's record. The variant sets `eval_delay: 0s` (the server's `-search.latencyOffset` is 0) and waits for the evaluation; +- the look-back: a bare selector of the recorded series answers from the last 5 minutes (an instant query's default look-back), so series that another arm or a removed rule recorded keep answering (seen in the conformance test: an earlier run's series); the dashboard query reads only the latest evaluation; +- counters: a rule computes VictoriaMetrics' `rate` / `increase`, as the native query does (the rows above). + +Conformance: `hand_written_rules_equal_the_hand_computed_answers` in `tests/victoriametrics_conformance.rs`. diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 6bf0b9b2..bc5c05d0 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -28,6 +28,7 @@ pub mod postgresql_command_line; mod restart_command; pub mod server_cgroup; pub mod victoriametrics; +pub mod victoriametrics_hand_written; pub mod victoriametrics_server; use plan_file::{PlanFile, Timing}; diff --git a/system-bench/src/engines_external/victoriametrics_hand_written.rs b/system-bench/src/engines_external/victoriametrics_hand_written.rs new file mode 100644 index 00000000..f8925457 --- /dev/null +++ b/system-bench/src/engines_external/victoriametrics_hand_written.rs @@ -0,0 +1,493 @@ +//! A hand-written VictoriaMetrics deployment: what an experienced user writes +//! by hand for each query of a workload, one stream aggregation or one vmalert +//! recording rule per query (nothing shared between queries), and the +//! dashboard query that reads the recorded series. It is the baseline next to +//! the planner's plan on the same engine. +//! +//! It is written by `scripts/victoriametrics-hand-written.py` as an arm's plan +//! file (the harness treats plan files as opaque), told apart from an +//! ASAPPlanner plan by its top-level key: +//! +//! ```json +//! {"victoriametrics_hand_written": { +//! "stream_aggregations": [{"query": "q4", "metric": "latency", "selector": "latency", +//! "interval_ms": 10000, "by": null, "outputs": ["max"]}], +//! "recording_rules": [{"query": "q5", "group": "joint-q5", "interval_ms": 10000, +//! "record": "job:requests_total:sum_rate_1m_q5", +//! "expr": "sum by (job) (rate(requests_total[1m]))", +//! "reads_counters": true, "longest_range_ms": 60000}], +//! "queries": [{"id": "q4", "query_text": "max_over_time(latency[1m])", +//! "precompute": "stream aggregation", +//! "expr": "max_over_time(latency:10s_max[60s] offset -4500ms)", +//! "time_step_ms": 10000, "difference": null}, ...] +//! }} +//! ``` +//! +//! Query `i` answers workload query `i`. A `difference` is where the +//! hand-written precompute answers otherwise than the query over raw samples; +//! the adapter reports it as a substitution. The adapter in +//! [`super::victoriametrics_server`] loads the stream aggregations like a +//! translated plan's and the rules into vmalert, each recording rule in its +//! own group evaluated every `interval_ms` with `eval_alignment: true` and +//! `eval_delay: 0s`. + +use std::collections::BTreeSet; + +use aqpbm_core::harness::engine::WorkloadSpec; +use serde::Deserialize; +use serde_json::Value; + +use super::victoriametrics::{StreamAggregation, StreamOutput, VictoriaMetricsDeployment}; + +/// The top-level key of a hand-written file. +pub const KEY: &str = "victoriametrics_hand_written"; + +const DAY_MS: u64 = 86_400_000; + +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HandWritten { + pub stream_aggregations: Vec, + pub recording_rules: Vec, + pub queries: Vec, +} + +/// One stream aggregation, written for one query. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct HandWrittenStream { + /// The workload query it is written for, e.g. `q4`. + pub query: String, + pub metric: String, + /// The `match` selector, e.g. `latency{job="a"}`. + pub selector: String, + pub interval_ms: u64, + /// `None`: every input label kept. + pub by: Option>, + /// Output names, e.g. `["max"]`. + pub outputs: Vec, +} + +/// One vmalert recording rule, in a group of its own. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct RecordingRule { + pub query: String, + /// The group name, e.g. `joint-q5`; the adapter prefixes each install's name. + pub group: String, + pub interval_ms: u64, + /// The recorded series' name, e.g. `job:requests_total:sum_rate_1m_q5`. + pub record: String, + pub expr: String, + /// Whether `expr` reads counters (`rate`, `increase`, ...), whose sample + /// before the range MetricsQL looks for up to 10 minutes back. + pub reads_counters: bool, + /// The longest range selector in `expr`, e.g. 60,000 for `[1m]`. + pub longest_range_ms: u64, +} + +/// The dashboard query of one workload query. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct DashboardQuery { + pub id: String, + /// One of the workload query's texts. + pub query_text: String, + /// `stream aggregation` or `recording rule`. + pub precompute: String, + /// The MetricsQL instant query that reads the recorded series. + pub expr: String, + /// The evaluation time must be a multiple of this, in ms. + pub time_step_ms: u64, + pub difference: Option, +} + +/// Whether `text` is a hand-written file (a JSON object with the key [`KEY`]). +pub fn is_hand_written(text: &str) -> bool { + serde_json::from_str::(text) + .ok() + .is_some_and(|value| value.get(KEY).is_some()) +} + +impl HandWritten { + /// Reads and checks a hand-written file. + pub fn from_json(text: &str) -> Result { + #[derive(Deserialize)] + #[serde(deny_unknown_fields)] + struct File { + victoriametrics_hand_written: HandWritten, + } + let file: File = serde_json::from_str(text).map_err(|e| e.to_string())?; + let spec = file.victoriametrics_hand_written; + spec.check()?; + Ok(spec) + } + + fn check(&self) -> Result<(), String> { + let ids: BTreeSet<&str> = self.queries.iter().map(|q| q.id.as_str()).collect(); + if ids.len() != self.queries.len() { + return Err("two queries with one id".into()); + } + for query in &self.queries { + if query.time_step_ms == 0 { + return Err(format!("query {}: time_step_ms 0", query.id)); + } + } + let mut names = BTreeSet::new(); + for stream in &self.stream_aggregations { + if !ids.contains(stream.query.as_str()) { + return Err(format!( + "stream aggregation for unknown query {}", + stream.query + )); + } + let width = stream.interval_ms; + if !width.is_multiple_of(1000) || width < 2000 || !DAY_MS.is_multiple_of(width) { + return Err(format!( + "query {}: stream interval {width} ms is not whole seconds, at least 2 s, \ + dividing a day", + stream.query + )); + } + if stream.outputs.is_empty() { + return Err(format!( + "query {}: a stream aggregation with no output", + stream.query + )); + } + if stream.by.as_ref().is_some_and(Vec::is_empty) { + return Err(format!("query {}: an empty by", stream.query)); + } + let aggregation = stream_aggregation(stream)?; + for &output in &aggregation.outputs { + let name = aggregation.output_metric(output); + if !names.insert(name.clone()) { + return Err(format!("two writers of the series {name}")); + } + } + } + let mut groups = BTreeSet::new(); + for rule in &self.recording_rules { + if !ids.contains(rule.query.as_str()) { + return Err(format!("recording rule for unknown query {}", rule.query)); + } + if rule.interval_ms == 0 || !rule.interval_ms.is_multiple_of(1000) { + return Err(format!( + "rule {}: interval {} ms is not whole seconds", + rule.record, rule.interval_ms + )); + } + if !names.insert(rule.record.clone()) { + return Err(format!("two writers of the series {}", rule.record)); + } + if !groups.insert(rule.group.as_str()) { + return Err(format!("two rules in the group {}", rule.group)); + } + } + Ok(()) + } + + /// Query `i` must answer workload query `i`: the same id, and its text one + /// of that query's texts. + pub fn check_workload(&self, workload: &WorkloadSpec) -> Result<(), String> { + if self.queries.len() != workload.queries.len() { + return Err(format!( + "the hand-written file has {} queries but workload {} has {}", + self.queries.len(), + workload.name, + workload.queries.len() + )); + } + for (query, asked) in self.queries.iter().zip(&workload.queries) { + if query.id != asked.id || !asked.texts.iter().any(|t| t.text == query.query_text) { + return Err(format!( + "hand-written query {} ('{}') is not workload query {}", + query.id, query.query_text, asked.id + )); + } + } + Ok(()) + } + + /// The stream aggregations, in file order. + pub fn stream_aggregations(&self) -> Vec { + self.stream_aggregations + .iter() + .map(|s| stream_aggregation(s).expect("checked when read")) + .collect() + } + + /// The `-streamAggr.config` YAML, each entry named `name` when given. + pub fn stream_aggregation_config(&self, name: Option<&str>) -> String { + let deployment = VictoriaMetricsDeployment { + stream_aggregations: self.stream_aggregations(), + queries: Vec::new(), + substitutions: Vec::new(), + sharing_lost: Vec::new(), + }; + match name { + Some(name) => deployment.stream_aggregation_config_named(name), + None => deployment.stream_aggregation_config(), + } + } + + /// The vmalert rules file: one group per rule, named `-` + /// when a prefix is given, e.g. + /// + /// ```yaml + /// groups: + /// - name: 'joint-q5' + /// interval: 10s + /// eval_alignment: true + /// eval_delay: 0s + /// rules: + /// - record: 'job:requests_total:sum_rate_1m_q5' + /// expr: 'sum by (job) (rate(requests_total[1m]))' + /// ``` + pub fn rules_yaml(&self, prefix: Option<&str>) -> String { + if self.recording_rules.is_empty() { + return "groups: []\n".into(); + } + let mut yaml = String::from("groups:\n"); + for rule in &self.recording_rules { + yaml.push_str(&format!( + " - name: {}\n interval: {}s\n eval_alignment: true\n eval_delay: 0s\n \ + rules:\n - record: {}\n expr: {}\n", + yaml_quoted(&self.group_name(rule, prefix)), + rule.interval_ms / 1000, + yaml_quoted(&rule.record), + yaml_quoted(&rule.expr) + )); + } + yaml + } + + /// The group name of `rule` as loaded with `prefix`. + pub fn group_name(&self, rule: &RecordingRule, prefix: Option<&str>) -> String { + match prefix { + Some(prefix) => format!("{prefix}-{}", rule.group), + None => rule.group.clone(), + } + } + + /// Whether a rule reads counters, and the longest range of those that do. + pub fn longest_counter_range_ms(&self) -> Option { + self.recording_rules + .iter() + .filter(|rule| rule.reads_counters) + .map(|rule| rule.longest_range_ms) + .max() + } + + /// Every recorded series: stream outputs and recording rules. + pub fn recorded_series(&self) -> Vec { + let mut names: Vec = self + .stream_aggregations() + .iter() + .flat_map(|a| { + a.outputs + .iter() + .map(|&o| a.output_metric(o)) + .collect::>() + }) + .collect(); + names.extend(self.recording_rules.iter().map(|r| r.record.clone())); + names + } +} + +fn stream_aggregation(stream: &HandWrittenStream) -> Result { + let outputs = stream + .outputs + .iter() + .map(|name| match name.as_str() { + "sum_samples" => Ok(StreamOutput::SumSamples), + "count_samples" => Ok(StreamOutput::CountSamples), + "min" => Ok(StreamOutput::Min), + "max" => Ok(StreamOutput::Max), + other => Err(format!( + "query {}: unknown stream output {other}", + stream.query + )), + }) + .collect::, _>>()?; + let mut by = stream.by.clone(); + if let Some(labels) = &mut by { + labels.sort(); + } + Ok(StreamAggregation { + metric: stream.metric.clone(), + selector: stream.selector.clone(), + interval_ms: stream.interval_ms, + by, + outputs, + }) +} + +/// A YAML single-quoted scalar: a quote is doubled. +fn yaml_quoted(value: &str) -> String { + format!("'{}'", value.replace('\'', "''")) +} + +/// An RFC 3339 UTC time as vmalert writes it (`2026-12-03T07:24:20Z`, or with +/// a fraction, or `+00:00`), in ms since the Unix epoch. +pub fn rfc3339_utc_ms(text: &str) -> Option { + let text = text + .strip_suffix('Z') + .or_else(|| text.strip_suffix("+00:00"))?; + let (date, time) = text.split_once('T')?; + let mut date = date.split('-').map(|p| p.parse::().ok()); + let (year, month, day) = (date.next()??, date.next()??, date.next()??); + let (time, fraction) = match time.split_once('.') { + Some((time, fraction)) => (time, fraction), + None => (time, ""), + }; + let mut time = time.split(':').map(|p| p.parse::().ok()); + let (hour, minute, second) = (time.next()??, time.next()??, time.next()??); + let fraction_ms = if fraction.is_empty() { + 0 + } else { + let digits: String = fraction.chars().chain("000".chars()).take(3).collect(); + digits.parse::().ok()? + }; + // Days from 1970-01-01 (Howard Hinnant's days_from_civil). + let y = if month <= 2 { year - 1 } else { year }; + let era = y.div_euclid(400); + let yoe = y - era * 400; + let mp = (month + 9) % 12; + let doy = (153 * mp + 2) / 5 + day - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(((days * 24 + hour) * 60 + minute) * 60_000 + second * 1000 + fraction_ms) +} + +/// One recording rule as vmalert runs it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoadedRule { + pub group_id: String, + pub rule_id: String, + pub record: String, + pub interval_ms: u64, +} + +/// The rules of `/api/v1/rules` in the groups named `groups` (name, record, +/// interval), when vmalert runs all of them. +pub fn loaded_rules( + rules_json: &str, + groups: &[(String, String, u64)], +) -> Result>, String> { + let value: Value = + serde_json::from_str(rules_json).map_err(|e| format!("vmalert rules: {e}"))?; + let listed = value["data"]["groups"] + .as_array() + .cloned() + .unwrap_or_default(); + let mut loaded = Vec::new(); + for (name, record, interval_ms) in groups { + let Some(group) = listed.iter().find(|g| g["name"] == name.as_str()) else { + return Ok(None); + }; + let Some(rule) = group["rules"] + .as_array() + .into_iter() + .flatten() + .find(|r| r["name"] == record.as_str()) + else { + return Ok(None); + }; + let id = |v: &Value| match v { + Value::String(s) => Some(s.clone()), + Value::Number(n) => Some(n.to_string()), + _ => None, + }; + loaded.push(LoadedRule { + group_id: id(&group["id"]).ok_or("vmalert group without id")?, + rule_id: id(&rule["id"]).ok_or("vmalert rule without id")?, + record: record.clone(), + interval_ms: *interval_ms, + }); + } + Ok(Some(loaded)) +} + +/// The latest evaluation of a rule in `/api/v1/rule`: its evaluation time +/// (`at`) in ms and its error, or `None` before the first. +pub fn last_evaluation(rule_json: &str) -> Result)>, String> { + let value: Value = serde_json::from_str(rule_json).map_err(|e| format!("vmalert rule: {e}"))?; + let Some(update) = value["updates"].as_array().and_then(|u| u.first()) else { + return Ok(None); + }; + let at = update["at"] + .as_str() + .and_then(rfc3339_utc_ms) + .ok_or_else(|| format!("vmalert rule update without a time: {update}"))?; + let error = match &update["error"] { + Value::Null => None, + Value::String(s) if s.is_empty() => None, + other => Some(other.to_string()), + }; + Ok(Some((at, error))) +} + +/// What the adapter reads from vmalert's `/metrics`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct VmalertMetrics { + /// `vmalert_config_last_reload_total`. + pub reloads: u64, + /// `vmalert_config_last_reload_errors_total`. + pub reload_errors: u64, + /// `vmalert_remotewrite_total`: rows queued for the server. + pub rows_queued: u64, + /// `vmalert_remotewrite_sent_rows_total`. + pub rows_sent: u64, + /// `vmalert_remotewrite_dropped_rows_total`. + pub rows_dropped: u64, + /// `vmalert_remotewrite_errors_total`. + pub write_errors: u64, +} + +impl VmalertMetrics { + pub fn parse(text: &str) -> VmalertMetrics { + let mut metrics = VmalertMetrics::default(); + for line in text.lines().filter(|l| !l.starts_with('#')) { + let Some((name, value)) = line.rsplit_once(' ') else { + continue; + }; + let value = value.parse::().map(|v| v as u64).unwrap_or(0); + match name { + "vmalert_config_last_reload_total" => metrics.reloads = value, + "vmalert_config_last_reload_errors_total" => metrics.reload_errors = value, + "vmalert_remotewrite_total" => metrics.rows_queued = value, + "vmalert_remotewrite_sent_rows_total" => metrics.rows_sent = value, + "vmalert_remotewrite_dropped_rows_total" => metrics.rows_dropped = value, + "vmalert_remotewrite_errors_total" => metrics.write_errors = value, + _ => {} + } + } + metrics + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rfc3339_times() { + assert_eq!(rfc3339_utc_ms("1970-01-01T00:00:00Z"), Some(0)); + assert_eq!( + rfc3339_utc_ms("2026-12-03T07:24:20Z"), + Some(1_796_282_660_000) + ); + assert_eq!( + rfc3339_utc_ms("2026-12-03T07:24:20.5Z"), + Some(1_796_282_660_500) + ); + assert_eq!( + rfc3339_utc_ms("2000-03-01T00:00:01+00:00"), + Some(951_868_801_000) + ); + assert_eq!(rfc3339_utc_ms("2026-12-03T07:24:20+01:00"), None); + assert_eq!(rfc3339_utc_ms("yesterday"), None); + } +} diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs index dbe01f91..1dd8bab7 100644 --- a/system-bench/src/engines_external/victoriametrics_server.rs +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -70,6 +70,9 @@ use super::server_cgroup::ServerCgroupOptions; use super::victoriametrics::{ translate, MetricsQlQuery, StreamAggregation, VictoriaMetricsDeployment, }; +use super::victoriametrics_hand_written::{ + is_hand_written, last_evaluation, loaded_rules, HandWritten, LoadedRule, VmalertMetrics, +}; use super::NodeId; use crate::prometheus_api::query_text_arm::{ ask_every_query, check_speed, queries_to_ask, write_chunk, QueryToAsk, Replay, @@ -106,6 +109,19 @@ pub struct VictoriaMetricsEngine { runs_per_arm: u32, installed_once: AtomicBool, restart_command: Option, + vmalert: Option, +} + +/// A vmalert that evaluates the recording rules of hand-written arms against +/// the server and writes their results back to it (run in the server's +/// container, so its CPU and memory are in the server's cgroup). +#[derive(Debug, Clone, PartialEq)] +pub struct VmalertServer { + /// Its HTTP interface, e.g. `http://10.0.0.1:8880`. + pub url: String, + /// Its `-rule` file on the server host, replaced for each arm with + /// recording rules through the server's cgroup source. + pub rules_file: PathBuf, } /// Installs so far in this process, for each install's config nonce. @@ -151,9 +167,16 @@ impl VictoriaMetricsEngine { runs_per_arm: 1, installed_once: AtomicBool::new(false), restart_command: None, + vmalert: None, }) } + /// The vmalert that runs hand-written arms' recording rules. + pub fn with_vmalert(mut self, vmalert: VmalertServer) -> VictoriaMetricsEngine { + self.vmalert = Some(vmalert); + self + } + fn restart_after_the_first_install(&self) -> Result<(), EngineError> { if !self.installed_once.swap(true, Ordering::SeqCst) { return Ok(()); @@ -260,13 +283,25 @@ impl EngineUnderTest for VictoriaMetricsEngine { }; 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}")))?; + let setup = if is_hand_written(&text) { + hand_written_setup(&text, workload) + } else { + plan_setup(&text, workload) + } + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; let interval_ms = evaluation_interval_ms(workload)?; - check_time_steps(workload, &deployment.queries, interval_ms)?; + check_time_steps(workload, &setup.time_steps_ms, interval_ms)?; + let vmalert = match (&setup.rules, &self.vmalert) { + (Some(_), None) => { + return Err(EngineError( + "an arm with recording rules loads them into vmalert: it needs \ + --victoriametrics-vmalert-url and --victoriametrics-vmalert-rules-file" + .into(), + )) + } + (Some(_), Some(vmalert)) => Some(vmalert.clone()), + (None, _) => None, + }; if self .arm_installed .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) @@ -288,25 +323,14 @@ impl EngineUnderTest for VictoriaMetricsEngine { newest_sample_wall_ms: Arc::clone(&self.newest_sample_wall_ms), aggregation_name: String::new(), flush_counts: (0, BTreeMap::new()), - queries: query_ids - .into_iter() - .zip(&deployment.queries) - .zip(&plan.roots) - .map(|((id, query), &root)| RootQuery { - asked_from_ms: workload - .query(&id) - .and_then(|query| workload.asked_from_ms(query)), - id, - expr: query.expr.clone(), - metric_name: answer_metric_name(&plan, root, query), - }) - .collect(), - aggregations: deployment.stream_aggregations.clone(), + queries: setup.queries, + lead_ms: lead_ms(&setup.aggregations), + aggregations: setup.aggregations, offset_ms: 0, - lead_ms: lead_ms(&deployment.stream_aggregations), too_old_at_install: 0, data_bytes_at_install: 0, - summary: plan_summary(&plan, &deployment), + summary: setup.summary, + rules: None, }; // Each install names its aggregators, so its config always differs // from the last one (a reload with unchanged bytes keeps the old @@ -316,22 +340,39 @@ impl EngineUnderTest for VictoriaMetricsEngine { std::process::id(), INSTALLS.fetch_add(1, Ordering::Relaxed) ); - let config = deployment.stream_aggregation_config_named(&installed.aggregation_name); - installed.load_config(&config, deployment.stream_aggregations.len())?; + let config = VictoriaMetricsDeployment { + stream_aggregations: installed.aggregations.clone(), + queries: Vec::new(), + substitutions: Vec::new(), + sharing_lost: Vec::new(), + } + .stream_aggregation_config_named(&installed.aggregation_name); + installed.load_config(&config, installed.aggregations.len())?; + if let (Some(spec), Some(vmalert)) = (&setup.rules, vmalert) { + installed.rules = Some(InstalledRules::load( + vmalert, + installed.cgroup.clone(), + spec, + &installed.aggregation_name, + )?); + } installed.http.force_flush()?; let metrics = installed.metrics()?; installed.too_old_at_install = metrics.too_old_samples; installed.data_bytes_at_install = metrics.data_size_bytes; let flushes_at_install = metrics.flushes_by_position; - let step_ms = deployment - .stream_aggregations + let step_ms = installed + .aggregations .iter() - .fold(least_common_multiple(1000, interval_ms), |step, a| { - least_common_multiple(step, a.interval_ms) - }); + .map(|a| a.interval_ms) + .chain(setup.time_steps_ms.iter().copied()) + .fold( + least_common_multiple(1000, interval_ms), + least_common_multiple, + ); let data_start = data_start_ms(workload); let earliest_start = now_ms() - .max(self.newest_sample_wall_ms.load(Ordering::SeqCst) + previous_arm_gap_ms(&plan)); + .max(self.newest_sample_wall_ms.load(Ordering::SeqCst) + setup.previous_arm_gap_ms); installed.offset_ms = wall_offset_ms(earliest_start, data_start, step_ms); // Flushes are counted for the ticks after the data start; earlier // ones (empty windows) only add to the counts. @@ -343,6 +384,102 @@ impl EngineUnderTest for VictoriaMetricsEngine { } } +/// What an arm with a plan file installs: from an ASAPPlanner plan or a +/// hand-written file. +struct ArmSetup { + aggregations: Vec, + queries: Vec, + /// Per workload query: the evaluation time must be a multiple of it. + time_steps_ms: Vec, + summary: PlanSummary, + previous_arm_gap_ms: i64, + /// The recording rules to load into vmalert, if any. + rules: Option, +} + +/// An ASAPPlanner plan file, translated by [`translate`]. +fn plan_setup(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(|error| error.0)?; + let deployment = translate(&plan).map_err(|error| error.to_string())?; + let queries = query_ids + .into_iter() + .zip(&deployment.queries) + .zip(&plan.roots) + .map(|((id, query), &root)| RootQuery { + asked_from_ms: workload + .query(&id) + .and_then(|query| workload.asked_from_ms(query)), + id, + expr: query.expr.clone(), + metric_name: answer_metric_name(&plan, root, query), + }) + .collect(); + let summary = plan_summary(&plan, &deployment); + Ok(ArmSetup { + aggregations: deployment.stream_aggregations.clone(), + queries, + time_steps_ms: deployment.queries.iter().map(|q| q.time_step_ms).collect(), + summary, + previous_arm_gap_ms: previous_arm_gap_ms(&plan), + rules: None, + }) +} + +/// A hand-written file: its stream aggregations, its recording rules (loaded +/// into vmalert) and its dashboard queries, which read the recorded series +/// (so no answer keeps `__name__`). +fn hand_written_setup(text: &str, workload: &WorkloadSpec) -> Result { + let spec = HandWritten::from_json(text)?; + spec.check_workload(workload)?; + let queries = spec + .queries + .iter() + .map(|query| RootQuery { + id: query.id.clone(), + expr: query.expr.clone(), + metric_name: None, + asked_from_ms: workload + .query(&query.id) + .and_then(|asked| workload.asked_from_ms(asked)), + }) + .collect(); + let queries_text: Vec<&str> = spec.queries.iter().map(|q| q.expr.as_str()).collect(); + let summary = PlanSummary { + text: format!( + "# -streamAggr.config\n{}# vmalert rules\n{}# queries\n{}\n", + spec.stream_aggregation_config(None), + spec.rules_yaml(None), + queries_text.join("\n") + ), + node_kinds: Vec::new(), + stored_outputs: spec.recorded_series(), + substitutions: spec + .queries + .iter() + .filter_map(|q| { + let difference = q.difference.as_ref()?; + Some(format!( + "victoriametrics.hand_written ({}) at query {}: {difference}", + q.precompute, q.id + )) + }) + .collect(), + sharing_lost: Vec::new(), + }; + let previous_arm_gap_ms = spec + .longest_counter_range_ms() + .map_or(0, |range_ms| PREVIOUS_SAMPLE_LOOKBACK_MS + range_ms as i64); + Ok(ArmSetup { + aggregations: spec.stream_aggregations(), + queries, + time_steps_ms: spec.queries.iter().map(|q| q.time_step_ms).collect(), + summary, + previous_arm_gap_ms, + rules: (!spec.recording_rules.is_empty()).then_some(spec), + }) +} + /// How long after the previous arm's newest sample this arm's data must /// start, in ms: 0 for a plan that reads only its windows, and /// [`PREVIOUS_SAMPLE_LOOKBACK_MS`] plus the longest range for one that reads @@ -388,20 +525,21 @@ fn evaluation_interval_ms(workload: &WorkloadSpec) -> Result { Ok(first) } -/// A query that reads stream outputs answers right only at a window end, so -/// its step must divide the evaluation interval (the data start is moved to -/// a window end by the wall offset). +/// A query that reads stream outputs (or recorded series) answers right only +/// at a window end (or a rule's evaluation time), so its step must divide the +/// evaluation interval (the data start is moved to a step boundary by the +/// wall offset). fn check_time_steps( workload: &WorkloadSpec, - queries: &[MetricsQlQuery], + time_steps_ms: &[u64], interval_ms: u64, ) -> Result<(), EngineError> { - for (query, plan_query) in workload.queries.iter().zip(queries) { - if !interval_ms.is_multiple_of(plan_query.time_step_ms) { + for (query, &step_ms) in workload.queries.iter().zip(time_steps_ms) { + if !interval_ms.is_multiple_of(step_ms) { return Err(EngineError(format!( - "query {} reads stream outputs of {} ms windows, which do not divide its \ + "query {} reads stream outputs of {step_ms} ms windows, which do not divide its \ evaluation interval ({interval_ms} ms)", - query.id, plan_query.time_step_ms + query.id ))); } } @@ -768,6 +906,8 @@ struct VictoriaMetricsArm { /// The server's data size after the config loaded. data_bytes_at_install: u64, summary: PlanSummary, + /// A hand-written arm's recording rules, loaded into vmalert. + rules: Option, } impl VictoriaMetricsArm { @@ -881,8 +1021,11 @@ impl VictoriaMetricsArm { impl Drop for VictoriaMetricsArm { fn drop(&mut self) { - // Best effort: stop the aggregators, so the next arm's server does - // no work for this one. + // Best effort: stop the rules and the aggregators, so the next arm's + // server does no work for this one. + if let Some(rules) = &self.rules { + let _ = rules.unload(); + } let _ = self.load_config("[]\n", 0); self.arm_installed.store(false, Ordering::SeqCst); } @@ -921,11 +1064,31 @@ impl InstalledArm for VictoriaMetricsArm { .fetch_max(wall_end, Ordering::SeqCst); } } + let tick = chunk.end_ms + self.offset_ms; + if self.rules.is_some() { + // vmalert evaluates its rules at the tick plus its start phase + // (0.1 s to 1.1 s), over what is searchable then: the chunk must + // be searchable before the tick. + self.http.force_flush()?; + let now = now_ms(); + if now >= tick { + return Err(EngineError(format!( + "pacing: the chunk ending at data time {} ms was searchable {} ms after its \ + end, when vmalert may already have evaluated its rules", + chunk.end_ms, + now - tick + ))); + } + } // The chunk's windows end at its end: wait for it, then for their // flushes (the flush is ingest work). - let tick = chunk.end_ms + self.offset_ms; sleep_until_wall_ms(tick); self.wait_for_flushes(tick)?; + if let Some(rules) = &self.rules { + // The rules evaluated at the tick and written back are ingest + // work too. + rules.wait_for_evaluations(tick)?; + } // Make the new rows and stream outputs searchable. self.http.force_flush()?; Ok(StepReport::default()) @@ -984,6 +1147,172 @@ impl InstalledArm for VictoriaMetricsArm { } } +/// A hand-written arm's recording rules as vmalert runs them. +struct InstalledRules { + http: VictoriaMetricsConnection, + cgroup: CgroupSource, + rules_file: PathBuf, + rules: Vec, + /// vmalert's counters after the rules loaded. + at_install: VmalertMetrics, +} + +/// How far after an interval boundary the rules are reloaded: with +/// `-group.maxStartDelay=1s`, each group then runs 0.1 s to 1.1 s after each +/// of its ticks. +const RULES_RELOAD_AFTER_TICK_MS: i64 = 100; + +impl InstalledRules { + /// Writes `spec`'s rules (groups named `-`) as vmalert's rule + /// file, reloads it just after a tick of the rules' interval, and waits + /// until vmalert runs every rule. + fn load( + vmalert: VmalertServer, + cgroup: CgroupSource, + spec: &HandWritten, + name: &str, + ) -> Result { + let http = VictoriaMetricsConnection::new(&vmalert.url, Duration::from_secs(60)); + let mut installed = InstalledRules { + http, + cgroup, + rules_file: vmalert.rules_file, + rules: Vec::new(), + at_install: VmalertMetrics::default(), + }; + let groups: Vec<(String, String, u64)> = spec + .recording_rules + .iter() + .map(|rule| { + ( + spec.group_name(rule, Some(name)), + rule.record.clone(), + rule.interval_ms, + ) + }) + .collect(); + let interval_ms = groups.iter().fold(1000, |step, &(_, _, interval)| { + least_common_multiple(step, interval) + }) as i64; + let tick = now_ms().div_euclid(interval_ms) * interval_ms + interval_ms; + installed.reload( + &spec.rules_yaml(Some(name)), + Some(tick + RULES_RELOAD_AFTER_TICK_MS), + )?; + let deadline = Instant::now() + RELOAD_TIMEOUT; + loop { + if let Some(rules) = loaded_rules(&installed.http.get("/api/v1/rules", &[])?, &groups) + .map_err(EngineError)? + { + installed.rules = rules; + break; + } + if Instant::now() > deadline { + return Err(EngineError( + "vmalert did not load the recording rules".into(), + )); + } + std::thread::sleep(POLL_INTERVAL); + } + installed.at_install = installed.metrics()?; + Ok(installed) + } + + fn metrics(&self) -> Result { + Ok(VmalertMetrics::parse(&self.http.get("/metrics", &[])?)) + } + + /// Replaces the rule file with `rules` and reloads it at wall time + /// `at_ms` (or now); a refused file is an error. + fn reload(&self, rules: &str, at_ms: Option) -> Result<(), EngineError> { + let before = self.metrics()?; + self.cgroup + .replace_file_on_server_host(&self.rules_file, rules) + .map_err(|error| EngineError(format!("writing the vmalert rules: {error}")))?; + if let Some(at_ms) = at_ms { + sleep_until_wall_ms(at_ms); + } + self.http.post("/-/reload")?; + let deadline = Instant::now() + RELOAD_TIMEOUT; + loop { + let metrics = self.metrics()?; + if metrics.reload_errors > before.reload_errors { + return Err(EngineError( + "vmalert refused the recording rules (see its log)".into(), + )); + } + if metrics.reloads > before.reloads { + return Ok(()); + } + if Instant::now() > deadline { + return Err(EngineError("vmalert did not reload its rules".into())); + } + std::thread::sleep(POLL_INTERVAL); + } + } + + fn unload(&self) -> Result<(), EngineError> { + self.reload("groups: []\n", None) + } + + /// Waits until every rule due at wall time `tick` has evaluated at `tick` + /// without an error and vmalert has written every row it made, failing + /// if that takes past the rule's next tick. + fn wait_for_evaluations(&self, tick: i64) -> Result<(), EngineError> { + for rule in &self.rules { + let interval = rule.interval_ms as i64; + if tick.rem_euclid(interval) != 0 { + continue; + } + loop { + let answer = self.http.get( + "/api/v1/rule", + &[("group_id", &rule.group_id), ("rule_id", &rule.rule_id)], + )?; + match last_evaluation(&answer).map_err(EngineError)? { + Some((at, Some(error))) if at >= tick => { + return Err(EngineError(format!( + "vmalert rule {} at wall time {tick} ms: {error}", + rule.record + ))) + } + Some((at, None)) if at >= tick => break, + _ => {} + } + if now_ms() > tick + interval { + return Err(EngineError(format!( + "vmalert did not evaluate rule {} at wall time {tick} ms within its \ + interval", + rule.record + ))); + } + std::thread::sleep(POLL_INTERVAL); + } + } + loop { + let metrics = self.metrics()?; + if metrics.rows_dropped > self.at_install.rows_dropped + || metrics.write_errors > self.at_install.write_errors + { + return Err(EngineError(format!( + "vmalert dropped {} rows ({} write errors) since the install", + metrics.rows_dropped - self.at_install.rows_dropped, + metrics.write_errors - self.at_install.write_errors + ))); + } + if metrics.rows_sent + metrics.rows_dropped >= metrics.rows_queued { + return Ok(()); + } + if now_ms() > tick + 60_000 { + return Err(EngineError( + "vmalert did not write its rows to the server within 60 s".into(), + )); + } + std::thread::sleep(POLL_INTERVAL); + } + } +} + struct VictoriaMetricsQueryTextArm { http: VictoriaMetricsConnection, arm_installed: Arc, @@ -1167,6 +1496,16 @@ pub struct VictoriaMetricsOptions { help = "A shell command that restarts the VictoriaMetrics server with its data deleted, e.g. `scripts/extbench-up-victoriametrics.sh restart /data/run-1/victoriametrics`, run before every install after the first and followed by a wait of up to 120 s for the server to answer: each run of an arm then starts on an empty server, so an arm without a plan file can run with warm-up and more than one measured run (engine `victoriametrics`)" )] pub victoriametrics_restart_command: Option, + /// A vmalert's HTTP interface, e.g. `http://10.0.0.1:8880`, that runs the + /// recording rules of hand-written arms against the server (engine + /// `victoriametrics`; `scripts/extbench-up-victoriametrics.sh` starts one + /// with `VMALERT_PORT`). + #[arg(long)] + pub victoriametrics_vmalert_url: Option, + /// That vmalert's `-rule` file on the server host, replaced for each arm + /// with recording rules (engine `victoriametrics`). + #[arg(long)] + pub victoriametrics_vmalert_rules_file: Option, } pub fn periodic_queries( @@ -1195,5 +1534,17 @@ pub fn periodic_queries( })?; engine.runs_per_arm = protocol.warmup_runs + protocol.measured_runs; engine.restart_command = options.victoriametrics_restart_command; + match ( + options.victoriametrics_vmalert_url, + options.victoriametrics_vmalert_rules_file, + ) { + (Some(url), Some(rules_file)) => { + engine = engine.with_vmalert(VmalertServer { url, rules_file }); + } + (None, None) => {} + _ => anyhow::bail!( + "--victoriametrics-vmalert-url and --victoriametrics-vmalert-rules-file go together" + ), + } Ok(Box::new(engine)) } diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/avg_quantile.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/avg_quantile.plan.json new file mode 100644 index 00000000..192f80c4 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/avg_quantile.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "avg_quantile-q1", + "interval_ms": 60000, + "record": "job:latency:avg_quantile_over_time_0_9_1h_q1", + "expr": "avg by (job) (quantile_over_time(0.9, latency[1h]))", + "reads_counters": false, + "longest_range_ms": 3600000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "avg by (job) (quantile_over_time(0.9, latency[1h]))", + "precompute": "recording rule", + "expr": "last_over_time(job:latency:avg_quantile_over_time_0_9_1h_q1[60s])", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/count.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/count.plan.json new file mode 100644 index 00000000..400350b4 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/count.plan.json @@ -0,0 +1,29 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 60000, + "by": [ + "job" + ], + "outputs": [ + "count_samples" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (count_over_time(latency[1h]))", + "precompute": "stream aggregation", + "expr": "sum_over_time(latency:60s_by_job_count_samples[3600s] offset -29500ms)", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/joint.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/joint.plan.json new file mode 100644 index 00000000..20c3ec04 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/joint.plan.json @@ -0,0 +1,96 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q4", + "metric": "latency", + "selector": "latency", + "interval_ms": 60000, + "by": null, + "outputs": [ + "max" + ] + } + ], + "recording_rules": [ + { + "query": "q1", + "group": "joint-q1", + "interval_ms": 60000, + "record": "series:latency:quantile_over_time_0_99_1h_q1", + "expr": "quantile_over_time(0.99, latency[1h])", + "reads_counters": false, + "longest_range_ms": 3600000 + }, + { + "query": "q2", + "group": "joint-q2", + "interval_ms": 60000, + "record": "series:latency:quantile_over_time_0_5_1h_q2", + "expr": "quantile_over_time(0.5, latency[1h])", + "reads_counters": false, + "longest_range_ms": 3600000 + }, + { + "query": "q3", + "group": "joint-q3", + "interval_ms": 60000, + "record": "job:latency:avg_quantile_over_time_0_9_1h_q3", + "expr": "avg by (job) (quantile_over_time(0.9, latency[1h]))", + "reads_counters": false, + "longest_range_ms": 3600000 + }, + { + "query": "q5", + "group": "joint-q5", + "interval_ms": 60000, + "record": "job:requests_total:sum_rate_1h_q5", + "expr": "sum by (job) (rate(requests_total[1h]))", + "reads_counters": true, + "longest_range_ms": 3600000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1h])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1h_q1[60s])", + "time_step_ms": 60000, + "difference": null + }, + { + "id": "q2", + "query_text": "quantile_over_time(0.5, latency[1h])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_5_1h_q2[60s])", + "time_step_ms": 60000, + "difference": null + }, + { + "id": "q3", + "query_text": "avg by (job) (quantile_over_time(0.9, latency[1h]))", + "precompute": "recording rule", + "expr": "last_over_time(job:latency:avg_quantile_over_time_0_9_1h_q3[60s])", + "time_step_ms": 60000, + "difference": null + }, + { + "id": "q4", + "query_text": "max_over_time(latency[1h])", + "precompute": "stream aggregation", + "expr": "max_over_time(latency:60s_max[3600s] offset -29500ms)", + "time_step_ms": 60000, + "difference": null + }, + { + "id": "q5", + "query_text": "sum by (job) (rate(requests_total[1h]))", + "precompute": "recording rule", + "expr": "last_over_time(job:requests_total:sum_rate_1h_q5[60s])", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/max.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/max.plan.json new file mode 100644 index 00000000..bf1938c3 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/max.plan.json @@ -0,0 +1,27 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 60000, + "by": null, + "outputs": [ + "max" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "max_over_time(latency[1h])", + "precompute": "stream aggregation", + "expr": "max_over_time(latency:60s_max[3600s] offset -29500ms)", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile.plan.json new file mode 100644 index 00000000..41ece572 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "quantile-q1", + "interval_ms": 60000, + "record": "series:latency:quantile_over_time_0_99_1h_q1", + "expr": "quantile_over_time(0.99, latency[1h])", + "reads_counters": false, + "longest_range_ms": 3600000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1h])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1h_q1[60s])", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile_rank.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile_rank.plan.json new file mode 100644 index 00000000..dc4697ae --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/quantile_rank.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "quantile_rank-q1", + "interval_ms": 60000, + "record": "series:latency:quantile_over_time_0_99_1h_q1", + "expr": "quantile_over_time(0.99, latency[1h])", + "reads_counters": false, + "longest_range_ms": 3600000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1h])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1h_q1[60s])", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_over_time.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_over_time.plan.json new file mode 100644 index 00000000..1964b1a2 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_over_time.plan.json @@ -0,0 +1,29 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 60000, + "by": [ + "job" + ], + "outputs": [ + "sum_samples" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (sum_over_time(latency[1h]))", + "precompute": "stream aggregation", + "expr": "sum_over_time(latency:60s_by_job_sum_samples[3600s] offset -29500ms)", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_rate.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_rate.plan.json new file mode 100644 index 00000000..bce43c99 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1h/sum_rate.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "sum_rate-q1", + "interval_ms": 60000, + "record": "job:requests_total:sum_rate_1h_q1", + "expr": "sum by (job) (rate(requests_total[1h]))", + "reads_counters": true, + "longest_range_ms": 3600000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (rate(requests_total[1h]))", + "precompute": "recording rule", + "expr": "last_over_time(job:requests_total:sum_rate_1h_q1[60s])", + "time_step_ms": 60000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/avg_quantile.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/avg_quantile.plan.json new file mode 100644 index 00000000..f36609de --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/avg_quantile.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "avg_quantile-q1", + "interval_ms": 10000, + "record": "job:latency:avg_quantile_over_time_0_9_1m_q1", + "expr": "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "reads_counters": false, + "longest_range_ms": 60000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "precompute": "recording rule", + "expr": "last_over_time(job:latency:avg_quantile_over_time_0_9_1m_q1[10s])", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/count.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/count.plan.json new file mode 100644 index 00000000..2c09418b --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/count.plan.json @@ -0,0 +1,29 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 10000, + "by": [ + "job" + ], + "outputs": [ + "count_samples" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (count_over_time(latency[1m]))", + "precompute": "stream aggregation", + "expr": "sum_over_time(latency:10s_by_job_count_samples[60s] offset -4500ms)", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/joint.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/joint.plan.json new file mode 100644 index 00000000..7c7e2857 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/joint.plan.json @@ -0,0 +1,96 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q4", + "metric": "latency", + "selector": "latency", + "interval_ms": 10000, + "by": null, + "outputs": [ + "max" + ] + } + ], + "recording_rules": [ + { + "query": "q1", + "group": "joint-q1", + "interval_ms": 10000, + "record": "series:latency:quantile_over_time_0_99_1m_q1", + "expr": "quantile_over_time(0.99, latency[1m])", + "reads_counters": false, + "longest_range_ms": 60000 + }, + { + "query": "q2", + "group": "joint-q2", + "interval_ms": 10000, + "record": "series:latency:quantile_over_time_0_5_1m_q2", + "expr": "quantile_over_time(0.5, latency[1m])", + "reads_counters": false, + "longest_range_ms": 60000 + }, + { + "query": "q3", + "group": "joint-q3", + "interval_ms": 10000, + "record": "job:latency:avg_quantile_over_time_0_9_1m_q3", + "expr": "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "reads_counters": false, + "longest_range_ms": 60000 + }, + { + "query": "q5", + "group": "joint-q5", + "interval_ms": 10000, + "record": "job:requests_total:sum_rate_1m_q5", + "expr": "sum by (job) (rate(requests_total[1m]))", + "reads_counters": true, + "longest_range_ms": 60000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1m])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1m_q1[10s])", + "time_step_ms": 10000, + "difference": null + }, + { + "id": "q2", + "query_text": "quantile_over_time(0.5, latency[1m])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_5_1m_q2[10s])", + "time_step_ms": 10000, + "difference": null + }, + { + "id": "q3", + "query_text": "avg by (job) (quantile_over_time(0.9, latency[1m]))", + "precompute": "recording rule", + "expr": "last_over_time(job:latency:avg_quantile_over_time_0_9_1m_q3[10s])", + "time_step_ms": 10000, + "difference": null + }, + { + "id": "q4", + "query_text": "max_over_time(latency[1m])", + "precompute": "stream aggregation", + "expr": "max_over_time(latency:10s_max[60s] offset -4500ms)", + "time_step_ms": 10000, + "difference": null + }, + { + "id": "q5", + "query_text": "sum by (job) (rate(requests_total[1m]))", + "precompute": "recording rule", + "expr": "last_over_time(job:requests_total:sum_rate_1m_q5[10s])", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/max.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/max.plan.json new file mode 100644 index 00000000..2ab925a1 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/max.plan.json @@ -0,0 +1,27 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 10000, + "by": null, + "outputs": [ + "max" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "max_over_time(latency[1m])", + "precompute": "stream aggregation", + "expr": "max_over_time(latency:10s_max[60s] offset -4500ms)", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile.plan.json new file mode 100644 index 00000000..cc435caa --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "quantile-q1", + "interval_ms": 10000, + "record": "series:latency:quantile_over_time_0_99_1m_q1", + "expr": "quantile_over_time(0.99, latency[1m])", + "reads_counters": false, + "longest_range_ms": 60000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1m])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1m_q1[10s])", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile_rank.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile_rank.plan.json new file mode 100644 index 00000000..3c17db30 --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/quantile_rank.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "quantile_rank-q1", + "interval_ms": 10000, + "record": "series:latency:quantile_over_time_0_99_1m_q1", + "expr": "quantile_over_time(0.99, latency[1m])", + "reads_counters": false, + "longest_range_ms": 60000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "quantile_over_time(0.99, latency[1m])", + "precompute": "recording rule", + "expr": "last_over_time(series:latency:quantile_over_time_0_99_1m_q1[10s])", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_over_time.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_over_time.plan.json new file mode 100644 index 00000000..0b39f22d --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_over_time.plan.json @@ -0,0 +1,29 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [ + { + "query": "q1", + "metric": "latency", + "selector": "latency", + "interval_ms": 10000, + "by": [ + "job" + ], + "outputs": [ + "sum_samples" + ] + } + ], + "recording_rules": [], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (sum_over_time(latency[1m]))", + "precompute": "stream aggregation", + "expr": "sum_over_time(latency:10s_by_job_sum_samples[60s] offset -4500ms)", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_rate.plan.json b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_rate.plan.json new file mode 100644 index 00000000..a1a3b3af --- /dev/null +++ b/system-bench/tests/fixtures/hand-written/victoriametrics/showcase-1m/sum_rate.plan.json @@ -0,0 +1,26 @@ +{ + "victoriametrics_hand_written": { + "stream_aggregations": [], + "recording_rules": [ + { + "query": "q1", + "group": "sum_rate-q1", + "interval_ms": 10000, + "record": "job:requests_total:sum_rate_1m_q1", + "expr": "sum by (job) (rate(requests_total[1m]))", + "reads_counters": true, + "longest_range_ms": 60000 + } + ], + "queries": [ + { + "id": "q1", + "query_text": "sum by (job) (rate(requests_total[1m]))", + "precompute": "recording rule", + "expr": "last_over_time(job:requests_total:sum_rate_1m_q1[10s])", + "time_step_ms": 10000, + "difference": null + } + ] + } +} diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs index 5e3ab90a..3f257eec 100644 --- a/system-bench/tests/victoriametrics_conformance.rs +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -11,6 +11,11 @@ //! answers with hand-computed ones: (a) rows to 1e-9 relative, (b) rows by //! the stated difference. The cases run in real time (about a minute each) //! and share the server: run with `--test-threads 1`. +//! +//! H1 runs the hand-written variant (`scripts/victoriametrics-hand-written.py`) +//! and also needs a vmalert running in the server's container +//! (`AQPBM_VICTORIAMETRICS_VMALERT_URL`, `AQPBM_VICTORIAMETRICS_VMALERT_RULES_FILE`; +//! `VMALERT_PORT` of `scripts/extbench-up-victoriametrics.sh`). mod common; @@ -28,7 +33,7 @@ use aqpbm_core::harness::engine::{ use common::{fixture_value_public, payload_body}; use serde_json::{json, Value}; use system_bench::engines_external::victoriametrics_server::{ - VictoriaMetricsEngine, VictoriaMetricsServer, + VictoriaMetricsEngine, VictoriaMetricsServer, VmalertServer, }; const EQUIVALENT_ONLY: &str = "victoriametrics.equivalent-only"; @@ -826,3 +831,259 @@ fn a_late_chunk_fails_the_step() { let error = installed.ingest(&all[0]).expect_err("a late chunk fails"); assert!(error.0.contains("pacing"), "{error}"); } + +/// The hand-written file `scripts/victoriametrics-hand-written.py` writes +/// for `workload`. +fn hand_written_file(workload: &WorkloadSpec) -> Value { + let dir = std::env::temp_dir().join(format!( + "victoriametrics-hand-written-{}-{}", + std::process::id(), + RUN.with(|run| run.clone()) + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("workloads")).unwrap(); + std::fs::write( + dir.join(format!("workloads/{}.json", workload.name)), + serde_json::to_string(workload).unwrap(), + ) + .unwrap(); + let script = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../scripts/victoriametrics-hand-written.py"); + let out = std::process::Command::new("python3") + .arg(&script) + .arg(&dir) + .output() + .expect("python3 runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let text = std::fs::read_to_string(dir.join(format!( + "plans/victoriametrics.hand-written/{}.plan.json", + workload.name + ))) + .unwrap(); + serde_json::from_str(&text).unwrap() +} + +/// H1: the hand-written variant of every showcase query shape (stream +/// aggregation by job for sum and count, per-series stream max, recording +/// rules for quantiles, an average of quantiles and a summed rate, the same +/// quantile twice as two rules) answers as the hand-computed answers of the +/// cases above, at every evaluation, through 30 s after the data ends. Also +/// prints how often an unshifted read of a stream output is wrong. +#[test] +#[ignore = "needs a VictoriaMetrics v1.154.1 server with vmalert (AQPBM_VICTORIAMETRICS_URL, AQPBM_SERVER_CGROUP_DIRECTORY, AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG, AQPBM_VICTORIAMETRICS_VMALERT_URL, AQPBM_VICTORIAMETRICS_VMALERT_RULES_FILE)"] +fn hand_written_rules_equal_the_hand_computed_answers() { + let run = RUN.with(|run| run.clone()); + let latency = format!("latency{{conformance_run=\"{run}\"}}"); + let requests = format!("requests_total{{conformance_run=\"{run}\"}}"); + let texts = [ + format!("sum by (job) (sum_over_time({latency}[1m]))"), + format!("sum by (job) (count_over_time({latency}[1m]))"), + format!("max_over_time({latency}[1m])"), + format!("quantile_over_time(0.99, {latency}[1m])"), + format!("quantile_over_time(0.5, {latency}[1m])"), + format!("avg by (job) (quantile_over_time(0.9, {latency}[1m]))"), + format!("sum by (job) (rate({requests}[1m]))"), + format!("quantile_over_time(0.5, {latency}[1m])"), + "unshifted read".to_string(), + format!("sum_over_time({latency}[1m])"), + ]; + let workload = WorkloadSpec::periodic( + "hand_written".into(), + texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.clone(), + dialect: None, + }], + window_ms: 60_000, + evaluation_interval_ms: 10_000, + truth: None, + threshold: None, + unit: None, + accuracy_metric: None, + }) + .collect(), + vec![], + ); + let mut file = hand_written_file(&workload); + let spec = &mut file["victoriametrics_hand_written"]; + // The generator makes the last text (no PromQL) a rule; read q0's stream + // output without the shift instead. + let rules = spec["recording_rules"].as_array_mut().unwrap(); + let unshifted_rule = rules.iter().position(|r| r["query"] == "q8").unwrap(); + rules.remove(unshifted_rule); + let shifted = spec["queries"][0]["expr"].as_str().unwrap().to_string(); + spec["queries"][8]["expr"] = json!(shifted.split(" offset").next().unwrap().to_string() + ")"); + spec["queries"][8]["precompute"] = json!("stream aggregation"); + spec["queries"][8]["time_step_ms"] = json!(10_000); + let kinds: Vec<&str> = spec["queries"] + .as_array() + .unwrap() + .iter() + .map(|q| q["precompute"].as_str().unwrap()) + .collect(); + assert_eq!(kinds[9], "stream aggregation"); + assert_eq!( + &kinds[..8], + [ + "stream aggregation", + "stream aggregation", + "stream aggregation", + "recording rule", + "recording rule", + "recording rule", + "recording rule", + "recording rule", + ] + ); + assert_ne!(spec["queries"][4]["expr"], spec["queries"][7]["expr"]); + println!( + "H1 hand-written file:\n{}", + serde_json::to_string_pretty(&file).unwrap() + ); + + let engine = engine().with_vmalert(VmalertServer { + url: std::env::var("AQPBM_VICTORIAMETRICS_VMALERT_URL") + .expect("AQPBM_VICTORIAMETRICS_VMALERT_URL"), + rules_file: std::env::var("AQPBM_VICTORIAMETRICS_VMALERT_RULES_FILE") + .expect("AQPBM_VICTORIAMETRICS_VMALERT_RULES_FILE") + .into(), + }); + let mut installed = engine + .install(&workload, &arm("hand-written", &file)) + .unwrap(); + println!("{}", installed.plan_summary().text); + let data = latency_data(); + let counters = counter_data(); + let mut samples = data.samples(); + samples.extend(counters.samples()); + let answers = run_until(installed.as_mut(), samples, 110_000); + assert_eq!(answers.len(), 6); + let per_series = |t: i64, f: &dyn Fn(&[f64]) -> f64| -> BTreeMap { + data.windows(t, 60_000) + .into_iter() + .map(|(labels, values)| ((**labels).clone(), f(&values))) + .collect() + }; + let grouped = |t: i64, f: &dyn Fn(&[f64]) -> f64, outer: &dyn Fn(&[f64]) -> f64| { + let mut groups: BTreeMap> = BTreeMap::new(); + for (labels, values) in data.windows(t, 60_000) { + groups + .entry(group_key(labels, &["job"])) + .or_default() + .push(f(&values)); + } + groups + .into_iter() + .map(|(k, v)| (k, outer(&v))) + .collect::>() + }; + let sum = |v: &[f64]| v.iter().sum::(); + let max = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max); + let mut unshifted_wrong = 0; + let mut zero_for_empty_group = Vec::new(); + let mut zero_for_empty_series = Vec::new(); + for (t, got) in &answers { + let t = *t; + // q0: a job whose series all stopped might answer 0 while its + // sum_samples output is not stale (why the translator pairs it with + // count_samples), where the truth has none: allowed, and printed. + let mut q0 = got.clone(); + let expected_q0 = grouped(t, &sum, &sum); + if let Some(series) = q0.0.get_mut("q0") { + series.retain(|labels, value| { + let extra = !expected_q0.contains_key(labels); + if extra { + assert_eq!( + *value, 0.0, + "q0 at {t}: an extra group {labels:?} that is not 0" + ); + zero_for_empty_group.push((t, labels.clone())); + } + !extra + }); + } + assert_answers(t, &q0, 0, &expected_q0); + assert_answers(t, got, 1, &grouped(t, &|v| v.len() as f64, &sum)); + assert_answers(t, got, 2, &per_series(t, &max)); + assert_answers(t, got, 3, &per_series(t, &|v| quantile(0.99, v))); + assert_answers(t, got, 4, &per_series(t, &|v| quantile(0.5, v))); + assert_answers( + t, + got, + 5, + &grouped(t, &|v| quantile(0.9, v), &|v| sum(v) / v.len() as f64), + ); + assert_answers(t, got, 7, &per_series(t, &|v| quantile(0.5, v))); + // q9, per-series sum_samples: the same allowance as q0. + let mut q9 = got.clone(); + let expected_q9 = per_series(t, &sum); + let expected_q9_keys: Vec = expected_q9 + .keys() + .map(|l| { + let mut l = l.clone(); + l.remove("__name__"); + l + }) + .collect(); + if let Some(series) = q9.0.get_mut("q9") { + series.retain(|labels, value| { + let extra = !expected_q9_keys.contains(labels); + if extra { + assert_eq!( + *value, 0.0, + "q9 at {t}: an extra series {labels:?} that is not 0" + ); + zero_for_empty_series.push((t, labels["instance"].clone())); + } + !extra + }); + } + assert_answers(t, &q9, 9, &expected_q9); + if t <= 80_000 { + let mut by_job: BTreeMap = BTreeMap::new(); + for (labels, points) in &counters.0 { + if let Some((_, rate)) = vm_increase_rate(points, t, 60_000) { + *by_job.entry(group_key(labels, &["job"])).or_default() += rate; + } + } + assert_answers(t, got, 6, &by_job); + } + let unshifted = got.0.get("q8").cloned().unwrap_or_default(); + let wrong = unshifted.len() != expected_q0.len() + || expected_q0.iter().any(|(labels, want)| { + unshifted + .get(labels) + .is_none_or(|have| (have - want).abs() > 1e-9 * want.abs().max(1.0)) + }); + if wrong { + unshifted_wrong += 1; + } + } + println!( + "H1 hand-written: {} evaluations x 9 queries equal (rate through 80 s); q0's group with no \ + sample answered 0 at {:?}; q9's series with no sample answered 0 at \ + {zero_for_empty_series:?}; the unshifted stream read was wrong at {unshifted_wrong} of {} \ + evaluations", + answers.len(), + zero_for_empty_group + .iter() + .map(|(t, labels)| format!("{t} ms {labels:?}")) + .collect::>(), + answers.len() + ); +} + +/// Feeds `samples` in real time in 10 s chunks through `end_ms` and evaluates +/// after each chunk from 60 s on. +fn run_until(arm: &mut dyn InstalledArm, samples: Vec, end_ms: i64) -> Vec<(i64, Answers)> { + run(arm, &chunks(samples, 10_000, end_ms), 60_000, 10_000) +} diff --git a/system-bench/tests/victoriametrics_hand_written.rs b/system-bench/tests/victoriametrics_hand_written.rs new file mode 100644 index 00000000..a81ebbdf --- /dev/null +++ b/system-bench/tests/victoriametrics_hand_written.rs @@ -0,0 +1,275 @@ +//! The hand-written VictoriaMetrics variant without a server: the generator +//! (`scripts/victoriametrics-hand-written.py`, run with `python3`) writes the +//! committed fixtures for the showcase suites, the adapter reads them, refuses +//! malformed files, and renders the configs it loads. + +use std::path::{Path, PathBuf}; + +use aqpbm_core::harness::engine::WorkloadSpec; +use serde_json::{json, Value}; +use system_bench::engines_external::victoriametrics_hand_written::{ + is_hand_written, last_evaluation, loaded_rules, HandWritten, VmalertMetrics, +}; + +fn repo() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("..") +} + +fn fixtures(suite: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("tests/fixtures/hand-written/victoriametrics") + .join(suite) +} + +fn suite_workload(suite: &str, name: &str) -> WorkloadSpec { + let path = repo().join(format!("suites/{suite}/{name}.workload.json")); + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap() +} + +fn fixture_text(suite: &str, name: &str) -> String { + std::fs::read_to_string(fixtures(suite).join(format!("{name}.plan.json"))).unwrap() +} + +const WORKLOADS: [&str; 8] = [ + "avg_quantile", + "count", + "joint", + "max", + "quantile", + "quantile_rank", + "sum_over_time", + "sum_rate", +]; + +#[test] +fn the_generator_writes_the_fixtures() { + for suite in ["showcase-1m", "showcase-1h"] { + let run = std::env::temp_dir().join(format!( + "victoriametrics-hand-written-{}-{suite}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&run); + std::fs::create_dir_all(run.join("workloads")).unwrap(); + for name in WORKLOADS { + std::fs::copy( + repo().join(format!("suites/{suite}/{name}.workload.json")), + run.join(format!("workloads/{name}.json")), + ) + .unwrap(); + } + let out = std::process::Command::new("python3") + .arg(repo().join("scripts/victoriametrics-hand-written.py")) + .arg(&run) + .output() + .expect("python3 runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let variant = run.join("plans/victoriametrics.hand-written"); + for name in WORKLOADS { + let written = + std::fs::read_to_string(variant.join(format!("{name}.plan.json"))).unwrap(); + assert_eq!(written, fixture_text(suite, name), "{suite}/{name}"); + } + let native: Value = serde_json::from_str( + &std::fs::read_to_string(run.join("plans/victoriametrics.native/variant.json")) + .unwrap(), + ) + .unwrap(); + assert_eq!( + native, + json!({"substitutions_allowed": true, "plans": false, "run_by_default": false}) + ); + std::fs::remove_dir_all(&run).unwrap(); + } +} + +#[test] +fn every_fixture_reads_and_answers_its_workload() { + for suite in ["showcase-1m", "showcase-1h"] { + for name in WORKLOADS { + let text = fixture_text(suite, name); + assert!(is_hand_written(&text)); + let spec = HandWritten::from_json(&text).unwrap(); + spec.check_workload(&suite_workload(suite, name)) + .unwrap_or_else(|e| panic!("{suite}/{name}: {e}")); + // One stream aggregation or one rule per query, nothing shared. + assert_eq!( + spec.stream_aggregations.len() + spec.recording_rules.len(), + spec.queries.len(), + "{suite}/{name}" + ); + } + } + // A planner plan file is not a hand-written one. + let plan = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join( + "tests/fixtures/plans/public/max__1m_1hz_10s.victoriametrics.equivalent-only.plan.json", + )) + .unwrap(); + assert!(!is_hand_written(&plan)); +} + +#[test] +fn the_showcase_rules_per_query() { + let rules = |suite: &str, name: &str| -> Vec { + let spec = HandWritten::from_json(&fixture_text(suite, name)).unwrap(); + spec.queries + .iter() + .map(|q| format!("{} -> {}", q.precompute, q.expr)) + .collect() + }; + assert_eq!( + rules("showcase-1m", "sum_over_time"), + ["stream aggregation -> sum_over_time(latency:10s_by_job_sum_samples[60s] offset -4500ms)"] + ); + assert_eq!( + rules("showcase-1m", "count"), + ["stream aggregation -> sum_over_time(latency:10s_by_job_count_samples[60s] offset -4500ms)"] + ); + assert_eq!( + rules("showcase-1h", "max"), + ["stream aggregation -> max_over_time(latency:60s_max[3600s] offset -29500ms)"] + ); + assert_eq!( + rules("showcase-1m", "sum_rate"), + ["recording rule -> last_over_time(job:requests_total:sum_rate_1m_q1[10s])"] + ); + assert_eq!( + rules("showcase-1m", "joint"), + [ + "recording rule -> last_over_time(series:latency:quantile_over_time_0_99_1m_q1[10s])", + "recording rule -> last_over_time(series:latency:quantile_over_time_0_5_1m_q2[10s])", + "recording rule -> last_over_time(job:latency:avg_quantile_over_time_0_9_1m_q3[10s])", + "stream aggregation -> max_over_time(latency:10s_max[60s] offset -4500ms)", + "recording rule -> last_over_time(job:requests_total:sum_rate_1m_q5[10s])", + ] + ); +} + +#[test] +fn the_configs_it_loads() { + let spec = HandWritten::from_json(&fixture_text("showcase-1m", "joint")).unwrap(); + assert_eq!( + spec.stream_aggregation_config(Some("install-1-0")), + "- match: 'latency'\n name: 'install-1-0'\n interval: 10s\n outputs: [max]\n \ + enable_windows: true\n ignore_first_intervals: 0\n flush_on_shutdown: false\n" + ); + let rules = spec.rules_yaml(Some("install-1-0")); + assert!(rules.starts_with( + "groups:\n - name: 'install-1-0-joint-q1'\n interval: 10s\n eval_alignment: true\n \ + eval_delay: 0s\n rules:\n - record: 'series:latency:quantile_over_time_0_99_1m_q1'\n \ + expr: 'quantile_over_time(0.99, latency[1m])'\n" + ), "{rules}"); + assert_eq!(rules.matches("- name:").count(), 4); + assert_eq!(spec.longest_counter_range_ms(), Some(60_000)); + let spec = HandWritten::from_json(&fixture_text("showcase-1m", "max")).unwrap(); + assert_eq!(spec.rules_yaml(None), "groups: []\n"); + assert_eq!(spec.longest_counter_range_ms(), None); + assert_eq!(spec.recorded_series(), ["latency:10s_max"]); +} + +#[test] +fn malformed_files_are_refused() { + let base: Value = serde_json::from_str(&fixture_text("showcase-1m", "joint")).unwrap(); + let refused = |change: &dyn Fn(&mut Value), needle: &str| { + let mut file = base.clone(); + change(&mut file["victoriametrics_hand_written"]); + let error = HandWritten::from_json(&file.to_string()).unwrap_err(); + assert!(error.contains(needle), "{error} does not contain {needle}"); + }; + refused(&|s| s["extra"] = json!(1), "unknown field"); + refused( + &|s| s["stream_aggregations"][0]["outputs"] = json!(["histogram_bucket"]), + "unknown stream output", + ); + refused( + &|s| s["stream_aggregations"][0]["interval_ms"] = json!(7_000), + "dividing a day", + ); + refused( + &|s| s["recording_rules"][1]["record"] = s["recording_rules"][0]["record"].clone(), + "two writers", + ); + refused( + &|s| s["recording_rules"][1]["group"] = s["recording_rules"][0]["group"].clone(), + "two rules in the group", + ); + refused( + &|s| s["recording_rules"][0]["interval_ms"] = json!(1_500), + "whole seconds", + ); + refused( + &|s| s["recording_rules"][0]["query"] = json!("q9"), + "unknown query", + ); + refused( + &|s| s["queries"][0]["time_step_ms"] = json!(0), + "time_step_ms 0", + ); + + let spec = HandWritten::from_json(&base.to_string()).unwrap(); + let workload = suite_workload("showcase-1m", "joint"); + let mut fewer = workload.clone(); + fewer.queries.pop(); + assert!(spec.check_workload(&fewer).unwrap_err().contains("has 4")); + let mut other_text = workload.clone(); + other_text.queries[0].texts[0].text = "max_over_time(latency[1m])".into(); + assert!(spec + .check_workload(&other_text) + .unwrap_err() + .contains("is not workload query q1")); + // The 1h file does not answer the 1m workload. + let hour = HandWritten::from_json(&fixture_text("showcase-1h", "joint")).unwrap(); + assert!(hour.check_workload(&workload).is_err()); +} + +#[test] +fn vmalert_answers_it_reads() { + let rules = r#"{"status":"success","data":{"groups":[{"name":"install-1-0-joint-q1","id":"44", + "rules":[{"name":"series:latency:quantile_over_time_0_99_1m_q1","id":"69","group_id":"44"}]}]}}"#; + let wanted = [( + "install-1-0-joint-q1".to_string(), + "series:latency:quantile_over_time_0_99_1m_q1".to_string(), + 10_000, + )]; + let loaded = loaded_rules(rules, &wanted).unwrap().unwrap(); + assert_eq!( + (loaded[0].group_id.as_str(), loaded[0].rule_id.as_str()), + ("44", "69") + ); + let missing = [("install-1-1-joint-q1".to_string(), "x".to_string(), 10_000)]; + assert_eq!(loaded_rules(rules, &missing).unwrap(), None); + + let rule = r#"{"name":"r","updates":[{"time":"2026-12-03T07:24:20.241503191Z","at":"2026-12-03T07:24:20Z","error":null,"samples":1}, + {"at":"2026-12-03T07:24:10Z","error":null}]}"#; + assert_eq!( + last_evaluation(rule).unwrap(), + Some((1_796_282_660_000, None)) + ); + let failed = r#"{"updates":[{"at":"2026-12-03T07:24:20Z","error":"bad query"}]}"#; + assert_eq!( + last_evaluation(failed).unwrap(), + Some((1_796_282_660_000, Some("\"bad query\"".into()))) + ); + assert_eq!(last_evaluation(r#"{"updates":[]}"#).unwrap(), None); + + let metrics = VmalertMetrics::parse( + "# HELP x\nvmalert_config_last_reload_total 3\nvmalert_config_last_reload_errors_total 1\n\ + vmalert_remotewrite_total 10\nvmalert_remotewrite_sent_rows_total 9\n\ + vmalert_remotewrite_dropped_rows_total 1\nvmalert_remotewrite_errors_total 0\n\ + vmalert_remotewrite_sent_rows_count 4\n", + ); + assert_eq!( + metrics, + VmalertMetrics { + reloads: 3, + reload_errors: 1, + rows_queued: 10, + rows_sent: 9, + rows_dropped: 1, + write_errors: 0, + } + ); +}