Skip to content

VictoriaMetrics: hand-written baseline variant (one stream aggregation or vmalert rule per query) - #291

Draft
zzylol wants to merge 1 commit into
mainfrom
feat/vm-handwritten-variant
Draft

zzylol wants to merge 1 commit into
mainfrom
feat/vm-handwritten-variant

Conversation

@zzylol

@zzylol zzylol commented Dec 3, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Problem: the E3 comparison "planner's plan vs hand-written precompute on the same engine" had no hand-written VictoriaMetrics side: the victoriametrics engine ran only the query texts (native) and planner plans.
  • Change: a new variant victoriametrics.hand-written: per query, the one stream aggregation or one vmalert recording rule an experienced user writes by hand (nothing shared between queries), with the dashboard query reading the recorded series. scripts/victoriametrics-hand-written.py writes it into a run directory; the adapter installs it (stream config as before, rules into a vmalert that runs inside the server's container).
  • Effect: native / planner plan / hand-written run on one engine into one report. Example: sum by (job) (rate(requests_total[1m])) every 10 s becomes the rule job:requests_total:sum_rate_1m_q1 (vmalert group every 10 s) read by last_over_time(job:requests_total:sum_rate_1m_q1[10s]); on the conformance data its answers equal the hand-computed VictoriaMetrics rate at every evaluation (1e-9).

Review guide

Base main. Read first:

  1. system-bench/src/engines_external/victoriametrics_hand_written.rs: the file format, its checks, the YAML it renders, vmalert API parsing.
  2. system-bench/src/engines_external/victoriametrics_server.rs: install now builds an ArmSetup from a plan (unchanged logic, moved into plan_setup) or a hand-written file (hand_written_setup); InstalledRules (load / wait / unload) and the ingest additions.
  3. scripts/victoriametrics-hand-written.py: the rules per query shape.

Mechanical: the fixtures under system-bench/tests/fixtures/hand-written/victoriametrics/ are the generator's output for suites/showcase-1m and -1h (a test regenerates and compares them). Shared files touched minimally: engines_external/mod.rs (one line), docs/system-bench.md (one paragraph). No aqpbm-core change: the hand-written file sits in the harness's opaque plans/<variant>/<w>.plan.json slot, told apart by its top-level key (the same convention as the ClickHouse hand-written variant).

Behavior: before → after

Before: a run directory for engine victoriametrics could hold victoriametrics.native and the planner's victoriametrics.equivalent-only / .with-substitutes.

After:

scripts/plan-suite.sh ...                              # planner variants, as before
python3 scripts/victoriametrics-hand-written.py $RUN   # + plans/victoriametrics.hand-written/ (+ victoriametrics.native if missing)
LISTEN_HOST=$H VMALERT_PORT=18880 scripts/extbench-up-victoriametrics.sh up $DATA $CORES 0 18428
approxbench benchmark-external run --run-directory $RUN --engine victoriametrics ... \
  --victoriametrics-vmalert-url http://$H:18880 --victoriametrics-vmalert-rules-file $DATA/config/rules.yaml \
  --warmup 0 --runs 1 --variant victoriametrics.hand-written --variant victoriametrics.with-substitutes ...
approxbench benchmark-external report --run-directory $RUN --truth victoriametrics/victoriametrics.native

Rules per showcase query (pane p = gcd(window, interval): 10 s for showcase-1m, 60 s for -1h; h = (p − 1 s)/2):

Workload Hand-written Dashboard query (showcase-1m)
sum_over_time sum by (job) (sum_over_time(latency[1m])) stream aggregation latency every 10 s, by: [job], sum_samples sum_over_time(latency:10s_by_job_sum_samples[60s] offset -4500ms)
count sum by (job) (count_over_time(latency[1m])) same, count_samples sum_over_time(latency:10s_by_job_count_samples[60s] offset -4500ms)
max max_over_time(latency[1m]) stream aggregation every 10 s, per series, max max_over_time(latency:10s_max[60s] offset -4500ms)
quantile / quantile_rank quantile_over_time(0.99, latency[1m]) vmalert rule series:latency:quantile_over_time_0_99_1m_q1 last_over_time(series:latency:quantile_over_time_0_99_1m_q1[10s])
avg_quantile avg by (job) (quantile_over_time(0.9, latency[1m])) rule job:latency:avg_quantile_over_time_0_9_1m_q1 last_over_time(…[10s])
sum_rate sum by (job) (rate(requests_total[1m])) rule job:requests_total:sum_rate_1m_q1 last_over_time(…[10s])
joint (q1–q5) rules for q1, q2, q3, q5 (q1 and q2 not shared), stream max for q4 as above

Each rule is its own vmalert group: interval = the evaluation interval, eval_alignment: true, eval_delay: 0s (the server's -search.latencyOffset is 0).

Where hand-written answers can differ (also in capabilities/README.md § Hand-written variant)

  • Look-back of the recorded series (measured): a bare selector job:…_q1 answers from the last 5 minutes (an instant query's default look-back), so series another arm or a removed rule recorded keep answering. The first conformance run showed it: the quantile record returned two series of an earlier test run besides the current three. The dashboard query therefore reads last_over_time(<record>[<interval>]), the latest evaluation only.
  • vmalert defaults: with -rule.evalDelay=30s (default) the record at t holds the window ending 30 s earlier (rounded down to the interval), and a dashboard reading before the group ran for t gets the previous interval's record (stale by one interval). The variant sets eval_delay: 0s and the adapter waits for the evaluation at t (ingest work).
  • Stream read shift: stream outputs are stamped at flush time ([end − 1 s, end + lag]), so an unshifted read can count one window too many or too few; the variant reads with offset -h like the translator. Measured: the unshifted read was wrong at 0 of 6 evaluations in the conformance run (timing-dependent hazard, not seen here).
  • sum_samples without count_samples: the translator pairs them in case an empty window is written as 0; v1.154.1 wrote no such 0 in the conformance test (by job and per series, 20–70 s after the series stopped), so the hand-written read has no companion.
  • Counters: the rule computes VictoriaMetrics rate / increase (no extrapolation, prev/8 reset rule), identical to the native query; the differences from PromQL are the ones the existing conformance documents.

Interfaces

system-bench/src/engines_external/victoriametrics_hand_written.rs (new):

+/// The top-level key of a hand-written file.
+pub const KEY: &str = "victoriametrics_hand_written";
+/// A hand-written deployment: per query one stream aggregation or one recording rule, and its dashboard query.
+pub struct HandWritten {
+    pub stream_aggregations: Vec<HandWrittenStream>,
+    pub recording_rules: Vec<RecordingRule>,
+    pub queries: Vec<DashboardQuery>,
+}
+/// One stream aggregation, written for one query (`query` = workload query id).
+pub struct HandWrittenStream { pub query: String, pub metric: String, pub selector: String, pub interval_ms: u64, pub by: Option<Vec<String>>, pub outputs: Vec<String> }
+/// One vmalert recording rule in a group of its own; `reads_counters` / `longest_range_ms` set the previous-arm gap.
+pub struct RecordingRule { pub query: String, pub group: String, pub interval_ms: u64, pub record: String, pub expr: String, pub reads_counters: bool, pub longest_range_ms: u64 }
+/// The dashboard query of workload query `id`; `difference` is reported as the cell's substitution.
+pub struct DashboardQuery { pub id: String, pub query_text: String, pub precompute: String, pub expr: String, pub time_step_ms: u64, pub difference: Option<String> }
+/// Whether a plan file is a hand-written file.
+pub fn is_hand_written(text: &str) -> bool;
+impl HandWritten {
+    /// Reads and checks a file (unique writers of each series, stream intervals VictoriaMetrics can hold, whole-second rule intervals).
+    pub fn from_json(text: &str) -> Result<HandWritten, String>;
+    /// Query i answers workload query i (id and one of its texts).
+    pub fn check_workload(&self, workload: &WorkloadSpec) -> Result<(), String>;
+    pub fn stream_aggregations(&self) -> Vec<StreamAggregation>;
+    pub fn stream_aggregation_config(&self, name: Option<&str>) -> String;
+    /// vmalert rules YAML, groups named `<prefix>-<group>`.
+    pub fn rules_yaml(&self, prefix: Option<&str>) -> String;
+    pub fn group_name(&self, rule: &RecordingRule, prefix: Option<&str>) -> String;
+    pub fn longest_counter_range_ms(&self) -> Option<u64>;
+    pub fn recorded_series(&self) -> Vec<String>;
+}
+/// vmalert API readers: RFC 3339 `at`, `/api/v1/rules`, `/api/v1/rule`, `/metrics`.
+pub fn rfc3339_utc_ms(text: &str) -> Option<i64>;
+pub struct LoadedRule { pub group_id: String, pub rule_id: String, pub record: String, pub interval_ms: u64 }
+pub fn loaded_rules(rules_json: &str, groups: &[(String, String, u64)]) -> Result<Option<Vec<LoadedRule>>, String>;
+pub fn last_evaluation(rule_json: &str) -> Result<Option<(i64, Option<String>)>, String>;
+pub struct VmalertMetrics { pub reloads: u64, pub reload_errors: u64, pub rows_queued: u64, pub rows_sent: u64, pub rows_dropped: u64, pub write_errors: u64 }

system-bench/src/engines_external/victoriametrics_server.rs:

 pub struct VictoriaMetricsEngine { /* private fields; + vmalert: Option<VmalertServer> */ }
+/// A vmalert that runs hand-written arms' rules against the server (in the server's container).
+pub struct VmalertServer {
+    /// e.g. `http://10.0.0.1:8880`
+    pub url: String,
+    /// its `-rule` file on the server host, replaced per arm
+    pub rules_file: PathBuf,
+}
 impl VictoriaMetricsEngine {
+    /// The vmalert that runs hand-written arms' recording rules.
+    pub fn with_vmalert(self, vmalert: VmalertServer) -> VictoriaMetricsEngine;
 }
 pub struct VictoriaMetricsOptions {
     pub victoriametrics_url: Option<String>,
     pub victoriametrics_stream_aggregation_config: Option<PathBuf>,
     pub speed: Option<f64>,
     pub cgroup: ServerCgroupOptions,
     pub victoriametrics_restart_command: Option<String>,
+    /// --victoriametrics-vmalert-url
+    pub victoriametrics_vmalert_url: Option<String>,
+    /// --victoriametrics-vmalert-rules-file (goes with the URL)
+    pub victoriametrics_vmalert_rules_file: Option<PathBuf>,
 }

Files and scripts:

+plans/victoriametrics.hand-written/<w>.plan.json   {"victoriametrics_hand_written": {...}} (format in the module docs)
+plans/victoriametrics.hand-written/variant.json    {"substitutions_allowed": true, "run_by_default": false}
+scripts/victoriametrics-hand-written.py <run-directory>
 scripts/extbench-up-victoriametrics.sh up|restart|down ...
+  VMALERT_PORT=<port>   also run vmalert (binary copied from the pinned vmalert v1.154.1 image) inside the server's container
+  VMALERT_IMAGE=<image@sha256:...>
+  versions.txt: + vmalert_image, vmalert_version, vmalert_url, vmalert_rules_file

Usage (the conformance test H1, end to end): the workload's nine queries → hand_written_file(&workload) runs the generator → engine().with_vmalert(VmalertServer { url, rules_file }) → install(&workload, &arm) loads 3 stream aggregations + 5 vmalert groups (reloaded 100 ms after a 10 s tick) → run_until(..., 110_000) feeds 10 s chunks in real time; each ingest waits for the stream flushes and each rule's evaluation at the chunk end → 6 evaluations (60–110 s) × 9 queries compared with the hand-computed answers.

Algorithm changes

Ingest of a hand-written arm with rules (new; planner arms unchanged):

  1. send the chunk's 1 s slices a lead early (as planner arms); then force_flush and require it done before the tick T (else a pacing error), since vmalert evaluates at T + 0.1–1.1 s;
  2. sleep until T, wait for stream flushes (as planner arms);
  3. per rule due at T: poll /api/v1/rule until updates[0].at ≥ T (an evaluation error fails the step; past T + interval fails);
  4. poll vmalert /metrics until sent + dropped ≥ queued (dropped or write errors since install fail the step); force_flush.
    The rule evaluation and its write-back thus count as ingest CPU; evaluation steps run only the dashboard queries.

vmalert phase: -group.maxStartDelay=1s makes a group start within 1 s of a reload, at a sub-second offset from its id; the adapter reloads 100 ms after a tick, so each group runs 0.1–1.1 s after each tick. Complexity: one HTTP poll per rule per 50 ms while waiting.

Decisions and open questions

Needs reviewer decision

  • vmalert in the server's container (docker exec) so one cgroup holds both; alternative was a second container measured separately (the harness reads one cgroup). Idle vmalert (no rules) is in native and planner arms' numbers too (~tens of MB RSS).
  • Dashboard query last_over_time(<record>[<interval>]) instead of the bare record name (see look-back above).
  • quantile_rank gets the same rule as quantile (same text; the hand-written baseline is exact).

Decided

  • 2026-12-03: one hand-written variant (exact precompute); approximate VictoriaMetrics features (histogram_bucket, quantiles outputs) are not a hand-written choice here.
  • 2026-12-03: file format = an opaque plan file with a top-level key, no harness change (same as the ClickHouse hand-written variant).

Verification

Scope Result Notes
cargo test -p system-bench --test victoriametrics_hand_written 6 passed generator reproduces fixtures (python3), every fixture reads and answers its suite workload, rules per showcase query, rendered configs, malformed files refused, vmalert API parsing
cargo test -p system-bench --lib passed + rfc3339_times
python3 -m unittest scripts/test_victoriametrics_hand_written.py 10 passed shapes, pane = gcd, no sharing, run-directory layout
victoriametrics_conformance --ignored on VictoriaMetrics v1.154.1 + vmalert v1.154.1 5 passed new H1 hand_written_rules_equal_the_hand_computed_answers: 6 evaluations × 9 queries equal to 1e-9 (rate through 80 s); existing R1–R9 still pass after the install refactor
cargo clippy -p system-bench --all-targets -- -D warnings, cargo fmt clean
End to end (benchmark-external run + report --truth victoriametrics/victoriametrics.native) 8/8 hand-written cells ran showcase-1m workloads (1000 series, 1 Hz) with data cut to 180 s, 13 evaluations each; planner plans from the committed public fixtures. Every hand-written cell: 0 missing, 0 extra series, max relative error ≤ 1.0e-12 against native (recorded values pass through VictoriaMetrics' JSON formatting; stream-only cells max/count exactly 0). Table below

End-to-end numbers (throttled shared test host, 7 server cores; correctness smoke, not headline timings)

Workload Variant ingest CPU ns/sample query CPU ms/evaluation server CPU ms whole arm max rel. error vs native
sum_over_time native 3,842 24.8 1,178 —
sum_over_time equivalent-only 20,954 31.4 4,259 3e-16
sum_over_time hand-written 17,854 9.0 3,619 7e-13
quantile native 3,726 25.6 1,198 —
quantile equivalent-only 19,734 36.9 4,140 0
quantile hand-written 26,732 19.3 5,148 1e-12
sum_rate native 3,945 18.8 1,105 —
sum_rate hand-written 23,738 3.8 4,387 1e-12
joint native 2,182 106.1 2,300 —
joint hand-written 20,392 52.2 8,077 1e-12

Native is replayed as fast as accepted; planner and hand-written arms are fed in wall-clock time (1 s slices and per-chunk flushes), which is most of their ingest CPU difference to native here.

Follow-ups

  • scripts/plan-suite.sh still lists no victoriametrics.* planner variants (runs add them locally); left alone here to keep shared files untouched.
  • Run commands for both suites are with the eval notes (not in the repo).

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi

…vmalert rules per query)

Adds victoriametrics.hand-written, what an experienced user writes by hand
for each query: one stream aggregation (sum/count/min/max over_time, grouped
at ingest when the outer aggregate allows) or one vmalert recording rule
(everything else), nothing shared between queries; the dashboard query reads
the recorded series. scripts/victoriametrics-hand-written.py writes it (and
victoriametrics.native) into a run directory, so native, planner plans and
hand-written run on one engine into one report.

The adapter installs a file with the key victoriametrics_hand_written
instead of translating it: stream aggregations as before, rules into a
vmalert (new --victoriametrics-vmalert-url / -rules-file) that the up script
runs inside the server's container (VMALERT_PORT), so its CPU and memory are
measured with the server's. Ingest waits for each rule's evaluation at the
chunk end and for vmalert's writes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@zzylol zzylol added the enhancement New feature or request label Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant