From 24e317f40821e473d5921fe2968d4e2718ba0260 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Tue, 24 Nov 2026 17:12:11 -0500 Subject: [PATCH] engines-external, cli: the VictoriaMetrics adapter and the victoriametrics engine, restacked on system-bench #265's ten commits (2aa86b20 .. 5c7a511d) rebuilt as one change on the ClickHouse restack (#263), since both add an engine to the same command: - the adapter lives in system-bench/src/engines_external/victoriametrics_server.rs; - it follows main's names (benchmark-external, --engine, --run-directory) and the spelled-out fixture and golden names; - decision D3 of #267: no HTTP agent. The server's cgroup is read over SSH or on this host (CgroupSource), and its -streamAggr.config file is replaced the same way: CgroupSource::replace_file_on_server_host writes a temporary file and renames it, locally or over main's shared SSH connection, before the HTTP reload. The victoriametrics engine takes --server-cgroup-directory, --server-ssh-host and --victoriametrics-stream-aggregation-config, and scripts/extbench-up-victoriametrics.sh no longer starts an agent and prints the config path; - #265's aqpbm-core changes served only the agent and are left out; - the replacement checks the written length before the rename, never follows a link at the temporary path, and removes the temporary file on failure; - RunArgs is boxed in the command enum (clippy large_enum_variant). Co-Authored-By: zz_y Co-Authored-By: Claude Opus 5.5 --- aqpbm-cli/src/benchmark_external_cmd.rs | 74 +- aqpbm-cli/tests/benchmark_external_cli.rs | 34 + aqpbm-core/src/harness/cgroup.rs | 92 ++ aqpbm-core/tests/harness_cgroup.rs | 53 + scripts/extbench-up-victoriametrics.sh | 101 ++ system-bench/src/engines_external/mod.rs | 4 +- .../src/engines_external/victoriametrics.rs | 21 +- .../victoriametrics_server.rs | 945 ++++++++++++++++++ .../tests/victoriametrics_conformance.rs | 820 +++++++++++++++ system-bench/tests/victoriametrics_server.rs | 487 +++++++++ .../tests/victoriametrics_translate.rs | 21 + 11 files changed, 2631 insertions(+), 21 deletions(-) create mode 100755 scripts/extbench-up-victoriametrics.sh create mode 100644 system-bench/src/engines_external/victoriametrics_server.rs create mode 100644 system-bench/tests/victoriametrics_conformance.rs create mode 100644 system-bench/tests/victoriametrics_server.rs diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs index e0b45e5b..0c24d104 100644 --- a/aqpbm-cli/src/benchmark_external_cmd.rs +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -17,9 +17,12 @@ use aqpbm_core::harness::protocol::{ use aqpbm_core::harness::run_directory::RunDirectory; use clap::{Parser, Subcommand}; use system_bench::engines_external::clickhouse_server::{ClickHouseEngine, ClickHouseServer}; +use system_bench::engines_external::victoriametrics_server::{ + VictoriaMetricsEngine, VictoriaMetricsServer, +}; /// The engines this binary can run. -pub const ENGINES: [&str; 2] = ["fake", "clickhouse"]; +pub const ENGINES: [&str; 3] = ["fake", "clickhouse", "victoriametrics"]; #[derive(Parser, Debug)] pub struct BenchmarkExternalArgs { @@ -30,7 +33,7 @@ pub struct BenchmarkExternalArgs { #[derive(Subcommand, Debug)] pub enum BenchmarkExternalCmd { /// Run every (workload, variant) cell of the run directory on one engine. - Run(RunArgs), + Run(Box), /// Join every engine run's cells into summary.csv, summary.md and accuracy.csv. Report(ReportArgs), } @@ -40,7 +43,8 @@ pub struct RunArgs { /// The run directory: workloads/, plans//, results/. #[arg(long)] pub run_directory: PathBuf, - /// The engine: `fake` (the harness's own fake engine) or `clickhouse`. + /// The engine: `fake` (the harness's own fake engine), `clickhouse` or + /// `victoriametrics`. #[arg(long)] pub engine: String, /// The ClickHouse server's HTTP interface, e.g. `http://10.0.0.1:8123` @@ -48,7 +52,8 @@ pub struct RunArgs { #[arg(long)] pub clickhouse_url: Option, /// The server's cgroup v2 directory, e.g. - /// `/sys/fs/cgroup/system.slice/docker-.scope` (engine `clickhouse`). + /// `/sys/fs/cgroup/system.slice/docker-.scope` (engines `clickhouse` + /// and `victoriametrics`). #[arg(long)] pub server_cgroup_directory: Option, /// The SSH destination of the server host, e.g. `bench@10.0.0.2`; the @@ -64,6 +69,14 @@ pub struct RunArgs { /// How long one ClickHouse statement may run, in seconds. #[arg(long, default_value_t = 600)] pub clickhouse_statement_timeout_seconds: u64, + /// The VictoriaMetrics server's HTTP interface, e.g. `http://10.0.0.1:8428` + /// (engine `victoriametrics`). + #[arg(long)] + pub victoriametrics_url: Option, + /// The server's `-streamAggr.config` file on the server host, replaced + /// for each arm (engine `victoriametrics`). + #[arg(long)] + pub victoriametrics_stream_aggregation_config: Option, /// Only these variants (repeatable); every variant under plans/ by default. #[arg(long = "variant")] pub variants: Vec, @@ -92,7 +105,7 @@ pub struct ReportArgs { pub fn run(args: BenchmarkExternalArgs) -> Result<()> { match args.command { - BenchmarkExternalCmd::Run(args) => run_engine_cmd(args), + BenchmarkExternalCmd::Run(args) => run_engine_cmd(*args), BenchmarkExternalCmd::Report(args) => report_cmd(args), } } @@ -101,30 +114,22 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> { let engine: Box = match args.engine.as_str() { "fake" => { if args.clickhouse_url.is_some() + || args.victoriametrics_url.is_some() + || args.victoriametrics_stream_aggregation_config.is_some() || args.server_cgroup_directory.is_some() || args.server_ssh_host.is_some() { bail!( - "--clickhouse-url, --server-cgroup-directory and --server-ssh-host are for engine clickhouse only" + "--clickhouse-url, --victoriametrics-url, --victoriametrics-stream-aggregation-config, --server-cgroup-directory and --server-ssh-host are for engines clickhouse and victoriametrics only" ); } Box::new(FakeEngine::default()) } "clickhouse" => { - let (Some(url), Some(cgroup_directory)) = ( - args.clickhouse_url.clone(), - args.server_cgroup_directory.clone(), - ) else { + let (Some(url), Some(cgroup)) = (args.clickhouse_url.clone(), server_cgroup(&args)) + else { bail!("engine clickhouse needs --clickhouse-url and --server-cgroup-directory"); }; - let cgroup = match args.server_ssh_host.clone() { - Some(host) => CgroupSource::Remote { - ssh_program: args.ssh_program.clone(), - host, - cgroup_directory, - }, - None => CgroupSource::Local(cgroup_directory), - }; Box::new(ClickHouseEngine::new(ClickHouseServer { url, cgroup, @@ -134,6 +139,27 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> { ), })?) } + "victoriametrics" => { + let (Some(url), Some(cgroup), Some(stream_aggregation_config)) = ( + args.victoriametrics_url.clone(), + server_cgroup(&args), + args.victoriametrics_stream_aggregation_config.clone(), + ) else { + bail!( + "engine victoriametrics needs --victoriametrics-url, --server-cgroup-directory and --victoriametrics-stream-aggregation-config" + ); + }; + // Wall-clock data runs one arm at a time. + if args.warmup != 0 || args.runs != 1 { + bail!("engine victoriametrics runs one arm at a time: pass --warmup 0 --runs 1"); + } + Box::new(VictoriaMetricsEngine::new(VictoriaMetricsServer { + url, + cgroup, + stream_aggregation_config, + request_timeout: std::time::Duration::from_secs(600), + })?) + } other => bail!( "unknown engine '{other}'; known engines: {}", ENGINES.join(", ") @@ -168,6 +194,18 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> { Ok(()) } +fn server_cgroup(args: &RunArgs) -> Option { + let cgroup_directory = args.server_cgroup_directory.clone()?; + Some(match args.server_ssh_host.clone() { + Some(host) => CgroupSource::Remote { + ssh_program: args.ssh_program.clone(), + host, + cgroup_directory, + }, + None => CgroupSource::Local(cgroup_directory), + }) +} + fn report_cmd(args: ReportArgs) -> Result<()> { let (engine, variant) = args .truth diff --git a/aqpbm-cli/tests/benchmark_external_cli.rs b/aqpbm-cli/tests/benchmark_external_cli.rs index 9c9a41c6..5f88c3b6 100644 --- a/aqpbm-cli/tests/benchmark_external_cli.rs +++ b/aqpbm-cli/tests/benchmark_external_cli.rs @@ -185,3 +185,37 @@ fn the_clickhouse_engine_needs_its_server() { ); let _ = std::fs::remove_dir_all(run.parent().unwrap()); } + +/// X4: engine `victoriametrics` needs its server, cgroup directory and +/// config file, and runs one arm at a time (wall-clock data): only with +/// `--warmup 0 --runs 1`. +#[test] +fn the_victoriametrics_engine_needs_its_server_and_one_run() { + let run = fixture("x4"); + let base = [ + "benchmark-external", + "run", + "--run-directory", + run.to_str().unwrap(), + "--engine", + "victoriametrics", + ]; + let out = approxbench(&base); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("--victoriametrics-url"), "{stderr}"); + let mut with_server = base.to_vec(); + with_server.extend([ + "--victoriametrics-url", + "http://127.0.0.1:1", + "--server-cgroup-directory", + "/sys/fs/cgroup/system.slice/docker-1.scope", + "--victoriametrics-stream-aggregation-config", + "/data/victoriametrics/config/stream-aggregation.yaml", + ]); + let out = approxbench(&with_server); + assert!(!out.status.success()); + let stderr = String::from_utf8_lossy(&out.stderr); + assert!(stderr.contains("--warmup 0 --runs 1"), "{stderr}"); + let _ = std::fs::remove_dir_all(run.parent().unwrap()); +} diff --git a/aqpbm-core/src/harness/cgroup.rs b/aqpbm-core/src/harness/cgroup.rs index 2dc2ed75..91c0cb12 100644 --- a/aqpbm-core/src/harness/cgroup.rs +++ b/aqpbm-core/src/harness/cgroup.rs @@ -89,6 +89,15 @@ impl CgroupSource { } } + pub fn replace_file_on_server_host(&self, path: &Path, text: &str) -> Result<(), CgroupError> { + match self { + CgroupSource::Local(_) => replace_local_file(path, text), + CgroupSource::Remote { + ssh_program, host, .. + } => ssh_replace(ssh_program, host, path, text), + } + } + /// `cpu.stat` read once. pub fn cpu(&self) -> Result { CgroupCpu::parse(&self.read("cpu.stat")?) @@ -243,6 +252,87 @@ fn ssh_read(ssh_program: &str, host: &str, path: &Path) -> Result PathBuf { + let mut name = path.as_os_str().to_owned(); + name.push(".tmp"); + PathBuf::from(name) +} + +fn replace_local_file(path: &Path, text: &str) -> Result<(), CgroupError> { + use std::io::Write; + let temporary = temporary_path(path); + let written = std::fs::remove_file(&temporary) + .or_else(|error| match error.kind() { + std::io::ErrorKind::NotFound => Ok(()), + _ => Err(error), + }) + .and_then(|()| { + std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&temporary) + }) + .and_then(|mut file| file.write_all(text.as_bytes())) + .and_then(|()| std::fs::rename(&temporary, path)); + written.map_err(|error| { + let _ = std::fs::remove_file(&temporary); + CgroupError::Write { + file: path.display().to_string(), + message: error.to_string(), + } + }) +} + +fn ssh_replace(ssh_program: &str, host: &str, path: &Path, text: &str) -> Result<(), CgroupError> { + use std::io::Write; + let quoted = shell_quoted(&path.to_string_lossy()); + let temporary = shell_quoted(&temporary_path(path).to_string_lossy()); + let length = text.len(); + let mut child = Command::new(ssh_program) + .args(SSH_OPTIONS) + .arg("--") + .arg(host) + .arg(format!( + "rm -f -- {temporary} && set -C && cat > {temporary} && \ + [ \"$(wc -c < {temporary})\" -eq {length} ] && exec mv -f -- {temporary} {quoted}; \ + status=$?; rm -f -- {temporary}; exit $status" + )) + .stdin(Stdio::piped()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| CgroupError::Remote { + host: host.into(), + message: format!("cannot start {ssh_program}: {error}"), + })?; + let written = child + .stdin + .take() + .expect("stdin is piped") + .write_all(text.as_bytes()); + let output = child + .wait_with_output() + .map_err(|error| CgroupError::Remote { + host: host.into(), + message: error.to_string(), + })?; + let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string(); + match (output.status.code(), written) { + (Some(0), Ok(())) => Ok(()), + (Some(255) | None, _) => Err(CgroupError::Remote { + host: host.into(), + message: stderr, + }), + (_, written) => Err(CgroupError::Write { + file: format!("{host}:{}", path.display()), + message: match written { + Err(error) if stderr.is_empty() => error.to_string(), + _ => stderr, + }, + }), + } +} + /// `text` in single quotes for the server host's shell, each `'` as `'\''`. fn shell_quoted(text: &str) -> String { format!("'{}'", text.replace('\'', r"'\''")) @@ -255,6 +345,8 @@ pub enum CgroupError { Read { file: String, message: String }, #[error("{file} has no '{field}' line")] MissingField { file: String, field: String }, + #[error("cannot write {file}: {message}")] + Write { file: String, message: String }, #[error("cannot parse {file}: {message}")] Parse { file: String, message: String }, #[error("SSH to {host}: {message}")] diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs index 47c31c3e..ed12957e 100644 --- a/aqpbm-core/tests/harness_cgroup.rs +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -447,3 +447,56 @@ fn a_group_with_a_foreign_process_is_not_the_server_cpu() { .unwrap(); assert_eq!(shared.cpu_source(), "schedstat"); } + +#[cfg(unix)] +#[test] +fn a_file_on_the_server_host_is_replaced_locally_and_over_ssh() { + let temp = TempDir::new("replace-'quoted'"); + let config = temp.0.join("stream-aggregation.yaml"); + std::fs::write(&config, "[]\n").unwrap(); + let local = CgroupSource::Local(temp.0.clone()); + local + .replace_file_on_server_host(&config, "- interval: 10s\n") + .unwrap(); + assert_eq!( + std::fs::read_to_string(&config).unwrap(), + "- interval: 10s\n" + ); + let remote = CgroupSource::Remote { + ssh_program: fake_ssh(&temp.0), + host: "bench@192.0.2.1".into(), + cgroup_directory: temp.0.clone(), + }; + remote + .replace_file_on_server_host(&config, "- interval: 20s\n") + .unwrap(); + assert_eq!( + std::fs::read_to_string(&config).unwrap(), + "- interval: 20s\n" + ); + assert!(!temp.0.join("stream-aggregation.yaml.tmp").exists()); + #[cfg(unix)] + { + let target = temp.0.join("not-the-config"); + std::fs::write(&target, "kept").unwrap(); + std::os::unix::fs::symlink(&target, temp.0.join("stream-aggregation.yaml.tmp")).unwrap(); + local + .replace_file_on_server_host(&config, "- interval: 30s\n") + .unwrap(); + assert_eq!(std::fs::read_to_string(&target).unwrap(), "kept"); + std::os::unix::fs::symlink(&target, temp.0.join("stream-aggregation.yaml.tmp")).unwrap(); + remote + .replace_file_on_server_host(&config, "- interval: 40s\n") + .unwrap(); + assert_eq!(std::fs::read_to_string(&target).unwrap(), "kept"); + assert_eq!( + std::fs::read_to_string(&config).unwrap(), + "- interval: 40s\n" + ); + } + let missing = temp.0.join("no-such-directory").join("config.yaml"); + assert!(matches!( + remote.replace_file_on_server_host(&missing, "x"), + Err(CgroupError::Write { .. }) + )); +} diff --git a/scripts/extbench-up-victoriametrics.sh b/scripts/extbench-up-victoriametrics.sh new file mode 100755 index 00000000..ee46ebf0 --- /dev/null +++ b/scripts/extbench-up-victoriametrics.sh @@ -0,0 +1,101 @@ +#!/usr/bin/env bash +# Start (or stop) a single-node VictoriaMetrics server for +# `approxbench benchmark-external --engine victoriametrics` on this host: a +# docker container pinned to given cores. The harness reads its cgroup and +# replaces its stream-aggregation config over SSH (`--server-ssh-host`, +# `--server-cgroup-directory`, `--victoriametrics-stream-aggregation-config`) +# and reloads the config for each arm. +# +# scripts/extbench-up-victoriametrics.sh up [] +# scripts/extbench-up-victoriametrics.sh down [] +# +# Example: LISTEN_HOST=10.0.0.2 \ +# scripts/extbench-up-victoriametrics.sh up /data/run-1/victoriametrics 2,22 0 18428 +# +# Environment: +# LISTEN_HOST address the server listens on (required): a +# private (10/8, 172.16/12, 192.168/16) or loopback address, +# never 0.0.0.0 or a public one: the server has no password +# IMAGE the image, pinned by digest (default: v1.154.1 below) +# +# Every start begins from an empty data dir. The script only deletes a data +# dir it created (it holds the marker file .extbench-data-dir). The +# container runs as the invoking user, with no CPU quota and no memory limit. +set -euo pipefail + +marker=.extbench-data-dir +default_image=victoriametrics/victoria-metrics@sha256:c7884f32920dd45a9d86542a717227e63af03e060e53bbf8031e6e6fd0e1e05d + +# Exit 0 when $1 is a private or loopback IPv4 address. +private_address() { + local a b c d + IFS=. read -r a b c d <<<"$1" || return 1 + for octet in "$a" "$b" "$c" "$d"; do + [[ "$octet" =~ ^[0-9]+$ ]] && [ "$octet" -le 255 ] || return 1 + done + [ "$a" = 10 ] && return 0 + [ "$a" = 127 ] && return 0 + [ "$a" = 172 ] && [ "$b" -ge 16 ] && [ "$b" -le 31 ] && return 0 + [ "$a" = 192 ] && [ "$b" = 168 ] && return 0 + return 1 +} + +action=${1:?up|down}; data_dir=${2:?data dir} + +if [ "$action" = down ]; then + name=${3:-extbench-victoriametrics} + docker rm -f "$name" >/dev/null 2>&1 || true + exit 0 +fi +[ "$action" = up ] || { echo "unknown action $action" >&2; exit 2; } + +cores=${3:?cores}; numa=${4:?numa node}; http_port=${5:?http port} +name=${6:-extbench-victoriametrics} +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; } + +if [ -e "$data_dir" ]; then + [ -f "$data_dir/$marker" ] || { echo "refused: $data_dir exists and was not made by this script" >&2; exit 1; } + docker rm -f "$name" >/dev/null 2>&1 || true + rm -rf "$data_dir" +fi +mkdir -p "$data_dir/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" + +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" \ + "$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 +for _ in $(seq 1 60); do + curl -sf "http://$LISTEN_HOST:$http_port/health" >/dev/null && break; sleep 1 +done +curl -sf "http://$LISTEN_HOST:$http_port/health" >/dev/null || { echo "the server did not start" >&2; docker logs "$name" >&2; exit 1; } + +id=$(docker inspect -f '{{.Id}}' "$name") +group="/sys/fs/cgroup/system.slice/docker-$id.scope" +[ -d "$group" ] || { echo "no cgroup at $group (is docker on the systemd cgroup driver?)" >&2; exit 1; } + +siblings() { + for core in ${cores//,/ }; do + printf '%s:%s ' "$core" "$(cat "/sys/devices/system/cpu/cpu$core/topology/thread_siblings_list")" + done +} +{ echo "image $image" + echo "image_id $(docker inspect -f '{{.Image}}' "$name")" + echo "version $(curl -sf "http://$LISTEN_HOST:$http_port/metrics" | sed -n 's/^vm_app_version{version="\([^"]*\)".*/\1/p')" + echo "cpuset $cores mems $numa" + echo "thread_siblings $(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" + echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" +cat "$data_dir/versions.txt" diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index bc18fa48..075ba3cd 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -4,7 +4,8 @@ //! version 15). [`clickhouse`] translates it into ClickHouse tables, //! materialized views and one SQL query per query root; //! [`victoriametrics`] into VictoriaMetrics stream aggregation and one -//! MetricsQL query per query root. A translator is the +//! MetricsQL query per query root, which [`victoriametrics_server`] runs on a +//! real server. A translator is the //! capability check: a node it has no rule for is refused with //! [`TranslationError::UnsupportedShape`], and a rule that changes the //! planner's guarantee is recorded as a [`Substitution`]. @@ -16,6 +17,7 @@ pub mod clickhouse; pub mod clickhouse_server; pub mod plan_file; pub mod victoriametrics; +pub mod victoriametrics_server; use plan_file::{PlanFile, Timing}; diff --git a/system-bench/src/engines_external/victoriametrics.rs b/system-bench/src/engines_external/victoriametrics.rs index caa53321..fbb2d9aa 100644 --- a/system-bench/src/engines_external/victoriametrics.rs +++ b/system-bench/src/engines_external/victoriametrics.rs @@ -209,14 +209,31 @@ impl VictoriaMetricsDeployment { /// The `-streamAggr.config` YAML: one list entry per stream aggregation; /// `[]` when there is none. pub fn stream_aggregation_config(&self) -> String { + self.config_yaml(None) + } + + /// The same config with every entry named `name` (the `name` label of the + /// server's stream-aggregation metrics), e.g. one name per install, so + /// an install can tell its aggregators' metrics from earlier ones. + pub fn stream_aggregation_config_named(&self, name: &str) -> String { + self.config_yaml(Some(name)) + } + + fn config_yaml(&self, name: Option<&str>) -> String { if self.stream_aggregations.is_empty() { return "[]\n".into(); } let mut yaml = String::new(); for aggregation in &self.stream_aggregations { yaml.push_str(&format!( - "- match: {}\n interval: {}\n", - yaml_quoted(&aggregation.selector), + "- match: {}\n", + yaml_quoted(&aggregation.selector) + )); + if let Some(name) = name { + yaml.push_str(&format!(" name: {}\n", yaml_quoted(name))); + } + yaml.push_str(&format!( + " interval: {}\n", duration(aggregation.interval_ms) )); if let Some(labels) = &aggregation.by { diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs new file mode 100644 index 00000000..81ca859a --- /dev/null +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -0,0 +1,945 @@ +//! A single-node VictoriaMetrics server as an engine under test: each arm is +//! a plan file translated by [`super::victoriametrics::translate`], its +//! stream aggregation loaded into the server, its data fed in real time with +//! wall-clock timestamps, and its queries run over HTTP. +//! +//! Stream aggregation runs on wall-clock time (see the capability README's +//! run contract), so an arm maps data time to wall time by an offset: a +//! sample at data time `ts` is sent with timestamp `ts + offset`, and an +//! evaluation at data time `t` queries `t + offset`. The offset is a whole +//! number of every window width and of the evaluation interval, so window +//! ends stay window ends. Example: windows of 10 s, evaluations every 10 s, +//! data from 0 ms, installed at wall time 1,794,932,831.4 s: offset +//! 1,794,932,840,000 ms, and the sample at data time 5,000 ms is sent with +//! timestamp 1,794,932,845,000 at wall time 1,794,932,840.5 s (the slice +//! `(4 s, 5 s]` sent 4.5 s early: `h` = 4.5 s). +//! +//! Feeding: each refresh chunk is cut into 1 s slices, and each slice is +//! sent a lead early: `max(1 s, h)`, `h = (w − 1 s) / 2` the narrowest +//! window's read shift. Every sample still lands in its own window (the +//! lead stays below the width), and a sample lags behind the wall clock +//! (which delays the server's flush by the lag) only when the harness's own +//! work between two chunks (the evaluation, the idle probe) takes longer +//! than the gap to the next chunk's first sample; the flush-lag check below +//! catches that. A slice that reaches the server less than 100 ms before +//! its window's end fails the step. The ingest of the chunk ending at `t` +//! then waits until `t`, then until every stream aggregation flushed once +//! for each of its ticks in the chunk (failing if that lags by `h` or more, +//! or if the server dropped a late sample), and makes the new rows +//! searchable, so this work is ingest CPU and an evaluation runs only its +//! queries. An arm that reads counters starts its data at least 10 minutes +//! plus its longest range after the previous arm's newest sample, so +//! MetricsQL's look-back for the sample before a range (`rate`, `increase`) +//! never reaches another arm's data; other arms start right away, since a +//! window rollup reads only its window, which holds only the arm's own data. One arm at a time per engine: the server's stream-aggregation +//! config is one file, and wall-clock data cannot be replayed into a second +//! arm, so run the engine with no warm-up and one measured run. +//! +//! Series: an answer is keyed by its labels without `__name__`, as PromQL +//! drops it in every function and aggregation; a bare selector's answer +//! keeps it (as the other engines key their answers). +//! +//! CPU: the server runs in its own cgroup, read over SSH or on this host, the +//! same way the server's `-streamAggr.config` file is replaced. VictoriaMetrics +//! keeps no per-query CPU counter, so [`StepReport`] carries none. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, AtomicI64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::data::Sample; +use aqpbm_core::harness::engine::{ + Answers, ArmSpec, CpuAccounting, EngineDescription, EngineError, EngineUnderTest, Footprint, + InstalledArm, PlanSummary, SampleChunk, SeriesLabels, StepReport, WorkloadSpec, +}; +use serde_json::Value; + +use super::plan_file::{PlanFile, PlanOperator, RangeKind, SummaryFamily}; +use super::victoriametrics::{ + translate, MetricsQlQuery, StreamAggregation, VictoriaMetricsDeployment, +}; +use super::NodeId; + +/// How to reach the server. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VictoriaMetricsServer { + /// The HTTP interface, e.g. `http://10.0.0.1:8428`. + pub url: String, + /// Where the server's cgroup is read, e.g. over SSH from `bench@10.0.0.1`. + pub cgroup: CgroupSource, + /// The server's `-streamAggr.config` file on the server host, replaced + /// for each arm through `cgroup`'s host access. + pub stream_aggregation_config: PathBuf, + /// How long one request may take, e.g. 600 s. + pub request_timeout: Duration, +} + +/// A VictoriaMetrics server; see the module docs. +pub struct VictoriaMetricsEngine { + server: VictoriaMetricsServer, + http: Http, + description: EngineDescription, + /// Set while an arm is installed. + arm_installed: Arc, + /// The wall time of the newest sample any arm of this engine sent, in + /// ms (0 before any). + newest_sample_wall_ms: Arc, +} + +/// Installs so far in this process, for each install's config nonce. +static INSTALLS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + +/// How long to wait for the server to apply a reloaded config. +const RELOAD_TIMEOUT: Duration = Duration::from_secs(10); +/// How often a wait polls the server's `/metrics`. +const POLL_INTERVAL: Duration = Duration::from_millis(50); +/// The least time a slice reaches the server before its window ends. +const BEFORE_WINDOW_END_MARGIN_MS: i64 = 100; +/// How far before a range MetricsQL reads a series for an instant query: +/// its silence interval (5 min) plus the larger of the range and the step +/// (5 min by default), where it finds the sample before the range that +/// `rate` and `increase` start from. An arm's data starts at least this +/// plus its longest range after the previous arm's newest sample, so no arm +/// reads another arm's samples of the same series. +const PREVIOUS_SAMPLE_LOOKBACK_MS: i64 = 600_000; +/// The least time between installing an arm and its first data, so the +/// data starts after the reloaded config's first tick. +const START_MARGIN_MS: i64 = 2_000; + +impl VictoriaMetricsEngine { + /// Connects to the server and reads its version. + pub fn new(server: VictoriaMetricsServer) -> Result { + let http = Http::new(&server.url, server.request_timeout); + let metrics = ServerMetrics::parse(&http.get("/metrics", &[])?, ""); + let version = metrics + .app_version + .ok_or_else(|| EngineError("the server's /metrics has no vm_app_version".into()))?; + Ok(VictoriaMetricsEngine { + description: EngineDescription { + id: "victoriametrics".into(), + version, + version_dirty: false, + build_profile: "single-node".into(), + }, + server, + http, + arm_installed: Arc::new(AtomicBool::new(false)), + newest_sample_wall_ms: Arc::new(AtomicI64::new(0)), + }) + } +} + +impl EngineUnderTest for VictoriaMetricsEngine { + fn description(&self) -> EngineDescription { + self.description.clone() + } + + fn cpu_accounting(&self) -> CpuAccounting { + CpuAccounting::Cgroup(self.server.cgroup.clone()) + } + + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + let path = arm + .engine_options + .get("plan_file") + .and_then(|p| p.as_str()) + .ok_or_else(|| EngineError("engine_options has no plan_file".into()))?; + let text = std::fs::read_to_string(path) + .map_err(|error| EngineError(format!("plan file {path}: {error}")))?; + let plan = 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 interval_ms = evaluation_interval_ms(workload)?; + check_time_steps(workload, &deployment.queries, interval_ms)?; + if self + .arm_installed + .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst) + .is_err() + { + return Err(EngineError( + "a VictoriaMetrics arm is already installed: wall-clock data runs one arm at a \ + time, so run this engine with --warmup 0 --runs 1" + .into(), + )); + } + // From here on, dropping the arm unloads its config and frees the engine. + let mut installed = VictoriaMetricsArm { + http: self.http.clone(), + cgroup: self.server.cgroup.clone(), + stream_aggregation_config: self.server.stream_aggregation_config.clone(), + arm_installed: Arc::clone(&self.arm_installed), + 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 { + id, + expr: query.expr.clone(), + metric_name: answer_metric_name(&plan, root, query), + }) + .collect(), + aggregations: deployment.stream_aggregations.clone(), + 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), + }; + // Each install names its aggregators, so its config always differs + // from the last one (a reload with unchanged bytes keeps the old + // aggregators) and its metrics are told apart from earlier ones. + installed.aggregation_name = format!( + "install-{}-{}", + 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())?; + installed.http.get("/internal/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 + .iter() + .fold(lcm(1000, interval_ms), |step, a| lcm(step, a.interval_ms)); + 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)); + 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. + installed.flush_counts = (data_start + installed.offset_ms, flushes_at_install); + // The wait for the data start is the install's, not the first + // chunk's. + sleep_until_wall_ms(data_start + installed.offset_ms - installed.lead_ms); + Ok(Box::new(installed)) + } +} + +/// 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 +/// counters (`rate` and `increase` start from the sample before their +/// range, which MetricsQL looks for that far back). Example: `sum by (job) +/// (rate(m[1m]))`: 660,000 ms; `max_over_time(m[1m])`: 0. +pub fn previous_arm_gap_ms(plan: &PlanFile) -> i64 { + let reads_counters = plan.nodes.iter().any(|node| match &node.operator { + PlanOperator::SummaryTumblingWindowChain { family, .. } + | PlanOperator::SummaryAgg { family, .. } => matches!( + family, + SummaryFamily::Exact(kind) if matches!(kind.as_str(), "Rate" | "Increase" | "IRate") + ), + _ => false, + }); + if !reads_counters { + return 0; + } + let longest_range_ms = plan + .nodes + .iter() + .filter_map(|node| match node.operator { + PlanOperator::TimeRange { range_ms, .. } => Some(range_ms as i64), + _ => None, + }) + .max() + .unwrap_or(0); + PREVIOUS_SAMPLE_LOOKBACK_MS + longest_range_ms +} + +/// The one evaluation interval of `workload`'s queries. +fn evaluation_interval_ms(workload: &WorkloadSpec) -> Result { + let mut intervals = workload.queries.iter().map(|q| q.evaluation_interval_ms); + let first = intervals + .next() + .ok_or_else(|| EngineError(format!("workload {} has no queries", workload.name)))?; + if first == 0 || intervals.any(|i| i != first) { + return Err(EngineError(format!( + "workload {}: one evaluation interval, above 0, for every query", + workload.name + ))); + } + 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). +fn check_time_steps( + workload: &WorkloadSpec, + queries: &[MetricsQlQuery], + 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) { + return Err(EngineError(format!( + "query {} reads stream outputs of {} ms windows, which do not divide its \ + evaluation interval ({interval_ms} ms)", + query.id, plan_query.time_step_ms + ))); + } + } + Ok(()) +} + +/// The workload's data start, or 0 when the spec carries no data (the +/// samples then come from the caller). +fn data_start_ms(workload: &WorkloadSpec) -> i64 { + workload + .data + .iter() + .map(|record| record.description.start_ms) + .min() + .unwrap_or(0) +} + +/// The offset from data time to wall time: the smallest multiple of +/// `step_ms` that puts the data start's step boundary (the data start +/// rounded down to a multiple of `step_ms`) at least [`START_MARGIN_MS`] +/// after `now_ms`. So the data's first window starts on a tick after the +/// config's load, even for a data start that is not a window end. Example: +/// now 1,000,000,500 ms, data from 10,000 ms, step 60,000 ms: 1,000,020,000 +/// ms (the data starts at wall time 1,000,030,000 ms, after the tick at +/// 1,000,020,000 ms). +pub fn wall_offset_ms(now_ms: i64, data_start_ms: i64, step_ms: u64) -> i64 { + let step = step_ms as i64; + let boundary = data_start_ms.div_euclid(step) * step; + let earliest = now_ms + START_MARGIN_MS - boundary; + earliest.div_euclid(step) * step + + if earliest.rem_euclid(step) == 0 { + 0 + } else { + step + } +} + +/// How early the feeder sends a slice: `max(1 s, h)` with `h = (w − 1 s) / +/// 2` the read shift of the narrowest window; 1 s with no stream +/// aggregation. Below the width, so a sample still lands in its own window. +/// Example: windows of 60 s and 10 s: 4,500 ms. +pub fn lead_ms(aggregations: &[StreamAggregation]) -> i64 { + aggregations + .iter() + .map(|a| (a.interval_ms as i64 - 1000) / 2) + .min() + .unwrap_or(0) + .max(1000) +} + +/// The feeder's slice length. +pub const SLICE_MS: i64 = 1000; + +/// One slice of a chunk: the samples in `(end − slice, end]` (data time), +/// to be sent at wall time `send_at_wall_ms`. +#[derive(Debug, Clone, PartialEq)] +pub struct Slice<'a> { + pub end_ms: i64, + pub send_at_wall_ms: i64, + pub samples: Vec<&'a Sample>, +} + +/// `chunk`'s samples cut into slices of [`SLICE_MS`] ending at its +/// multiples, in time order, each to be sent `lead_ms` before its end in +/// wall time. Example: 1 Hz samples at 1,000..3,000 ms, offset 10,000, lead +/// 1,000: three slices sent at 10,000, 11,000 and 12,000. +pub fn slices(chunk: &SampleChunk, offset_ms: i64, lead_ms: i64) -> Vec> { + let mut by_end: BTreeMap> = BTreeMap::new(); + for sample in &chunk.samples { + let end = (sample.ts_ms + SLICE_MS - 1).div_euclid(SLICE_MS) * SLICE_MS; + by_end.entry(end).or_default().push(sample); + } + by_end + .into_iter() + .map(|(end_ms, samples)| Slice { + end_ms, + send_at_wall_ms: end_ms + offset_ms - lead_ms, + samples, + }) + .collect() +} + +/// `/api/v1/import` JSON lines: one line per series, its values and +/// timestamps (data time + `offset_ms`) in order. NaN and ±Inf are written +/// as VictoriaMetrics reads them (`NaN`, `Inf`, `-Inf`, as JSON strings +/// would not be read). +pub fn import_body(samples: &[&Sample], offset_ms: i64) -> String { + let mut series: BTreeMap<&SeriesLabels, (Vec, Vec)> = BTreeMap::new(); + for sample in samples { + let (values, timestamps) = series.entry(&*sample.labels).or_default(); + values.push(number_text(sample.value)); + timestamps.push(sample.ts_ms + offset_ms); + } + let mut body = String::new(); + for (labels, (values, timestamps)) in series { + let timestamps: Vec = timestamps.iter().map(i64::to_string).collect(); + body.push_str(&format!( + "{{\"metric\":{},\"values\":[{}],\"timestamps\":[{}]}}\n", + serde_json::to_string(labels).expect("a string map serializes"), + values.join(","), + timestamps.join(",") + )); + } + body +} + +fn number_text(value: f64) -> String { + if value.is_nan() { + "NaN".into() + } else if value == f64::INFINITY { + "Inf".into() + } else if value == f64::NEG_INFINITY { + "-Inf".into() + } else { + value.to_string() + } +} + +/// What the adapter reads from the server's `/metrics`. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ServerMetrics { + /// `vm_app_version`'s `version` label. + pub app_version: Option, + /// `vminsert_streamagg_config_reloads_total`. + pub config_reloads: u64, + /// `vminsert_streamagg_config_reloads_errors_total`. + pub config_reload_errors: u64, + /// The positions of the aggregations named `aggregation_name` the server + /// runs (they have an ignored-samples counter from their start). + pub running_positions: std::collections::BTreeSet, + /// Per stream aggregation named `aggregation_name`, by its 1-based + /// `position` in the config: `vm_streamaggr_flush_duration_seconds_count`, + /// the flushes so far. + pub flushes_by_position: BTreeMap, + /// `vm_streamaggr_ignored_samples_total{reason="too_old"}` of the + /// aggregations named `aggregation_name`, summed: samples that arrived + /// after their window had flushed. + pub too_old_samples: u64, + /// `vm_data_size_bytes`, summed over every type: the server's whole data. + pub data_size_bytes: u64, +} + +impl ServerMetrics { + /// The metrics of `/metrics` text; the stream-aggregation counters of the + /// aggregations named `aggregation_name` only. + pub fn parse(text: &str, aggregation_name: &str) -> ServerMetrics { + let mut metrics = ServerMetrics::default(); + for line in text.lines() { + let (name_and_labels, value) = match line.rsplit_once(' ') { + Some(pair) if !line.starts_with('#') => pair, + _ => continue, + }; + let (name, labels) = match name_and_labels.split_once('{') { + Some((name, labels)) => (name, labels.trim_end_matches('}')), + None => (name_and_labels, ""), + }; + let count = || value.parse::().map(|v| v as u64).unwrap_or(0); + let ours = || label(labels, "name").as_deref() == Some(aggregation_name); + match name { + "vm_app_version" => metrics.app_version = label(labels, "version"), + "vminsert_streamagg_config_reloads_total" => metrics.config_reloads = count(), + "vminsert_streamagg_config_reloads_errors_total" => { + metrics.config_reload_errors = count() + } + "vm_streamaggr_flush_duration_seconds_count" if ours() => { + if let Some(position) = label(labels, "position").and_then(|p| p.parse().ok()) { + *metrics.flushes_by_position.entry(position).or_default() += count(); + } + } + "vm_streamaggr_ignored_samples_total" if ours() => { + if let Some(position) = label(labels, "position").and_then(|p| p.parse().ok()) { + metrics.running_positions.insert(position); + } + if label(labels, "reason").as_deref() == Some("too_old") { + metrics.too_old_samples += count(); + } + } + "vm_data_size_bytes" => metrics.data_size_bytes += count(), + _ => {} + } + } + metrics + } +} + +/// The value of `name="value"` in a Prometheus label list such as +/// `a="1",name="x"` (not the `name` inside `short_name`). +fn label(labels: &str, name: &str) -> Option { + let mut rest = labels; + loop { + let (key, after) = rest.split_once("=\"")?; + let end = after.find('"')?; + if key.trim_start_matches([',', ' ']) == name { + return Some(after[..end].to_string()); + } + rest = &after[end + 1..]; + } +} + +/// The series of one `/api/v1/query` answer: labels without `__name__`, +/// plus `__name__ = metric` when given (a bare selector's answer, see +/// [`answer_metric_name`]). +pub fn parse_answer( + body: &str, + metric_name: Option<&str>, +) -> Result, String> { + let answer: Value = serde_json::from_str(body).map_err(|e| format!("answer: {e}"))?; + if answer["status"] != "success" { + return Err(format!("answer: {body}")); + } + if answer["data"]["resultType"] != "vector" { + return Err(format!("answer of type {}", answer["data"]["resultType"])); + } + let mut series = BTreeMap::new(); + for result in answer["data"]["result"].as_array().into_iter().flatten() { + let mut labels: SeriesLabels = result["metric"] + .as_object() + .ok_or_else(|| format!("result without labels: {result}"))? + .iter() + .filter(|(name, _)| name.as_str() != "__name__") + .map(|(name, value)| (name.clone(), value.as_str().unwrap_or("").to_string())) + .collect(); + if let Some(metric) = metric_name { + labels.insert("__name__".into(), metric.into()); + } + let text = result["value"][1] + .as_str() + .ok_or_else(|| format!("result without a value: {result}"))?; + let value = match text { + "NaN" => f64::NAN, + "+Inf" | "Inf" => f64::INFINITY, + "-Inf" => f64::NEG_INFINITY, + _ => text + .parse() + .map_err(|_| format!("value '{text}' is not a number"))?, + }; + if series.insert(labels.clone(), value).is_some() { + return Err(format!("two series with the labels {labels:?}")); + } + } + Ok(series) +} + +/// The workload query id of each plan root: root i answers query i, whose +/// texts must include the plan's text of root i. +fn query_ids_of(plan: &PlanFile, workload: &WorkloadSpec) -> Result, EngineError> { + if plan.query_texts.len() != workload.queries.len() { + return Err(EngineError(format!( + "the plan has {} queries but workload {} has {}", + plan.query_texts.len(), + workload.name, + workload.queries.len() + ))); + } + plan.query_texts + .iter() + .zip(&workload.queries) + .map(|(plan_text, query)| { + if query.texts.iter().any(|text| &text.text == plan_text) { + Ok(query.id.clone()) + } else { + let texts: Vec<&str> = query.texts.iter().map(|t| t.text.as_str()).collect(); + Err(EngineError(format!( + "query {}: the plan answers '{plan_text}', but the workload's texts are {texts:?}", + query.id + ))) + } + }) + .collect() +} + +fn plan_summary(plan: &PlanFile, deployment: &VictoriaMetricsDeployment) -> PlanSummary { + let queries: Vec<&str> = deployment.queries.iter().map(|q| q.expr.as_str()).collect(); + PlanSummary { + text: format!( + "# -streamAggr.config\n{}# queries\n{}\n", + deployment.stream_aggregation_config(), + queries.join("\n") + ), + node_kinds: plan + .nodes + .iter() + .map(|node| operator_kind(&node.operator)) + .collect(), + stored_outputs: deployment + .stream_aggregations + .iter() + .flat_map(|a| a.outputs.iter().map(|&o| a.output_metric(o))) + .collect(), + substitutions: deployment + .substitutions + .iter() + .map(|s| format!("{} at node {}: {}", s.rule, s.node, s.guarantee_difference)) + .collect(), + sharing_lost: deployment + .sharing_lost + .iter() + .map(|lost| { + let readers: Vec = lost.readers.iter().map(|r| r.to_string()).collect(); + format!("node {} for nodes {}", lost.node, readers.join(", ")) + }) + .collect(), + } +} + +/// The planner's operator name of `operator`, e.g. `SummaryAgg`. +fn operator_kind(operator: &PlanOperator) -> String { + match operator { + PlanOperator::Scan { .. } => "Scan", + PlanOperator::TimeRange { .. } => "TimeRange", + PlanOperator::SummaryTumblingWindowChain { .. } => "SummaryTumblingWindowChain", + PlanOperator::SummaryAgg { .. } => "SummaryAgg", + PlanOperator::SummaryMerge { .. } => "SummaryMerge", + PlanOperator::FinalizeExactAccumulator { .. } => "FinalizeExactAccumulator", + PlanOperator::SummaryEstimate { .. } => "SummaryEstimate", + PlanOperator::Aggregate { .. } => "Aggregate", + PlanOperator::Project { .. } => "Project", + PlanOperator::BinaryOp { .. } => "BinaryOp", + PlanOperator::Other { kind } => kind, + } + .to_string() +} + +/// One query of an arm: its workload query id, its MetricsQL, and the +/// `__name__` its answers keep (see [`answer_metric_name`]). +struct RootQuery { + id: String, + expr: String, + metric_name: Option, +} + +/// The `__name__` the answers of `query` (the translation of `root`) keep: +/// the metric for a root that is a bare selector (an instant `TimeRange`, +/// e.g. `latency`), and none otherwise, since PromQL drops it in every +/// function and aggregation (e.g. `max_over_time(latency[1m])` answers +/// `{job="a"}`). The other engines key their answers the same way. +pub fn answer_metric_name(plan: &PlanFile, root: NodeId, query: &MetricsQlQuery) -> Option { + let bare_selector = matches!( + plan.nodes[root].operator, + PlanOperator::TimeRange { + kind: RangeKind::Instant, + .. + } + ); + query.per_series_of.clone().filter(|_| bare_selector) +} + +/// The installed arm: its stream aggregations, queries and wall offset. +struct VictoriaMetricsArm { + http: Http, + cgroup: CgroupSource, + stream_aggregation_config: PathBuf, + arm_installed: Arc, + newest_sample_wall_ms: Arc, + /// The `name` of this install's stream aggregations, e.g. `install-41-0`. + aggregation_name: String, + /// The flush counts per position, and the wall time (ms) whose later + /// ticks they do not include yet: the data start, then each chunk end. + flush_counts: (i64, BTreeMap), + /// Per plan root, in root order. + queries: Vec, + /// In config order: aggregation `i` has `position` `i + 1`. + aggregations: Vec, + offset_ms: i64, + lead_ms: i64, + /// The server's too-old count after the config loaded. + too_old_at_install: u64, + /// The server's data size after the config loaded. + data_bytes_at_install: u64, + summary: PlanSummary, +} + +impl VictoriaMetricsArm { + fn metrics(&self) -> Result { + Ok(ServerMetrics::parse( + &self.http.get("/metrics", &[])?, + &self.aggregation_name, + )) + } + + /// Writes `config` as the server's `-streamAggr.config`, reloads it, and + /// waits until the server runs its `aggregations` aggregations (named + /// [`Self::aggregation_name`]); a refused config is an error. + fn load_config(&self, config: &str, aggregations: usize) -> Result<(), EngineError> { + let before = self.metrics()?; + self.cgroup + .replace_file_on_server_host(&self.stream_aggregation_config, config) + .map_err(|error| { + EngineError(format!("writing the stream-aggregation config: {error}")) + })?; + self.http.post("/-/reload")?; + let deadline = Instant::now() + RELOAD_TIMEOUT; + loop { + let metrics = self.metrics()?; + if metrics.config_reload_errors > before.config_reload_errors { + return Err(EngineError( + "the server refused the stream-aggregation config (see its log)".into(), + )); + } + // The reload counter grows when a reload starts; the named + // aggregations' counters appear once it has loaded them. + if metrics.config_reloads > before.config_reloads + && metrics.running_positions.len() == aggregations + { + if aggregations == 0 { + // Nothing to see for an empty config: give the reload + // its few milliseconds. + std::thread::sleep(POLL_INTERVAL); + } + return Ok(()); + } + if Instant::now() > deadline { + return Err(EngineError("the server did not reload its config".into())); + } + std::thread::sleep(POLL_INTERVAL); + } + } + + /// The read shift `h` of the narrowest window, in ms: the most a flush + /// may lag. + fn narrowest_shift_ms(&self) -> Option { + self.aggregations + .iter() + .map(|a| (a.interval_ms as i64 - 1000) / 2) + .min() + } + + /// Waits until every aggregation flushed once for each of its ticks in + /// `(counted up to, tick]`, failing if that takes `h` or more after + /// `tick`. + fn wait_for_flushes(&mut self, tick: i64) -> Result<(), EngineError> { + let Some(shift_ms) = self.narrowest_shift_ms() else { + return Ok(()); + }; + let (counted_at, before) = self.flush_counts.clone(); + let expected: Vec<(u32, u64)> = self + .aggregations + .iter() + .enumerate() + .map(|(i, a)| { + let width = a.interval_ms as i64; + let ticks = tick.div_euclid(width) - counted_at.div_euclid(width); + let position = i as u32 + 1; + ( + position, + before.get(&position).copied().unwrap_or(0) + ticks.max(0) as u64, + ) + }) + .collect(); + loop { + let metrics = self.metrics()?; + let flushed = expected.iter().all(|(position, count)| { + metrics + .flushes_by_position + .get(position) + .copied() + .unwrap_or(0) + >= *count + }); + let lag = now_ms() - tick; + if lag >= shift_ms { + return Err(EngineError(format!( + "the stream flushes up to wall time {tick} ms took {lag} ms, at least the \ + read's shift {shift_ms} ms" + ))); + } + if flushed { + if metrics.too_old_samples > self.too_old_at_install { + return Err(EngineError(format!( + "the server dropped {} samples that arrived after their window", + metrics.too_old_samples - self.too_old_at_install + ))); + } + self.flush_counts = (tick, metrics.flushes_by_position); + return Ok(()); + } + std::thread::sleep(POLL_INTERVAL); + } + } +} + +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. + let _ = self.load_config("[]\n", 0); + self.arm_installed.store(false, Ordering::SeqCst); + } +} + +impl InstalledArm for VictoriaMetricsArm { + fn plan_summary(&self) -> PlanSummary { + self.summary.clone() + } + + fn ingest(&mut self, chunk: &SampleChunk) -> Result { + for slice in slices(chunk, self.offset_ms, self.lead_ms) { + sleep_until_wall_ms(slice.send_at_wall_ms); + // Every sample must arrive before its window's flush: for each + // stream aggregation, its window ending at or after the slice end. + let wall_end = slice.end_ms + self.offset_ms; + let now = now_ms(); + for aggregation in &self.aggregations { + let width = aggregation.interval_ms as i64; + let window_end = (wall_end + width - 1).div_euclid(width) * width; + if now >= window_end - BEFORE_WINDOW_END_MARGIN_MS { + return Err(EngineError(format!( + "pacing: the slice ending at data time {} ms was sent {} ms before its \ + {width} ms window ended, under {BEFORE_WINDOW_END_MARGIN_MS} ms", + slice.end_ms, + window_end - now + ))); + } + } + if !slice.samples.is_empty() { + self.http.post_body( + "/api/v1/import", + &import_body(&slice.samples, self.offset_ms), + )?; + self.newest_sample_wall_ms + .fetch_max(wall_end, Ordering::SeqCst); + } + } + // 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)?; + // Make the new rows and stream outputs searchable. + self.http.get("/internal/force_flush", &[])?; + Ok(StepReport::default()) + } + + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError> { + let wall_ms = at_ms + self.offset_ms; + // The chunk ending at `at_ms` was ingested (and flushed) already. + if now_ms() < wall_ms { + return Err(EngineError(format!( + "evaluation at data time {at_ms} ms before its data was ingested" + ))); + } + let time = format!( + "{}.{:03}", + wall_ms.div_euclid(1000), + wall_ms.rem_euclid(1000) + ); + let mut answers = BTreeMap::new(); + for query in &self.queries { + let body = self.http.get( + "/api/v1/query", + &[("query", &query.expr), ("time", &time), ("nocache", "1")], + )?; + let series = parse_answer(&body, query.metric_name.as_deref()) + .map_err(|e| EngineError(format!("query {}: {e}", query.id)))?; + answers.insert(query.id.clone(), series); + } + Ok((Answers(answers), StepReport::default())) + } + + fn footprint(&self) -> Result { + // The server's data growth since this arm's install: raw series and + // stream outputs together (VictoriaMetrics does not split them). + self.http.get("/internal/force_flush", &[])?; + Ok(Footprint { + view_bytes: 0, + raw_retained_bytes: self + .metrics()? + .data_size_bytes + .saturating_sub(self.data_bytes_at_install), + peak_bytes: None, + }) + } +} + +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("after 1970") + .as_millis() as i64 +} + +fn sleep_until_wall_ms(wall_ms: i64) { + let wait = wall_ms - now_ms(); + if wait > 0 { + std::thread::sleep(Duration::from_millis(wait as u64)); + } +} + +fn lcm(a: u64, b: u64) -> u64 { + let (mut x, mut y) = (a, b); + while y != 0 { + (x, y) = (y, x % y); + } + a / x * b +} + +/// The server's HTTP interface. +#[derive(Clone)] +struct Http { + agent: ureq::Agent, + url: String, +} + +impl Http { + fn new(url: &str, timeout: Duration) -> Http { + Http { + agent: ureq::AgentBuilder::new() + .timeout_connect(Duration::from_secs(5)) + .timeout(timeout) + .build(), + url: url.trim_end_matches('/').to_string(), + } + } + + fn get(&self, path: &str, params: &[(&str, &str)]) -> Result { + let mut request = self.agent.get(&format!("{}{path}", self.url)); + for (name, value) in params { + request = request.query(name, value); + } + Self::text(request.call(), &self.url) + } + + fn post(&self, path: &str) -> Result { + Self::text( + self.agent.post(&format!("{}{path}", self.url)).call(), + &self.url, + ) + } + + fn post_body(&self, path: &str, body: &str) -> Result { + Self::text( + self.agent + .post(&format!("{}{path}", self.url)) + .send_string(body), + &self.url, + ) + } + + fn text(sent: Result, url: &str) -> Result { + match sent { + Ok(response) => { + let mut text = String::new(); + std::io::Read::read_to_string(&mut response.into_reader(), &mut text) + .map_err(|error| EngineError(format!("reading the answer: {error}")))?; + Ok(text) + } + Err(ureq::Error::Status(code, response)) => Err(EngineError(format!( + "VictoriaMetrics answered {code}: {}", + response.into_string().unwrap_or_default().trim_end() + ))), + Err(error) => Err(EngineError(format!("VictoriaMetrics at {url}: {error}"))), + } + } +} diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs new file mode 100644 index 00000000..567a83e1 --- /dev/null +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -0,0 +1,820 @@ +//! Conformance of the VictoriaMetrics adapter against a real server, one +//! case per row of `capabilities/README.md` § VictoriaMetrics (`#[ignore]`: +//! set `AQPBM_VICTORIAMETRICS_URL` to the server's HTTP interface, +//! `AQPBM_SERVER_CGROUP_DIRECTORY` to its cgroup directory, +//! `AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG` to its +//! `-streamAggr.config` file and, for a server on another host, +//! `AQPBM_SERVER_SSH_HOST` to that host, e.g. a server started with +//! `scripts/extbench-up-victoriametrics.sh`). Each case installs a +//! planner-written plan (changed in test code where a shape needs it) +//! through the engine, feeds hand-made samples in real time and compares the +//! 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`. + +mod common; + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::data::Sample; +use aqpbm_core::harness::engine::{ + Answers, ArmSpec, EngineUnderTest, InstalledArm, QueryLanguage, QueryText, SampleChunk, + SeriesLabels, WorkloadQuery, WorkloadSpec, +}; +use common::{fixture_value_public, payload_body}; +use serde_json::{json, Value}; +use system_bench::engines_external::victoriametrics_server::{ + VictoriaMetricsEngine, VictoriaMetricsServer, +}; + +const EQUIVALENT_ONLY: &str = "victoriametrics.equivalent-only"; +const WITH_SUBSTITUTES: &str = "victoriametrics.with-substitutes"; + +fn engine() -> VictoriaMetricsEngine { + VictoriaMetricsEngine::new(VictoriaMetricsServer { + url: std::env::var("AQPBM_VICTORIAMETRICS_URL").expect("AQPBM_VICTORIAMETRICS_URL"), + cgroup: { + let cgroup_directory = std::env::var("AQPBM_SERVER_CGROUP_DIRECTORY") + .expect("AQPBM_SERVER_CGROUP_DIRECTORY") + .into(); + match std::env::var("AQPBM_SERVER_SSH_HOST") { + Ok(host) => CgroupSource::Remote { + ssh_program: "ssh".into(), + host, + cgroup_directory, + }, + Err(_) => CgroupSource::Local(cgroup_directory), + } + }, + stream_aggregation_config: std::env::var("AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG") + .expect("AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG") + .into(), + request_timeout: Duration::from_secs(60), + }) + .expect("the server answers") +} + +/// `plan` written to a temporary file, as an arm's `plan_file`. +fn arm(name: &str, plan: &Value) -> ArmSpec { + let dir = std::env::temp_dir().join(format!( + "victoriametrics-conformance-{}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + let path: PathBuf = dir.join(format!("{name}.plan.json")); + std::fs::write(&path, plan.to_string()).unwrap(); + ArmSpec { + name: "conformance".into(), + raw_data_retained: true, + engine_options: json!({ "plan_file": path }), + } +} + +/// A workload of `plan`'s query texts (ids `q0`, `q1`, …), evaluated every +/// `interval_ms`, with data from 0 ms supplied by the test. +fn workload(plan: &Value, interval_ms: u64) -> WorkloadSpec { + let texts: Vec = serde_json::from_value(plan["query_texts"].clone()).unwrap(); + WorkloadSpec { + name: "conformance".into(), + queries: texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.clone(), + }], + window_ms: 60_000, + evaluation_interval_ms: interval_ms, + }) + .collect(), + data: vec![], + } +} + +/// A series with `pairs` and a `conformance_run` label unique to this +/// process, so a rerun never reads an earlier run's samples of the series +/// (MetricsQL looks up to 10 minutes back for the sample before a range). +fn series(pairs: &[(&str, &str)]) -> Arc { + let mut labels: SeriesLabels = pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(); + labels.insert("conformance_run".into(), RUN.with(|run| run.clone())); + Arc::new(labels) +} + +thread_local! { + static RUN: String = format!( + "{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs() + ); +} + +/// `samples` cut into chunks ending at multiples of `chunk_ms` from +/// `chunk_ms` to `end_ms` (empty chunks included), time-major. +fn chunks(mut samples: Vec, chunk_ms: i64, end_ms: i64) -> Vec { + samples.sort_by_key(|s| s.ts_ms); + (1..=end_ms / chunk_ms) + .map(|k| SampleChunk { + end_ms: k * chunk_ms, + samples: samples + .iter() + .filter(|s| s.ts_ms > (k - 1) * chunk_ms && s.ts_ms <= k * chunk_ms) + .cloned() + .collect(), + }) + .collect() +} + +/// Feeds every chunk in real time and evaluates after each chunk ending at +/// a multiple of `interval_ms` from `first_eval_ms`; the answers per time. +fn run( + arm: &mut dyn InstalledArm, + chunks: &[SampleChunk], + first_eval_ms: i64, + interval_ms: i64, +) -> Vec<(i64, Answers)> { + let mut out = Vec::new(); + for chunk in chunks { + arm.ingest(chunk) + .unwrap_or_else(|e| panic!("ingest {}: {e}", chunk.end_ms)); + let t = chunk.end_ms; + if t >= first_eval_ms && (t - first_eval_ms) % interval_ms == 0 { + let (answers, _) = arm + .evaluate(t) + .unwrap_or_else(|e| panic!("evaluate {t}: {e}")); + out.push((t, answers)); + } + } + out +} + +/// Asserts `answers` of query `q` equal `expected` to 1e-9 relative, +/// series by series; NaN equals NaN. +/// Answers are keyed as PromQL keys them: only a bare selector (query +/// `q{INSTANT_QUERY}` of the query-time case) keeps `__name__`. +fn assert_answers(t: i64, answers: &Answers, index: usize, expected: &BTreeMap) { + let id = format!("q{index}"); + let got = answers.0.get(&id).cloned().unwrap_or_default(); + let keeps_name = got.keys().any(|labels| labels.contains_key("__name__")); + let expected: BTreeMap = expected + .iter() + .map(|(labels, &v)| { + let mut labels = labels.clone(); + if !keeps_name { + labels.remove("__name__"); + } + (labels, v) + }) + .collect(); + let expected = &expected; + let keys = |m: &BTreeMap| m.keys().cloned().collect::>(); + assert_eq!(keys(&got), keys(expected), "{id} at {t}: series"); + for (labels, &want) in expected { + let have = got[labels]; + let close = have == want + || (have.is_nan() && want.is_nan()) + || (have - want).abs() <= 1e-9 * want.abs().max(1.0); + assert!(close, "{id} at {t}, {labels:?}: {have} != {want}"); + } +} + +/// One series' points: (data time in ms, value). +type Points = Vec<(i64, f64)>; + +/// The samples of each series. +struct Data(Vec<(Arc, Points)>); + +impl Data { + fn samples(&self) -> Vec { + self.0 + .iter() + .flat_map(|(labels, points)| { + points.iter().map(|&(ts_ms, value)| Sample { + labels: Arc::clone(labels), + ts_ms, + value, + }) + }) + .collect() + } + + /// Per series, the values in `(t − range, t]`. + fn windows(&self, t: i64, range_ms: i64) -> Vec<(&Arc, Vec)> { + self.0 + .iter() + .map(|(labels, points)| { + let values = points + .iter() + .filter(|(ts, _)| *ts > t - range_ms && *ts <= t) + .map(|&(_, v)| v) + .collect(); + (labels, values) + }) + .filter(|(_, values): &(_, Vec)| !values.is_empty()) + .collect() + } +} + +fn group_key(labels: &SeriesLabels, by: &[&str]) -> SeriesLabels { + by.iter() + .filter_map(|l| Some((l.to_string(), labels.get(*l)?.clone()))) + .collect() +} + +/// PromQL `quantile` over `values`: linear interpolation at rank q·(n − 1). +fn quantile(q: f64, values: &[f64]) -> f64 { + let mut sorted = values.to_vec(); + sorted.sort_by(f64::total_cmp); + let rank = q * (sorted.len() - 1) as f64; + let (lower, upper) = (rank.floor() as usize, rank.ceil() as usize); + sorted[lower] + (sorted[upper] - sorted[lower]) * (rank - lower as f64) +} + +/// Appends a stored-chain read to `plan` (a copy of the chain, range, merge +/// and finalize nodes 1–4 of `sum_over_time__1h__1hz__60s`) with `kind`, `width_ms`, +/// `range_ms` and `reduction`; returns the read's root node. +fn add_chain_read( + plan: &mut Value, + kind: &str, + width_ms: u64, + range_ms: u64, + reduction: Value, +) -> u64 { + let template = fixture_value_public("sum_over_time__1h__1hz__60s", EQUIVALENT_ONLY); + let base = plan["dag"]["nodes"].as_array().unwrap().len() as u64; + for (offset, id) in (1..=4).enumerate() { + let mut node = template["dag"]["nodes"][id].clone(); + node["id"] = json!(base + offset as u64); + plan["dag"]["nodes"].as_array_mut().unwrap().push(node); + } + let (chain, range, merge, finalize) = ( + base as usize, + base as usize + 1, + base as usize + 2, + base as usize + 3, + ); + payload_body(plan, chain)["summary_type"] = json!({"ExactAggregate": [kind, kind]}); + payload_body(plan, chain)["tumbling_window_width_ms"] = json!(width_ms); + payload_body(plan, chain)["reduction"] = reduction; + payload_body(plan, range)["child"] = json!(chain); + payload_body(plan, range)["range"] = json!({"secs": range_ms / 1000, "nanos": 0}); + payload_body(plan, merge)["children"] = json!([range]); + payload_body(plan, finalize)["child"] = json!(merge); + let edge = template["dag"]["edges"][0].clone(); + for (producer, consumer) in [ + (0, chain), + (chain, range), + (range, merge), + (merge, finalize), + ] { + let mut e = edge.clone(); + e["producer"] = json!(producer); + e["consumer"] = json!(consumer); + plan["dag"]["edges"].as_array_mut().unwrap().push(e); + } + finalize as u64 +} + +/// `plans` merged into one plan file: node ids shifted, roots and query +/// texts concatenated. +fn merged(plans: &[Value]) -> Value { + let mut out = plans[0].clone(); + for plan in &plans[1..] { + let shift = out["dag"]["nodes"].as_array().unwrap().len() as u64; + let shifted = |v: &Value| json!(v.as_u64().unwrap() + shift); + for node in plan["dag"]["nodes"].as_array().unwrap() { + let mut node = node.clone(); + node["id"] = shifted(&node["id"]); + let body = node["payload"] + .as_object_mut() + .unwrap() + .values_mut() + .next() + .unwrap() + .as_object_mut() + .unwrap() + .values_mut() + .next() + .unwrap(); + for field in ["child", "lhs", "rhs", "summary_input"] { + if let Some(v) = body.get(field).cloned() { + body[field] = shifted(&v); + } + } + if let Some(children) = body.get("children").cloned() { + body["children"] = children.as_array().unwrap().iter().map(shifted).collect(); + } + out["dag"]["nodes"].as_array_mut().unwrap().push(node); + } + for edge in plan["dag"]["edges"].as_array().unwrap() { + let mut edge = edge.clone(); + edge["producer"] = shifted(&edge["producer"]); + edge["consumer"] = shifted(&edge["consumer"]); + out["dag"]["edges"].as_array_mut().unwrap().push(edge); + } + for root in plan["dag"]["roots"].as_array().unwrap() { + out["dag"]["roots"] + .as_array_mut() + .unwrap() + .push(shifted(root)); + } + for text in plan["query_texts"].as_array().unwrap() { + out["query_texts"] + .as_array_mut() + .unwrap() + .push(text.clone()); + } + } + out +} + +/// Three latency series at 1 Hz over (0, 80 s]; `i3` stops at 40 s, a window +/// end, so its later windows are empty. +fn latency_data() -> Data { + let points = |base: f64, last_s: i64| -> Vec<(i64, f64)> { + (1..=last_s) + .map(|s| (s * 1000, base * ((s * 7) % 11) as f64 - 3.0)) + .collect() + }; + Data(vec![ + ( + series(&[("__name__", "latency"), ("job", "a"), ("instance", "i1")]), + points(1.0, 80), + ), + ( + series(&[("__name__", "latency"), ("job", "a"), ("instance", "i2")]), + points(2.5, 80), + ), + ( + series(&[("__name__", "latency"), ("job", "b"), ("instance", "i3")]), + points(-1.0, 40), + ), + ]) +} + +/// R1–R5: stored Sum / Count / Min / Max per series (no `by`), a grouped +/// chain (`by: [job]`), chains grouped by no label (per-series form plus the +/// outer aggregate), two stream intervals in one install, windows that end +/// exactly on samples, and a series whose later windows are empty. +#[test] +#[ignore = "needs a VictoriaMetrics v1.154.1 server (AQPBM_VICTORIAMETRICS_URL, AQPBM_SERVER_CGROUP_DIRECTORY, AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG)"] +fn stored_windows_equal_the_exact_windows() { + let mut plan = fixture_value_public("sum_over_time__1h__1hz__60s", EQUIVALENT_ONLY); + plan["dag"]["roots"] = json!([]); + plan["query_texts"] = json!([]); + let reads = [ + ("Sum", 10_000, 30_000, json!("PerEntity")), + ("Count", 10_000, 30_000, json!("PerEntity")), + ("Min", 10_000, 30_000, json!("PerEntity")), + ("Max", 20_000, 40_000, json!("PerEntity")), + ("Sum", 10_000, 30_000, json!({"Reduce": [2]})), + ("Sum", 10_000, 30_000, json!({"Reduce": []})), + ("Max", 20_000, 40_000, json!({"Reduce": []})), + ]; + for (i, (kind, width, range, reduction)) in reads.iter().enumerate() { + let root = add_chain_read(&mut plan, kind, *width, *range, reduction.clone()); + plan["dag"]["roots"] + .as_array_mut() + .unwrap() + .push(json!(root)); + plan["query_texts"] + .as_array_mut() + .unwrap() + .push(json!(format!("read {i}"))); + } + let engine = engine(); + let mut installed = engine + .install(&workload(&plan, 20_000), &arm("stored", &plan)) + .unwrap(); + let text = installed.plan_summary().text; + assert!( + !text.contains("by:") || text.contains("by: ['job']"), + "{text}" + ); + let data = latency_data(); + let answers = run( + installed.as_mut(), + &chunks(data.samples(), 20_000, 80_000), + 40_000, + 20_000, + ); + assert_eq!(answers.len(), 3); + for (_, got) in &answers { + for series in got.0.values() { + assert!(series.keys().all(|l| !l.contains_key("__name__"))); + } + } + for (t, got) in &answers { + for (i, (kind, _, range, reduction)) in reads.iter().enumerate() { + let fold = |values: &[f64]| -> f64 { + match *kind { + "Sum" => values.iter().sum(), + "Count" => values.len() as f64, + "Min" => values.iter().copied().fold(f64::INFINITY, f64::min), + _ => values.iter().copied().fold(f64::NEG_INFINITY, f64::max), + } + }; + let windows = data.windows(*t, *range as i64); + let mut expected = BTreeMap::new(); + match reduction { + Value::String(_) => { + for (labels, values) in &windows { + expected.insert((***labels).clone(), fold(values)); + } + } + _ if reduction["Reduce"] == json!([2]) => { + let mut groups: BTreeMap> = BTreeMap::new(); + for (labels, values) in &windows { + groups + .entry(group_key(labels, &["job"])) + .or_default() + .extend(values); + } + for (key, values) in groups { + expected.insert(key, fold(&values)); + } + } + _ => { + let all: Vec = windows.iter().flat_map(|(_, v)| v.clone()).collect(); + if !all.is_empty() { + expected.insert(SeriesLabels::new(), fold(&all)); + } + } + } + assert_answers(*t, got, i, &expected); + } + } + // At 80 s with 30 s ranges, `i3` (stopped at 40 s) has no answer. + let (_, last) = answers.last().unwrap(); + assert!(last.0["q0"].keys().all(|l| l["instance"] != "i3")); + println!( + "R1-R5 stored windows: {} evaluations x {} queries equal", + answers.len(), + reads.len() + ); +} + +/// Builds a one-node-more plan from `base`: `node` (a copy of node `like` +/// with `payload`) read by a new root. +fn with_root(mut plan: Value, like: usize, payload: Value, inputs: &[usize]) -> Value { + let id = plan["dag"]["nodes"].as_array().unwrap().len(); + let mut node = plan["dag"]["nodes"][like].clone(); + node["id"] = json!(id); + node["payload"] = payload; + plan["dag"]["nodes"].as_array_mut().unwrap().push(node); + let edge = plan["dag"]["edges"][0].clone(); + for &input in inputs { + let mut e = edge.clone(); + e["producer"] = json!(input); + e["consumer"] = json!(id); + plan["dag"]["edges"].as_array_mut().unwrap().push(e); + } + plan["dag"]["roots"] = json!([id]); + plan +} + +/// Requests counters at 1 Hz over (0, 80 s]: `r1` has a full reset to 0 at +/// 25 s and a partial drop smaller than prev/8 at 52 s; `r2` grows steadily. +fn counter_data() -> Data { + let r1: Vec<(i64, f64)> = (1..=80) + .map(|s| { + let v = match s { + ..=24 => 100.0 + 3.0 * s as f64, + 25..=51 => 2.0 * (s - 25) as f64, + 52 => 2.0 * 26.0 - 4.0, // 48 after 52 at 51: a drop of 4 < 52/8 + _ => 48.0 + 5.0 * (s - 52) as f64, + }; + (s * 1000, v) + }) + .collect(); + let r2: Vec<(i64, f64)> = (1..=80).map(|s| (s * 1000, 10.0 * s as f64)).collect(); + Data(vec![ + ( + series(&[ + ("__name__", "requests_total"), + ("job", "a"), + ("instance", "r1"), + ]), + r1, + ), + ( + series(&[ + ("__name__", "requests_total"), + ("job", "a"), + ("instance", "r2"), + ]), + r2, + ), + ]) +} + +/// VictoriaMetrics `increase` and `rate` over `(t − range, t]` of one series +/// (`rollupDelta`, `rollupDerivFast`, `removeCounterResets` at +/// v1.154.1): values corrected for resets (a drop smaller than prev/8 adds +/// prev − v, a larger one adds prev); with a sample at or before +/// `t − range`, both run from it to the last sample in the range. With +/// none, `rate` runs from the first sample in the range (none from one +/// sample), and `increase` from 0 when the first value is under 10 × (the +/// next step + 1), else from the first value. +fn vm_increase_rate(points: &[(i64, f64)], t: i64, range_ms: i64) -> Option<(f64, f64)> { + let mut corrected = Vec::new(); + let (mut correction, mut prev) = (0.0, points.first()?.1); + for &(ts, v) in points.iter().filter(|(ts, _)| *ts <= t) { + let d = v - prev; + if d < 0.0 { + correction += if -d * 8.0 < prev { prev - v } else { prev }; + } + prev = v; + corrected.push((ts, v + correction)); + } + let previous = corrected + .iter() + .copied() + .rfind(|(ts, _)| *ts <= t - range_ms); + let inside: Vec<(i64, f64)> = corrected + .iter() + .copied() + .filter(|(ts, _)| *ts > t - range_ms) + .collect(); + let &(last_ts, last) = inside.last()?; + match previous { + Some((prev_ts, prev_value)) => Some(( + last - prev_value, + (last - prev_value) / ((last_ts - prev_ts) as f64 / 1000.0), + )), + None => { + let (first_ts, first) = inside[0]; + if inside.len() < 2 { + return None; + } + let step = inside[1].1 - first; + let increase = if first.abs() < 10.0 * (step.abs() + 1.0) { + last + } else { + last - first + }; + Some(( + increase, + (last - first) / ((last_ts - first_ts) as f64 / 1000.0), + )) + } + } +} + +/// R6–R7 and the query-time rows: per-series and grouped rollups, quantiles, +/// avg, instant selector, topk, a division whose 0/0 series is dropped, and +/// rate/increase by VictoriaMetrics' formula (with-substitutes plans). +#[test] +#[ignore = "needs a VictoriaMetrics v1.154.1 server (AQPBM_VICTORIAMETRICS_URL, AQPBM_SERVER_CGROUP_DIRECTORY, AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG)"] +fn query_time_rows_equal_the_hand_computed_answers() { + let q4b = fixture_value_public("max__1m_1hz_10s", EQUIVALENT_ONLY); + let max_body = q4b["dag"]["nodes"][2]["payload"].clone(); + let measure = |kind: Value| { + let mut p = max_body.clone(); + p["NonASAP"]["Aggregate"]["measures"] = json!([kind]); + p + }; + let avg = with_root( + q4b.clone(), + 2, + measure(json!({"kind": "avg", "col": null})), + &[1], + ); + let mut instant = q4b.clone(); + payload_body(&mut instant, 1)["kind"] = json!("instant"); + payload_body(&mut instant, 1)["range"] = json!({"secs": 0, "nanos": 5_000_000}); + instant["dag"]["roots"] = json!([1]); + let topk = with_root( + q4b.clone(), + 2, + json!({"NonASAP": {"Aggregate": {"child": 2, "measures": [{"kind": "top_k", "k": 2}], + "reduction": {"Reduce": []}, "filters": [], "having": null}}}), + &[2], + ); + let quantile_1m = fixture_value_public("quantile__1m_1hz_10s", EQUIVALENT_ONLY); + let q50 = with_root( + quantile_1m.clone(), + 2, + { + let mut p = quantile_1m["dag"]["nodes"][2]["payload"].clone(); + p["NonASAP"]["Aggregate"]["measures"] = + json!([{"kind": "quantile", "col": null, "q": 0.5}]); + p + }, + &[1], + ); + let ratio = with_root( + q50, + 2, + json!({"NonASAP": {"BinaryOp": {"lhs": 2, "rhs": 3, "return_bool": false, + "operator": {"checked_relative_division": false, "checked_finite_division": false, + "kind": {"Arithmetic": "Div"}, "vector_match": null}}}}), + &[2, 3], + ); + let parts = [ + fixture_value_public("sum_over_time__1m_1hz_10s", EQUIVALENT_ONLY), + quantile_1m, + fixture_value_public("avg_quantile__1m_1hz_10s", EQUIVALENT_ONLY), + fixture_value_public("count__1m_1hz_10s", EQUIVALENT_ONLY), + q4b, + avg, + instant, + topk, + ratio, + fixture_value_public("sum_rate__1m_1hz_10s", WITH_SUBSTITUTES), + ]; + let mut plan = merged(&parts); + // A rate per series and an increase per series of the same counters. + let q2 = fixture_value_public("sum_rate__1m_1hz_10s", WITH_SUBSTITUTES); + let mut increase = q2.clone(); + payload_body(&mut increase, 2)["summary_type"] = + json!({"ExactAggregate": ["Increase", "Increase"]}); + increase["dag"]["roots"] = json!([3]); + let mut rate = q2; + rate["dag"]["roots"] = json!([3]); + plan = merged(&[plan, rate, increase]); + let texts: Vec = (0..plan["dag"]["roots"].as_array().unwrap().len()) + .map(|i| format!("query {i}")) + .collect(); + plan["query_texts"] = json!(texts); + + let engine = engine(); + let mut installed = engine + .install(&workload(&plan, 10_000), &arm("query-time", &plan)) + .unwrap(); + let mut data = latency_data(); + // A series of zeros: its 0.9/0.5 quantile ratio is 0/0. + data.0.push(( + series(&[("__name__", "latency"), ("job", "b"), ("instance", "z0")]), + (1..=80).map(|s| (s * 1000, 0.0)).collect(), + )); + let counters = counter_data(); + let mut samples = data.samples(); + samples.extend(counters.samples()); + let answers = run( + installed.as_mut(), + &chunks(samples, 10_000, 80_000), + 60_000, + 10_000, + ); + assert_eq!(answers.len(), 3); + let per_series = |t: i64, f: &dyn Fn(&[f64]) -> Option| -> BTreeMap { + data.windows(t, 60_000) + .into_iter() + .filter_map(|(labels, values)| Some(((**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); + for (t, got) in &answers { + let t = *t; + assert_answers(t, got, 0, &grouped(t, &sum, &sum)); + assert_answers(t, got, 1, &per_series(t, &|v| Some(quantile(0.99, v)))); + assert_answers( + t, + got, + 2, + &grouped(t, &|v| quantile(0.9, v), &|v| sum(v) / v.len() as f64), + ); + assert_answers(t, got, 3, &grouped(t, &|v| v.len() as f64, &sum)); + assert_answers(t, got, 4, &per_series(t, &|v| Some(max(v)))); + assert_answers( + t, + got, + 5, + &per_series(t, &|v| Some(sum(v) / v.len() as f64)), + ); + // The instant selector: each series' sample at exactly t. + let at_t: BTreeMap = data + .0 + .iter() + .filter_map(|(labels, points)| { + let &(_, v) = points.iter().find(|(ts, _)| *ts == t)?; + Some(((**labels).clone(), v)) + }) + .collect(); + assert_answers(t, got, 6, &at_t); + // Only the bare selector keeps `__name__`. + assert!(got.0["q6"].keys().all(|l| l.contains_key("__name__"))); + for other in ["q1", "q4", "q5", "q7", "q8", "q10", "q11"] { + assert!( + got.0[other].keys().all(|l| !l.contains_key("__name__")), + "{other}" + ); + } + let mut maxes: Vec<(SeriesLabels, f64)> = + per_series(t, &|v| Some(max(v))).into_iter().collect(); + maxes.sort_by(|a, b| b.1.total_cmp(&a.1)); + assert_answers(t, got, 7, &maxes.into_iter().take(2).collect()); + // 0/0 is NaN: VictoriaMetrics drops that series (the recorded substitution). + assert_answers( + t, + got, + 8, + &per_series(t, &|v| { + let r = quantile(0.99, v) / quantile(0.5, v); + (!r.is_nan()).then_some(r) + }), + ); + let counter = |f: &dyn Fn((f64, f64)) -> f64| -> BTreeMap { + counters + .0 + .iter() + .filter_map(|(labels, points)| { + Some(((**labels).clone(), f(vm_increase_rate(points, t, 60_000)?))) + }) + .collect() + }; + let rates = counter(&|(_, rate)| rate); + let mut by_job: BTreeMap = BTreeMap::new(); + for (labels, rate) in &rates { + *by_job.entry(group_key(labels, &["job"])).or_default() += rate; + } + assert_answers(t, got, 9, &by_job); + assert_answers(t, got, 10, &rates); + assert_answers(t, got, 11, &counter(&|(increase, _)| increase)); + } + println!( + "R6-R7 query-time rows: {} evaluations x 12 queries equal", + answers.len() + ); +} + +/// R8: with `-search.latencyOffset=0`, a point written at wall time t is +/// visible to `/api/v1/query?time=t` at once. +#[test] +#[ignore = "needs a VictoriaMetrics v1.154.1 server (AQPBM_VICTORIAMETRICS_URL, AQPBM_SERVER_CGROUP_DIRECTORY, AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG)"] +fn a_point_is_visible_at_its_own_time() { + let url = std::env::var("AQPBM_VICTORIAMETRICS_URL").unwrap(); + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_millis() as i64; + let line = format!( + "{{\"metric\":{{\"__name__\":\"latency_probe\",\"run\":\"{now_ms}\"}},\"values\":[42],\"timestamps\":[{now_ms}]}}\n" + ); + ureq::post(&format!("{url}/api/v1/import")) + .send_string(&line) + .unwrap(); + ureq::get(&format!("{url}/internal/force_flush")) + .call() + .unwrap(); + let time = format!("{}.{:03}", now_ms / 1000, now_ms % 1000); + let body = ureq::get(&format!("{url}/api/v1/query")) + .query( + "query", + &format!("last_over_time(latency_probe{{run=\"{now_ms}\"}}[1s])"), + ) + .query("time", &time) + .query("nocache", "1") + .call() + .unwrap() + .into_string() + .unwrap(); + assert!(body.contains("\"42\""), "{body}"); +} + +/// R9: a chunk sent after its window flushed fails the step (pacing). +#[test] +#[ignore = "needs a VictoriaMetrics v1.154.1 server (AQPBM_VICTORIAMETRICS_URL, AQPBM_SERVER_CGROUP_DIRECTORY, AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG)"] +fn a_late_chunk_fails_the_step() { + let mut plan = fixture_value_public("sum_over_time__1h__1hz__60s", EQUIVALENT_ONLY); + plan["dag"]["roots"] = json!([]); + plan["query_texts"] = json!(["late"]); + let root = add_chain_read(&mut plan, "Sum", 10_000, 10_000, json!("PerEntity")); + plan["dag"]["roots"] = json!([root]); + let engine = engine(); + let mut installed = engine + .install(&workload(&plan, 10_000), &arm("late", &plan)) + .unwrap(); + let data = latency_data(); + let all = chunks(data.samples(), 10_000, 20_000); + // Wait past the first window's end (its slices are due before it). + std::thread::sleep(Duration::from_secs(16)); + let error = installed.ingest(&all[0]).expect_err("a late chunk fails"); + assert!(error.0.contains("pacing"), "{error}"); +} diff --git a/system-bench/tests/victoriametrics_server.rs b/system-bench/tests/victoriametrics_server.rs new file mode 100644 index 00000000..72b26515 --- /dev/null +++ b/system-bench/tests/victoriametrics_server.rs @@ -0,0 +1,487 @@ +//! U1–U7: the VictoriaMetrics adapter's pieces without a real server: the +//! wall offset, the paced slices, the import body, the server metrics and +//! answers it reads, and the install path against a small fake server. + +mod common; + +use std::collections::BTreeMap; +use std::io::{BufRead, BufReader, Read, Write}; +use std::net::TcpListener; +use std::path::PathBuf; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use aqpbm_core::harness::cgroup::CgroupSource; +use aqpbm_core::harness::data::Sample; +use aqpbm_core::harness::engine::{ + ArmSpec, EngineUnderTest, QueryLanguage, QueryText, SampleChunk, SeriesLabels, WorkloadQuery, + WorkloadSpec, +}; +use common::{fixture_value_public, payload_body}; +use serde_json::json; +use system_bench::engines_external::victoriametrics::{StreamAggregation, StreamOutput}; +use system_bench::engines_external::victoriametrics_server::{ + answer_metric_name, import_body, lead_ms, parse_answer, previous_arm_gap_ms, slices, + wall_offset_ms, ServerMetrics, VictoriaMetricsEngine, VictoriaMetricsServer, SLICE_MS, +}; + +fn aggregation(interval_ms: u64) -> StreamAggregation { + StreamAggregation { + metric: "m".into(), + selector: "m".into(), + interval_ms, + by: None, + outputs: vec![StreamOutput::Max], + } +} + +fn labels(pairs: &[(&str, &str)]) -> Arc { + Arc::new( + pairs + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ) +} + +#[test] +fn wall_offset_puts_the_data_start_on_a_later_tick() { + // Aligned data start: the next multiple of the step at least 2 s ahead. + assert_eq!(wall_offset_ms(1_000_000_500, 0, 10_000), 1_000_010_000); + assert_eq!(wall_offset_ms(1_000_008_000, 0, 10_000), 1_000_010_000); + assert_eq!(wall_offset_ms(1_000_008_001, 0, 10_000), 1_000_020_000); + // A data start that is not a window end: its step boundary (0) goes on + // the tick, so the first samples are after the first flushed window's start. + assert_eq!(wall_offset_ms(1_000_000_500, 10_000, 60_000), 1_000_020_000); + let offset = wall_offset_ms(1_000_000_500, 10_000, 60_000); + assert_eq!(offset % 60_000, 0); + assert!(offset >= 1_000_002_500); +} + +#[test] +fn lead_is_at_least_a_second_and_below_every_width() { + assert_eq!(lead_ms(&[]), 1_000); + assert_eq!(lead_ms(&[aggregation(60_000), aggregation(10_000)]), 4_500); + assert_eq!(lead_ms(&[aggregation(2_000)]), 1_000); + for width in [2_000, 3_000, 10_000, 60_000, 3_600_000] { + assert!(lead_ms(&[aggregation(width)]) < width as i64); + } +} + +#[test] +fn slices_are_one_second_and_sent_a_lead_early() { + let series = labels(&[("__name__", "m"), ("job", "a")]); + let sample = |ts_ms| Sample { + labels: Arc::clone(&series), + ts_ms, + value: 1.0, + }; + // 1 Hz and 10 Hz samples in (0, 3 s]. + let mut samples = vec![sample(1_000), sample(2_000), sample(3_000)]; + samples.extend((1..=10).map(|i| sample(2_000 + i * 100))); + let chunk = SampleChunk { + end_ms: 3_000, + samples, + }; + let cut = slices(&chunk, 10_000, 1_000); + let ends: Vec = cut.iter().map(|s| s.end_ms).collect(); + assert_eq!(ends, vec![1_000, 2_000, 3_000]); + let sends: Vec = cut.iter().map(|s| s.send_at_wall_ms).collect(); + assert_eq!(sends, vec![10_000, 11_000, 12_000]); + assert_eq!(cut[2].samples.len(), 11); + // On time, no sample is older than the wall clock when sent: a slice + // ends `lead` after its send time, and holds samples of the last second. + for slice in &cut { + for sample in &slice.samples { + assert!(sample.ts_ms + 10_000 > slice.send_at_wall_ms); + assert!(sample.ts_ms > slice.end_ms - SLICE_MS); + } + } +} + +#[test] +fn import_body_is_one_line_per_series() { + let a = labels(&[("__name__", "m"), ("job", "a")]); + let b = labels(&[("__name__", "m"), ("job", "b")]); + let samples = [ + Sample { + labels: Arc::clone(&a), + ts_ms: 1_000, + value: 1.5, + }, + Sample { + labels: Arc::clone(&b), + ts_ms: 1_000, + value: f64::INFINITY, + }, + Sample { + labels: Arc::clone(&a), + ts_ms: 2_000, + value: f64::NAN, + }, + ]; + let refs: Vec<&Sample> = samples.iter().collect(); + assert_eq!( + import_body(&refs, 10_000), + "{\"metric\":{\"__name__\":\"m\",\"job\":\"a\"},\"values\":[1.5,NaN],\"timestamps\":[11000,12000]}\n\ + {\"metric\":{\"__name__\":\"m\",\"job\":\"b\"},\"values\":[Inf],\"timestamps\":[11000]}\n" + ); +} + +#[test] +fn server_metrics_are_read_from_the_exposition() { + let text = "\ +# HELP ignored\n\ +vm_app_version{version=\"victoria-metrics-20251019-v1.154.1\", short_version=\"v1.154.1\"} 1\n\ +vminsert_streamagg_config_reloads_total 3\n\ +vminsert_streamagg_config_last_reload_successful 1\n\ +vminsert_streamagg_config_reloads_errors_total 1\n\ +vm_streamaggr_flush_duration_seconds_count{outputs=\"max\",name=\"none\",path=\"/w/a.yaml\",url=\"global\",position=\"1\"} 7\n\ +vm_streamaggr_flush_duration_seconds_count{outputs=\"sum_samples,count_samples\",name=\"none\",path=\"/w/a.yaml\",url=\"global\",position=\"2\"} 4\n\ +vm_streamaggr_ignored_samples_total{reason=\"nan\",outputs=\"max\",name=\"none\",position=\"1\"} 9\n\ +vm_streamaggr_ignored_samples_total{reason=\"too_old\",outputs=\"max\",name=\"none\",position=\"1\"} 2\n\ +vm_streamaggr_ignored_samples_total{reason=\"too_old\",outputs=\"max\",name=\"none\",position=\"2\"} 1\n\ +vm_data_size_bytes{type=\"storage/small\"} 100\n\ +vm_data_size_bytes{type=\"indexdb/file\"} 20\n"; + assert_eq!( + ServerMetrics::parse(text, "none"), + ServerMetrics { + app_version: Some("victoria-metrics-20251019-v1.154.1".into()), + config_reloads: 3, + config_reload_errors: 1, + running_positions: [1, 2].into(), + flushes_by_position: BTreeMap::from([(1, 7), (2, 4)]), + too_old_samples: 3, + data_size_bytes: 120, + } + ); + // Another install's aggregations are not counted. + let other = ServerMetrics::parse(text, "install-1-0"); + assert!(other.flushes_by_position.is_empty() && other.running_positions.is_empty()); + assert_eq!(other.too_old_samples, 0); +} + +#[test] +fn answers_are_keyed_like_the_harness() { + let body = json!({"status": "success", "data": {"resultType": "vector", "result": [ + {"metric": {"__name__": "latency:60s_max", "job": "a"}, "value": [1, "3.5"]}, + {"metric": {"job": "b"}, "value": [1, "NaN"]}, + {"metric": {"job": "c"}, "value": [1, "+Inf"]} + ]}}) + .to_string(); + let per_series = parse_answer(&body, Some("latency")).unwrap(); + let key = |job: &str| -> SeriesLabels { + [("__name__", "latency"), ("job", job)] + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() + }; + assert_eq!(per_series[&key("a")], 3.5); + assert!(per_series[&key("b")].is_nan()); + assert_eq!(per_series[&key("c")], f64::INFINITY); + let grouped = parse_answer(&body, None).unwrap(); + let job_a: SeriesLabels = [("job".to_string(), "a".to_string())].into(); + assert_eq!(grouped[&job_a], 3.5); + // Two results with one key once `__name__` is dropped. + let twice = json!({"status": "success", "data": {"resultType": "vector", "result": [ + {"metric": {"__name__": "x", "job": "a"}, "value": [1, "1"]}, + {"metric": {"__name__": "y", "job": "a"}, "value": [1, "2"]} + ]}}) + .to_string(); + assert!(parse_answer(&twice, None) + .unwrap_err() + .contains("two series")); +} + +/// A fake VictoriaMetrics: `/metrics` with a version, a reload counter that +/// grows on `POST /-/reload`, an ignored-samples counter per entry of the +/// stream-aggregation config at `config` (named as the config names it), +/// `/api/v1/query` with no series, and `/internal/force_flush`. +fn fake_server(config: PathBuf) -> String { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + let reloads = Arc::new(AtomicU64::new(0)); + std::thread::spawn(move || { + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + let mut length = 0; + let mut header = String::new(); + while reader.read_line(&mut header).unwrap() > 0 && header.trim() != "" { + if let Some(v) = header.to_ascii_lowercase().strip_prefix("content-length:") { + length = v.trim().parse().unwrap(); + } + header.clear(); + } + let mut body = vec![0; length]; + reader.read_exact(&mut body).unwrap(); + let path = line.split_whitespace().nth(1).unwrap_or(""); + let answer = if path.starts_with("/-/reload") { + reloads.fetch_add(1, Ordering::SeqCst); + String::new() + } else if path.starts_with("/api/v1/query") { + "{\"status\":\"success\",\"data\":{\"resultType\":\"vector\",\"result\":[]}}" + .to_string() + } else if path.starts_with("/metrics") { + let entries: String = std::fs::read_to_string(&config) + .unwrap_or_default() + .lines() + .filter_map(|line| line.strip_prefix(" name: ")) + .enumerate() + .map(|(i, name)| { + format!( + "vm_streamaggr_ignored_samples_total{{reason=\"too_old\",name=\"{}\",position=\"{}\"}} 0\n", + name.trim_matches('\''), + i + 1 + ) + }) + .collect(); + format!( + "vm_app_version{{version=\"victoria-metrics-fake-v1.154.1\"}} 1\n\ + vminsert_streamagg_config_reloads_total {}\n\ + vminsert_streamagg_config_reloads_errors_total 0\n\ + vm_data_size_bytes{{type=\"storage/small\"}} 0\n{entries}", + reloads.load(Ordering::SeqCst) + ) + } else { + String::new() + }; + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{answer}", + answer.len() + ); + } + }); + url +} + +fn fake_cgroup(dir: &std::path::Path) -> CgroupSource { + std::fs::write(dir.join("stream-aggregation.yaml"), "[]\n").unwrap(); + CgroupSource::Local(dir.to_path_buf()) +} + +fn temp_dir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "victoriametrics-server-{}-{test}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +fn workload(texts: &[&str], interval_ms: u64) -> WorkloadSpec { + WorkloadSpec { + name: "u".into(), + queries: texts + .iter() + .enumerate() + .map(|(i, text)| WorkloadQuery { + id: format!("q{i}"), + texts: vec![QueryText { + language: QueryLanguage::PromQl, + text: text.to_string(), + }], + window_ms: 60_000, + evaluation_interval_ms: interval_ms, + }) + .collect(), + data: vec![], + } +} + +fn arm(dir: &std::path::Path, plan: &serde_json::Value) -> ArmSpec { + let path = dir.join("p.plan.json"); + std::fs::write(&path, plan.to_string()).unwrap(); + ArmSpec { + name: "u".into(), + raw_data_retained: true, + engine_options: json!({ "plan_file": path }), + } +} + +#[test] +fn one_arm_at_a_time_and_its_config_reaches_the_server() { + let dir = temp_dir("one-arm"); + let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { + url: fake_server(dir.join("stream-aggregation.yaml")), + cgroup: fake_cgroup(&dir), + stream_aggregation_config: dir.join("stream-aggregation.yaml"), + request_timeout: Duration::from_secs(10), + }) + .unwrap(); + assert_eq!(engine.description().id, "victoriametrics"); + assert_eq!( + engine.description().version, + "victoria-metrics-fake-v1.154.1" + ); + // A stored plan with 10 s windows: the install waits at most the + // margin plus one step of 10 s. + let mut plan = fixture_value_public( + "sum_over_time__1h__1hz__60s", + "victoriametrics.equivalent-only", + ); + payload_body(&mut plan, 1)["tumbling_window_width_ms"] = json!(10_000); + let texts = ["sum by (job) (sum_over_time(latency[1h]))"]; + let first = engine + .install(&workload(&texts, 10_000), &arm(&dir, &plan)) + .unwrap(); + let config = std::fs::read_to_string(dir.join("stream-aggregation.yaml")).unwrap(); + assert!(config.contains(" name: 'install-"), "{config}"); + assert!(config.contains(" interval: 10s\n"), "{config}"); + let error = engine + .install(&workload(&texts, 10_000), &arm(&dir, &plan)) + .err() + .expect("a second arm is refused"); + assert!(error.0.contains("--warmup 0 --runs 1"), "{error}"); + drop(first); + // Dropping the arm unloads its config and frees the engine; the next + // install's config has another name. + assert_eq!( + std::fs::read_to_string(dir.join("stream-aggregation.yaml")).unwrap(), + "[]\n" + ); + let second = engine + .install(&workload(&texts, 10_000), &arm(&dir, &plan)) + .unwrap(); + let again = std::fs::read_to_string(dir.join("stream-aggregation.yaml")).unwrap(); + assert_ne!(again, config); + drop(second); +} + +#[test] +fn plans_are_checked_against_the_workload_before_anything_loads() { + let dir = temp_dir("checks"); + let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { + url: fake_server(dir.join("stream-aggregation.yaml")), + cgroup: fake_cgroup(&dir), + stream_aggregation_config: dir.join("stream-aggregation.yaml"), + request_timeout: Duration::from_secs(10), + }) + .unwrap(); + let plan = fixture_value_public( + "sum_over_time__1h__1hz__60s", + "victoriametrics.equivalent-only", + ); + // Another query text than the plan's. + let error = engine + .install(&workload(&["other"], 60_000), &arm(&dir, &plan)) + .err() + .unwrap(); + assert!(error.0.contains("the plan answers"), "{error}"); + // Stored windows of 60 s cannot be read every 10 s. + let error = engine + .install( + &workload(&["sum by (job) (sum_over_time(latency[1h]))"], 10_000), + &arm(&dir, &plan), + ) + .err() + .unwrap(); + assert!( + error.0.contains("do not divide its evaluation interval"), + "{error}" + ); + // Nothing was loaded. + assert_eq!( + std::fs::read_to_string(dir.join("stream-aggregation.yaml")).unwrap(), + "[]\n" + ); +} + +#[test] +fn a_query_time_arm_ingests_then_evaluates() { + // No stream aggregation: the ingest of the chunk ending at t still + // returns only once wall time reached t, so the evaluation at t follows. + let dir = temp_dir("query-time"); + let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { + url: fake_server(dir.join("stream-aggregation.yaml")), + cgroup: fake_cgroup(&dir), + stream_aggregation_config: dir.join("stream-aggregation.yaml"), + request_timeout: Duration::from_secs(10), + }) + .unwrap(); + let plan = fixture_value_public( + "sum_over_time__1m_1hz_10s", + "victoriametrics.equivalent-only", + ); + let texts = ["sum by (job) (sum_over_time(latency[1m]))"]; + let mut installed = engine + .install(&workload(&texts, 10_000), &arm(&dir, &plan)) + .unwrap(); + let series = labels(&[("__name__", "latency"), ("job", "a")]); + let chunk = SampleChunk { + end_ms: 10_000, + samples: (1..=10) + .map(|s| Sample { + labels: Arc::clone(&series), + ts_ms: s * 1000, + value: s as f64, + }) + .collect(), + }; + installed.ingest(&chunk).unwrap(); + let (answers, _) = installed.evaluate(10_000).unwrap(); + assert!(answers.0["q0"].is_empty()); +} + +#[test] +fn only_counter_plans_wait_for_the_previous_arms_samples_to_age_out() { + use system_bench::engines_external::plan_file::PlanFile; + let plan = |workload: &str, variant: &str| { + PlanFile::from_value(fixture_value_public(workload, variant)).unwrap() + }; + // Rollups over a window read only the window: no wait. + assert_eq!( + previous_arm_gap_ms(&plan( + "sum_over_time__1m_1hz_10s", + "victoriametrics.equivalent-only" + )), + 0 + ); + assert_eq!( + previous_arm_gap_ms(&plan( + "sum_over_time__1h__1hz__60s", + "victoriametrics.equivalent-only" + )), + 0 + ); + // `rate` looks back for the sample before its range: 10 min plus the + // longest range (60 s). + assert_eq!( + previous_arm_gap_ms(&plan( + "sum_rate__1m_1hz_10s", + "victoriametrics.with-substitutes" + )), + 660_000 + ); +} + +#[test] +fn only_a_bare_selector_answer_keeps_the_metric_name() { + use system_bench::engines_external::plan_file::PlanFile; + use system_bench::engines_external::victoriametrics::translate; + // PromQL drops `__name__` in every function and aggregation, e.g. + // `max_over_time(latency[1m])` answers `{job="a", instance="i"}`. + let value = fixture_value_public("max__1m_1hz_10s", "victoriametrics.equivalent-only"); + let plan = PlanFile::from_value(value.clone()).unwrap(); + let deployment = translate(&plan).unwrap(); + assert_eq!( + answer_metric_name(&plan, plan.roots[0], &deployment.queries[0]), + None + ); + // A root that is the instant selector `latency` keeps it. + let mut instant = value; + payload_body(&mut instant, 1)["kind"] = json!("instant"); + payload_body(&mut instant, 1)["range"] = json!({"secs": 0, "nanos": 5_000_000}); + instant["dag"]["roots"] = json!([1]); + let plan = PlanFile::from_value(instant).unwrap(); + let deployment = translate(&plan).unwrap(); + assert_eq!( + answer_metric_name(&plan, plan.roots[0], &deployment.queries[0]).as_deref(), + Some("latency") + ); +} diff --git a/system-bench/tests/victoriametrics_translate.rs b/system-bench/tests/victoriametrics_translate.rs index 94d2089f..0f92a714 100644 --- a/system-bench/tests/victoriametrics_translate.rs +++ b/system-bench/tests/victoriametrics_translate.rs @@ -460,6 +460,8 @@ fn interval_must_divide_a_day() { (3_600_000, true), (2_000, true), (7_000, false), + // A 7-minute window: 86,400 s is not a whole number of them. + (420_000, false), (1_500, false), (1_000, false), ] { @@ -478,6 +480,7 @@ fn interval_must_divide_a_day() { } else { let reason = match width_ms { 7_000 => "window width 7000 ms does not divide 86,400 s", + 420_000 => "window width 420000 ms does not divide 86,400 s", 1_500 => "window width 1500 ms is not whole seconds", _ => "window width 1000 ms is below 2 s", }; @@ -803,3 +806,21 @@ fn public_plan_translations_match_the_snapshot() { } assert_eq!(snapshot, std::fs::read_to_string(path).expect("snapshot")); } + +#[test] +fn a_named_config_names_every_entry() { + let deployment = translated("sum_over_time__1h__1hz__60s", EQUIVALENT_ONLY); + let named = deployment.stream_aggregation_config_named("install-7"); + assert_eq!( + named, + golden("sum_over_time_1h.yaml").replace( + "- match: 'latency'\n", + "- match: 'latency'\n name: 'install-7'\n" + ) + ); + assert_eq!( + translated("sum_over_time__1m_1hz_10s", EQUIVALENT_ONLY) + .stream_aggregation_config_named("x"), + "[]\n" + ); +}