From d4b11968b5962c7ff7e049552ec8bf01951cc56e Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:31:12 +0000 Subject: [PATCH 01/51] repository: LICENSE with the MIT license the workspace already declares Cargo.toml declares license = "MIT" for every crate, but the repository had no license text. The file is asap_sketchlib's LICENSE, word for word. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..251d3c97 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 - present ProjectASAP + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 99488aa9145dfccf6faec4154cb6272fffdb7ebf Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:32:40 +0000 Subject: [PATCH 02/51] toolchain: pin Rust 1.100.0 with rust-toolchain.toml, and CI installs that version rust-toolchain.toml pins the compiler to 1.100.0 (minimal profile, plus rustfmt and clippy), so a build anywhere uses the same rustc. Both CI jobs read the channel from that file and install it through dtolnay/rust-toolchain instead of stable; the test job now also installs clippy, which its last step runs. The cargo cache key includes the file, so a new pin does not reuse a target directory built by another compiler. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- .github/workflows/rust.yml | 21 +++++++++++++++------ rust-toolchain.toml | 4 ++++ 2 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 rust-toolchain.toml diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 3e65d9bc..438d623e 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -31,10 +31,14 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Read the pinned Rust version + id: rust-version + run: echo "channel=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)" >> "$GITHUB_OUTPUT" + - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: ${{ steps.rust-version.outputs.channel }} components: rustfmt, clippy - name: Run sccache-cache @@ -47,7 +51,7 @@ jobs: ~/.cargo/registry ~/.cargo/git target - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml') }} + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml', 'rust-toolchain.toml') }} - name: Check formatting run: cargo fmt --all -- --check @@ -63,10 +67,15 @@ jobs: steps: - uses: actions/checkout@v4 + - name: Read the pinned Rust version + id: rust-version + run: echo "channel=$(sed -n 's/^channel = "\(.*\)"$/\1/p' rust-toolchain.toml)" >> "$GITHUB_OUTPUT" + - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@master with: - toolchain: stable + toolchain: ${{ steps.rust-version.outputs.channel }} + components: clippy - name: Run sccache-cache uses: mozilla-actions/sccache-action@v0.0.4 @@ -78,7 +87,7 @@ jobs: ~/.cargo/registry ~/.cargo/git target - key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml') }} + key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock', '**/Cargo.toml', 'rust-toolchain.toml') }} - name: Run all workspace tests run: cargo test --workspace --locked diff --git a/rust-toolchain.toml b/rust-toolchain.toml new file mode 100644 index 00000000..87cd0e8b --- /dev/null +++ b/rust-toolchain.toml @@ -0,0 +1,4 @@ +[toolchain] +channel = "1.100.0" +components = ["rustfmt", "clippy"] +profile = "minimal" From 026bfc7296dd02e39452ade7592dec5821bd9bab Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:57 +0000 Subject: [PATCH 03/51] scripts: start and stop PostgreSQL 17.12 with TimescaleDB 2.32.1 and timescaledb_toolkit scripts/extbench-up-timescaledb.sh up|down follows extbench-up.sh: one docker container from an image pinned by digest (timescale/timescaledb-ha pg17.12-ts2.32.1, with timescaledb_toolkit 1.29.0), pinned to the given cores and NUMA node, host network, listening only on a private or loopback LISTEN_HOST, running as the invoking user with no CPU quota or memory limit. Every start initializes an empty data dir, and the script deletes only a data dir it created. The data dir is tuned as ClickBench sets TimescaleDB up: timescaledb-tune over the container's cores and TUNE_MEMORY (all of the host's by default), with timescaledb as the only preloaded library. The script creates DATABASE (bench) with both extensions, trusts connections, names the superuser after the invoking user, and writes versions.txt: image, PostgreSQL and extension versions, the settings from the configuration file, the connection string, the cpuset and the cgroup the harness reads. DATA_DIRECTORY is mounted read-only at the same path for server-side reads. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/extbench-up-timescaledb.sh | 114 +++++++++++++++++++++++++++++ 1 file changed, 114 insertions(+) create mode 100755 scripts/extbench-up-timescaledb.sh diff --git a/scripts/extbench-up-timescaledb.sh b/scripts/extbench-up-timescaledb.sh new file mode 100755 index 00000000..ce2237ed --- /dev/null +++ b/scripts/extbench-up-timescaledb.sh @@ -0,0 +1,114 @@ +#!/usr/bin/env bash +# scripts/extbench-up-timescaledb.sh up [] +# scripts/extbench-up-timescaledb.sh down [] +# +# Environment: +# LISTEN_HOST address the server listens on (required): a private (10/8, 172.16/12, +# 192.168/16) or loopback address +# IMAGE the image, pinned by digest (default: PostgreSQL 17.12, TimescaleDB 2.32.1 +# and timescaledb_toolkit 1.29.0 below) +# DATABASE the database created with both extensions (default: bench) +# TUNE_MEMORY the memory timescaledb-tune sizes the settings for, e.g. 32GB (default: +# all of this host's) +# DATA_DIRECTORY a directory mounted read-only at the same path, for files the server reads +set -euo pipefail + +marker=.extbench-data-dir +default_image=timescale/timescaledb-ha@sha256:3143e29f69e0e68c25071dca76307fa66b5a98c0cc5f33d1f5c1f9b0b4e085d4 + +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=$(realpath -m "${2:?data dir}") + +if [ "$action" = down ]; then + name=${3:-extbench-timescaledb} + 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}; port=${5:?port} +name=${6:-extbench-timescaledb} +image=${IMAGE:-$default_image} +database=${DATABASE:-bench} +user=$(id -un) +: "${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; } +mounts=() +if [ -n "${DATA_DIRECTORY:-}" ]; then + data_directory=$(realpath "$DATA_DIRECTORY") + mounts=(-v "$data_directory:$data_directory:ro") +fi + +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"; touch "$data_dir/$marker" +printf '%s:x:%s:%s::/data:/bin/sh\n' "$user" "$(id -u)" "$(id -g)" > "$data_dir/passwd" +nss=(-e LD_PRELOAD=libnss_wrapper.so -e NSS_WRAPPER_PASSWD=/data/passwd -e NSS_WRAPPER_GROUP=/etc/group) +as_user=(--user "$(id -u):$(id -g)" "${nss[@]}") + +docker run --rm --cpuset-cpus "$cores" --cpuset-mems "$numa" "${as_user[@]}" -v "$data_dir:/data" \ + --entrypoint bash "$image" -c 'initdb -D /data/pgdata --auth=trust --encoding=UTF8 --locale=C.UTF-8 && + timescaledb-tune --yes --quiet --color=false --conf-path=/data/pgdata/postgresql.conf ${1:+--memory="$1"}' \ + bash "${TUNE_MEMORY:-}" > "$data_dir/initdb.log" 2>&1 \ + || { echo "initdb or timescaledb-tune failed" >&2; cat "$data_dir/initdb.log" >&2; exit 1; } + +docker rm -f "$name" >/dev/null 2>&1 || true +docker run -d --name "$name" --network host \ + --cpuset-cpus "$cores" --cpuset-mems "$numa" "${as_user[@]}" \ + --shm-size "$(($(awk '/^MemTotal:/ {print $2}' /proc/meminfo) / 2))k" \ + -v "$data_dir:/data" ${mounts[@]+"${mounts[@]}"} \ + --entrypoint postgres "$image" -D /data/pgdata -c listen_addresses="$LISTEN_HOST" -c port="$port" \ + -c unix_socket_directories= -c shared_preload_libraries=timescaledb >/dev/null +ready() { docker exec "$name" pg_isready -q -h "$LISTEN_HOST" -p "$port" -U "$user"; } +for _ in $(seq 1 60); do + ready && break; sleep 1 +done +ready || { echo "the server did not start" >&2; docker logs "$name" >&2; exit 1; } + +run_psql() { + docker exec -i "${nss[@]}" "$name" psql -X -q -At -v ON_ERROR_STOP=1 -h "$LISTEN_HOST" -p "$port" \ + -U "$user" "$@" +} +run_psql -d postgres -c "CREATE DATABASE \"$database\"" +run_psql -d "$database" -c "CREATE EXTENSION timescaledb" -c "CREATE EXTENSION timescaledb_toolkit" +query() { run_psql -d "$database" -c "$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 $(query "SELECT version()")" + echo "timescaledb $(query "SELECT extversion FROM pg_extension WHERE extname = 'timescaledb'")" + echo "timescaledb_toolkit $(query "SELECT extversion FROM pg_extension WHERE extname = 'timescaledb_toolkit'")" + echo "settings $(query "SELECT string_agg(name || '=' || current_setting(name), ' ' ORDER BY name) + FROM pg_settings WHERE source = 'configuration file'")" + echo "connection host=$LISTEN_HOST port=$port user=$user dbname=$database" + echo "cpuset $cores mems $numa" + echo "thread_siblings $(siblings)" + echo "cpu_model $(lscpu | sed -n 's/^Model name: *//p')" + echo "cgroup $group" + echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" +cat "$data_dir/versions.txt" From 44f4285306f1eaad0efb16ffbc9fe3baa5b9e453 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:57 +0000 Subject: [PATCH 04/51] scripts: build, plan with, start and stop ASAPQuery-backend at a pinned commit scripts/extbench-up-asapquery-backend.sh: - build: clones ASAPQuery-backend, checks out commit 8263b22b (main on 2026-11-29), refuses local changes, and builds control_plane and data_plane with cargo --locked into /target; build.txt records the commit, rustc and both binaries' sha256. - plan: runs that control_plane on an ASAPPlanner PlanningWorkload, such as suites/*/.planner.json. - up/down: as extbench-up.sh does for ClickHouse, the data_plane binary runs bind-mounted in a base image pinned by digest (Ubuntu 26.04, glibc 2.43), pinned to the given cores and NUMA node, as the invoking user, listening on a private or loopback LISTEN_HOST, with --no-forward and its views in an empty data dir; DATA_PLANE_ARGUMENTS adds arguments such as --stream-start-ms. Only a data dir the script created is deleted. versions.txt records the commit, the binary's and the plan's sha256, the image, the cpuset and the cgroup for `benchmark-external run --engine asapquery-backend`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/extbench-up-asapquery-backend.sh | 131 +++++++++++++++++++++++ 1 file changed, 131 insertions(+) create mode 100755 scripts/extbench-up-asapquery-backend.sh diff --git a/scripts/extbench-up-asapquery-backend.sh b/scripts/extbench-up-asapquery-backend.sh new file mode 100755 index 00000000..6213fa10 --- /dev/null +++ b/scripts/extbench-up-asapquery-backend.sh @@ -0,0 +1,131 @@ +#!/usr/bin/env bash +# scripts/extbench-up-asapquery-backend.sh build +# scripts/extbench-up-asapquery-backend.sh plan +# scripts/extbench-up-asapquery-backend.sh up [] +# scripts/extbench-up-asapquery-backend.sh down [] +# +# Environment: +# LISTEN_HOST address the server listens on (required for up): a private +# (10/8, 172.16/12, 192.168/16) or loopback address +# BASE_IMAGE the image the data plane runs in, pinned by digest (default: +# Ubuntu 26.04 below); its glibc must be at least the build host's +# DATA_PLANE_ARGUMENTS more data_plane arguments, space-separated +# CARGO the cargo that builds (default: cargo) +set -euo pipefail + +marker=.extbench-data-dir +commit=8263b22b6880f03f7c14fc08a182c27b7f617f34 +repository=https://github.com/ProjectASAP/ASAPQuery-backend +default_image=ubuntu@sha256:d66b366dac61b575bee2aef07e9c26e8070096fbe84a3d4d3eb0da069b5d76db + +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 +} + +built() { + local source=$1/source + [ -d "$source/.git" ] || { echo "no build in $1; run: $0 build $1" >&2; exit 1; } + [ "$(git -C "$source" rev-parse HEAD)" = "$commit" ] \ + || { echo "$source is not at $commit; run: $0 build $1" >&2; exit 1; } + for binary in control_plane data_plane; do + [ -x "$1/target/release/$binary" ] || { echo "no $binary in $1; run: $0 build $1" >&2; exit 1; } + done +} + +action=${1:?build|plan|up|down} + +case "$action" in + build) + build_dir=$(realpath -m "${2:?build dir}") + source=$build_dir/source + mkdir -p "$build_dir" + [ -d "$source/.git" ] || git clone --quiet "$repository" "$source" + git -C "$source" fetch --quiet origin "$commit" + git -C "$source" checkout --quiet --detach "$commit" + [ -z "$(git -C "$source" status --porcelain)" ] || { echo "refused: $source has local changes" >&2; exit 1; } + (cd "$source" && "${CARGO:-cargo}" build --release --locked --target-dir "$build_dir/target" \ + -p control_plane -p data_plane) + { echo "commit $commit" + echo "rustc $(cd "$source" && rustc --version)" + for binary in control_plane data_plane; do + echo "${binary}_sha256 $(sha256sum "$build_dir/target/release/$binary" | cut -d' ' -f1)" + done; } > "$build_dir/build.txt" + cat "$build_dir/build.txt" + exit 0 + ;; + plan) + build_dir=$(realpath -m "${2:?build dir}"); workload=${3:?planner workload}; plan=${4:?plan file} + built "$build_dir" + "$build_dir/target/release/control_plane" --workload "$workload" --out "$plan" + exit 0 + ;; + down) + data_dir=${2:?data dir} + name=${3:-extbench-asapquery-backend} + docker rm -f "$name" >/dev/null 2>&1 || true + exit 0 + ;; + up) ;; + *) echo "unknown action $action" >&2; exit 2 ;; +esac + +build_dir=$(realpath -m "${2:?build dir}"); data_dir=$(realpath -m "${3:?data dir}") +cores=${4:?cores}; numa=${5:?numa node}; http_port=${6:?http port}; plan=$(realpath "${7:?plan file}") +name=${8:-extbench-asapquery-backend} +image=${BASE_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: BASE_IMAGE must be pinned by digest" >&2; exit 1; } +built "$build_dir" +binary=$build_dir/target/release/data_plane +read -r -a extra <<<"${DATA_PLANE_ARGUMENTS:-}" + +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/views"; touch "$data_dir/$marker" +cp "$plan" "$data_dir/plan.json" + +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 "$binary:/usr/local/bin/data_plane:ro" -v "$data_dir/plan.json:/plan.json:ro" \ + -v "$data_dir/views:/views" \ + "$image" /usr/local/bin/data_plane --plan /plan.json --no-forward \ + --listen "$LISTEN_HOST:$http_port" --view-dir /views ${extra[@]+"${extra[@]}"} >/dev/null +for _ in $(seq 1 60); do + curl -sf "http://$LISTEN_HOST:$http_port/-/ready" >/dev/null && break; sleep 1 +done +curl -sf "http://$LISTEN_HOST:$http_port/-/ready" >/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 "commit $commit" + echo "data_plane_sha256 $(sha256sum "$binary" | cut -d' ' -f1)" + echo "plan_sha256 $(sha256sum "$data_dir/plan.json" | cut -d' ' -f1)" + echo "base_image $image" + echo "data_plane_arguments ${DATA_PLANE_ARGUMENTS:-}" + echo "cpuset $cores mems $numa" + echo "thread_siblings $(siblings)" + echo "cpu_model $(lscpu | sed -n 's/^Model name: *//p')" + echo "cgroup $group" + echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" +cat "$data_dir/versions.txt" From 4d757b1bdf86813cda126f438f907456ce0194f1 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:57 +0000 Subject: [PATCH 05/51] scripts: install the DuckDB 1.3.1 command line scripts/install-duckdb.sh downloads DuckDB v1.3.1's release binary for Linux x86_64, Linux arm64 or macOS, checks it against the sha256 GitHub lists for the asset, and writes /duckdb. 1.3.1 is the version PilotDB's duckdb package reads and the one #277 ran. An existing duckdb of another version is refused, never replaced. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/install-duckdb.sh | 40 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100755 scripts/install-duckdb.sh diff --git a/scripts/install-duckdb.sh b/scripts/install-duckdb.sh new file mode 100755 index 00000000..de938385 --- /dev/null +++ b/scripts/install-duckdb.sh @@ -0,0 +1,40 @@ +#!/usr/bin/env bash +# scripts/install-duckdb.sh +set -euo pipefail + +version=v1.3.1 +case "$(uname -s) $(uname -m)" in + "Linux x86_64") + asset=duckdb_cli-linux-amd64.gz + sha256=aa61ab7e300759d7af30e19b9367d7df6297fbdb2f674c140ee80dcad08a3123 ;; + "Linux aarch64" | "Linux arm64") + asset=duckdb_cli-linux-arm64.gz + sha256=b454f1561389adf302af2f5ddea9bc4917ca540d2c356b17061f8c987320999d ;; + "Darwin x86_64" | "Darwin arm64") + asset=duckdb_cli-osx-universal.gz + sha256=3bab425d30f1b704a8f637eeee968405ecfeae56f7fc2e3a3bd46b6cd3f29ae1 ;; + *) echo "no DuckDB $version command line for $(uname -s) $(uname -m)" >&2; exit 1 ;; +esac + +install_dir=${1:?install dir} +target=$install_dir/duckdb +if [ -e "$target" ]; then + installed=$("$target" --version 2>/dev/null | cut -d' ' -f1 || true) + [ "$installed" = "$version" ] || { echo "refused: $target exists and is not DuckDB $version" >&2; exit 1; } + echo "$target is DuckDB $version" + exit 0 +fi +mkdir -p "$install_dir" +download=$(mktemp "$install_dir/.duckdb-download.XXXXXX") +trap 'rm -f "$download" "$download.binary"' EXIT +curl -fsSL --retry 3 -o "$download" "https://github.com/duckdb/duckdb/releases/download/$version/$asset" +if command -v sha256sum >/dev/null; then + actual=$(sha256sum "$download" | cut -d' ' -f1) +else + actual=$(shasum -a 256 "$download" | cut -d' ' -f1) +fi +[ "$actual" = "$sha256" ] || { echo "$asset sha256 $actual != $sha256" >&2; exit 1; } +gzip -dc "$download" > "$download.binary" +chmod +x "$download.binary" +mv "$download.binary" "$target" +echo "$target is DuckDB $("$target" --version)" From 9e462ac48ca6d839f993c3b0f38d439397dad69c Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:57 +0000 Subject: [PATCH 06/51] scripts: install PilotDB and its Python packages at the versions #277 ran scripts/install-pilotdb.sh checks PilotDB out at d1210ce (refusing local changes), makes a virtual environment from PYTHON (python3), installs the exact package versions of the environment #277 ran (duckdb 1.3.1, numpy 2.5.5, pandas 3.1.1, scipy 1.18.1, sqlglot 26.30.0 and the rest, without resolving other dependencies), then PilotDB itself as editable, so the adapter's version line reads its commit. It checks that PilotDB imports, which needs unixODBC's libodbc.so.2 for pyodbc, and prints the PILOTDB_PYTHON to use. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/install-pilotdb.sh | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100755 scripts/install-pilotdb.sh diff --git a/scripts/install-pilotdb.sh b/scripts/install-pilotdb.sh new file mode 100755 index 00000000..023694ae --- /dev/null +++ b/scripts/install-pilotdb.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# scripts/install-pilotdb.sh +# +# Environment: +# PYTHON the Python the virtual environment is made from, 3.11 or later (default: python3) +set -euo pipefail + +commit=d1210ce13bbacba7ee77faae4a9be07371ed208a +repository=https://github.com/uiuc-kang-lab/PilotDB +requirements=( + blinker==1.9.0 click==8.5.1 duckdb==1.3.1 Flask==3.1.3 itsdangerous==2.2.0 Jinja2==3.1.6 + MarkupSafe==3.0.4 numpy==2.5.5 pandas==3.1.1 psycopg2-binary==2.9.13 pyodbc==5.5.0 + python-dateutil==4.0.0 PyYAML==6.0.4 scipy==1.18.1 sqlglot==26.30.0 tzdata==2026.6 Werkzeug==3.1.9 +) + +install_dir=$(realpath -m "${1:?install dir}") +source=$install_dir/PilotDB +environment=$install_dir/venv +mkdir -p "$install_dir" +[ -d "$source/.git" ] || git clone --quiet "$repository" "$source" +git -C "$source" fetch --quiet origin "$commit" +git -C "$source" checkout --quiet --detach "$commit" +[ -z "$(git -C "$source" status --porcelain)" ] || { echo "refused: $source has local changes" >&2; exit 1; } +[ -x "$environment/bin/python" ] || "${PYTHON:-python3}" -m venv "$environment" +"$environment/bin/python" -m pip install --quiet --no-deps "${requirements[@]}" +"$environment/bin/python" -m pip install --quiet --no-deps --editable "$source" +"$environment/bin/python" -I -c "import pilotdb.execute" \ + || { echo "PilotDB does not import; its pyodbc needs unixODBC's libodbc.so.2 (Debian and Ubuntu: libodbc2)" >&2; exit 1; } +echo "PILOTDB_PYTHON=$environment/bin/python" From c41d04ccf54176c1fccb0803ccc5c0fadd2012ac Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:56:00 +0000 Subject: [PATCH 07/51] scripts: start and stop Druid 37.0.0 scripts/extbench-up-druid.sh up|down runs Druid's single-server medium profile, as ClickBench does, in one container from apache/druid 37.0.0 pinned by digest: ZooKeeper and the five services are started with the image's own bin/run-zk and bin/run-druid (the image has no perl for bin/supervise), so the whole of Druid, ingestion tasks included, is one cgroup pinned to the given cores and NUMA node. The container runs as the invoking user, with no CPU quota or memory limit, on its own network: the profile opens fixed ports on every interface, so only the router is published, on a private or loopback LISTEN_HOST. The profile is copied into an empty data dir and edited as ClickBench's install does (historical caches off, 1000MiB processing buffers, 21g direct memory, a 5000000000 merging dictionary, 5g task direct memory), and each ingestion task gets TASK_HEAP (8g): the profile's 1g ran out of memory on ClickBench's 105-column table. DATA_DIRECTORY is mounted read-only at the same path for local input sources. The script waits for SQL and for a worker, deletes only a data dir it created, and writes versions.txt: image, Druid version, task heap, URL, cpuset and cgroup. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/extbench-up-druid.sh | 122 +++++++++++++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100755 scripts/extbench-up-druid.sh diff --git a/scripts/extbench-up-druid.sh b/scripts/extbench-up-druid.sh new file mode 100755 index 00000000..07444ecd --- /dev/null +++ b/scripts/extbench-up-druid.sh @@ -0,0 +1,122 @@ +#!/usr/bin/env bash +# scripts/extbench-up-druid.sh up [] +# scripts/extbench-up-druid.sh down [] +# +# Environment: +# LISTEN_HOST address the router is published on (required): a private (10/8, +# 172.16/12, 192.168/16) or loopback address +# IMAGE the image, pinned by digest (default: Druid 37.0.0 below) +# TASK_HEAP the heap of each ingestion task, e.g. 8g (default: 8g) +# DATA_DIRECTORY a directory mounted read-only at the same path, for files ingestion reads +set -euo pipefail + +marker=.extbench-data-dir +default_image=apache/druid@sha256:0116fb802786649fc3635d6d4ab5be4da8abee3edafbe95c7f358a564d4c82e8 +profile=conf/druid/single-server/medium + +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=$(realpath -m "${2:?data dir}") + +if [ "$action" = down ]; then + name=${3:-extbench-druid} + 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}; port=${5:?router port} +name=${6:-extbench-druid} +image=${IMAGE:-$default_image} +task_heap=${TASK_HEAP:-8g} +: "${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; } +[[ "$task_heap" =~ ^[0-9]+[kmgKMG]$ ]] || { echo "refused: TASK_HEAP $task_heap is not a JVM size such as 8g" >&2; exit 1; } +mounts=() +if [ -n "${DATA_DIRECTORY:-}" ]; then + data_directory=$(realpath "$DATA_DIRECTORY") + mounts=(-v "$data_directory:$data_directory:ro") +fi + +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/var/tmp"; touch "$data_dir/$marker" + +docker run --rm --user "$(id -u):$(id -g)" -v "$data_dir:/out" --entrypoint cp "$image" \ + -R /opt/druid/bin /opt/druid/conf /etc/passwd /etc/group /out/ +printf '%s:x:%s:%s::/opt/druid:/bin/sh\n' "$(id -un)" "$(id -u)" "$(id -g)" >> "$data_dir/passwd" +printf '%s:x:%s:\n' "$(id -gn)" "$(id -g)" >> "$data_dir/group" +edit() { + local file=$data_dir/$profile/$1 from=$2 to=$3 + grep -qF -- "$from" "$file" || { echo "no $from in $file" >&2; exit 1; } + sed -i "s|$from|$to|" "$file" +} +edit middleManager/runtime.properties '"-Xms1g","-Xmx1g","-XX:MaxDirectMemorySize=1g"' \ + "\"-Xms$task_heap\",\"-Xmx$task_heap\",\"-XX:MaxDirectMemorySize=5g\"" +edit historical/runtime.properties druid.historical.cache.useCache=true druid.historical.cache.useCache=false +edit historical/runtime.properties druid.historical.cache.populateCache=true druid.historical.cache.populateCache=false +edit historical/runtime.properties druid.processing.buffer.sizeBytes=500MiB druid.processing.buffer.sizeBytes=1000MiB +edit historical/jvm.config -XX:MaxDirectMemorySize=13g -XX:MaxDirectMemorySize=21g +echo druid.query.groupBy.maxMergingDictionarySize=5000000000 >> "$data_dir/$profile/historical/runtime.properties" + +docker rm -f "$name" >/dev/null 2>&1 || true +docker run -d --name "$name" -p "$LISTEN_HOST:$port:8888" \ + --cpuset-cpus "$cores" --cpuset-mems "$numa" --user "$(id -u):$(id -g)" \ + -v "$data_dir/bin:/opt/druid/bin:ro" -v "$data_dir/conf:/opt/druid/conf:ro" -v "$data_dir/var:/opt/druid/var" \ + -v "$data_dir/passwd:/etc/passwd:ro" -v "$data_dir/group:/etc/group:ro" -e DRUID_LOG_DIR=/opt/druid/var/log \ + ${mounts[@]+"${mounts[@]}"} \ + --entrypoint bash "$image" -c ' + bin/run-zk conf & + for service in coordinator-overlord broker router historical middleManager; do + bin/run-druid "$service" "$0" & + done + wait -n' "$profile" >/dev/null +url=http://$LISTEN_HOST:$port +ready() { + curl -sf -o /dev/null --max-time 5 -H 'Content-Type: application/json' "$url/druid/v2/sql/" \ + -d '{"query": "SELECT 1"}' && + workers=$(curl -sf --max-time 5 "$url/druid/indexer/v1/workers") && [ "$workers" != "[]" ] +} +for _ in $(seq 1 300); do + ready && break + [ "$(docker inspect -f '{{.State.Running}}' "$name")" = true ] || break + sleep 1 +done +ready || { echo "Druid 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 "$url/status" | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')" + echo "profile $profile" + echo "task_heap $task_heap" + echo "url $url" + echo "cpuset $cores mems $numa" + echo "thread_siblings $(siblings)" + echo "cpu_model $(lscpu | sed -n 's/^Model name: *//p')" + echo "cgroup $group" + echo "kernel $(uname -r)"; } > "$data_dir/versions.txt" +cat "$data_dir/versions.txt" From 2193e8a804a62ff628d77a128473a717c2a05cc0 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:00:02 +0000 Subject: [PATCH 08/51] scripts: one-shot-workload.sh runs the configurations a comparison file lists What to compare was written into the script: five engines, their configurations, duckdb/exact as the truth and each engine's exact run as a baseline. A new engine meant editing the script. When /comparison.json exists, the script runs the configurations it lists, in order, through one-shot-queries, then one-shot-report with the file's truth and baselines. Each configuration names the system (any --engine approxbench knows), the configuration, the arguments passed after --engine and --configuration ({run_directory} and {workload} are replaced), optionally a query variant and runs (RUNS, else 3). The arguments are passed as given, so an engine's options, or any flag one-shot-queries accepts, need no change to the script. The file is JSON, read with the python3 the script already needs; it is checked before any engine starts: known fields, result-file names, no configuration twice, variants of the workload, and a truth and baselines among the listed configurations. ENGINE_CPUS, COLD_FIRST_RUN, CPU_FREQUENCY_GOVERNOR and APPROXBENCH still apply; the engine options in the environment do not. DuckDB is then needed only to read the group columns of a query that does not declare them. Without the file nothing changes: on a 2000-row table with DuckDB the results, the report and the printed output equal those of the script before this change, and a file listing only duckdb/exact and duckdb/approximate with the same options gives the same answers and report values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/one-shot-workload.sh | 144 +++++++++++++++++++++++++++++++++-- 1 file changed, 136 insertions(+), 8 deletions(-) diff --git a/scripts/one-shot-workload.sh b/scripts/one-shot-workload.sh index ce1384dc..a300f328 100755 --- a/scripts/one-shot-workload.sh +++ b/scripts/one-shot-workload.sh @@ -46,6 +46,32 @@ and defaults. Needs python3 and a DuckDB command line of the version PilotDB's duckdb package reads. +A comparison file, /comparison.json, replaces the configurations above: when it +exists, the script runs the configurations it lists, in order, then reports with its truth and +baselines. DuckDB is then needed only to read the group columns of a query that does not declare +them, and the engine options in the environment do not apply; APPROXBENCH, DUCKDB, RUNS, +ENGINE_CPUS, COLD_FIRST_RUN and CPU_FREQUENCY_GOVERNOR still do. + {"configurations": [ + {"system": "duckdb", "configuration": "exact", + "arguments": ["--duckdb-program", "/opt/duckdb/duckdb", + "--duckdb-database", "{run_directory}/{workload}.duckdb"]}, + {"system": "druid", "configuration": "exact", "runs": 5, + "arguments": ["--druid-url", "http://127.0.0.1:8888", + "--druid-context", "useApproximateCountDistinct=false"]}, + {"system": "duckdb", "configuration": "approximate", "query_variant": "approximate", + "arguments": ["--duckdb-program", "/opt/duckdb/duckdb", + "--duckdb-database", "{run_directory}/{workload}.duckdb"]}], + "truth": "duckdb/exact", "baselines": ["duckdb/exact", "druid/exact"]} + system an engine of approxbench benchmark-external one-shot-queries --engine + configuration the name its result is written under: letters, digits, '.', '-' and '_' + arguments passed to one-shot-queries after --engine and --configuration, such as the + engine's options; {run_directory} and {workload} are replaced [none] + query_variant only the queries with a text in this variant of the workload [every query] + runs runs per query [RUNS, else 3] + truth the configuration, as /, answers are compared with + [none] + baselines the configurations speedups are computed over [none] + Environment (defaults in brackets): APPROXBENCH the approxbench binary [approxbench] DUCKDB the duckdb command line [duckdb] @@ -102,7 +128,10 @@ command -v python3 >/dev/null || { echo "needs python3" >&2; exit 1; } approxbench=${APPROXBENCH:-approxbench} command -v "$approxbench" >/dev/null || { echo "no $approxbench on PATH; set APPROXBENCH" >&2; exit 1; } duckdb=${DUCKDB:-duckdb} -command -v "$duckdb" >/dev/null || { echo "no $duckdb on PATH; set DUCKDB" >&2; exit 1; } +comparison=$run/comparison.json +if [ ! -f "$comparison" ]; then + command -v "$duckdb" >/dev/null || { echo "no $duckdb on PATH; set DUCKDB" >&2; exit 1; } +fi clickhouse_url=${CLICKHOUSE_URL-http://127.0.0.1:8123} postgresql_connection=${POSTGRESQL_CONNECTION:-} druid_url=${DRUID_URL:-} @@ -197,6 +226,9 @@ def parsed(sql): def group_by_column_positions(query_id, sql): + if not duckdb: + sys.exit(f"query {query_id}: declare group_by_column_positions, or set DUCKDB to a DuckDB " + "command line that reads them from its SQL") tree = parsed(sql) if tree.get("error"): sys.exit(f"query {query_id}: DuckDB cannot parse it: {tree.get('error_message')}") @@ -284,13 +316,6 @@ fi if [ -n "${CPU_FREQUENCY_GOVERNOR:-}" ]; then common+=(--cpu-frequency-governor "$CPU_FREQUENCY_GOVERNOR") fi -duckdb_options=(--duckdb-program "$(command -v "$duckdb")" --duckdb-database "$database") -if [ -n "${DUCKDB_STORAGE_VERSION-latest}" ]; then - duckdb_options+=(--duckdb-storage-version "${DUCKDB_STORAGE_VERSION-latest}") -fi -if [ -n "${THREADS:-}" ]; then - duckdb_options+=(--duckdb-threads "$THREADS") -fi one_shot() { local result=$run/results/$1/${name}__$2.one-shot.json @@ -302,6 +327,109 @@ one_shot() { "${common[@]}" --engine "$1" --configuration "$2" "${@:3}" } +if [ -f "$comparison" ]; then + configurations=$(python3 - "$comparison" "$run" "$name" "${RUNS:-3}" <<'PY' +import json, re, shlex, sys + +source, run, name, default_runs = sys.argv[1:] +with open(source) as file: + comparison = json.load(file) +with open(f"{run}/workloads/{name}.json") as file: + workload = json.load(file) +variants = {variant for query in workload["one_shot_queries"] for variant in query.get("variants", {})} + + +def check(what, value, required, optional): + if not isinstance(value, dict): + sys.exit(f"{source}: {what} must be a JSON object") + missing = required - value.keys() + unknown = value.keys() - required - optional + if missing or unknown: + sys.exit(f"{source}: {what} missing {sorted(missing)}, unknown {sorted(unknown)}") + + +def result_name(value): + return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_][A-Za-z0-9_.-]*", value) and "__" not in value + + +check("the comparison", comparison, {"configurations"}, {"truth", "baselines"}) +if not isinstance(comparison["configurations"], list) or not comparison["configurations"]: + sys.exit(f"{source}: configurations must be a non-empty list") +lines = [] +listed = [] +for configuration in comparison["configurations"]: + check("a configuration", configuration, {"system", "configuration"}, {"arguments", "query_variant", "runs"}) + system, label = configuration["system"], configuration["configuration"] + if not result_name(system) or not result_name(label): + sys.exit(f"{source}: system and configuration are letters, digits, '.', '-' and '_', not starting " + f"with '.' and without '__': {system!r}/{label!r}") + if f"{system}/{label}" in listed: + sys.exit(f"{source}: {system}/{label} is listed twice") + listed.append(f"{system}/{label}") + variant = configuration.get("query_variant", "") + if variant and variant not in variants: + sys.exit(f"{source}: {system}/{label}: workload {name} has no variant {variant!r}; it has {sorted(variants)}") + runs = configuration.get("runs", int(default_runs)) + if not isinstance(runs, int) or isinstance(runs, bool) or runs < 1: + sys.exit(f"{source}: {system}/{label}: runs must be a positive integer") + arguments = configuration.get("arguments", []) + if not isinstance(arguments, list) or not all(isinstance(a, str) and "\n" not in a for a in arguments): + sys.exit(f"{source}: {system}/{label}: arguments must be a list of strings, each on one line") + arguments = [a.replace("{run_directory}", run).replace("{workload}", name) for a in arguments] + lines.append(shlex.join([system, label, str(runs), variant] + arguments)) +report = [] +truth = comparison.get("truth") +if truth is not None: + if truth not in listed: + sys.exit(f"{source}: the truth {truth!r} is not one of the configurations {listed}") + report += ["--truth", truth] +baselines = comparison.get("baselines", []) +if not isinstance(baselines, list): + sys.exit(f"{source}: baselines must be a list") +for baseline in baselines: + if baseline not in listed: + sys.exit(f"{source}: the baseline {baseline!r} is not one of the configurations {listed}") + report += ["--baseline", baseline] +print(shlex.join(report)) +print("\n".join(lines)) +PY +) + lines=() + { + read -r report_line + while IFS= read -r line; do + lines+=("$line") + done + } <<<"$configurations" + eval "report=($report_line)" + status=0 + for line in "${lines[@]}"; do + eval "words=($line)" + variant=() + if [ -n "${words[3]}" ]; then + variant=(--query-variant "${words[3]}") + fi + if [ "$status" -eq 0 ]; then + one_shot "${words[0]}" "${words[1]}" ${variant[@]+"${variant[@]}"} --runs "${words[2]}" \ + "${words[@]:4}" || status=$? + fi + done + if [ ${#prefix[@]} -gt 0 ] && [ "${prefix[0]}" = sudo ]; then + sudo chown -R "$(id -u):$(id -g)" "$run" + fi + [ "$status" -eq 0 ] || exit "$status" + "$approxbench" benchmark-external one-shot-report --run-directory "$run" ${report[@]+"${report[@]}"} + exit 0 +fi + +duckdb_options=(--duckdb-program "$(command -v "$duckdb")" --duckdb-database "$database") +if [ -n "${DUCKDB_STORAGE_VERSION-latest}" ]; then + duckdb_options+=(--duckdb-storage-version "${DUCKDB_STORAGE_VERSION-latest}") +fi +if [ -n "${THREADS:-}" ]; then + duckdb_options+=(--duckdb-threads "$THREADS") +fi + variant_runs() { local engine=$1 dialect=$2 line variant dialects shift 2 From 19ebd7b43ab8be85562b3bac1af2669075828834 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:24 +0000 Subject: [PATCH 09/51] harness, system-bench: one-shot queries read CPU and peak memory the way periodic queries do A one-shot adapter now tells the harness where its work runs, and the harness reads CPU and peak memory around every run with the same code as for periodic queries: - ClickHouse, PostgreSQL and Druid: the server's cgroup, given with the periodic flags --server-cgroup-directory, --server-ssh-host and --ssh-program; CPU from cpu.stat around the run, peak memory from memory.peak. Without the flags nothing is measured and the results are as before. - DuckDB and PilotDB, which start a process for every run: that process's user and system CPU and largest resident set size, from wait4. Each run records harness_cpu_seconds and peak_memory_bytes, each result cpu_and_memory_source. one-shot-report appends the source and the first run, hot minimum, median and maximum of both to one-shot-summary.csv, and the hot medians to one-shot-summary.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- .../tests/benchmark_external_one_shot_cli.rs | 10 + aqpbm-core/src/harness/one_shot.rs | 121 +++++++++ aqpbm-core/src/harness/one_shot_report.rs | 84 +++++- aqpbm-core/src/harness/protocol.rs | 94 ++++++- aqpbm-core/tests/harness_one_shot.rs | 248 +++++++++++++++++- aqpbm-core/tests/harness_one_shot_report.rs | 96 +++++++ .../engines_external/clickhouse_query_text.rs | 28 +- .../src/engines_external/druid_sql.rs | 48 +++- .../engines_external/duckdb_command_line.rs | 13 +- system-bench/src/engines_external/pilotdb.rs | 29 +- .../postgresql_command_line.rs | 36 ++- 11 files changed, 758 insertions(+), 49 deletions(-) diff --git a/aqpbm-cli/tests/benchmark_external_one_shot_cli.rs b/aqpbm-cli/tests/benchmark_external_one_shot_cli.rs index 71bbbba5..7b227c42 100644 --- a/aqpbm-cli/tests/benchmark_external_one_shot_cli.rs +++ b/aqpbm-cli/tests/benchmark_external_one_shot_cli.rs @@ -271,6 +271,16 @@ fn duckdb_loads_runs_and_reports_against_itself() { assert_eq!(row["max_relative_error"], "0", "{row:?}"); assert!(row["engine_time_covers"].contains(".timer"), "{row:?}"); assert!(!row["hot_median_wall_seconds"].is_empty(), "{row:?}"); + assert!(row["cpu_and_memory_source"].contains("wait4"), "{row:?}"); + for column in [ + "hot_median_harness_cpu_seconds", + "hot_median_peak_memory_bytes", + ] { + assert!( + row[column].parse::().is_ok_and(|value| value > 0.0), + "{column}: {row:?}" + ); + } } assert!(run.join("one-shot-summary.md").is_file()); assert!(std::fs::read_to_string(run.join("one-shot-tables.csv")) diff --git a/aqpbm-core/src/harness/one_shot.rs b/aqpbm-core/src/harness/one_shot.rs index 5c5760ab..e4620903 100644 --- a/aqpbm-core/src/harness/one_shot.rs +++ b/aqpbm-core/src/harness/one_shot.rs @@ -4,7 +4,9 @@ use std::time::Instant; use serde::{Deserialize, Serialize}; +use crate::harness::cgroup::CgroupSource; use crate::harness::engine::{EngineDescription, EngineError, SqlDialect, WorkloadSpec}; +use crate::harness::protocol::{CgroupCpuClock, ChildProcesses, CpuClock, ProtocolError}; pub const LINUX_DROP_CACHES: &str = "/proc/sys/vm/drop_caches"; @@ -150,6 +152,12 @@ pub struct QueryRun { pub details: BTreeMap, } +#[derive(Debug, Clone)] +pub enum OneShotCpuAccounting { + Cgroup(CgroupSource), + ChildProcesses(ChildProcesses), +} + pub trait OneShotQueryEngine { fn description(&self) -> EngineDescription; fn dialect(&self) -> SqlDialect; @@ -180,6 +188,9 @@ pub trait OneShotQueryEngine { fn wait_until_idle(&mut self) -> Result<(), EngineError> { Ok(()) } + fn cpu_accounting(&self) -> Option { + None + } } #[derive(Debug, Clone, PartialEq)] @@ -204,6 +215,8 @@ pub struct OneShotResult { pub cold_first_run: bool, #[serde(default, skip_serializing_if = "Option::is_none")] pub engine_time_covers: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub cpu_and_memory_source: Option, pub tables: Vec, pub queries: Vec, #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] @@ -244,6 +257,10 @@ pub struct RunRecord { pub engine_reported_seconds: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub engine_reported_cpu_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub harness_cpu_seconds: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub peak_memory_bytes: Option, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub details: BTreeMap, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -281,6 +298,8 @@ pub enum OneShotError { path: PathBuf, source: std::io::Error, }, + #[error("reading the engine's CPU and memory: {0}")] + Measurement(#[from] ProtocolError), } fn root_hint(source: &std::io::Error) -> &'static str { @@ -302,6 +321,95 @@ pub fn drop_page_cache(drop_caches: &Path) -> Result<(), OneShotError> { }) } +enum CpuAndMemory { + Cgroup { + source: CgroupSource, + clock: Box, + }, + ChildProcesses(ChildProcesses), +} + +struct RunUsage { + cpu_seconds: Option, + peak_memory_bytes: Option, +} + +const NOT_MEASURED: RunUsage = RunUsage { + cpu_seconds: None, + peak_memory_bytes: None, +}; + +impl CpuAndMemory { + fn new(accounting: OneShotCpuAccounting) -> Result { + Ok(match accounting { + OneShotCpuAccounting::Cgroup(source) => CpuAndMemory::Cgroup { + clock: Box::new(CgroupCpuClock::new(source.clone())?), + source, + }, + OneShotCpuAccounting::ChildProcesses(children) => { + CpuAndMemory::ChildProcesses(children) + } + }) + } + + fn source(&self) -> String { + let group = match self { + CpuAndMemory::Cgroup { + source: CgroupSource::Local(directory), + .. + } => directory.display().to_string(), + CpuAndMemory::Cgroup { + source: + CgroupSource::Remote { + host, + cgroup_directory, + .. + }, + .. + } => format!("{host}:{} over SSH", cgroup_directory.display()), + CpuAndMemory::ChildProcesses(_) => { + return "the processes the adapter started for each run: their user and system CPU and largest resident set size, from wait4".into(); + } + }; + format!("cgroup {group}: cpu.stat around each run, memory.peak since the group started") + } + + fn before_run(&self) -> u64 { + match self { + CpuAndMemory::Cgroup { clock, .. } => clock.process_cpu_ns(), + CpuAndMemory::ChildProcesses(children) => { + children.take(); + 0 + } + } + } + + fn after_run(&self, cpu_ns_before: u64) -> Result { + match self { + CpuAndMemory::Cgroup { source, clock } => { + let cpu_ns = clock.process_cpu_ns().saturating_sub(cpu_ns_before); + if let Some(error) = clock.take_read_error() { + return Err(error); + } + Ok(RunUsage { + cpu_seconds: Some(cpu_ns as f64 / 1e9), + peak_memory_bytes: source.memory()?.lifetime_peak_bytes, + }) + } + CpuAndMemory::ChildProcesses(children) => { + let usage = children.take(); + Ok(match usage.processes { + 0 => NOT_MEASURED, + _ => RunUsage { + cpu_seconds: Some(usage.cpu_ns as f64 / 1e9), + peak_memory_bytes: Some(usage.peak_resident_set_size_bytes), + }, + }) + } + } + } +} + pub struct OneShotSetup<'a> { pub configuration: &'a str, pub schedule: &'a OneShotSchedule, @@ -347,6 +455,7 @@ pub fn run_one_shot_queries( }); } } + let cpu_and_memory = engine.cpu_accounting().map(CpuAndMemory::new).transpose()?; let dialect = engine.dialect(); let mut tables = Vec::with_capacity(workload.tables.len()); for table in &workload.tables { @@ -445,15 +554,22 @@ pub fn run_one_shot_queries( wall_seconds: 0.0, engine_reported_seconds: None, engine_reported_cpu_seconds: None, + harness_cpu_seconds: None, + peak_memory_bytes: None, details: BTreeMap::new(), result: None, error: Some(error), }); break; } + let cpu_ns_before = cpu_and_memory.as_ref().map(CpuAndMemory::before_run); let start = Instant::now(); let outcome = engine.run_query(sql); let wall_seconds = start.elapsed().as_secs_f64(); + let usage = match (&cpu_and_memory, cpu_ns_before) { + (Some(cpu_and_memory), Some(before)) => cpu_and_memory.after_run(before)?, + _ => NOT_MEASURED, + }; match outcome { Ok(answer) => runs.push(RunRecord { cold, @@ -462,6 +578,8 @@ pub fn run_one_shot_queries( engine_reported_cpu_seconds: answer .engine_reported_cpu_seconds .or_else(|| engine.last_query_cpu_seconds()), + harness_cpu_seconds: usage.cpu_seconds, + peak_memory_bytes: usage.peak_memory_bytes, details: answer.details, result: Some(answer.table), error: None, @@ -472,6 +590,8 @@ pub fn run_one_shot_queries( wall_seconds, engine_reported_seconds: None, engine_reported_cpu_seconds: None, + harness_cpu_seconds: usage.cpu_seconds, + peak_memory_bytes: usage.peak_memory_bytes, details: BTreeMap::new(), result: None, error: Some(error.0), @@ -510,6 +630,7 @@ pub fn run_one_shot_queries( query_variant: schedule.query_variant.clone(), cold_first_run: schedule.cold_first_run, engine_time_covers: engine.engine_time_covers().map(str::to_string), + cpu_and_memory_source: cpu_and_memory.as_ref().map(CpuAndMemory::source), tables, queries, cpu_frequency_governors: BTreeSet::new(), diff --git a/aqpbm-core/src/harness/one_shot_report.rs b/aqpbm-core/src/harness/one_shot_report.rs index 833edd05..96fae60f 100644 --- a/aqpbm-core/src/harness/one_shot_report.rs +++ b/aqpbm-core/src/harness/one_shot_report.rs @@ -148,6 +148,15 @@ pub struct OneShotReportRow { pub hot_min_engine_seconds: Option, pub hot_median_engine_seconds: Option, pub hot_median_engine_cpu_seconds: Option, + pub cpu_and_memory_source: Option, + pub first_run_harness_cpu_seconds: Option, + pub hot_min_harness_cpu_seconds: Option, + pub hot_median_harness_cpu_seconds: Option, + pub hot_max_harness_cpu_seconds: Option, + pub first_run_peak_memory_bytes: Option, + pub hot_min_peak_memory_bytes: Option, + pub hot_median_peak_memory_bytes: Option, + pub hot_max_peak_memory_bytes: Option, pub speedups: Vec<(ConfigurationName, Option)>, pub target_relative_error: Option, pub max_relative_error: Option, @@ -177,16 +186,19 @@ pub struct TableRow { pub data_size_bytes: Option, } -struct Seconds { +struct FirstAndHot { first: Option, hot_min: Option, hot_median: Option, + hot_max: Option, } struct Timing { - wall: Seconds, - engine: Seconds, + wall: FirstAndHot, + engine: FirstAndHot, hot_cpu_median: Option, + harness_cpu: FirstAndHot, + peak_memory: FirstAndHot, } fn every<'a>( @@ -200,26 +212,29 @@ fn hot_runs(query: &QueryRecord) -> impl Iterator { query.runs.iter().skip(1).filter(|run| run.error.is_none()) } -fn seconds_of(query: &QueryRecord, seconds: impl Fn(&RunRecord) -> Option) -> Seconds { +fn first_and_hot(query: &QueryRecord, value: impl Fn(&RunRecord) -> Option) -> FirstAndHot { let first = query .runs .first() .filter(|run| run.error.is_none()) - .and_then(&seconds); - let hot = every(hot_runs(query), &seconds).unwrap_or_default(); - Seconds { + .and_then(&value); + let hot = every(hot_runs(query), &value).unwrap_or_default(); + FirstAndHot { first, hot_min: hot.iter().copied().min_by(f64::total_cmp), hot_median: median_of(&hot), + hot_max: hot.iter().copied().max_by(f64::total_cmp), } } fn timing_of(query: &QueryRecord) -> Timing { Timing { - wall: seconds_of(query, |run| Some(run.wall_seconds)), - engine: seconds_of(query, |run| run.engine_reported_seconds), + wall: first_and_hot(query, |run| Some(run.wall_seconds)), + engine: first_and_hot(query, |run| run.engine_reported_seconds), hot_cpu_median: every(hot_runs(query), |run| run.engine_reported_cpu_seconds) .and_then(|hot_cpu| median_of(&hot_cpu)), + harness_cpu: first_and_hot(query, |run| run.harness_cpu_seconds), + peak_memory: first_and_hot(query, |run| run.peak_memory_bytes.map(|bytes| bytes as f64)), } } @@ -288,6 +303,15 @@ pub fn one_shot_report( hot_min_engine_seconds: timing.engine.hot_min, hot_median_engine_seconds: timing.engine.hot_median, hot_median_engine_cpu_seconds: timing.hot_cpu_median, + cpu_and_memory_source: result.cpu_and_memory_source.clone(), + first_run_harness_cpu_seconds: timing.harness_cpu.first, + hot_min_harness_cpu_seconds: timing.harness_cpu.hot_min, + hot_median_harness_cpu_seconds: timing.harness_cpu.hot_median, + hot_max_harness_cpu_seconds: timing.harness_cpu.hot_max, + first_run_peak_memory_bytes: timing.peak_memory.first, + hot_min_peak_memory_bytes: timing.peak_memory.hot_min, + hot_median_peak_memory_bytes: timing.peak_memory.hot_median, + hot_max_peak_memory_bytes: timing.peak_memory.hot_max, speedups, target_relative_error: result.error_target.map(|target| target.relative_error), max_relative_error: None, @@ -457,6 +481,15 @@ impl OneShotReport { "differing_text_cells", "truth_runs_agree", "runs_answered_exactly", + "cpu_and_memory_source", + "first_run_harness_cpu_seconds", + "hot_min_harness_cpu_seconds", + "hot_median_harness_cpu_seconds", + "hot_max_harness_cpu_seconds", + "first_run_peak_memory_bytes", + "hot_min_peak_memory_bytes", + "hot_median_peak_memory_bytes", + "hot_max_peak_memory_bytes", ] .map(str::to_string), ); @@ -496,6 +529,15 @@ impl OneShotReport { format_count(row.differing_text_cells), format_flag(row.truth_runs_agree), format_count(row.runs_answered_exactly), + row.cpu_and_memory_source.clone().unwrap_or_default(), + format_number(row.first_run_harness_cpu_seconds), + format_number(row.hot_min_harness_cpu_seconds), + format_number(row.hot_median_harness_cpu_seconds), + format_number(row.hot_max_harness_cpu_seconds), + format_number(row.first_run_peak_memory_bytes), + format_number(row.hot_min_peak_memory_bytes), + format_number(row.hot_median_peak_memory_bytes), + format_number(row.hot_max_peak_memory_bytes), ]); fields }) @@ -557,6 +599,23 @@ impl OneShotReport { } text.push('\n'); } + let sources: BTreeMap = self + .rows + .iter() + .filter_map(|row| { + Some(( + row.configuration.to_string(), + row.cpu_and_memory_source.as_deref()?, + )) + }) + .collect(); + if !sources.is_empty() { + text.push_str("Harness CPU and peak memory:\n\n"); + for (configuration, source) in sources { + text.push_str(&format!("- {configuration}: {source}\n")); + } + text.push('\n'); + } let mut header = vec![ "workload".to_string(), "engine/configuration".into(), @@ -565,6 +624,8 @@ impl OneShotReport { "first run wall s".into(), "hot median wall s".into(), "hot median engine s".into(), + "hot median harness CPU s".into(), + "hot median peak memory MiB".into(), ]; header.extend( self.baselines @@ -588,6 +649,11 @@ impl OneShotReport { format_for_reading(row.first_run_wall_seconds), format_for_reading(row.hot_median_wall_seconds), format_for_reading(row.hot_median_engine_seconds), + format_for_reading(row.hot_median_harness_cpu_seconds), + format_for_reading( + row.hot_median_peak_memory_bytes + .map(|bytes| bytes / (1024.0 * 1024.0)), + ), ]; cells.extend( row.speedups diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index 894527f2..07dcd2d3 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -7,7 +7,8 @@ use std::cell::{Cell, RefCell}; use std::path::{Path, PathBuf}; -use std::sync::OnceLock; +use std::process::{Command, Output, Stdio}; +use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use std::time::Instant; use crate::metrics::{CpuTimeSampler, ThreadCpuTime}; @@ -401,6 +402,97 @@ pub fn processes_memory(proc_root: &Path, pids: &[u32]) -> Result>); + +impl ChildProcesses { + pub fn output(&self, command: &mut Command) -> std::io::Result { + let (output, usage) = output_with_usage(command)?; + let mut total = self.0.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(usage) = usage { + total.processes += 1; + total.cpu_ns += usage.cpu_ns; + total.peak_resident_set_size_bytes = total + .peak_resident_set_size_bytes + .max(usage.peak_resident_set_size_bytes); + } + Ok(output) + } + + pub fn take(&self) -> ChildUsage { + std::mem::take(&mut *self.0.lock().unwrap_or_else(PoisonError::into_inner)) + } +} + +#[cfg(unix)] +fn output_with_usage(command: &mut Command) -> std::io::Result<(Output, Option)> { + use std::io::Read; + use std::os::unix::process::ExitStatusExt; + let mut child = command + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + let mut stdout_pipe = child.stdout.take().expect("stdout is piped"); + let mut stderr_pipe = child.stderr.take().expect("stderr is piped"); + let stderr_reader = std::thread::spawn(move || { + let mut bytes = Vec::new(); + stderr_pipe.read_to_end(&mut bytes).map(|_| bytes) + }); + let mut stdout = Vec::new(); + let stdout_read = stdout_pipe.read_to_end(&mut stdout); + drop(stdout_pipe); + let stderr = stderr_reader + .join() + .unwrap_or_else(|_| Err(std::io::Error::other("reading stderr panicked"))); + let pid = child.id() as libc::pid_t; + let mut status = 0; + let mut usage = std::mem::MaybeUninit::::zeroed(); + loop { + let reaped = unsafe { libc::wait4(pid, &mut status, 0, usage.as_mut_ptr()) }; + if reaped == pid { + break; + } + let error = std::io::Error::last_os_error(); + if error.kind() != std::io::ErrorKind::Interrupted { + return Err(error); + } + } + let usage = unsafe { usage.assume_init() }; + stdout_read?; + let stderr = stderr?; + let microseconds = |time: libc::timeval| time.tv_sec as u64 * 1_000_000 + time.tv_usec as u64; + let resident_set_size_unit: u64 = if cfg!(target_vendor = "apple") { + 1 + } else { + 1024 + }; + Ok(( + Output { + status: std::process::ExitStatus::from_raw(status), + stdout, + stderr, + }, + Some(ChildUsage { + processes: 1, + cpu_ns: (microseconds(usage.ru_utime) + microseconds(usage.ru_stime)) * 1_000, + peak_resident_set_size_bytes: usage.ru_maxrss.max(0) as u64 * resident_set_size_unit, + }), + )) +} + +#[cfg(not(unix))] +fn output_with_usage(command: &mut Command) -> std::io::Result<(Output, Option)> { + Ok((command.output()?, None)) +} + fn proc_file_bytes(pid: u32, path: &Path, field: &str) -> Result { let text = std::fs::read_to_string(path).map_err(|_| ProtocolError::MissingProcess { pid, diff --git a/aqpbm-core/tests/harness_one_shot.rs b/aqpbm-core/tests/harness_one_shot.rs index c556268b..0578e38b 100644 --- a/aqpbm-core/tests/harness_one_shot.rs +++ b/aqpbm-core/tests/harness_one_shot.rs @@ -1,14 +1,17 @@ use std::collections::BTreeMap; use std::path::{Path, PathBuf}; +use std::process::Command; +use aqpbm_core::harness::cgroup::CgroupSource; use aqpbm_core::harness::engine::{ EngineDescription, EngineError, LoadStatements, OneShotQuery, QueryLanguage, QueryText, SqlDialect, TableSource, WorkloadSpec, }; use aqpbm_core::harness::one_shot::{ - run_one_shot_queries, OneShotError, OneShotQueryEngine, OneShotSchedule, OneShotSetup, - QueryRun, ResultTable, ResultValue, + run_one_shot_queries, OneShotCpuAccounting, OneShotError, OneShotQueryEngine, OneShotSchedule, + OneShotSetup, QueryRun, ResultTable, ResultValue, }; +use aqpbm_core::harness::protocol::ChildProcesses; use aqpbm_core::harness::run_directory::RunDirectory; struct TempDirectory(PathBuf); @@ -526,3 +529,244 @@ fn a_result_is_written_once_and_read_back() { assert!(run_directory.write_one_shot(&result).is_err()); assert_eq!(run_directory.read_one_shot_results().unwrap(), vec![result]); } + +struct ChildProcessEngine { + children: ChildProcesses, +} + +impl OneShotQueryEngine for ChildProcessEngine { + fn description(&self) -> EngineDescription { + EngineDescription { + id: "children".into(), + version: "1".into(), + version_dirty: false, + build_profile: "test".into(), + } + } + fn dialect(&self) -> SqlDialect { + SqlDialect::new("DuckDb") + } + fn engine_time_covers(&self) -> Option<&'static str> { + None + } + fn table_rows(&mut self, _table: &str) -> Result, EngineError> { + self.children + .output(Command::new("sh").args(["-c", "exit 0"])) + .map_err(|error| EngineError(error.to_string()))?; + Ok(Some(10)) + } + fn restart(&mut self) -> Result<(), EngineError> { + Ok(()) + } + fn run_query(&mut self, _sql: &str) -> Result { + let output = self + .children + .output(Command::new("sh").args([ + "-c", + "i=0; while [ $i -lt 20000 ]; do i=$((i+1)); done; echo n; echo $i; echo done >&2", + ])) + .map_err(|error| EngineError(error.to_string()))?; + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stderr), "done\n"); + Ok(QueryRun { + table: ResultTable::from_csv_with_header(&String::from_utf8_lossy(&output.stdout))?, + engine_reported_seconds: None, + engine_reported_cpu_seconds: None, + details: BTreeMap::new(), + }) + } + fn cpu_accounting(&self) -> Option { + Some(OneShotCpuAccounting::ChildProcesses(self.children.clone())) + } +} + +#[test] +fn the_harness_reads_the_cpu_and_peak_memory_of_each_runs_child_processes() { + let directory = TempDirectory::new("children"); + let drop_caches = directory.0.join("drop_caches"); + let schedule = schedule(2, false); + let mut engine = ChildProcessEngine { + children: ChildProcesses::default(), + }; + let result = run_one_shot_queries( + &mut engine, + &workload(), + &setup(&schedule, None, &drop_caches), + &mut |_| {}, + ) + .unwrap(); + assert!(result + .cpu_and_memory_source + .as_deref() + .unwrap() + .contains("wait4")); + let runs: Vec<_> = result + .queries + .iter() + .flat_map(|query| &query.runs) + .collect(); + assert_eq!(runs.len(), 4); + for run in runs { + assert_eq!( + run.result.as_ref().unwrap().rows, + vec![vec![ResultValue::Integer(20000)]] + ); + assert!(run.harness_cpu_seconds.unwrap() > 0.0, "{run:?}"); + assert!(run.peak_memory_bytes.unwrap() > 0, "{run:?}"); + } + + let mut unmeasured = ScriptedEngine { + rows: Some(10), + ..ScriptedEngine::default() + }; + let result = run_one_shot_queries( + &mut unmeasured, + &workload(), + &setup(&schedule, None, &drop_caches), + &mut |_| {}, + ) + .unwrap(); + assert_eq!(result.cpu_and_memory_source, None); + assert!(result + .queries + .iter() + .flat_map(|query| &query.runs) + .all(|run| run.harness_cpu_seconds.is_none() && run.peak_memory_bytes.is_none())); +} + +struct CgroupServerEngine { + group: PathBuf, + usage_usec: u64, + throttle_on_call: Option, + calls: u32, +} + +fn write_group(group: &Path, usage_usec: u64, nr_throttled: u64, peak_bytes: u64) { + std::fs::write( + group.join("cpu.stat"), + format!("usage_usec {usage_usec}\nnr_throttled {nr_throttled}\n"), + ) + .unwrap(); + std::fs::write(group.join("memory.current"), "1048576\n").unwrap(); + std::fs::write(group.join("memory.peak"), format!("{peak_bytes}\n")).unwrap(); + std::fs::write(group.join("memory.stat"), "anon 524288\nfile 262144\n").unwrap(); +} + +impl OneShotQueryEngine for CgroupServerEngine { + fn description(&self) -> EngineDescription { + EngineDescription { + id: "server".into(), + version: "1".into(), + version_dirty: false, + build_profile: "test".into(), + } + } + fn dialect(&self) -> SqlDialect { + SqlDialect::new("DuckDb") + } + fn engine_time_covers(&self) -> Option<&'static str> { + None + } + fn table_rows(&mut self, _table: &str) -> Result, EngineError> { + Ok(Some(10)) + } + fn restart(&mut self) -> Result<(), EngineError> { + Ok(()) + } + fn run_query(&mut self, _sql: &str) -> Result { + self.calls += 1; + self.usage_usec += 1_500; + let throttled = u64::from(self.throttle_on_call == Some(self.calls)); + write_group( + &self.group, + self.usage_usec, + throttled, + 4_000_000 + u64::from(self.calls), + ); + Ok(QueryRun { + table: ResultTable { + columns: vec!["n".into()], + rows: vec![vec![ResultValue::Integer(1)]], + }, + engine_reported_seconds: None, + engine_reported_cpu_seconds: None, + details: BTreeMap::new(), + }) + } + fn cpu_accounting(&self) -> Option { + Some(OneShotCpuAccounting::Cgroup(CgroupSource::Local( + self.group.clone(), + ))) + } +} + +#[test] +fn the_harness_reads_a_servers_cgroup_around_each_run_and_refuses_a_throttled_one() { + let directory = TempDirectory::new("cgroup"); + let drop_caches = directory.0.join("drop_caches"); + let group = directory.0.join("group"); + std::fs::create_dir_all(&group).unwrap(); + write_group(&group, 10_000, 0, 4_000_000); + let mut chosen = schedule(2, false); + chosen.queries = vec!["1".into()]; + let mut engine = CgroupServerEngine { + group: group.clone(), + usage_usec: 10_000, + throttle_on_call: None, + calls: 0, + }; + let result = run_one_shot_queries( + &mut engine, + &workload(), + &setup(&chosen, None, &drop_caches), + &mut |_| {}, + ) + .unwrap(); + let source = result.cpu_and_memory_source.unwrap(); + assert!( + source.starts_with(&format!("cgroup {}", group.display())), + "{source}" + ); + let runs = &result.queries[0].runs; + assert_eq!( + runs.iter() + .map(|run| (run.harness_cpu_seconds, run.peak_memory_bytes)) + .collect::>(), + vec![ + (Some(0.0015), Some(4_000_001)), + (Some(0.0015), Some(4_000_002)) + ] + ); + + let mut throttled = CgroupServerEngine { + group: group.clone(), + usage_usec: 10_000, + throttle_on_call: Some(2), + calls: 0, + }; + write_group(&group, 10_000, 0, 4_000_000); + let error = run_one_shot_queries( + &mut throttled, + &workload(), + &setup(&chosen, None, &drop_caches), + &mut |_| {}, + ) + .unwrap_err(); + assert!(matches!(error, OneShotError::Measurement(_)), "{error}"); + + let mut missing = CgroupServerEngine { + group: directory.0.join("no-such-group"), + usage_usec: 0, + throttle_on_call: None, + calls: 0, + }; + let error = run_one_shot_queries( + &mut missing, + &workload(), + &setup(&chosen, None, &drop_caches), + &mut |_| {}, + ) + .unwrap_err(); + assert!(matches!(error, OneShotError::Measurement(_)), "{error}"); + assert_eq!(missing.calls, 0); +} diff --git a/aqpbm-core/tests/harness_one_shot_report.rs b/aqpbm-core/tests/harness_one_shot_report.rs index a74e6dc3..6152e779 100644 --- a/aqpbm-core/tests/harness_one_shot_report.rs +++ b/aqpbm-core/tests/harness_one_shot_report.rs @@ -57,6 +57,8 @@ fn run(seconds: f64, value: f64, exact: Option) -> RunRecord { wall_seconds: seconds + 1.0, engine_reported_seconds: Some(seconds), engine_reported_cpu_seconds: Some(seconds * 4.0), + harness_cpu_seconds: None, + peak_memory_bytes: None, details: exact .map(|exact| BTreeMap::from([("answered_exactly".to_string(), exact.into())])) .unwrap_or_default(), @@ -85,6 +87,7 @@ fn result( query_variant: None, cold_first_run: true, engine_time_covers: None, + cpu_and_memory_source: None, tables: vec![TableRecord { name: "hits".into(), rows: 10, @@ -295,3 +298,96 @@ fn speedups_divide_wall_times_whatever_each_engine_reports() { assert_eq!(druid.hot_median_wall_seconds, Some(2.0)); assert_eq!(druid.speedups[0].1, Some(3.0 / 2.0)); } + +const SUMMARY_COLUMNS_BEFORE_HARNESS_CPU: [&str; 24] = [ + "workload", + "engine", + "configuration", + "query", + "status", + "runs", + "first_run_cold", + "engine_time_covers", + "first_run_wall_seconds", + "hot_min_wall_seconds", + "hot_median_wall_seconds", + "first_run_engine_seconds", + "hot_min_engine_seconds", + "hot_median_engine_seconds", + "hot_median_engine_cpu_seconds", + "target_relative_error", + "max_relative_error", + "median_max_relative_error", + "runs_over_target", + "max_missing_groups", + "max_extra_groups", + "differing_text_cells", + "truth_runs_agree", + "runs_answered_exactly", +]; + +#[test] +fn harness_cpu_and_peak_memory_are_reported_after_the_existing_columns() { + let mut runs = vec![ + run(4.0, 100.0, None), + run(2.0, 100.0, None), + run(3.0, 100.0, None), + run(1.0, 100.0, None), + ]; + for (run, (cpu, memory)) in + runs.iter_mut() + .zip([(8.0, 400), (2.0, 100), (6.0, 300), (4.0, 200)]) + { + run.harness_cpu_seconds = Some(cpu); + run.peak_memory_bytes = Some(memory); + } + let mut measured = result("duckdb", "exact", runs, None); + measured.cpu_and_memory_source = Some("the processes of each run".into()); + let unmeasured = result("clickhouse", "exact", vec![run(1.0, 100.0, None)], None); + let report = one_shot_report(&[measured, unmeasured], None, &[]).unwrap(); + let row = &report.rows[0]; + assert_eq!(row.first_run_harness_cpu_seconds, Some(8.0)); + assert_eq!( + ( + row.hot_min_harness_cpu_seconds, + row.hot_median_harness_cpu_seconds, + row.hot_max_harness_cpu_seconds + ), + (Some(2.0), Some(4.0), Some(6.0)) + ); + assert_eq!(row.first_run_peak_memory_bytes, Some(400.0)); + assert_eq!( + ( + row.hot_min_peak_memory_bytes, + row.hot_median_peak_memory_bytes, + row.hot_max_peak_memory_bytes + ), + (Some(100.0), Some(200.0), Some(300.0)) + ); + + let csv = report.summary_csv(); + let mut reader = csv::Reader::from_reader(csv.as_bytes()); + let header: Vec = reader.headers().unwrap().iter().map(String::from).collect(); + assert_eq!( + header[..SUMMARY_COLUMNS_BEFORE_HARNESS_CPU.len()], + SUMMARY_COLUMNS_BEFORE_HARNESS_CPU + ); + let records: Vec = reader.records().map(Result::unwrap).collect(); + let field = |record: usize, name: &str| { + let column = header.iter().position(|known| known == name).unwrap(); + records[record][column].to_string() + }; + assert_eq!( + field(0, "cpu_and_memory_source"), + "the processes of each run" + ); + assert_eq!(field(0, "hot_median_harness_cpu_seconds"), "4"); + assert_eq!(field(0, "hot_max_peak_memory_bytes"), "300"); + for name in &header[SUMMARY_COLUMNS_BEFORE_HARNESS_CPU.len()..] { + assert_eq!(field(1, name), "", "{name}"); + } + + let markdown = report.summary_markdown(); + assert!(markdown.contains("- duckdb/exact: the processes of each run")); + assert!(!markdown.contains("- clickhouse/exact:")); +} diff --git a/system-bench/src/engines_external/clickhouse_query_text.rs b/system-bench/src/engines_external/clickhouse_query_text.rs index 7f5cfa78..9ad6a5fa 100644 --- a/system-bench/src/engines_external/clickhouse_query_text.rs +++ b/system-bench/src/engines_external/clickhouse_query_text.rs @@ -2,12 +2,16 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use std::time::{Duration, Instant}; +use aqpbm_core::harness::cgroup::CgroupSource; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; -use aqpbm_core::harness::one_shot::{OneShotQueryEngine, QueryRun, ResultTable}; +use aqpbm_core::harness::one_shot::{ + OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, +}; use super::clickhouse_connection::ClickHouseConnectionOptions; use super::clickhouse_connection::{ClickHouseConnection, Http}; use super::restart_command::restart_and_wait; +use super::server_cgroup::ServerCgroupOptions; pub const DIALECT: &str = "ClickHouse"; @@ -27,6 +31,7 @@ pub struct ClickHouseQueryTextEngine { http: Http, version: String, last_query_id: Option, + server_cgroup: Option, } static QUERY_COUNT: AtomicU64 = AtomicU64::new(0); @@ -45,11 +50,17 @@ impl ClickHouseQueryTextEngine { http, version: String::new(), last_query_id: None, + server_cgroup: None, }; engine.version = engine.text("SELECT version()")?.trim().to_string(); Ok(engine) } + pub fn with_server_cgroup(mut self, server_cgroup: Option) -> Self { + self.server_cgroup = server_cgroup; + self + } + fn settings(&self) -> Vec<(&'static str, String)> { let mut settings = vec![ ("database", self.server.database.clone()), @@ -236,6 +247,10 @@ impl OneShotQueryEngine for ClickHouseQueryTextEngine { let query_id = self.last_query_id.take()?; self.query_cpu_seconds(&query_id) } + + fn cpu_accounting(&self) -> Option { + self.server_cgroup.clone().map(OneShotCpuAccounting::Cgroup) + } } #[derive(clap::Args, Debug, Clone)] @@ -254,6 +269,8 @@ pub struct ClickHouseQueryTextOptions { pub clickhouse_idle_timeout_seconds: u64, #[arg(long = "clickhouse-setting", value_parser = super::parse_setting)] pub clickhouse_settings: Vec<(String, String)>, + #[command(flatten)] + pub cgroup: ServerCgroupOptions, } pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result> { @@ -261,8 +278,8 @@ pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result anyhow::Result, } pub fn context_value(text: &str) -> Value { @@ -115,6 +120,11 @@ fn quoted_name(name: &str) -> String { } impl DruidEngine { + pub fn with_server_cgroup(mut self, server_cgroup: Option) -> Self { + self.server_cgroup = server_cgroup; + self + } + pub fn new(server: DruidServer) -> Result { let agent = ureq::AgentBuilder::new() .timeout_connect(CONNECT_TIMEOUT) @@ -126,6 +136,7 @@ impl DruidEngine { agent, url, version: String::new(), + server_cgroup: None, }; let status = engine.get("/status")?; engine.version = status @@ -361,6 +372,10 @@ impl OneShotQueryEngine for DruidEngine { std::thread::sleep(Duration::from_secs(1)); } } + + fn cpu_accounting(&self) -> Option { + self.server_cgroup.clone().map(OneShotCpuAccounting::Cgroup) + } } #[derive(clap::Args, Debug, Clone)] @@ -379,6 +394,8 @@ pub struct DruidOptions { pub druid_ready_timeout_seconds: u64, #[arg(long, default_value_t = 3600)] pub druid_idle_timeout_seconds: u64, + #[command(flatten)] + pub cgroup: ServerCgroupOptions, } pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result> { @@ -386,17 +403,20 @@ pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result Option { + Some(OneShotCpuAccounting::ChildProcesses(self.children.clone())) + } } #[derive(clap::Args, Debug, Clone)] diff --git a/system-bench/src/engines_external/pilotdb.rs b/system-bench/src/engines_external/pilotdb.rs index dd598691..ffd65604 100644 --- a/system-bench/src/engines_external/pilotdb.rs +++ b/system-bench/src/engines_external/pilotdb.rs @@ -6,8 +6,9 @@ use std::sync::atomic::{AtomicU64, Ordering}; use super::duckdb_command_line::DuckDbDatabaseOptions; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; use aqpbm_core::harness::one_shot::{ - ErrorTarget, OneShotQueryEngine, QueryRun, ResultTable, ResultValue, + ErrorTarget, OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, ResultValue, }; +use aqpbm_core::harness::protocol::ChildProcesses; use serde::Deserialize; const DRIVER: &str = include_str!("pilotdb_duckdb.py"); @@ -30,6 +31,7 @@ pub struct PilotDbOnDuckDb { pub struct PilotDbEngine { setup: PilotDbOnDuckDb, version: String, + children: ChildProcesses, } #[derive(Debug, Deserialize)] @@ -106,7 +108,11 @@ impl PilotDbEngine { ))); } let version = last_line(&String::from_utf8_lossy(&output.stdout)).to_string(); - Ok(PilotDbEngine { setup, version }) + Ok(PilotDbEngine { + setup, + version, + children: ChildProcesses::default(), + }) } fn driver(&self, arguments: &[&str]) -> Result { @@ -117,12 +123,15 @@ impl PilotDbEngine { ))); std::fs::create_dir_all(&scratch.0) .map_err(|error| EngineError(format!("{}: {error}", scratch.0.display())))?; - let output = Command::new(&self.setup.python) - .arg("-c") - .arg(DRIVER) - .args(arguments) - .current_dir(&scratch.0) - .output() + let output = self + .children + .output( + Command::new(&self.setup.python) + .arg("-c") + .arg(DRIVER) + .args(arguments) + .current_dir(&scratch.0), + ) .map_err(|error| EngineError(format!("{}: {error}", self.setup.python.display())))?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); @@ -219,6 +228,10 @@ impl OneShotQueryEngine for PilotDbEngine { ])?; parse_driver_answer(&line) } + + fn cpu_accounting(&self) -> Option { + Some(OneShotCpuAccounting::ChildProcesses(self.children.clone())) + } } #[derive(clap::Args, Debug, Clone)] diff --git a/system-bench/src/engines_external/postgresql_command_line.rs b/system-bench/src/engines_external/postgresql_command_line.rs index c16ab2d3..e7c223fc 100644 --- a/system-bench/src/engines_external/postgresql_command_line.rs +++ b/system-bench/src/engines_external/postgresql_command_line.rs @@ -4,10 +4,14 @@ use std::path::PathBuf; use std::process::{Command, Stdio}; use std::time::Duration; +use aqpbm_core::harness::cgroup::CgroupSource; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; -use aqpbm_core::harness::one_shot::{OneShotQueryEngine, QueryRun, ResultTable}; +use aqpbm_core::harness::one_shot::{ + OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, +}; use super::restart_command::restart_and_wait; +use super::server_cgroup::ServerCgroupOptions; pub const DIALECT: &str = "PostgreSql"; @@ -23,6 +27,7 @@ pub struct PostgreSqlCommandLine { pub struct PostgreSqlEngine { command_line: PostgreSqlCommandLine, client_version: String, + server_cgroup: Option, } pub fn split_timing_lines(output: &str) -> (String, Option) { @@ -75,11 +80,17 @@ impl PostgreSqlEngine { let engine = PostgreSqlEngine { command_line, client_version, + server_cgroup: None, }; engine.text("SELECT 1")?; Ok(engine) } + pub fn with_server_cgroup(mut self, server_cgroup: Option) -> Self { + self.server_cgroup = server_cgroup; + self + } + fn psql(&self, arguments: &[&str], script: Option<&str>) -> Result { let mut command = Command::new(&self.command_line.program); command @@ -254,6 +265,10 @@ impl OneShotQueryEngine for PostgreSqlEngine { details: BTreeMap::new(), }) } + + fn cpu_accounting(&self) -> Option { + self.server_cgroup.clone().map(OneShotCpuAccounting::Cgroup) + } } #[derive(clap::Args, Debug, Clone)] @@ -268,6 +283,8 @@ pub struct PostgreSqlOptions { pub postgresql_restart_command: Option, #[arg(long, default_value_t = 120)] pub postgresql_ready_timeout_seconds: u64, + #[command(flatten)] + pub cgroup: ServerCgroupOptions, } pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result> { @@ -275,11 +292,14 @@ pub fn one_shot_queries(matches: &clap::ArgMatches) -> anyhow::Result Date: Sun, 29 Nov 2026 20:58:31 +0000 Subject: [PATCH 10/51] harness: one-shot-report adds the hot maximum of wall and engine time, and the hot minimum and maximum of engine CPU one-shot-summary.csv gave the first run, the hot minimum and the hot median of wall and engine time, and only the hot median of the engine's own CPU, so a reader could not see how far the runs spread. It now appends hot_max_wall_seconds, hot_max_engine_seconds, hot_min_engine_cpu_seconds and hot_max_engine_cpu_seconds, so each time and CPU quantity has its count (runs), minimum, median and maximum. Existing columns keep their names, positions and values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-core/src/harness/one_shot_report.rs | 23 +++++++++++++++--- aqpbm-core/tests/harness_one_shot_report.rs | 27 ++++++++++++++++++++- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/aqpbm-core/src/harness/one_shot_report.rs b/aqpbm-core/src/harness/one_shot_report.rs index 96fae60f..a2b4ae69 100644 --- a/aqpbm-core/src/harness/one_shot_report.rs +++ b/aqpbm-core/src/harness/one_shot_report.rs @@ -157,6 +157,10 @@ pub struct OneShotReportRow { pub hot_min_peak_memory_bytes: Option, pub hot_median_peak_memory_bytes: Option, pub hot_max_peak_memory_bytes: Option, + pub hot_max_wall_seconds: Option, + pub hot_max_engine_seconds: Option, + pub hot_min_engine_cpu_seconds: Option, + pub hot_max_engine_cpu_seconds: Option, pub speedups: Vec<(ConfigurationName, Option)>, pub target_relative_error: Option, pub max_relative_error: Option, @@ -196,7 +200,7 @@ struct FirstAndHot { struct Timing { wall: FirstAndHot, engine: FirstAndHot, - hot_cpu_median: Option, + engine_cpu: FirstAndHot, harness_cpu: FirstAndHot, peak_memory: FirstAndHot, } @@ -231,8 +235,7 @@ fn timing_of(query: &QueryRecord) -> Timing { Timing { wall: first_and_hot(query, |run| Some(run.wall_seconds)), engine: first_and_hot(query, |run| run.engine_reported_seconds), - hot_cpu_median: every(hot_runs(query), |run| run.engine_reported_cpu_seconds) - .and_then(|hot_cpu| median_of(&hot_cpu)), + engine_cpu: first_and_hot(query, |run| run.engine_reported_cpu_seconds), harness_cpu: first_and_hot(query, |run| run.harness_cpu_seconds), peak_memory: first_and_hot(query, |run| run.peak_memory_bytes.map(|bytes| bytes as f64)), } @@ -302,7 +305,7 @@ pub fn one_shot_report( first_run_engine_seconds: timing.engine.first, hot_min_engine_seconds: timing.engine.hot_min, hot_median_engine_seconds: timing.engine.hot_median, - hot_median_engine_cpu_seconds: timing.hot_cpu_median, + hot_median_engine_cpu_seconds: timing.engine_cpu.hot_median, cpu_and_memory_source: result.cpu_and_memory_source.clone(), first_run_harness_cpu_seconds: timing.harness_cpu.first, hot_min_harness_cpu_seconds: timing.harness_cpu.hot_min, @@ -312,6 +315,10 @@ pub fn one_shot_report( hot_min_peak_memory_bytes: timing.peak_memory.hot_min, hot_median_peak_memory_bytes: timing.peak_memory.hot_median, hot_max_peak_memory_bytes: timing.peak_memory.hot_max, + hot_max_wall_seconds: timing.wall.hot_max, + hot_max_engine_seconds: timing.engine.hot_max, + hot_min_engine_cpu_seconds: timing.engine_cpu.hot_min, + hot_max_engine_cpu_seconds: timing.engine_cpu.hot_max, speedups, target_relative_error: result.error_target.map(|target| target.relative_error), max_relative_error: None, @@ -490,6 +497,10 @@ impl OneShotReport { "hot_min_peak_memory_bytes", "hot_median_peak_memory_bytes", "hot_max_peak_memory_bytes", + "hot_max_wall_seconds", + "hot_max_engine_seconds", + "hot_min_engine_cpu_seconds", + "hot_max_engine_cpu_seconds", ] .map(str::to_string), ); @@ -538,6 +549,10 @@ impl OneShotReport { format_number(row.hot_min_peak_memory_bytes), format_number(row.hot_median_peak_memory_bytes), format_number(row.hot_max_peak_memory_bytes), + format_number(row.hot_max_wall_seconds), + format_number(row.hot_max_engine_seconds), + format_number(row.hot_min_engine_cpu_seconds), + format_number(row.hot_max_engine_cpu_seconds), ]); fields }) diff --git a/aqpbm-core/tests/harness_one_shot_report.rs b/aqpbm-core/tests/harness_one_shot_report.rs index 6152e779..86551ebd 100644 --- a/aqpbm-core/tests/harness_one_shot_report.rs +++ b/aqpbm-core/tests/harness_one_shot_report.rs @@ -151,6 +151,10 @@ fn the_report_times_hot_runs_scores_against_the_truth_and_counts_misses() { assert_eq!(pilotdb.hot_min_engine_seconds, Some(0.4)); assert_eq!(pilotdb.hot_median_engine_seconds, Some(0.5)); assert_eq!(pilotdb.hot_median_engine_cpu_seconds, Some(2.0)); + assert_eq!(pilotdb.hot_max_wall_seconds, Some(1.6)); + assert_eq!(pilotdb.hot_max_engine_seconds, Some(0.6)); + assert_eq!(pilotdb.hot_min_engine_cpu_seconds, Some(1.6)); + assert_eq!(pilotdb.hot_max_engine_cpu_seconds, Some(2.4)); assert!((pilotdb.speedups[0].1.unwrap() - 3.1 / 1.5).abs() < 1e-12); assert!((pilotdb.max_relative_error.unwrap() - 0.1).abs() < 1e-12); assert_eq!(pilotdb.runs_over_target, Some(1)); @@ -383,9 +387,30 @@ fn harness_cpu_and_peak_memory_are_reported_after_the_existing_columns() { ); assert_eq!(field(0, "hot_median_harness_cpu_seconds"), "4"); assert_eq!(field(0, "hot_max_peak_memory_bytes"), "300"); - for name in &header[SUMMARY_COLUMNS_BEFORE_HARNESS_CPU.len()..] { + for name in [ + "cpu_and_memory_source", + "first_run_harness_cpu_seconds", + "hot_min_harness_cpu_seconds", + "hot_median_harness_cpu_seconds", + "hot_max_harness_cpu_seconds", + "first_run_peak_memory_bytes", + "hot_min_peak_memory_bytes", + "hot_median_peak_memory_bytes", + "hot_max_peak_memory_bytes", + ] { assert_eq!(field(1, name), "", "{name}"); } + assert_eq!( + header[header.len() - 4..], + [ + "hot_max_wall_seconds", + "hot_max_engine_seconds", + "hot_min_engine_cpu_seconds", + "hot_max_engine_cpu_seconds" + ] + ); + assert_eq!(field(0, "hot_max_wall_seconds"), "4"); + assert_eq!(field(0, "hot_max_engine_cpu_seconds"), "12"); let markdown = report.summary_markdown(); assert!(markdown.contains("- duckdb/exact: the processes of each run")); From a9a67b1a33951a67ba45d0232c3102ddb2ac7169 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:03:56 +0000 Subject: [PATCH 11/51] harness: summary.csv adds measured runs, minimum and maximum of ingest and query CPU summary.csv gave one number each for ingest_cpu_ns_per_sample (the sum over refresh chunks of each chunk's median CPU, per sample) and query_cpu_ms_per_evaluation (the mean over evaluation times of each time's median CPU), so the spread between runs was not visible. It now appends, for each, the number of measured runs and the same sum or mean taken over each step's least and greatest measured run: ingest_cpu_ns_per_sample_measured_runs, ingest_cpu_ns_per_sample_min, ingest_cpu_ns_per_sample_max, query_cpu_ms_per_evaluation_measured_runs, query_cpu_ms_per_evaluation_min and query_cpu_ms_per_evaluation_max. Taken per step like the median, the minimum and maximum always bound the existing value. Existing columns keep their names, positions and values. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-core/src/harness/benchmark_external.rs | 43 +++++++++++++++++-- .../tests/harness_benchmark_external.rs | 34 ++++++++++++--- 2 files changed, 69 insertions(+), 8 deletions(-) diff --git a/aqpbm-core/src/harness/benchmark_external.rs b/aqpbm-core/src/harness/benchmark_external.rs index 5ffa7c1f..107c4349 100644 --- a/aqpbm-core/src/harness/benchmark_external.rs +++ b/aqpbm-core/src/harness/benchmark_external.rs @@ -35,7 +35,7 @@ use crate::harness::data::{workload_chunks, SeriesLabels}; use crate::harness::engine::{ ArmSpec, CpuAccounting, EngineDescription, EngineUnderTest, WorkloadSpec, }; -use crate::harness::protocol::{LoadProbe, MeasurementClocks, Protocol}; +use crate::harness::protocol::{JobRecord, LoadProbe, MeasurementClocks, Protocol}; use crate::harness::records::ArmResult; use crate::harness::run_directory::{ check_result_name, write_json, RunDirectory, RunDirectoryError, @@ -434,6 +434,12 @@ pub struct ReportRow { pub accuracy: Option, pub substitutions: Vec, pub sharing_lost: Vec, + pub ingest_cpu_ns_per_sample_measured_runs: Option, + pub ingest_cpu_ns_per_sample_min: Option, + pub ingest_cpu_ns_per_sample_max: Option, + pub query_cpu_ms_per_evaluation_measured_runs: Option, + pub query_cpu_ms_per_evaluation_min: Option, + pub query_cpu_ms_per_evaluation_max: Option, } /// Relative errors of answers against the truth over a set of points. @@ -694,6 +700,12 @@ pub fn report( accuracy: None, substitutions: Vec::new(), sharing_lost: Vec::new(), + ingest_cpu_ns_per_sample_measured_runs: None, + ingest_cpu_ns_per_sample_min: None, + ingest_cpu_ns_per_sample_max: None, + query_cpu_ms_per_evaluation_measured_runs: None, + query_cpu_ms_per_evaluation_min: None, + query_cpu_ms_per_evaluation_max: None, }; if let Some(result) = result { fill_measurements(&mut row, result); @@ -926,8 +938,23 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { .iter() .map(|job| step_cpu_ns(&job.median)) .sum(); + let measured_runs = |jobs: &[JobRecord]| jobs.iter().map(|job| job.samples.len()).min(); + let sum_of_step = |jobs: &[JobRecord], least: bool| -> u64 { + jobs.iter() + .map(|job| { + let samples = job.samples.iter().map(step_cpu_ns); + if least { samples.min() } else { samples.max() }.unwrap_or(0) + }) + .sum() + }; row.ingest_cpu_ns_per_sample = (result.ingested_samples > 0).then(|| ingest_ns as f64 / result.ingested_samples as f64); + if result.ingested_samples > 0 { + let per_sample = |ns: u64| Some(ns as f64 / result.ingested_samples as f64); + row.ingest_cpu_ns_per_sample_measured_runs = measured_runs(&result.ingest); + row.ingest_cpu_ns_per_sample_min = per_sample(sum_of_step(&result.ingest, true)); + row.ingest_cpu_ns_per_sample_max = per_sample(sum_of_step(&result.ingest, false)); + } let evaluations = result.evaluate.len(); if evaluations > 0 { let query_ns: u64 = result @@ -936,6 +963,10 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { .map(|job| step_cpu_ns(&job.median)) .sum(); row.query_cpu_ms_per_evaluation = Some(query_ns as f64 / 1e6 / evaluations as f64); + let per_evaluation = |ns: u64| Some(ns as f64 / 1e6 / evaluations as f64); + row.query_cpu_ms_per_evaluation_measured_runs = measured_runs(&result.evaluate); + row.query_cpu_ms_per_evaluation_min = per_evaluation(sum_of_step(&result.evaluate, true)); + row.query_cpu_ms_per_evaluation_max = per_evaluation(sum_of_step(&result.evaluate, false)); row.engine_counter_cpu_ms_per_evaluation = result .evaluate .iter() @@ -970,7 +1001,7 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { } /// The `summary.csv` header. -pub const SUMMARY_CSV_HEADER: &str = "workload,engine,variant,status,cpu_accounting,ingest_cpu_ns_per_sample,query_cpu_ms_per_evaluation,engine_counter_cpu_ms_per_evaluation,server_cpu_ms_whole_arm,server_memory_before_bytes,server_memory_after_bytes,server_lifetime_peak_bytes,server_process_proportional_set_size_before_bytes,server_process_proportional_set_size_after_bytes,server_process_peak_resident_set_size_bytes,installs_held,stored_bytes_last_install,max_relative_error,median_relative_error,points,missing_points,extra_points,substitutions,sharing_lost"; +pub const SUMMARY_CSV_HEADER: &str = "workload,engine,variant,status,cpu_accounting,ingest_cpu_ns_per_sample,query_cpu_ms_per_evaluation,engine_counter_cpu_ms_per_evaluation,server_cpu_ms_whole_arm,server_memory_before_bytes,server_memory_after_bytes,server_lifetime_peak_bytes,server_process_proportional_set_size_before_bytes,server_process_proportional_set_size_after_bytes,server_process_peak_resident_set_size_bytes,installs_held,stored_bytes_last_install,max_relative_error,median_relative_error,points,missing_points,extra_points,substitutions,sharing_lost,ingest_cpu_ns_per_sample_measured_runs,ingest_cpu_ns_per_sample_min,ingest_cpu_ns_per_sample_max,query_cpu_ms_per_evaluation_measured_runs,query_cpu_ms_per_evaluation_min,query_cpu_ms_per_evaluation_max"; pub const SCORES_CSV_HEADER: &str = "workload,engine,variant,query,score,max,median,points"; @@ -1011,7 +1042,7 @@ impl Report { let mut text = format!("{SUMMARY_CSV_HEADER}\n"); for row in &self.rows { text.push_str(&format!( - "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n", + "{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}\n", csv_text(&row.workload), csv_text(&row.engine), csv_text(&row.variant), @@ -1032,6 +1063,12 @@ impl Report { error_fields(row.accuracy.as_ref()), csv_text(&row.substitutions.join(";")), csv_text(&row.sharing_lost.join(";")), + field(row.ingest_cpu_ns_per_sample_measured_runs), + field(row.ingest_cpu_ns_per_sample_min), + field(row.ingest_cpu_ns_per_sample_max), + field(row.query_cpu_ms_per_evaluation_measured_runs), + field(row.query_cpu_ms_per_evaluation_min), + field(row.query_cpu_ms_per_evaluation_max), )); } text diff --git a/aqpbm-core/tests/harness_benchmark_external.rs b/aqpbm-core/tests/harness_benchmark_external.rs index 1327547e..59e6ab8d 100644 --- a/aqpbm-core/tests/harness_benchmark_external.rs +++ b/aqpbm-core/tests/harness_benchmark_external.rs @@ -443,6 +443,27 @@ fn report_fixture(temp: &TempDir) -> RunDirectory { server_job(1_500_000, Some(1_000_000)), server_job(2_500_000, Some(3_000_000)), ]; + let spread = |job: &mut JobRecord, [low, high]: [u64; 2]| { + let median = job.median.clone(); + job.samples = vec![ + StepCost { + process_cpu_ns: low, + wall_ns: low, + ..median.clone() + }, + median.clone(), + StepCost { + process_cpu_ns: high, + wall_ns: high, + ..median + }, + ]; + job.median_run = 1; + }; + spread(&mut b.ingest[0], [1_000, 7_000]); + spread(&mut b.ingest[1], [4_000, 6_000]); + spread(&mut b.evaluate[0], [1_000_000, 2_000_000]); + spread(&mut b.evaluate[1], [2_000_000, 4_500_000]); b.server_cpu_ns_whole_arm = Some(9_000_000); b.cpu_source = "cgroup bench@192.0.2.1:/sys/fs/cgroup/system.slice/docker-1a2b.scope/cpu.stat over SSH" @@ -521,14 +542,17 @@ fn the_summary_has_absolute_numbers_and_errors_against_the_truth() { let csv = report.summary_csv(); let lines: Vec<&str> = csv.lines().collect(); assert_eq!(lines[0], SUMMARY_CSV_HEADER); - assert_eq!(SUMMARY_CSV_HEADER.split(',').count(), 24); - let empty_after_status = ",".repeat(20); + assert_eq!(SUMMARY_CSV_HEADER.split(',').count(), 30); + assert!(SUMMARY_CSV_HEADER.ends_with( + ",sharing_lost,ingest_cpu_ns_per_sample_measured_runs,ingest_cpu_ns_per_sample_min,ingest_cpu_ns_per_sample_max,query_cpu_ms_per_evaluation_measured_runs,query_cpu_ms_per_evaluation_min,query_cpu_ms_per_evaluation_max" + )); + let empty_after_status = ",".repeat(26); let expected = [ - "w1,a,v1,ok,thread,250,0.001,,,,,,,,,1,0,0,0,2,0,0,,".to_string(), + "w1,a,v1,ok,thread,250,0.001,,,,,,,,,1,0,0,0,2,0,0,,,1,250,250,1,0.001,0.001".to_string(), "w2,a,v1,no plan: ExcludedByDeployment".to_string() + &empty_after_status, - "w1,b,v1,ok,cgroup,2000,2,2,9,3145728,3145728,5242880,,,,6,120,0.1,0.05,2,0,1,quantileDD for Kll at node 3;x,\"node 4 for nodes 6, 7\"".to_string(), + "w1,b,v1,ok,cgroup,2000,2,2,9,3145728,3145728,5242880,,,,6,120,0.1,0.05,2,0,1,quantileDD for Kll at node 3;x,\"node 4 for nodes 6, 7\",3,1250,3250,3,1.5,3.25".to_string(), "w1,b,v2,no plan: ExcludedByDeployment".to_string() + &empty_after_status, - "w2,b,v1,ok,thread,250,0.001,,,,,,,,,1,0,,,,,,,".to_string(), + "w2,b,v1,ok,thread,250,0.001,,,,,,,,,1,0,,,,,,,,1,250,250,1,0.001,0.001".to_string(), "w1,c,v1,not run: refused: filter@node 3".to_string() + &empty_after_status, ]; assert_eq!( From a7f0a0c802936038de0186aff3583519d115d591 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:17:42 +0000 Subject: [PATCH 12/51] harness: an engine that holds one install at a time runs an arm once per run run_arm gives every warm-up and measured run its own install up front and runs each step on all of them in turn. An engine that cannot hold two installs (a server whose state one install owns) could therefore only run with --warmup 0 --runs 1. EngineUnderTest::holds_one_install_at_a_time (false by default) now makes run_arm install, run every step and drop the install once per run, one after another; each step's job then holds that step's call from every measured run, with its median, so the record has the same shape as with every install at once. installs_held is 1, and server_cpu_ns_whole_arm sums each install's span, from its install (the first from before it), so a server restarted at an install is counted from its restart. With one run nothing changes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-core/src/harness/arm_run.rs | 254 ++++++++++++++++++++++++----- aqpbm-core/src/harness/engine.rs | 3 + aqpbm-core/src/harness/protocol.rs | 25 +++ aqpbm-core/src/harness/records.rs | 13 +- aqpbm-core/tests/harness_cgroup.rs | 82 +++++++++- aqpbm-core/tests/harness_fake.rs | 108 +++++++++++- 6 files changed, 435 insertions(+), 50 deletions(-) diff --git a/aqpbm-core/src/harness/arm_run.rs b/aqpbm-core/src/harness/arm_run.rs index 6621dc81..b313c6be 100644 --- a/aqpbm-core/src/harness/arm_run.rs +++ b/aqpbm-core/src/harness/arm_run.rs @@ -2,14 +2,15 @@ //! refresh chunk, evaluate at every time, and record the costs the harness //! measured. +use crate::harness::cgroup::CgroupSource; use crate::harness::data::{workload_chunks, DataError}; use crate::harness::engine::{ Answers, ArmSpec, CpuAccounting, EngineError, EngineUnderTest, InstalledArm, MeasuredUsage, WorkloadSpec, }; use crate::harness::protocol::{ - processes_memory, CoreLoad, EngineClock, JobRecord, LoadProbe, MeasurementClocks, Protocol, - ProtocolError, + job_over_runs, processes_memory, CoreLoad, EngineClock, JobRecord, LoadProbe, + MeasurementClocks, Protocol, ProtocolError, }; use crate::harness::records::ArmResult; @@ -151,11 +152,13 @@ pub enum ScheduleError { /// `Processes(pids)` a clock over the server pids under `clocks.process_cpu_files` that /// `run_arm` builds itself, never the harness process. /// -/// Every run gets its own install up front, and each step (one refresh -/// chunk, or one evaluation) is one protocol job whose k-th call goes to -/// install k. Example: warm-up 1 and 5 runs install 6 arms; the job of chunk -/// 3 ingests chunk 3 into each of them in turn and records the 5 measured -/// calls. An evaluation time runs after the chunk that ends at or after it. +/// Every run gets its own install up front (an engine that holds one +/// install at a time runs the arm once per run, one install after +/// another), and each step (one refresh chunk, or one evaluation) is one +/// protocol job whose k-th call goes to install k. Example: warm-up 1 and +/// 5 runs install 6 arms; the job of chunk 3 ingests chunk 3 into each of +/// them in turn and records the 5 measured calls. An evaluation time runs +/// after the chunk that ends at or after it. /// /// Memory: all `warmup_runs + measured_runs` installs are held at once, so a /// run needs that many times the memory of one arm (6× with the default @@ -197,7 +200,6 @@ pub fn run_arm( }); } let clock = clocks.clock_for(&engine.cpu_accounting())?; - let runs = (protocol.warmup_runs + protocol.measured_runs) as usize; let server_cgroup = match engine.cpu_accounting() { CpuAccounting::Cgroup(source) => Some(source), _ => None, @@ -217,6 +219,96 @@ pub fn run_arm( .transpose() }; let process_memory_before = read_process_memory()?; + let Steps { + mut installs, + ingest, + evaluate, + answers, + ingested_samples, + server_cpu_ns_of_earlier_installs, + server_cpu_ns_at_last_install, + } = if engine.holds_one_install_at_a_time() { + steps_one_install_at_a_time( + engine, + workload, + arm, + schedule, + protocol, + core, + probe, + &clock, + server_cgroup.as_ref(), + server_before.map(|(before_ns, _)| before_ns), + )? + } else { + steps_on_every_install_at_once( + engine, workload, arm, schedule, protocol, core, probe, &clock, + )? + }; + + let last = installs.last_mut().expect("at least one measured run"); + let footprint = last.footprint()?; + let server_after = server_cgroup + .as_ref() + .map(|source| Ok::<_, ProtocolError>((source.cpu()?.usage_ns, source.memory()?))) + .transpose()?; + let process_memory_after = read_process_memory()?; + let data_seconds = data_ms as f64 / 1_000.0; + let usage = MeasuredUsage { + ingest_cpu_ns_per_second: median_cpu_ns(&ingest, &clock) / data_seconds, + query_cpu_ns_per_second: median_cpu_ns(&evaluate, &clock) / data_seconds, + held_bytes: footprint.view_bytes + footprint.raw_retained_bytes, + }; + Ok(ArmResult { + engine: engine.description().id, + workload: workload.name.clone(), + arm: arm.name.clone(), + plan: last.plan_summary(), + predicted: last.predicted(), + measured_engine_cost_per_second: last.price(&usage), + node_profiles: last.node_profiles(), + ingest, + evaluate, + answers, + footprint, + ingested_samples, + server_memory_before: server_before.map(|(_, memory)| memory), + server_memory_after: server_after.map(|(_, memory)| memory), + server_process_memory_before: process_memory_before, + server_process_memory_after: process_memory_after, + server_cpu_ns_whole_arm: server_before.zip(server_after).map( + |((before_ns, _), (after_ns, _))| { + server_cpu_ns_of_earlier_installs + + after_ns.saturating_sub(server_cpu_ns_at_last_install.unwrap_or(before_ns)) + }, + ), + cpu_source: clock.cpu_source(), + installs_held: installs.len() as u32, + }) +} + +struct Steps { + installs: Vec>, + ingest: Vec, + evaluate: Vec, + answers: Vec<(i64, Answers)>, + ingested_samples: u64, + server_cpu_ns_of_earlier_installs: u64, + server_cpu_ns_at_last_install: Option, +} + +#[allow(clippy::too_many_arguments)] +fn steps_on_every_install_at_once( + engine: &dyn EngineUnderTest, + workload: &WorkloadSpec, + arm: &ArmSpec, + schedule: &ArmSchedule, + protocol: &Protocol, + core: usize, + probe: &mut dyn LoadProbe, + clock: &EngineClock, +) -> Result { + let runs = (protocol.warmup_runs + protocol.measured_runs) as usize; let mut installs: Vec> = (0..runs) .map(|_| engine.install(workload, arm)) .collect::>()?; @@ -236,7 +328,7 @@ pub fn run_arm( // Every call's answers, reserved up front so the timed calls only // move into it; freed after the job, outside every timed window. let mut answers_per_call: Vec = Vec::with_capacity(runs); - let job = protocol.run_next_job(core, probe, *load, &clock, &mut || { + let job = protocol.run_next_job(core, probe, *load, clock, &mut || { let (step_answers, report) = installs[answers_per_call.len()].evaluate(at_ms)?; answers_per_call.push(step_answers); Ok(report) @@ -252,7 +344,7 @@ pub fn run_arm( let chunk = chunk?; ingested_samples += chunk.samples.len() as u64; let mut call = 0; - let job = protocol.run_next_job(core, probe, load, &clock, &mut || { + let job = protocol.run_next_job(core, probe, load, clock, &mut || { let report = installs[call].ingest(&chunk); call += 1; report @@ -266,42 +358,120 @@ pub fn run_arm( for at_ms in pending_evaluations { evaluate_at(at_ms, &mut installs, probe, &mut load)?; } - - let last = installs.last_mut().expect("at least one measured run"); - let footprint = last.footprint()?; - let server_after = server_cgroup - .as_ref() - .map(|source| Ok::<_, ProtocolError>((source.cpu()?.usage_ns, source.memory()?))) - .transpose()?; - let process_memory_after = read_process_memory()?; - let data_seconds = data_ms as f64 / 1_000.0; - let usage = MeasuredUsage { - ingest_cpu_ns_per_second: median_cpu_ns(&ingest, &clock) / data_seconds, - query_cpu_ns_per_second: median_cpu_ns(&evaluate, &clock) / data_seconds, - held_bytes: footprint.view_bytes + footprint.raw_retained_bytes, - }; - Ok(ArmResult { - engine: engine.description().id, - workload: workload.name.clone(), - arm: arm.name.clone(), - plan: last.plan_summary(), - predicted: last.predicted(), - measured_engine_cost_per_second: last.price(&usage), - node_profiles: last.node_profiles(), + Ok(Steps { + installs, ingest, evaluate, answers, - footprint, ingested_samples, - server_memory_before: server_before.map(|(_, memory)| memory), - server_memory_after: server_after.map(|(_, memory)| memory), - server_process_memory_before: process_memory_before, - server_process_memory_after: process_memory_after, - server_cpu_ns_whole_arm: server_before - .zip(server_after) - .map(|((before_ns, _), (after_ns, _))| after_ns.saturating_sub(before_ns)), - cpu_source: clock.cpu_source(), - installs_held: runs as u32, + server_cpu_ns_of_earlier_installs: 0, + server_cpu_ns_at_last_install: None, + }) +} + +#[allow(clippy::too_many_arguments)] +fn steps_one_install_at_a_time( + engine: &dyn EngineUnderTest, + workload: &WorkloadSpec, + arm: &ArmSpec, + schedule: &ArmSchedule, + protocol: &Protocol, + core: usize, + probe: &mut dyn LoadProbe, + clock: &EngineClock, + server_cgroup: Option<&CgroupSource>, + server_cpu_ns_before: Option, +) -> Result { + let one_call = Protocol { + warmup_runs: 0, + measured_runs: 1, + ..protocol.clone() + }; + let server_cpu_ns = || { + server_cgroup + .map(|source| source.cpu().map(|cpu| cpu.usage_ns)) + .transpose() + .map_err(ProtocolError::from) + }; + let mut measured_ingest: Vec> = Vec::new(); + let mut measured_evaluate: Vec> = Vec::new(); + let mut last: Option> = None; + let mut answers = Vec::new(); + let mut ingested_samples = 0; + let mut server_cpu_ns_of_earlier_installs = 0; + let mut server_cpu_ns_at_last_install = server_cpu_ns_before; + for run in 0..protocol.warmup_runs + protocol.measured_runs { + if let Some(previous) = last.take() { + if let (Some(started_ns), Some(ended_ns)) = + (server_cpu_ns_at_last_install, server_cpu_ns()?) + { + server_cpu_ns_of_earlier_installs += ended_ns.saturating_sub(started_ns); + } + drop(previous); + } + let mut install = engine.install(workload, arm)?; + if run > 0 { + server_cpu_ns_at_last_install = server_cpu_ns()?; + } + answers.clear(); + ingested_samples = 0; + let mut ingest = Vec::new(); + let mut evaluate = Vec::new(); + let mut load: Option = None; + let mut pending_evaluations = schedule.evaluate_at_ms.iter().copied().peekable(); + let mut evaluate_at = |at_ms: i64, + install: &mut Box, + probe: &mut dyn LoadProbe, + load: &mut Option| + -> Result<(), ArmRunError> { + let mut step_answers = None; + let job = one_call.run_next_job(core, probe, *load, clock, &mut || { + let (call_answers, report) = install.evaluate(at_ms)?; + step_answers = Some(call_answers); + Ok(report) + })?; + *load = Some(job.load_after()); + evaluate.push(job); + answers.push((at_ms, step_answers.expect("one measured call"))); + Ok(()) + }; + for chunk in workload_chunks(&workload.data, schedule.refresh_ms)? { + let chunk = chunk?; + ingested_samples += chunk.samples.len() as u64; + let job = + one_call.run_next_job(core, probe, load, clock, &mut || install.ingest(&chunk))?; + load = Some(job.load_after()); + ingest.push(job); + while let Some(at_ms) = pending_evaluations.next_if(|&at_ms| at_ms <= chunk.end_ms) { + evaluate_at(at_ms, &mut install, probe, &mut load)?; + } + } + for at_ms in pending_evaluations { + evaluate_at(at_ms, &mut install, probe, &mut load)?; + } + if run >= protocol.warmup_runs { + measured_ingest.push(ingest); + measured_evaluate.push(evaluate); + } + last = Some(install); + } + let over_runs = |runs: Vec>| -> Vec { + let steps = runs.iter().map(Vec::len).min().unwrap_or(0); + (0..steps) + .map(|step| { + let calls: Vec<&JobRecord> = runs.iter().map(|jobs| &jobs[step]).collect(); + job_over_runs(&calls, clock) + }) + .collect() + }; + Ok(Steps { + installs: last.into_iter().collect(), + ingest: over_runs(measured_ingest), + evaluate: over_runs(measured_evaluate), + answers, + ingested_samples, + server_cpu_ns_of_earlier_installs, + server_cpu_ns_at_last_install, }) } diff --git a/aqpbm-core/src/harness/engine.rs b/aqpbm-core/src/harness/engine.rs index 327cb818..18c7286e 100644 --- a/aqpbm-core/src/harness/engine.rs +++ b/aqpbm-core/src/harness/engine.rs @@ -29,6 +29,9 @@ pub trait EngineUnderTest { fn calibration(&mut self) -> Option<&mut dyn Calibratable> { None } + fn holds_one_install_at_a_time(&self) -> bool { + false + } } /// Which engine and which build a measurement ran on. diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index 07dcd2d3..481bbab2 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -1163,6 +1163,31 @@ impl Protocol { } } +pub(crate) fn job_over_runs(jobs: &[&JobRecord], clock: &EngineClock) -> JobRecord { + let samples: Vec = jobs + .iter() + .flat_map(|job| job.samples.iter().cloned()) + .collect(); + let median_run = median_run(&samples, clock); + let highest = + |value: fn(&JobRecord) -> f64| jobs.iter().map(|job| value(job)).fold(0.0, f64::max); + let highest_loadavg = |at: usize| { + jobs.iter() + .filter_map(|job| job.loadavg[at]) + .reduce(f64::max) + }; + JobRecord { + core: jobs.first().map_or(0, |job| job.core), + busy_before: highest(|job| job.busy_before), + busy_after: highest(|job| job.busy_after), + loadavg: [highest_loadavg(0), highest_loadavg(1)], + marks: jobs.iter().flat_map(|job| job.marks.clone()).collect(), + median: samples[median_run].clone(), + samples, + median_run, + } +} + /// The sample in the middle of an odd number of samples, ordered by the CPU /// `clock` measures the engine by; ties keep run order, so the choice is /// deterministic. diff --git a/aqpbm-core/src/harness/records.rs b/aqpbm-core/src/harness/records.rs index 3038943f..40163c1b 100644 --- a/aqpbm-core/src/harness/records.rs +++ b/aqpbm-core/src/harness/records.rs @@ -45,8 +45,8 @@ pub struct ArmResult { /// For a [`crate::harness::engine::CpuAccounting::Cgroup`] engine, the server's /// memory before the installs. pub server_memory_before: Option, - /// The same after the last step. The server then holds every install of - /// the arm at once (`installs_held` of them), so this is not one + /// The same after the last step. The server then holds `installs_held` + /// installs of the arm at once, so with more than one this is not one /// install's memory. pub server_memory_after: Option, #[serde(default, skip_serializing_if = "Option::is_none")] @@ -55,13 +55,18 @@ pub struct ArmResult { pub server_process_memory_after: Option, /// For a `Cgroup` engine, the server's CPU from before the installs to /// after the footprint, in ns: the steps plus work between them, such - /// as background merges, over every install. + /// as background merges, over every install. For an engine that holds + /// one install at a time, the sum over its installs, each from its + /// install (the first from before it) to its last step (the last to + /// after the footprint), so a server restarted at an install counts + /// from its restart. pub server_cpu_ns_whole_arm: Option, /// Where the engine's CPU was read ([`crate::harness::protocol::EngineClock::cpu_source`]), /// such as `cgroup /sys/fs/cgroup/system.slice/docker-1a2b.scope/cpu.stat` /// or `schedstat`. pub cpu_source: String, - /// Installs held at once while the arm ran: warm-up plus measured runs. + /// Installs held at once while the arm ran: warm-up plus measured runs, + /// or 1 for an engine that holds one install at a time. pub installs_held: u32, /// The usage the harness measured, priced at the engine's own prices /// ([`crate::harness::engine::InstalledArm::price`]); `None` for an engine without diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs index f8cc8f9b..468c8a48 100644 --- a/aqpbm-core/tests/harness_cgroup.rs +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -8,8 +8,8 @@ use aqpbm_core::harness::arm_run::{run_arm, ArmSchedule}; use aqpbm_core::harness::cgroup::{CgroupCpu, CgroupError, CgroupMemory, CgroupSource}; use aqpbm_core::harness::data::DataRecord; use aqpbm_core::harness::engine::{ - ArmSpec, CpuAccounting, EngineUnderTest, QueryLanguage, QueryText, StepReport, WorkloadQuery, - WorkloadSpec, + ArmSpec, CpuAccounting, EngineDescription, EngineError, EngineUnderTest, InstalledArm, + QueryLanguage, QueryText, StepReport, WorkloadQuery, WorkloadSpec, }; use aqpbm_core::harness::fake::{FakeEngine, FakeServer}; use aqpbm_core::harness::protocol::{ @@ -359,6 +359,84 @@ fn an_arm_on_a_cgroup_server_records_cpu_memory_and_samples() { assert_eq!(result.server_cpu_ns_whole_arm, Some(steps_ns + 3 * 500_000)); } +struct OneInstallAtATime(FakeEngine); + +impl EngineUnderTest for OneInstallAtATime { + fn description(&self) -> EngineDescription { + self.0.description() + } + fn cpu_accounting(&self) -> CpuAccounting { + self.0.cpu_accounting() + } + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + self.0.install(workload, arm) + } + fn holds_one_install_at_a_time(&self) -> bool { + true + } +} + +#[test] +fn installs_one_after_another_count_the_server_cpu_from_each_install() { + let temp = TempDir::new("one-at-a-time"); + let server = + FakeServer::start_in_cgroup(&temp.0.join("proc"), 4244, &temp.0.join("group")).unwrap(); + let engine = OneInstallAtATime(FakeEngine { + server: Some(server), + ns_per_install: 500_000, + ns_per_series: 500, + ..FakeEngine::default() + }); + let workload = two_series_workload(); + let schedule = ArmSchedule { + refresh_ms: 10_000, + evaluate_at_ms: vec![61_000], + }; + let protocol = Protocol { + warmup_runs: 1, + measured_runs: 3, + max_core_busy_fraction: 1.0, + }; + let arm = ArmSpec { + name: "exact".into(), + raw_data_retained: true, + engine_options: serde_json::Value::Null, + }; + let result = run_arm( + &engine, + &workload, + &arm, + &schedule, + &protocol, + 0, + &mut IdleProbe, + &MeasurementClocks::with_calling_thread(&OsCpuClock), + ) + .unwrap(); + assert_eq!(engine.0.installs.get(), 4); + assert_eq!(result.installs_held, 1); + assert_eq!(result.ingest.len(), 6); + for job in result.ingest.iter().chain(&result.evaluate) { + assert_eq!(job.samples.len(), 3); + } + let measured_steps_ns: u64 = result + .ingest + .iter() + .chain(&result.evaluate) + .flat_map(|job| &job.samples) + .map(|cost| cost.process_cpu_ns) + .sum(); + let warmup_steps_ns = measured_steps_ns / 3; + assert_eq!( + result.server_cpu_ns_whole_arm, + Some(warmup_steps_ns + measured_steps_ns + 500_000) + ); +} + /// The server's cores come from its cpu list; the idle check takes the /// busiest of them. #[test] diff --git a/aqpbm-core/tests/harness_fake.rs b/aqpbm-core/tests/harness_fake.rs index 857810c5..bec9af80 100644 --- a/aqpbm-core/tests/harness_fake.rs +++ b/aqpbm-core/tests/harness_fake.rs @@ -1,13 +1,16 @@ //! The fake engine: step costs from the harness clock, a whole harness run, //! node profiles from the operator timing hook, and engine-reported CPU. +use std::cell::Cell; +use std::rc::Rc; + use aqpbm_core::harness::arm_run::ArmRunError; use aqpbm_core::harness::arm_run::{run_arm, ArmSchedule}; use aqpbm_core::harness::conformance::probe_workloads; use aqpbm_core::harness::data::{DataRecord, Sample, SampleChunk, SeriesLabels}; use aqpbm_core::harness::engine::{ - ArmSpec, CpuAccounting, EngineUnderTest, QueryLanguage, QueryText, StepReport, WorkloadQuery, - WorkloadSpec, + Answers, ArmSpec, CpuAccounting, EngineDescription, EngineError, EngineUnderTest, Footprint, + InstalledArm, PlanSummary, QueryLanguage, QueryText, StepReport, WorkloadQuery, WorkloadSpec, }; use aqpbm_core::harness::fake::{FakeEngine, FakeServer}; use aqpbm_core::harness::protocol::{ @@ -493,3 +496,104 @@ fn a_calling_thread_engine_records_no_server_memory() { assert_eq!(result.server_process_memory_before, None); assert_eq!(result.server_process_memory_after, None); } + +struct OneInstallAtATime { + fake: FakeEngine, + held: Rc>, +} + +struct HeldInstall { + arm: Box, + held: Rc>, +} + +impl Drop for HeldInstall { + fn drop(&mut self) { + self.held.set(self.held.get() - 1); + } +} + +impl InstalledArm for HeldInstall { + fn plan_summary(&self) -> PlanSummary { + self.arm.plan_summary() + } + fn ingest(&mut self, chunk: &SampleChunk) -> Result { + self.arm.ingest(chunk) + } + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError> { + self.arm.evaluate(at_ms) + } + fn footprint(&self) -> Result { + self.arm.footprint() + } +} + +impl EngineUnderTest for OneInstallAtATime { + fn description(&self) -> EngineDescription { + self.fake.description() + } + fn cpu_accounting(&self) -> CpuAccounting { + self.fake.cpu_accounting() + } + fn install( + &self, + workload: &WorkloadSpec, + arm: &ArmSpec, + ) -> Result, EngineError> { + if self.held.get() > 0 { + return Err(EngineError("an install is still held".into())); + } + let arm = self.fake.install(workload, arm)?; + self.held.set(self.held.get() + 1); + Ok(Box::new(HeldInstall { + arm, + held: Rc::clone(&self.held), + })) + } + fn holds_one_install_at_a_time(&self) -> bool { + true + } +} + +#[test] +fn an_engine_that_holds_one_install_at_a_time_runs_the_arm_once_per_run() { + let at_once = run_probe(&FakeEngine::default(), 7); + let engine = OneInstallAtATime { + fake: FakeEngine::default(), + held: Rc::default(), + }; + let clock = engine.fake.clock.clone(); + let mut probe = CountingProbe(0); + let workload = probe_workload(7); + let protocol = Protocol::default(); + let result = run_arm( + &engine, + &workload, + &arm(), + &probe_schedule(&workload), + &protocol, + 0, + &mut probe, + &MeasurementClocks::with_calling_thread(&clock), + ) + .unwrap(); + let runs = protocol.warmup_runs + protocol.measured_runs; + assert_eq!(engine.fake.installs.get(), runs); + assert_eq!(engine.held.get(), 0); + assert_eq!(result.installs_held, 1); + assert_eq!(at_once.installs_held, runs); + let jobs = result.ingest.len() + result.evaluate.len(); + assert_eq!(probe.0, (jobs + 1) * runs as usize); + for (one, all) in result + .ingest + .iter() + .chain(&result.evaluate) + .zip(at_once.ingest.iter().chain(&at_once.evaluate)) + { + assert_eq!(one.samples.len(), protocol.measured_runs as usize); + assert_eq!(one.samples, all.samples); + assert_eq!(one.median, all.median); + } + assert_eq!(result.answers, at_once.answers); + assert_eq!(result.ingested_samples, at_once.ingested_samples); +} From c06ce78f034555c722ea84fd7d87a119f1b6e694 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:17:42 +0000 Subject: [PATCH 13/51] system-bench: VictoriaMetrics and ASAPQuery-backend arms without a plan file run more than once Both adapters refused any protocol but --warmup 0 --runs 1. They now hold one install at a time, so the harness runs their arms one run after another: - victoriametrics: an arm without a plan file deletes the workload's series when it installs and when it is dropped, so it repeats as is. An arm with a plan file feeds its data on the wall clock and is still refused more than one run, now when it installs. - asapquery-backend keeps every sample written to it, so a run after the first needs a fresh server: the new --asapquery-backend-restart-command is run before every install after the first, followed by a wait for the server to answer. Without it the limit stays as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-cli/tests/benchmark_external_cli.rs | 16 +++- .../asapquery_backend_server.rs | 53 +++++++++---- .../victoriametrics_server.rs | 33 +++++--- system-bench/tests/end_to_end_adapters.rs | 75 ++++++++++++++++++- 4 files changed, 145 insertions(+), 32 deletions(-) diff --git a/aqpbm-cli/tests/benchmark_external_cli.rs b/aqpbm-cli/tests/benchmark_external_cli.rs index 2245a672..134291ee 100644 --- a/aqpbm-cli/tests/benchmark_external_cli.rs +++ b/aqpbm-cli/tests/benchmark_external_cli.rs @@ -189,10 +189,11 @@ fn the_clickhouse_engine_needs_its_server() { } /// 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`. +/// config file; it takes any warm-up and run count, since it runs one +/// install at a time and an arm with a plan file is refused more than one +/// run when it installs. #[test] -fn the_victoriametrics_engine_needs_its_server_and_one_run() { +fn the_victoriametrics_engine_needs_its_server() { let run = fixture("x4"); let base = [ "benchmark-external", @@ -218,7 +219,8 @@ fn the_victoriametrics_engine_needs_its_server_and_one_run() { 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}"); + assert!(!stderr.contains("--warmup 0 --runs 1"), "{stderr}"); + assert!(stderr.contains("127.0.0.1:1"), "{stderr}"); let _ = std::fs::remove_dir_all(run.parent().unwrap()); } @@ -248,6 +250,12 @@ fn the_asapquery_backend_engine_needs_its_server_and_one_run() { assert!(!out.status.success()); let stderr = String::from_utf8_lossy(&out.stderr); assert!(stderr.contains("--warmup 0 --runs 1"), "{stderr}"); + with_server.extend(["--asapquery-backend-restart-command", "true"]); + 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}"); + assert!(stderr.contains("127.0.0.1:1"), "{stderr}"); let _ = std::fs::remove_dir_all(run.parent().unwrap()); } diff --git a/system-bench/src/engines_external/asapquery_backend_server.rs b/system-bench/src/engines_external/asapquery_backend_server.rs index 807caf8a..299510dd 100644 --- a/system-bench/src/engines_external/asapquery_backend_server.rs +++ b/system-bench/src/engines_external/asapquery_backend_server.rs @@ -8,6 +8,7 @@ use aqpbm_core::harness::engine::{ InstalledArm, PlanSummary, QueryLanguage, StepReport, WorkloadSpec, }; +use super::restart_command::restart_and_wait; use super::server_cgroup::ServerCgroupOptions; use crate::prometheus_api::query_text_arm::{ ask_every_query, queries_to_ask, write_chunk, QueryToAsk, @@ -25,8 +26,11 @@ pub struct AsapqueryBackendEngine { server: AsapqueryBackendServer, connection: AsapqueryBackendConnection, installed_once: AtomicBool, + restart_command: Option, } +const RESTART_READY_TIMEOUT: Duration = Duration::from_secs(120); + #[derive(Clone)] pub struct AsapqueryBackendConnection { pub agent: ureq::Agent, @@ -99,6 +103,7 @@ impl AsapqueryBackendEngine { server, connection, installed_once: AtomicBool::new(false), + restart_command: None, }) } } @@ -117,6 +122,10 @@ impl EngineUnderTest for AsapqueryBackendEngine { CpuAccounting::Cgroup(self.server.cgroup.clone()) } + fn holds_one_install_at_a_time(&self) -> bool { + true + } + fn install( &self, workload: &WorkloadSpec, @@ -131,11 +140,20 @@ impl EngineUnderTest for AsapqueryBackendEngine { } let queries = queries_to_ask(workload, &[QueryLanguage::PromQl])?; if self.installed_once.swap(true, Ordering::SeqCst) { - return Err(EngineError( - "ASAPQuery-backend keeps every sample written to it: restart the server before \ - the next arm, and run this engine with --warmup 0 --runs 1" - .into(), - )); + let Some(command) = self.restart_command.as_deref() else { + return Err(EngineError( + "ASAPQuery-backend keeps every sample written to it: restart the server before \ + the next arm, and run this engine with --warmup 0 --runs 1, or give \ + --asapquery-backend-restart-command" + .into(), + )); + }; + restart_and_wait( + "ASAPQuery-backend", + Some(command), + RESTART_READY_TIMEOUT, + || self.connection.status().is_ok(), + )?; } Ok(Box::new(AsapqueryBackendArm { connection: self.connection.clone(), @@ -188,6 +206,11 @@ pub struct AsapqueryBackendOptions { pub asapquery_backend_url: Option, #[command(flatten)] pub cgroup: ServerCgroupOptions, + #[arg( + long, + help = "A shell command that restarts the ASAPQuery-backend server, e.g. `docker restart asapquery-backend`, run before every install after the first and followed by a wait of up to 120 s for the server to answer: each run of an arm then starts on an empty server, so an arm can run with warm-up and more than one measured run (engine `asapquery-backend`)" + )] + pub asapquery_backend_restart_command: Option, } pub fn periodic_queries( @@ -200,16 +223,18 @@ pub fn periodic_queries( "engine asapquery-backend needs --asapquery-backend-url and --server-cgroup-directory" ); }; - if protocol.warmup_runs != 0 || protocol.measured_runs != 1 { + if protocol.warmup_runs + protocol.measured_runs != 1 + && options.asapquery_backend_restart_command.is_none() + { anyhow::bail!( - "engine asapquery-backend runs one arm per server start: pass --warmup 0 --runs 1" + "engine asapquery-backend runs one arm per server start: pass --warmup 0 --runs 1, or give --asapquery-backend-restart-command" ); } - Ok(Box::new(AsapqueryBackendEngine::new( - AsapqueryBackendServer { - url, - cgroup, - request_timeout: Duration::from_secs(600), - }, - )?)) + let mut engine = AsapqueryBackendEngine::new(AsapqueryBackendServer { + url, + cgroup, + request_timeout: Duration::from_secs(600), + })?; + engine.restart_command = options.asapquery_backend_restart_command; + Ok(Box::new(engine)) } diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs index 62f42d40..59320fb7 100644 --- a/system-bench/src/engines_external/victoriametrics_server.rs +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -98,6 +98,7 @@ pub struct VictoriaMetricsEngine { /// The wall time of the newest sample any arm of this engine sent, in /// ms (0 before any). newest_sample_wall_ms: Arc, + runs_per_arm: u32, } /// Installs so far in this process, for each install's config nonce. @@ -139,6 +140,7 @@ impl VictoriaMetricsEngine { http, arm_installed: Arc::new(AtomicBool::new(false)), newest_sample_wall_ms: Arc::new(AtomicI64::new(0)), + runs_per_arm: 1, }) } @@ -186,6 +188,10 @@ impl EngineUnderTest for VictoriaMetricsEngine { CpuAccounting::Cgroup(self.server.cgroup.clone()) } + fn holds_one_install_at_a_time(&self) -> bool { + true + } + fn install( &self, workload: &WorkloadSpec, @@ -194,6 +200,13 @@ impl EngineUnderTest for VictoriaMetricsEngine { let Some(path) = arm.engine_options.get("plan_file").and_then(|p| p.as_str()) else { return self.install_query_text(workload); }; + if self.runs_per_arm != 1 { + return Err(EngineError( + "an arm with a plan file feeds its data on the wall clock, so it runs once: run \ + it with --warmup 0 --runs 1" + .into(), + )); + } let cgroup = self.server.cgroup.clone(); let Some(stream_aggregation_config) = self.server.stream_aggregation_config.clone() else { return Err(EngineError( @@ -1093,16 +1106,12 @@ pub fn periodic_queries( "engine victoriametrics needs --victoriametrics-url and --server-cgroup-directory" ); }; - // Wall-clock data runs one arm at a time. - if protocol.warmup_runs != 0 || protocol.measured_runs != 1 { - anyhow::bail!("engine victoriametrics runs one arm at a time: pass --warmup 0 --runs 1"); - } - Ok(Box::new(VictoriaMetricsEngine::new( - VictoriaMetricsServer { - url, - cgroup, - stream_aggregation_config: options.victoriametrics_stream_aggregation_config, - request_timeout: Duration::from_secs(600), - }, - )?)) + let mut engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { + url, + cgroup, + stream_aggregation_config: options.victoriametrics_stream_aggregation_config, + request_timeout: Duration::from_secs(600), + })?; + engine.runs_per_arm = protocol.warmup_runs + protocol.measured_runs; + Ok(Box::new(engine)) } diff --git a/system-bench/tests/end_to_end_adapters.rs b/system-bench/tests/end_to_end_adapters.rs index 49fb9667..579224c8 100644 --- a/system-bench/tests/end_to_end_adapters.rs +++ b/system-bench/tests/end_to_end_adapters.rs @@ -8,17 +8,19 @@ use aqpbm_core::harness::engine::{ ArmSpec, EngineUnderTest, QueryLanguage, QueryText, SampleChunk, SeriesLabels, WorkloadQuery, WorkloadSpec, }; +use aqpbm_core::harness::protocol::Protocol; use aqpbm_datagen::{DataDistribution, SeriesLabelSpec, TimeSeriesDescription, UniformParameter}; +use clap::Args; use prost::Message; use serde_json::json; use system_bench::engines_external::asapquery_backend_server::{ - AsapqueryBackendEngine, AsapqueryBackendServer, + self, AsapqueryBackendEngine, AsapqueryBackendOptions, AsapqueryBackendServer, }; use system_bench::engines_external::asapquery_precompute_engine_server::{ AsapqueryPrecomputeEngine, AsapqueryPrecomputeEngineServer, }; use system_bench::engines_external::victoriametrics_server::{ - VictoriaMetricsEngine, VictoriaMetricsServer, + self, VictoriaMetricsEngine, VictoriaMetricsOptions, VictoriaMetricsServer, }; use system_bench::prometheus_api::remote_write::WriteRequest; @@ -294,6 +296,75 @@ fn asapquery_backend_writes_closes_panes_and_asks_the_promql() { assert!(engine.install(&workload(), &query_text_arm()).is_err()); } +fn periodic_options(arguments: &[&str]) -> clap::ArgMatches { + O::augment_args(clap::Command::new("run")) + .try_get_matches_from(std::iter::once("run").chain(arguments.iter().copied())) + .unwrap() +} + +#[test] +fn repeated_runs_install_one_after_another_and_a_plan_file_runs_once() { + let (url, _) = recording_server(); + let group = std::env::temp_dir(); + let group = group.to_str().unwrap(); + let with_plan = ArmSpec { + engine_options: json!({ "plan_file": "p.plan.json" }), + ..query_text_arm() + }; + + let matches = periodic_options::(&[ + "--victoriametrics-url", + &url, + "--server-cgroup-directory", + group, + ]); + let engine = victoriametrics_server::periodic_queries(&matches, &Protocol::default()).unwrap(); + assert!(engine.holds_one_install_at_a_time()); + let refused = engine.install(&workload(), &with_plan).err().unwrap(); + assert!(refused.0.contains("--warmup 0 --runs 1"), "{}", refused.0); + drop(engine.install(&workload(), &query_text_arm()).unwrap()); + drop(engine.install(&workload(), &query_text_arm()).unwrap()); + + let without_restart = periodic_options::(&[ + "--asapquery-backend-url", + &url, + "--server-cgroup-directory", + group, + ]); + let refused = + asapquery_backend_server::periodic_queries(&without_restart, &Protocol::default()) + .err() + .unwrap(); + assert!( + refused + .to_string() + .contains("--asapquery-backend-restart-command"), + "{refused}" + ); + let restarted = std::env::temp_dir().join(format!( + "system-bench-asapquery-backend-restarted-{}", + std::process::id() + )); + let _ = std::fs::remove_file(&restarted); + let restart_command = format!("touch '{}'", restarted.display()); + let with_restart = periodic_options::(&[ + "--asapquery-backend-url", + &url, + "--server-cgroup-directory", + group, + "--asapquery-backend-restart-command", + &restart_command, + ]); + let engine = + asapquery_backend_server::periodic_queries(&with_restart, &Protocol::default()).unwrap(); + assert!(engine.holds_one_install_at_a_time()); + drop(engine.install(&workload(), &query_text_arm()).unwrap()); + assert!(!restarted.exists()); + drop(engine.install(&workload(), &query_text_arm()).unwrap()); + assert!(restarted.exists()); + let _ = std::fs::remove_file(&restarted); +} + #[test] fn two_answers_for_one_series_are_refused() { let (url, _) = recording_server(); From 4a03057793537c2a46318126adbad1dc4fed5e84 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:44:10 +0000 Subject: [PATCH 14/51] system-bench: planeval writes the samples it generated, on request planeval --samples-out PATH writes every generated series of the spec as one JSON line: its labels, sample times in ms and values. Without the flag nothing changes. The error injection in scripts/use_cases/ reads it to turn a rank error into a value with each window's samples. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- system-bench/src/bin/planeval.rs | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index 3a14e0d9..097208f7 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -1,11 +1,12 @@ -use std::path::PathBuf; +use std::io::Write; +use std::path::{Path, PathBuf}; use std::time::Instant; use anyhow::{Context, Result}; use clap::Parser; use aqpbm_usecase::accuracy::AnswerAt; -use aqpbm_usecase::data::generate; +use aqpbm_usecase::data::{generate, Series}; use aqpbm_usecase::output::{ PlanevalCost, PlanevalOutput, PlanevalQuery, PlannedQuery, UnsupportedQuery, OUTPUT_SCHEMA_VERSION, @@ -71,10 +72,32 @@ struct Args { )] data_root: PathBuf, + #[arg( + long, + help = "Also write every generated series to this file: one JSON line per series with its labels, sample times (ms) and values" + )] + samples_out: Option, + #[arg(long)] out: PathBuf, } +fn write_samples(path: &Path, series: &[Series]) -> Result<()> { + let file = + std::fs::File::create(path).with_context(|| format!("creating {}", path.display()))?; + let mut out = std::io::BufWriter::new(file); + for s in series { + let (times, values): (Vec, Vec) = s.points.iter().copied().unzip(); + serde_json::to_writer( + &mut out, + &serde_json::json!({"labels": s.labels, "times": times, "values": values}), + )?; + out.write_all(b"\n")?; + } + out.flush() + .with_context(|| format!("writing {}", path.display())) +} + #[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { let args = Args::parse(); @@ -95,6 +118,9 @@ async fn main() -> Result<()> { series.len(), generated.elapsed().as_secs_f64() ); + if let Some(path) = &args.samples_out { + write_samples(path, &series)?; + } let mut queries = Vec::new(); for query in &spec.queries { if !args.queries.is_empty() && !args.queries.contains(&query.id) { From fb6bbd74e037fc90e5e58c0f32cc467fdbd6c44a Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:44:10 +0000 Subject: [PATCH 15/51] scripts: inject error into a use case's exact answers and score every rule scripts/use_cases/inject_errors.py is an approximation source without a sketch: it takes the exact run's answers, adds error and hands them to the use case's derive functions, as an arm's answers. Sizes 0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.5 and 1 by default (--size); shapes high (always plus the size), low (always minus) and random (uniform in plus or minus the size per answer, seeds 1 to --seeds, default 5). Quantile queries (declared truth statistic quantile) move by rank: the answer becomes the sample that many ranks above or below it in its window, stopping at the window's smallest and largest sample; the other queries move by relative error. The exact run comes from planeval --samples-out, or from --exact and --samples. Each size, shape and seed is one run named uc-inject--[-seed] with the same rows as an arm, written to target/grafana-data/injected; its details carry the size, shape, seed and the measured rank and relative errors. uc-injected.csv lists every rule's agreement, and the script prints the smallest size at which each rule's decisions first differ from the exact ones, per shape. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/use_cases/inject_errors.py | 285 ++++++++++++++++++++++++ scripts/use_cases/test_inject_errors.py | 149 +++++++++++++ 2 files changed, 434 insertions(+) create mode 100644 scripts/use_cases/inject_errors.py create mode 100644 scripts/use_cases/test_inject_errors.py diff --git a/scripts/use_cases/inject_errors.py b/scripts/use_cases/inject_errors.py new file mode 100644 index 00000000..1f0fd22d --- /dev/null +++ b/scripts/use_cases/inject_errors.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 + +import argparse +import bisect +import csv +import json +import math +import os +import random +import sys +from array import array + +import bounds +import cases +import run_use_case as in_process +import scenario +from approx_rows import write_run + +REPO = in_process.REPO +SIZES = (0.001, 0.005, 0.01, 0.05, 0.1, 0.2, 0.5, 1.0) +HIGH, LOW, RANDOM = "high", "low", "random" +SHAPES = (HIGH, LOW, RANDOM) +DIRECTION = {HIGH: 1.0, LOW: -1.0} +SEEDS = 5 +KEPT = ("id", "promql", "unit", "threshold") + + +def quantile_queries(spec): + return {q["id"]: q for q in spec["queries"] + if isinstance((q.get("truth") or {}).get("statistic"), dict) and "quantile" in q["truth"]["statistic"]} + + +def selects(truth, labels): + return labels.get("__name__") == truth["metric"] and all( + labels.get(name, "") == value for name, value in (truth.get("matchers") or {}).items()) + + +def series_key(labels): + return tuple(sorted((k, v) for k, v in labels.items() if k != "__name__" and v != "")) + + +def read_samples(path, truths): + out = [] + with open(path) as f: + for line in f: + series = json.loads(line) + if any(selects(truth, series["labels"]) for truth in truths): + out.append(series) + return out + + +class Windows: + def __init__(self, samples, truth, window_ms): + self.width = window_ms + self.series = {series_key(s["labels"]): (s["times"], s["values"]) + for s in samples if selects(truth, s["labels"])} + + def sorted_at(self, time, labels): + found = self.series.get(series_key(labels)) + if found is None: + raise ValueError(f"no samples for series {dict(series_key(labels))}") + times, values = found + return sorted(values[bisect.bisect_right(times, time - self.width):bisect.bisect_right(times, time)]) + + +def shifted_by_rank(window, exact, error): + steps = math.floor(abs(error) * len(window)) + if steps == 0: + return exact + if error > 0: + return window[min(len(window) - 1, bisect.bisect_right(window, exact) + steps)] + return window[max(0, bisect.bisect_left(window, exact) - 1 - steps)] + + +def rank_distance(window, reference, estimate): + n = len(window) + if n == 0: + return 0.0 + return max(0.0, (bisect.bisect_left(window, estimate) - bisect.bisect_right(window, reference)) / n, + (bisect.bisect_left(window, reference) - bisect.bisect_right(window, estimate)) / n) + + +def shifted_by_ratio(exact, error): + return exact + abs(exact) * error + + +def scalar_error(truth, estimate): + absolute = abs(estimate - truth) + return {"truth": truth, "estimate": estimate, "absolute_error": absolute, + "relative_error": absolute / truth if truth > 0 else 0.0} + + +def injections_of(sizes, shapes, seeds): + out = [] + for shape in shapes: + for size in sizes: + if shape == RANDOM: + out += [(size, shape, seed) for seed in range(1, seeds + 1)] + else: + out.append((size, shape, None)) + return out + + +def arm_name(size, shape, seed): + name = f"inject-{shape}-{size:g}" + return name if seed is None else f"{name}-seed{seed}" + + +def inject(exact, windows, injections): + streams = {seed: random.Random(seed) for _, shape, seed in injections if shape == RANDOM} + values = [{} for _ in injections] + ranks = [{} for _ in injections] + for q in exact["queries"]: + found = windows.get(q["id"]) + for k in range(len(injections)): + values[k][q["id"]] = array("d") + if found is not None: + ranks[k][q["id"]] = array("d") + for a in q["answers"]: + draws = {seed: stream.uniform(-1.0, 1.0) for seed, stream in streams.items()} + window = found.sorted_at(a["time"], a["series"]) if found is not None else None + for k, (size, shape, seed) in enumerate(injections): + error = size * (draws[seed] if shape == RANDOM else DIRECTION[shape]) + if window is None: + values[k][q["id"]].append(shifted_by_ratio(a["value"], error)) + continue + value = shifted_by_rank(window, a["value"], error) + values[k][q["id"]].append(value) + ranks[k][q["id"]].append(rank_distance(window, a["value"], value)) + return values, ranks + + +def approx_document(exact, values, ranks, arm): + queries = [] + for q in exact["queries"]: + answers = [] + for n, a in enumerate(q["answers"]): + value = values[q["id"]][n] + scored = scalar_error(a["value"], value) + if q["id"] in ranks: + scored["rank_error"] = ranks[q["id"]][n] + answers.append({"time": a["time"], "series": a["series"], "value": value, "exact_plan": scored}) + queries.append({**{k: q[k] for k in KEPT if k in q}, "answers": answers}) + return {"use_case": exact["use_case"], "arm": arm, "queries": queries} + + +def max_rank_errors(errors): + out = {} + for r in errors: + query = r["labels"]["query"] + out[query] = max(out.get(query, 0.0), r["value"]) + return out + + +def write_injected(data, case, prefix, exact, approx, spec): + arm = approx["arm"] + run_id = f"{prefix}-{arm_name(arm['injected_error'], arm['shape'], arm['seed'])}" + use_case = exact["use_case"] + exact_by_id = {q["id"]: q for q in exact["queries"]} + rows, errors, relative = [], [], [] + for q in approx["queries"]: + signal = case["signal"](q["id"]) + rows += in_process.query_rows(run_id, use_case, signal, exact_by_id[q["id"]], q) + errors += in_process.rank_errors(run_id, use_case, signal, q) + relative += in_process.relative_errors(run_id, use_case, signal, q) + derived = case["derive"](rows, approx["queries"], bounds.PLAIN, None) + relative + errors + scored_rows, scored = scenario.derive(run_id, spec, case.get("scenario_entity"), derived, + case.get("signals", case["signal"])) + derived += scored_rows + details = { + "arm": arm, + "exact_plans": {q["id"]: in_process.describe_plan(q["plan"]) for q in exact["queries"] if "plan" in q}, + "promql": {q["id"]: q["promql"] for q in exact["queries"]}, + "planner_rev": exact.get("planner_rev"), + "process": {"exact": exact.get("process")}, + "dashboard": case["dashboard"], + "signals": {q["id"]: case.get("signals", case["signal"])(q["id"]) for q in exact["queries"]}, + "scenario": scored, + "max_relative_error": in_process.max_relative_errors(derived), + "max_rank_error": max_rank_errors(errors), + "fidelity": in_process.headlines(derived), + } + if "rules" in case: + details["rules"] = {name: rule["description"] for name, rule in case["rules"].items()} + details["signal_dashboards"] = {name: "rules" for name in case["rules"]} + for signal, by_arm in scored.items(): + if signal in details["fidelity"]: + details["fidelity"][signal]["fidelity"] += in_process.caught_text(by_arm) + if "stage2" in case: + details["stage2"] = case["stage2"](derived, errors) + write_run(data, run_id, use_case, rows + derived, details, case["split"]) + return run_id, details["fidelity"] + + +def first_changes(table, sizes): + out = {} + for r in table: + if r["agreement"] < 1: + key = (r["signal"], r["shape"]) + out[key] = min(out.get(key, math.inf), r["size"]) + signals = sorted({r["signal"] for r in table}) + shapes = [s for s in SHAPES if any(r["shape"] == s for r in table)] + lines = ["signal".ljust(24) + "".join(s.ljust(12) for s in shapes)] + for signal in signals: + lines.append(signal.ljust(24) + "".join( + (f"{out[(signal, s)]:g}" if (signal, s) in out else f"> {max(sizes):g}").ljust(12) for s in shapes)) + return out, "\n".join(lines) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description="Add error of chosen sizes and shapes to the exact answers of a use case, without any sketch, " + "and score each use case rule's decisions on them against the exact decisions" + ) + parser.add_argument("use_case", choices=sorted(in_process.USE_CASES)) + parser.add_argument("--binary", default=os.path.join(REPO, "target", "release", "planeval")) + parser.add_argument("--data", default=os.path.join(REPO, "target", "grafana-data", "injected")) + parser.add_argument("--raw-out", default=os.path.join(REPO, "target", "planeval")) + parser.add_argument("--size", type=float, action="append", + help="repeatable; error size: rank error for quantile queries, relative error for the " + f"others; default {', '.join(f'{s:g}' for s in SIZES)}") + parser.add_argument("--shape", action="append", choices=SHAPES, + help="repeatable; high always adds the size, low always subtracts it, random adds a size " + "drawn uniformly from minus to plus the size for each answer; default every shape") + parser.add_argument("--seeds", type=int, default=SEEDS, + help="random shape: runs with seeds 1 to this, each drawing its own errors") + parser.add_argument("--exact", help="planeval output of the exact run to inject into, instead of running " + "planeval") + parser.add_argument("--samples", help="with --exact: samples of the same spec written by planeval " + "--samples-out; needed when the use case has quantile queries") + args = parser.parse_args(argv) + sizes = args.size or list(SIZES) + if any(s < 0 for s in sizes): + parser.error("--size must not be negative") + if args.seeds < 1: + parser.error("--seeds must be at least 1") + case = in_process.USE_CASES[args.use_case] + prefix = f"uc{args.use_case}" + spec_path = os.path.join(cases.WORKLOADS, case["spec"]) + with open(spec_path) as f: + spec = json.load(f) + ranked = quantile_queries(spec) + if args.exact: + if ranked and not args.samples: + parser.error(f"use case {args.use_case} has quantile queries {sorted(ranked)}: give --samples") + with open(args.exact) as f: + exact = json.load(f) + samples_path = args.samples + else: + os.makedirs(args.raw_out, exist_ok=True) + samples_path = os.path.join(args.raw_out, f"{prefix}-samples.jsonl") if ranked else None + exact_out = os.path.join(args.raw_out, f"{prefix}-injected-exact.json") + exact = in_process.run_binary(args.binary, spec_path, exact_out, case.get("planeval_flags", []) + + (["--samples-out", samples_path] if samples_path else [])) + for q in exact["queries"]: + if "unsupported" in q: + sys.exit(f"the exact plan of {q['id']} is unsupported: {q['unsupported']}") + samples = read_samples(samples_path, [q["truth"] for q in ranked.values()]) if ranked else [] + windows = {query: Windows(samples, q["truth"], q["window_ms"]) for query, q in ranked.items()} + injections = injections_of(sizes, args.shape or SHAPES, args.seeds) + values, ranks = inject(exact, windows, injections) + del samples, windows + table = [] + for k, (size, shape, seed) in enumerate(injections): + arm = {"injected_error": size, "shape": shape, "seed": seed, + "error_metric": {q["id"]: "rank" if q["id"] in ranked else "relative" for q in exact["queries"]}} + run_id, fidelity = write_injected(args.data, case, prefix, exact, + approx_document(exact, values[k], ranks[k], arm), spec) + values[k] = ranks[k] = None + for signal, found in sorted(fidelity.items()): + table.append({"run_id": run_id, "signal": signal, "application": found["application"], "shape": shape, + "size": size, "seed": "" if seed is None else seed, "agreement": found["agreement"]}) + print(f"{run_id}: written", file=sys.stderr) + out = os.path.join(args.data, f"{prefix}-injected.csv") + with open(out, "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=list(table[0])) + writer.writeheader() + writer.writerows(table) + _, text = first_changes(table, sizes) + print(f"smallest injected error at which a decision differs from the exact one ({out}):") + print(text) + + +if __name__ == "__main__": + main() diff --git a/scripts/use_cases/test_inject_errors.py b/scripts/use_cases/test_inject_errors.py new file mode 100644 index 00000000..a1b97584 --- /dev/null +++ b/scripts/use_cases/test_inject_errors.py @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 + +import json +import os +import tempfile +import unittest + +import inject_errors +from approx_rows import read_index +from cases import uc4_canary_release +from inject_errors import (HIGH, LOW, RANDOM, Windows, approx_document, first_changes, inject, injections_of, + rank_distance, shifted_by_rank, write_injected) +from run_use_case import USE_CASES + +WINDOW = [float(v) for v in range(100)] + + +class RankShiftTest(unittest.TestCase): + def test_moves_the_answer_by_the_error_in_ranks(self): + self.assertEqual(shifted_by_rank(WINDOW, 50.0, 0.05), 56.0) + self.assertEqual(shifted_by_rank(WINDOW, 50.0, -0.05), 44.0) + self.assertEqual(rank_distance(WINDOW, 50.0, 56.0), 0.05) + self.assertEqual(rank_distance(WINDOW, 50.0, 44.0), 0.05) + + def test_an_answer_between_samples_moves_from_its_neighbours(self): + self.assertEqual(shifted_by_rank(WINDOW, 50.5, 0.02), 53.0) + self.assertEqual(rank_distance(WINDOW, 50.5, 53.0), 0.02) + + def test_less_than_one_sample_keeps_the_answer(self): + self.assertEqual(shifted_by_rank(WINDOW, 50.0, 0.009), 50.0) + self.assertEqual(shifted_by_rank(WINDOW, 50.0, 0.0), 50.0) + + def test_stops_at_the_smallest_and_largest_sample(self): + self.assertEqual(shifted_by_rank(WINDOW, 99.0 * 0.99, 1.0), 99.0) + self.assertEqual(shifted_by_rank(WINDOW, 1.0, -0.5), 0.0) + + +def answers(values, start=60_000): + return [{"time": start + i * 60_000, "series": {"version": "canary"}, "value": v} for i, v in enumerate(values)] + + +def exact_document(): + queries = {"p99_canary": [0.3] * 70 + [0.45] * 30, "p95_canary": [0.2] * 100, + "p99_stable": [0.29] * 100, "success_rate_canary": [0.999] * 80 + [0.98] * 20} + return {"use_case": "canary_release", "planner_rev": "r", + "queries": [{"id": q, "promql": q, "unit": "s", "threshold": None, "answers": answers(v)} + for q, v in queries.items()]} + + +def samples(): + return [{"labels": {"__name__": "request_latency", "version": "canary"}, + "times": list(range(0, 6_060_000, 600)), "values": [(i % 100) / 200 for i in range(10_100)]}] + + +def spec(): + truth = {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "canary"}} + return {"use_case": "canary_release", "metrics": [], + "queries": [{"id": "p99_canary", "window_ms": 300_000, "truth": truth}]} + + +class InjectTest(unittest.TestCase): + def windows(self): + q = spec()["queries"][0] + return {"p99_canary": Windows(samples(), q["truth"], q["window_ms"])} + + def test_size_zero_gives_the_exact_answers_in_every_shape(self): + exact = exact_document() + injections = injections_of([0.0], (HIGH, LOW, RANDOM), 2) + values, ranks = inject(exact, self.windows(), injections) + for k in range(len(injections)): + for q in exact["queries"]: + self.assertEqual(list(values[k][q["id"]]), [a["value"] for a in q["answers"]]) + self.assertEqual(set(ranks[k]["p99_canary"]), {0.0}) + + def test_shapes_and_seeds(self): + exact = exact_document() + injections = injections_of([0.1], (HIGH, LOW, RANDOM), 2) + self.assertEqual(injections, [(0.1, HIGH, None), (0.1, LOW, None), (0.1, RANDOM, 1), (0.1, RANDOM, 2)]) + values, ranks = inject(exact, self.windows(), injections) + rate = [a["value"] for a in exact["queries"][3]["answers"]] + self.assertEqual(list(values[0]["success_rate_canary"]), [v * 1.1 for v in rate]) + self.assertEqual(list(values[1]["success_rate_canary"]), [v * 0.9 for v in rate]) + for k in (2, 3): + self.assertTrue(all(abs(v / e - 1) <= 0.1 for v, e in zip(values[k]["success_rate_canary"], rate))) + self.assertTrue(all(r <= 0.1 for r in ranks[k]["p99_canary"])) + self.assertNotEqual(list(values[2]["success_rate_canary"]), list(values[3]["success_rate_canary"])) + again, _ = inject(exact, self.windows(), injections) + self.assertEqual(list(again[2]["success_rate_canary"]), list(values[2]["success_rate_canary"])) + p99 = [a["value"] for a in exact["queries"][0]["answers"]] + self.assertTrue(all(h > e > low for h, e, low in zip(values[0]["p99_canary"], p99, values[1]["p99_canary"]))) + + def test_a_series_without_samples_is_an_error(self): + exact = exact_document() + exact["queries"][0]["answers"][0]["series"] = {"version": "stable"} + with self.assertRaises(ValueError): + inject(exact, self.windows(), injections_of([0.1], (HIGH,), 1)) + + +class WriteTest(unittest.TestCase): + def run_size(self, size, shape): + exact = exact_document() + injections = injections_of([size], (shape,), 1) + values, ranks = inject(exact, InjectTest.windows(self), injections) + arm = {"injected_error": size, "shape": shape, "seed": injections[0][2]} + with tempfile.TemporaryDirectory() as data: + run_id, fidelity = write_injected(data, USE_CASES["4"], "uc4", exact, + approx_document(exact, values[0], ranks[0], arm), spec()) + (entry,) = read_index(data) + return run_id, fidelity, entry + + def test_error_zero_agrees_with_every_exact_decision(self): + run_id, fidelity, entry = self.run_size(0.0, HIGH) + self.assertEqual(run_id, "uc4-inject-high-0") + self.assertEqual(set(fidelity), set(uc4_canary_release.RULES)) + self.assertEqual({signal: found["agreement"] for signal, found in fidelity.items()}, + {signal: 1.0 for signal in uc4_canary_release.RULES}) + self.assertEqual(entry["details"]["max_rank_error"], {"p99_canary": 0.0}) + + def test_a_large_error_changes_a_decision(self): + run_id, fidelity, entry = self.run_size(0.5, LOW) + self.assertEqual(run_id, "uc4-inject-low-0.5") + self.assertLess(fidelity["argo_rollouts"]["agreement"], 1.0) + self.assertEqual(entry["details"]["arm"]["shape"], LOW) + + +class FirstChangesTest(unittest.TestCase): + def test_smallest_size_with_any_disagreement(self): + table = [{"signal": "a", "shape": RANDOM, "size": s, "agreement": g} + for s, g in ((0.01, 1.0), (0.1, 0.9), (0.05, 0.95))] + table += [{"signal": "a", "shape": HIGH, "size": 0.5, "agreement": 1.0}] + found, text = first_changes(table, [0.01, 0.05, 0.1, 0.5]) + self.assertEqual(found, {("a", RANDOM): 0.05}) + self.assertIn("> 0.5", text) + + +class ReadSamplesTest(unittest.TestCase): + def test_keeps_the_series_a_quantile_query_reads(self): + with tempfile.TemporaryDirectory() as tmp: + samples_path = os.path.join(tmp, "samples.jsonl") + with open(samples_path, "w") as f: + for series in samples() + [{"labels": {"__name__": "requests", "code": "200"}, "times": [0], + "values": [1.0]}]: + f.write(json.dumps(series) + "\n") + loaded = inject_errors.read_samples(samples_path, [spec()["queries"][0]["truth"]]) + self.assertEqual(len(loaded), 1) + + +if __name__ == "__main__": + unittest.main() From c480d712d306c212a7c534f12cd89aa84ee4781e Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:54:40 +0000 Subject: [PATCH 16/51] scripts: use case 4's rule parameters from outside, and a sweep over them rollout.py's thresholds and counts stay module constants, and each check and decide function takes them as keyword arguments that default to the constants. rule_set(changed) builds the five rules from PARAMETERS with some of them changed, and RULES = rule_set(). scaled(threshold, count) gives the changed parameters for one pair of multipliers: a threshold multiplier scales each threshold's distance from where a check surely passes (tolerance from 1, success rates from 1, the p99 and p95 limits from 0 s); a count multiplier scales the failed checks each rule rolls back after (streak, Flagger's failure threshold, Argo Rollouts' failure limit, CloudWatch's M and the last N it counts them in), rounded half up and at least 1. scripts/use_cases/sweep_rollout_parameters.py scores use case 4's arms again for each pair, thresholds 0.8, 0.9, 1, 1.1, 1.25 by counts 0.5, 1, 2 by default, from the planeval outputs run_use_case.py 4 wrote, so every pair scores the same answers. Each pair is a run named -thresholdx-countx with the rule parameters in its details, written to target/grafana-data/rollout-parameters; the pair 1, 1 keeps the arm's own run name and writes the same rows and details as run_use_case.py, except details.process, which stays empty since no planeval runs. uc4-rollout-parameters.csv lists every rule's agreement. write_arm takes extra_details, merged into the run's details. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- scripts/use_cases/cases/uc4_canary_release.py | 8 +- scripts/use_cases/rollout.py | 121 +++++++++----- scripts/use_cases/run_use_case.py | 4 +- scripts/use_cases/sweep_rollout_parameters.py | 150 ++++++++++++++++++ scripts/use_cases/test_rollout.py | 36 ++++- .../test_sweep_rollout_parameters.py | 79 +++++++++ 6 files changed, 352 insertions(+), 46 deletions(-) create mode 100644 scripts/use_cases/sweep_rollout_parameters.py create mode 100644 scripts/use_cases/test_sweep_rollout_parameters.py diff --git a/scripts/use_cases/cases/uc4_canary_release.py b/scripts/use_cases/cases/uc4_canary_release.py index a5a77fa0..c9be395e 100644 --- a/scripts/use_cases/cases/uc4_canary_release.py +++ b/scripts/use_cases/cases/uc4_canary_release.py @@ -8,15 +8,15 @@ QUERY_COLORS = {"p99_canary": "orange", "p99_stable": "blue", "success_rate_canary": "green", "p95_canary": "purple"} -def derive(rows, queries, policy=bounds.PLAIN, widen=None): - return rollout.derive(rows, RULES, policy, widen) +def derive(rows, queries, policy=bounds.PLAIN, widen=None, rules=RULES, tolerance=rollout.TOLERANCE): + return rollout.derive(rows, rules, policy, widen, tolerance) -def stage2(derived, errors): +def stage2(derived, errors, rules=RULES): ranked = {r["labels"]["query"] for r in errors} relative = [r for r in derived if r["kind"] == "low_level" and r["metric"] == "relative_error" and r["labels"]["query"] not in ranked] - return rollout.rollout_errors(derived, errors + relative, RULES) + return rollout.rollout_errors(derived, errors + relative, rules) DASHBOARD = {"uid": "canary-release", "title": "4 · Canary release", "figure": "uc4-canary-release.svg", diff --git a/scripts/use_cases/rollout.py b/scripts/use_cases/rollout.py index 31486b01..842b514e 100644 --- a/scripts/use_cases/rollout.py +++ b/scripts/use_cases/rollout.py @@ -1,5 +1,8 @@ #!/usr/bin/env python3 +import math +from functools import partial + from approx_rows import row from bounds import PLAIN, any_of, ge, gt, judge, lt, point, ratio, widen_values from threshold_alert import EVENT_LABELS, NOTHING, annotations, cells_of, delay_summary, episodes_of, series @@ -13,26 +16,38 @@ ARGO_ROLLOUTS_MIN_SUCCESS_RATE, ARGO_ROLLOUTS_INTERVAL, ARGO_ROLLOUTS_COUNT, FAILURE_LIMIT = 0.95, 5, 10, 3 CLOUDWATCH_CHECKS, BREACHING_POINTS, EVALUATED_POINTS = 10, 4, 5 KEPTN_INTERVAL, KEPTN_RELATIVE, KEPTN_MAX_P95, KEPTN_PASSING = 10, 1.1, 0.6, 3 - - -def slower(p99_canary, p99_stable): - return [gt(ratio(c, s), TOLERANCE) for c, s in zip(p99_canary, p99_stable)] - - -def flagger_failed(p99_canary, success_rate_canary): - return [any_of(gt(p, MAX_P99), lt(s, FLAGGER_MIN_SUCCESS_RATE)) +PARAMETERS = {"checks": CHECKS, "streak": STREAK, "tolerance": TOLERANCE, "max_p99": MAX_P99, + "flagger_min_success_rate": FLAGGER_MIN_SUCCESS_RATE, "failure_threshold": FAILURE_THRESHOLD, + "passes_to_promote": PASSES_TO_PROMOTE, + "argo_rollouts_min_success_rate": ARGO_ROLLOUTS_MIN_SUCCESS_RATE, + "argo_rollouts_interval": ARGO_ROLLOUTS_INTERVAL, "argo_rollouts_count": ARGO_ROLLOUTS_COUNT, + "failure_limit": FAILURE_LIMIT, "cloudwatch_checks": CLOUDWATCH_CHECKS, + "breaching_points": BREACHING_POINTS, "evaluated_points": EVALUATED_POINTS, + "keptn_interval": KEPTN_INTERVAL, "keptn_relative": KEPTN_RELATIVE, "keptn_max_p95": KEPTN_MAX_P95, + "keptn_passing": KEPTN_PASSING} +NOT_FAILING = {"tolerance": 1.0, "max_p99": 0.0, "flagger_min_success_rate": 1.0, + "argo_rollouts_min_success_rate": 1.0, "keptn_relative": 1.0, "keptn_max_p95": 0.0} +FAILURE_COUNTS = ("streak", "failure_threshold", "failure_limit", "breaching_points", "evaluated_points") + + +def slower(p99_canary, p99_stable, tolerance=TOLERANCE): + return [gt(ratio(c, s), tolerance) for c, s in zip(p99_canary, p99_stable)] + + +def flagger_failed(p99_canary, success_rate_canary, max_p99=MAX_P99, min_success_rate=FLAGGER_MIN_SUCCESS_RATE): + return [any_of(gt(p, max_p99), lt(s, min_success_rate)) for p, s in zip(p99_canary, success_rate_canary)] -def argo_rollouts_failed(success_rate_canary): - return [lt(s, ARGO_ROLLOUTS_MIN_SUCCESS_RATE) for s in success_rate_canary] +def argo_rollouts_failed(success_rate_canary, min_success_rate=ARGO_ROLLOUTS_MIN_SUCCESS_RATE): + return [lt(s, min_success_rate) for s in success_rate_canary] -def cloudwatch_breaching(p99_canary): - return [gt(p, MAX_P99) for p in p99_canary] +def cloudwatch_breaching(p99_canary, max_p99=MAX_P99): + return [gt(p, max_p99) for p in p99_canary] -def keptn_failed(p95_canary): +def keptn_failed(p95_canary, factor=KEPTN_RELATIVE, max_p95=KEPTN_MAX_P95, baseline_size=KEPTN_PASSING): """Keptn's objective: p95 at most 10% above the average of the last 3 passing evaluations, and below 600 ms. Only a passing evaluation joins the baseline; an unsure one does not. The first evaluation has no baseline @@ -40,9 +55,9 @@ def keptn_failed(p95_canary): """ out, passing = [], [] for p in p95_canary: - baseline = sum(passing[-KEPTN_PASSING:]) / len(passing[-KEPTN_PASSING:]) if passing else None - relative = gt(p, KEPTN_RELATIVE * baseline) if baseline is not None else False - failed = any_of(relative, ge(p, KEPTN_MAX_P95)) + baseline = sum(passing[-baseline_size:]) / len(passing[-baseline_size:]) if passing else None + relative = gt(p, factor * baseline) if baseline is not None else False + failed = any_of(relative, ge(p, max_p95)) if failed is False: passing.append(point(p)) out.append(failed) @@ -53,55 +68,83 @@ def each_check(failed): return 0, ROLLBACK if failed[0] else PROMOTE -def in_a_row(failed): +def in_a_row(failed, streak=STREAK): run = 0 for i, f in enumerate(failed): run = run + 1 if f else 0 - if run == STREAK: + if run == streak: return i, ROLLBACK return len(failed) - 1, PROMOTE -def failures_or_passes(failed): +def failures_or_passes(failed, failure_threshold=FAILURE_THRESHOLD, passes_to_promote=PASSES_TO_PROMOTE): failures = passes = 0 for i, f in enumerate(failed): failures += f passes += not f - if failures == FAILURE_THRESHOLD: + if failures == failure_threshold: return i, ROLLBACK - if passes == PASSES_TO_PROMOTE: + if passes == passes_to_promote: return i, PROMOTE return len(failed) - 1, PROMOTE -def failures_over_limit(failed): +def failures_over_limit(failed, failure_limit=FAILURE_LIMIT): failures = 0 for i, f in enumerate(failed): failures += f - if failures > FAILURE_LIMIT: + if failures > failure_limit: return i, ROLLBACK return len(failed) - 1, PROMOTE -def m_of_last_n(failed): +def m_of_last_n(failed, breaching_points=BREACHING_POINTS, evaluated_points=EVALUATED_POINTS): for i in range(len(failed)): - if sum(failed[max(0, i - EVALUATED_POINTS + 1):i + 1]) >= BREACHING_POINTS: + if sum(failed[max(0, i - evaluated_points + 1):i + 1]) >= breaching_points: return i, ROLLBACK return len(failed) - 1, PROMOTE -RULES = { - "ours": {"queries": ("p99_canary", "p99_stable"), "check": slower, "every": 1, "checks": CHECKS, - "decide": in_a_row}, - "flagger": {"queries": ("p99_canary", "success_rate_canary"), "check": flagger_failed, "every": 1, - "checks": FAILURE_THRESHOLD - 1 + PASSES_TO_PROMOTE, "decide": failures_or_passes}, - "argo_rollouts": {"queries": ("success_rate_canary",), "check": argo_rollouts_failed, - "every": ARGO_ROLLOUTS_INTERVAL, "checks": ARGO_ROLLOUTS_COUNT, "decide": failures_over_limit}, - "cloudwatch": {"queries": ("p99_canary",), "check": cloudwatch_breaching, "every": 1, - "checks": CLOUDWATCH_CHECKS, "decide": m_of_last_n}, - "keptn": {"queries": ("p95_canary",), "check": keptn_failed, "every": KEPTN_INTERVAL, "checks": 1, - "decide": each_check}, -} +def rule_set(changed=None): + unknown = set(changed or {}) - set(PARAMETERS) + if unknown: + raise ValueError(f"no rule parameters {sorted(unknown)}; they are {sorted(PARAMETERS)}") + p = {**PARAMETERS, **(changed or {})} + return { + "ours": {"queries": ("p99_canary", "p99_stable"), "check": partial(slower, tolerance=p["tolerance"]), + "every": 1, "checks": p["checks"], "decide": partial(in_a_row, streak=p["streak"])}, + "flagger": {"queries": ("p99_canary", "success_rate_canary"), + "check": partial(flagger_failed, max_p99=p["max_p99"], + min_success_rate=p["flagger_min_success_rate"]), + "every": 1, "checks": p["failure_threshold"] - 1 + p["passes_to_promote"], + "decide": partial(failures_or_passes, failure_threshold=p["failure_threshold"], + passes_to_promote=p["passes_to_promote"])}, + "argo_rollouts": {"queries": ("success_rate_canary",), + "check": partial(argo_rollouts_failed, min_success_rate=p["argo_rollouts_min_success_rate"]), + "every": p["argo_rollouts_interval"], "checks": p["argo_rollouts_count"], + "decide": partial(failures_over_limit, failure_limit=p["failure_limit"])}, + "cloudwatch": {"queries": ("p99_canary",), "check": partial(cloudwatch_breaching, max_p99=p["max_p99"]), + "every": 1, "checks": p["cloudwatch_checks"], + "decide": partial(m_of_last_n, breaching_points=p["breaching_points"], + evaluated_points=p["evaluated_points"])}, + "keptn": {"queries": ("p95_canary",), + "check": partial(keptn_failed, factor=p["keptn_relative"], max_p95=p["keptn_max_p95"], + baseline_size=p["keptn_passing"]), + "every": p["keptn_interval"], "checks": 1, "decide": each_check}, + } + + +RULES = rule_set() + + +def scaled(threshold=1.0, count=1.0): + out = {} + for name, passing in NOT_FAILING.items(): + out[name] = PARAMETERS[name] if threshold == 1 else round( + passing + (PARAMETERS[name] - passing) * threshold, 12) + for name in FAILURE_COUNTS: + out[name] = PARAMETERS[name] if count == 1 else max(1, math.floor(PARAMETERS[name] * count + 0.5)) + return out def decisions_of(failed, checks=CHECKS, decide=in_a_row): @@ -146,7 +189,7 @@ def actions(length, decided, arm): return out -def derive(query_rows, rules=RULES, policy=PLAIN, widen=None): +def derive(query_rows, rules=RULES, policy=PLAIN, widen=None, tolerance=TOLERANCE): if any(r["kind"] != "query_result" for r in query_rows): raise ValueError("derive reads query_result rows only") run_ids = {r["run_id"] for r in query_rows} @@ -168,7 +211,7 @@ def derive(query_rows, rules=RULES, policy=PLAIN, widen=None): for arm, by_query in values.items(): out.append(row(t, "app_state", run_id, {**app, "arm": arm}, "ratio", point(by_query["p99_canary"][n]) / point(by_query["p99_stable"][n]), "ratio")) - out.append(row(t, "app_state", run_id, app, "tolerance", TOLERANCE, "ratio")) + out.append(row(t, "app_state", run_id, app, "tolerance", tolerance, "ratio")) for name, rule in rules.items(): out += rule_rows(run_id, {**app, "signal": name}, rule, times, values, policy) return out diff --git a/scripts/use_cases/run_use_case.py b/scripts/use_cases/run_use_case.py index bfb37c45..019cbd14 100644 --- a/scripts/use_cases/run_use_case.py +++ b/scripts/use_cases/run_use_case.py @@ -280,7 +280,8 @@ def caught_text(by_arm): f"{arm} {by_arm[arm]['caught']} of {by_arm[arm]['incidents']}" for arm in ("exact", "approx") if arm in by_arm) -def write_arm(data, case, prefix, arm, exact, approx, trial=1, policy=bounds.PLAIN, widen=None, spec=None): +def write_arm(data, case, prefix, arm, exact, approx, trial=1, policy=bounds.PLAIN, widen=None, spec=None, + extra_details=None): run_id = run_name(prefix, arm, trial, policy) use_case = exact["use_case"] exact_by_id = {q["id"]: q for q in exact["queries"]} @@ -333,6 +334,7 @@ def write_arm(data, case, prefix, arm, exact, approx, trial=1, policy=bounds.PLA details["stage1"] = [stage1(approx["arm"], exact_by_id[q["id"]], q, derived) for q in planned] if "stage2" in case: details["stage2"] = case["stage2"](derived, errors) + details.update(extra_details or {}) write_run(data, run_id, use_case, rows + derived + costs, details, case["split"]) print(f"{run_id}: {len(plans)} queries, {len(unsupported)} unsupported", file=sys.stderr) diff --git a/scripts/use_cases/sweep_rollout_parameters.py b/scripts/use_cases/sweep_rollout_parameters.py new file mode 100644 index 00000000..c4722b89 --- /dev/null +++ b/scripts/use_cases/sweep_rollout_parameters.py @@ -0,0 +1,150 @@ +#!/usr/bin/env python3 + +import argparse +import csv +import json +import os +import sys +from functools import partial + +import bounds +import cases +import rollout +import run_use_case as in_process +from approx_rows import read_index +from cases import uc4_canary_release as uc4 + +REPO = in_process.REPO +USE_CASE = uc4.ID +PREFIX = f"uc{USE_CASE}" +THRESHOLDS = (0.8, 0.9, 1.0, 1.1, 1.25) +COUNTS = (0.5, 1.0, 2.0) + + +def parameter_suffix(threshold, count): + return "" if threshold == 1 and count == 1 else f"-threshold{threshold:g}x-count{count:g}x" + + +def swept_case(case, changed): + rules = rollout.rule_set(changed) + tolerance = changed.get("tolerance", rollout.TOLERANCE) + return {**case, "derive": partial(case["derive"], rules=rules, tolerance=tolerance), + "stage2": partial(case["stage2"], rules=rules)} + + +def raw_path(raw_out, arm, trial): + return os.path.join(raw_out, f"{PREFIX}-{arm if trial == 1 else f'{arm}-trial{trial}'}.json") + + +def read(path): + with open(path) as f: + return json.load(f) + + +def sweep(data, case, exact, approx, arm, trial, policies, groups, spec): + max_error = in_process.max_error_of(arm) + widen = bounds.Widen(approx, max_error) if max_error is not None else None + written = [] + for policy in policies: + if policy != bounds.PLAIN and not (widen and widen.bounded_queries()): + print(f"{in_process.run_name(PREFIX, arm, trial, policy)}: no plan has an error bound; not written", + file=sys.stderr) + continue + for threshold, count in groups: + changed = rollout.scaled(threshold, count) + label = arm + parameter_suffix(threshold, count) + extra = None if threshold == 1 and count == 1 else { + "rule_parameters": changed, "rule_multipliers": {"threshold": threshold, "count": count}} + in_process.write_arm(data, swept_case(case, changed), PREFIX, label, exact, approx, trial, policy, + widen if policy != bounds.PLAIN else None, spec, extra) + written.append({"run_id": in_process.run_name(PREFIX, label, trial, policy), "arm": arm, + "trial": trial, "policy": policy, "threshold": threshold, "count": count}) + return written + + +def agreement_table(data, written): + fidelity = {e["run_id"]: e["details"]["fidelity"] for e in read_index(data)} + table = [] + for w in written: + for signal, found in sorted(fidelity.get(w["run_id"], {}).items()): + table.append({**w, "rule": signal, "agreement": found["agreement"]}) + return table + + +def grid_text(table, thresholds, counts): + lines = [] + for run in sorted({(r["arm"], r["trial"], r["policy"]) for r in table}): + at = {(r["rule"], r["threshold"], r["count"]): r["agreement"] for r in table + if (r["arm"], r["trial"], r["policy"]) == run} + lines.append(f"{run[0]} trial {run[1]} {run[2]}: agreement at count x " + "/".join(f"{c:g}" for c in counts)) + lines.append(" rule".ljust(16) + "".join(f"threshold x{t:g}".ljust(18) for t in thresholds)) + for rule in sorted({key[0] for key in at}): + lines.append(f" {rule}".ljust(16) + "".join( + "/".join(f"{at[(rule, t, c)]:.2f}" if (rule, t, c) in at else "-" for c in counts).ljust(18) + for t in thresholds)) + return "\n".join(lines) + + +def main(argv=None): + parser = argparse.ArgumentParser( + description=f"Score use case {USE_CASE}'s approximate arms again for each set of rule parameters: every " + "rule's check thresholds and failure counts scaled by a multiplier, on the planeval outputs " + f"run_use_case.py {USE_CASE} wrote, so every set scores the same answers" + ) + parser.add_argument("--raw-out", default=os.path.join(REPO, "target", "planeval"), + help=f"where run_use_case.py {USE_CASE} wrote {PREFIX}-exact.json and one output per arm") + parser.add_argument("--data", default=os.path.join(REPO, "target", "grafana-data", "rollout-parameters")) + parser.add_argument("--arm", action="append", + help=f"repeatable; default every arm of use case {USE_CASE} with an output in --raw-out") + parser.add_argument("--trials", type=int, default=1, + help="trials of each arm to score, as run_use_case.py --trials wrote them") + parser.add_argument("--policy", action="append", choices=bounds.POLICIES, + help="repeatable; default every policy an arm's output supports") + parser.add_argument("--threshold", type=float, action="append", + help="repeatable; multiplier on each threshold's distance from where a check surely " + f"passes: tolerance 1 + {rollout.TOLERANCE - 1:g} x, success rate 1 - " + f"{1 - rollout.FLAGGER_MIN_SUCCESS_RATE:g} x, p99 limit {rollout.MAX_P99:g} s x; " + f"default {', '.join(f'{t:g}' for t in THRESHOLDS)}") + parser.add_argument("--count", type=float, action="append", + help="repeatable; multiplier on the failed checks each rule rolls back after (CloudWatch's " + "M and the N it counts them in), rounded half up and at least 1; default " + f"{', '.join(f'{c:g}' for c in COUNTS)}") + args = parser.parse_args(argv) + if any(t <= 0 for t in args.threshold or []) or any(c <= 0 for c in args.count or []): + parser.error("multipliers must be positive") + case = in_process.USE_CASES[USE_CASE] + exact_path = os.path.join(args.raw_out, f"{PREFIX}-exact.json") + if not os.path.exists(exact_path): + parser.error(f"no {exact_path}: run run_use_case.py {USE_CASE} first") + arms = args.arm or [arm for arm in case["arms"] if os.path.exists(raw_path(args.raw_out, arm, 1))] + for arm in arms: + if arm not in case["arms"]: + parser.error(f"arm {arm} is not one of {case['arms']}") + for trial in range(1, args.trials + 1): + if not os.path.exists(raw_path(args.raw_out, arm, trial)): + parser.error(f"no {raw_path(args.raw_out, arm, trial)}: run run_use_case.py {USE_CASE} first") + if not arms: + parser.error(f"no arm of use case {USE_CASE} has an output in {args.raw_out}") + with open(os.path.join(cases.WORKLOADS, case["spec"])) as f: + spec = json.load(f) + exact = read(exact_path) + thresholds, counts = args.threshold or list(THRESHOLDS), args.count or list(COUNTS) + groups = [(t, c) for t in thresholds for c in counts] + written = [] + for arm in arms: + for trial in range(1, args.trials + 1): + written += sweep(args.data, case, exact, read(raw_path(args.raw_out, arm, trial)), arm, trial, + args.policy or bounds.POLICIES, groups, spec) + table = agreement_table(args.data, written) + out = os.path.join(args.data, f"{PREFIX}-rollout-parameters.csv") + with open(out, "w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=["run_id", "arm", "trial", "policy", "threshold", "count", "rule", + "agreement"]) + writer.writeheader() + writer.writerows(table) + print(f"decision agreement of approx with exact ({out}):") + print(grid_text(table, thresholds, counts)) + + +if __name__ == "__main__": + main() diff --git a/scripts/use_cases/test_rollout.py b/scripts/use_cases/test_rollout.py index 63d982d1..f8ce474e 100644 --- a/scripts/use_cases/test_rollout.py +++ b/scripts/use_cases/test_rollout.py @@ -4,8 +4,9 @@ from approx_rows import row from bounds import Bounded -from rollout import (PROMOTE, ROLLBACK, RULES, argo_rollouts_failed, cloudwatch_breaching, decisions_of, derive, - failures_or_passes, failures_over_limit, flagger_failed, keptn_failed, m_of_last_n, rollouts) +from rollout import (PARAMETERS, PROMOTE, ROLLBACK, RULES, argo_rollouts_failed, cloudwatch_breaching, decisions_of, + derive, failures_or_passes, failures_over_limit, flagger_failed, keptn_failed, m_of_last_n, + rollouts, rule_set, scaled) def flags(bits): @@ -138,5 +139,36 @@ def test_an_unsure_evaluation_stays_out_of_the_baseline(self): self.assertEqual(out, [False, None, True]) +class ParametersTest(unittest.TestCase): + def test_multipliers_of_one_keep_every_constant(self): + self.assertEqual(scaled(1, 1), {name: PARAMETERS[name] for name in scaled(1, 1)}) + self.assertEqual(rule_set(scaled(1, 1))["flagger"]["checks"], RULES["flagger"]["checks"]) + + def test_thresholds_scale_their_distance_from_passing_and_counts_round_half_up(self): + self.assertEqual(scaled(0.8, 2), { + "tolerance": 1.08, "max_p99": 0.4, "flagger_min_success_rate": 0.992, + "argo_rollouts_min_success_rate": 0.96, "keptn_relative": 1.08, "keptn_max_p95": 0.48, + "streak": 6, "failure_threshold": 20, "failure_limit": 6, "breaching_points": 8, "evaluated_points": 10}) + half = scaled(1.25, 0.5) + self.assertEqual((half["tolerance"], half["flagger_min_success_rate"], half["max_p99"]), (1.125, 0.9875, 0.625)) + self.assertEqual([half[n] for n in ("streak", "failure_threshold", "failure_limit", "breaching_points", + "evaluated_points")], [2, 5, 2, 2, 3]) + self.assertEqual(scaled(1, 0.1)["streak"], 1) + + def test_rules_follow_their_parameters(self): + self.assertEqual(RULES["ours"]["check"]([1.2], [1.0]), [True]) + self.assertEqual(rule_set({"tolerance": 1.3})["ours"]["check"]([1.2], [1.0]), [False]) + rules = rule_set(scaled(1, 2)) + self.assertEqual(rules["flagger"]["checks"], 20 - 1 + 25) + self.assertEqual(rules["cloudwatch"]["decide"](flags("1101100000")), (9, PROMOTE)) + self.assertEqual(rules["argo_rollouts"]["decide"](flags("1010101000")), (9, PROMOTE)) + self.assertEqual(rules["keptn"]["check"]([0.65]), [True]) + self.assertEqual(rule_set(scaled(1.25, 1))["keptn"]["check"]([0.7]), [False]) + + def test_unknown_parameter(self): + with self.assertRaises(ValueError): + rule_set({"tolerence": 1.2}) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/use_cases/test_sweep_rollout_parameters.py b/scripts/use_cases/test_sweep_rollout_parameters.py new file mode 100644 index 00000000..bb1c2d02 --- /dev/null +++ b/scripts/use_cases/test_sweep_rollout_parameters.py @@ -0,0 +1,79 @@ +#!/usr/bin/env python3 + +import os +import tempfile +import unittest + +import bounds +from approx_rows import read_index +from run_use_case import USE_CASES, write_arm +from sweep_rollout_parameters import agreement_table, grid_text, parameter_suffix, sweep + +ARM = "noraw-eps0.01" +RUN = "uc4-noraw-eps0.01" +PLAN = {"sketches": [], "materialized_views": [], "planning_ms": 1.0} + + +def files(root): + out = {} + for folder, _, names in os.walk(root): + for name in names: + with open(os.path.join(folder, name), "rb") as f: + out[os.path.relpath(os.path.join(folder, name), root)] = f.read() + return out + + +def document(values, arm=None, exact=None): + queries = [] + for q, series in values.items(): + answers = [] + for i, v in enumerate(series): + a = {"time": 60_000 * (i + 1), "series": {"version": "canary"}, "value": v} + if exact is not None: + truth = exact[q][i] + a["exact_plan"] = {"relative_error": abs(v - truth) / truth} + answers.append(a) + queries.append({"id": q, "promql": q, "unit": "s", "threshold": None, "plan": PLAN, "answers": answers}) + out = {"use_case": "canary_release", "planner_rev": "r", "queries": queries} + if arm is not None: + out["arm"] = arm + return out + + +EXACT = {"p99_canary": [0.3] * 60 + [0.52] * 40, "p95_canary": [0.2] * 100, "p99_stable": [0.29] * 100, + "success_rate_canary": [0.999] * 70 + [0.96] * 30} +APPROX = {"p99_canary": [0.31] * 60 + [0.49] * 40, "p95_canary": [0.21] * 100, "p99_stable": [0.28] * 100, + "success_rate_canary": [0.998] * 70 + [0.94] * 30} +SPEC = {"use_case": "canary_release", "metrics": [], "queries": []} + + +class SweepTest(unittest.TestCase): + def test_multipliers_of_one_write_what_run_use_case_writes(self): + case = USE_CASES["4"] + exact = document(EXACT) + approx = document(APPROX, {"max_error": 0.01, "failure_probability": 0.01}, EXACT) + with tempfile.TemporaryDirectory() as swept, tempfile.TemporaryDirectory() as plain: + written = sweep(swept, case, exact, approx, ARM, 1, (bounds.PLAIN,), [(1.0, 1.0), (0.8, 2.0)], SPEC) + write_arm(plain, case, "uc4", ARM, exact, approx, 1, bounds.PLAIN, None, SPEC) + self.assertEqual([w["run_id"] for w in written], [RUN, f"{RUN}-threshold0.8x-count2x"]) + run = os.path.join("runs", RUN) + self.assertEqual(files(os.path.join(swept, run)), files(os.path.join(plain, run))) + entries = {e["run_id"]: e for e in read_index(swept)} + self.assertEqual(entries[RUN], read_index(plain)[0]) + changed = entries[f"{RUN}-threshold0.8x-count2x"]["details"] + self.assertEqual(changed["rule_parameters"]["tolerance"], 1.08) + self.assertEqual(changed["rule_multipliers"], {"threshold": 0.8, "count": 2.0}) + table = agreement_table(swept, written) + self.assertEqual({r["rule"] for r in table}, set(case["signals"]("p99_canary")) | {"argo_rollouts", "keptn"}) + at = {(r["rule"], r["threshold"]): r["agreement"] for r in table} + self.assertLess(at[("cloudwatch", 1.0)], 1.0) + self.assertEqual(at[("cloudwatch", 0.8)], 1.0) + self.assertIn("threshold x0.8", grid_text(table, [1.0, 0.8], [1.0, 2.0])) + + def test_suffix(self): + self.assertEqual(parameter_suffix(1.0, 1.0), "") + self.assertEqual(parameter_suffix(1.25, 0.5), "-threshold1.25x-count0.5x") + + +if __name__ == "__main__": + unittest.main() From ff74e048769241d16f0de69613691c5e0e6f29fe Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 20:44:57 +0000 Subject: [PATCH 17/51] aqpbm-usecase: phase choices and a group's other distributions draw from their own random streams Fixes #254. The phase-choice stream is seeded from the spec seed tagged as the phase choice, and each distribution of a series group after its baseline from its own seed tagged with its position in the group. The baseline keeps its stream, so it still draws what a TimeSeriesDescription with the same seed draws. So a baseline seed equal to the spec seed, or two distributions of one group with one seed, no longer replay one sequence. The generated data changes for every spec with a mix phase: uc1_syn_flood, uc3_video, uc4_canary, uc5_top_clients, and the generated metrics of uc4_canary_real and uc4_canary_real_native. uc2_autoscaling and every imported table draw the same samples as before. The uc1 golden hash is re-recorded. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-usecase/src/data.rs | 24 ++++++++-- aqpbm-usecase/tests/random_streams.rs | 67 +++++++++++++++++++++++++++ aqpbm-usecase/tests/uc1.rs | 2 +- 3 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 aqpbm-usecase/tests/random_streams.rs diff --git a/aqpbm-usecase/src/data.rs b/aqpbm-usecase/src/data.rs index 8908c8ad..9930852e 100644 --- a/aqpbm-usecase/src/data.rs +++ b/aqpbm-usecase/src/data.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use anyhow::Result; -use aqpbm_datagen::{sample_offsets_ms, series_stream_seed, DataDistribution, Sampler}; +use aqpbm_datagen::{sample_offsets_ms, series_stream_seed, splitmix64, DataDistribution, Sampler}; use rand::{Rng, SeedableRng}; use rand_xoshiro::Xoshiro256PlusPlus; @@ -46,6 +46,15 @@ pub fn intensity(phase: &Phase, offset_ms: i64, shift_ms: i64) -> f64 { rise.min(fall).min(1.0) } +const PHASE_CHOICE_TAG: u64 = u64::MAX; + +fn tagged_seed(seed: u64, tag: u64) -> u64 { + match tag { + 0 => seed, + tag => seed ^ splitmix64(tag), + } +} + struct Stream<'a> { metric: &'a MetricSpec, group: &'a SeriesGroup, @@ -81,10 +90,14 @@ impl<'a> Stream<'a> { } let distributions = known .iter() - .map(|d| { + .zip(0u64..) + .map(|(d, tag)| { Ok(( d.sampler()?, - Xoshiro256PlusPlus::seed_from_u64(series_stream_seed(d.seed(), stream)), + Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( + tagged_seed(d.seed(), tag), + stream, + )), )) }) .collect::>()?; @@ -94,7 +107,10 @@ impl<'a> Stream<'a> { index, distributions, phase_distribution, - choice: Xoshiro256PlusPlus::seed_from_u64(series_stream_seed(spec.seed, stream)), + choice: Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( + tagged_seed(spec.seed, PHASE_CHOICE_TAG), + stream, + )), }) } diff --git a/aqpbm-usecase/tests/random_streams.rs b/aqpbm-usecase/tests/random_streams.rs new file mode 100644 index 00000000..792bc720 --- /dev/null +++ b/aqpbm-usecase/tests/random_streams.rs @@ -0,0 +1,67 @@ +use std::path::Path; + +use aqpbm_datagen::{series_stream_seed, DataDistribution, UniformParameter}; +use aqpbm_usecase::data::generate; +use aqpbm_usecase::spec::Spec; +use rand::{Rng, SeedableRng}; +use rand_xoshiro::Xoshiro256PlusPlus; + +fn spec(baseline_seed: u64, mix_seed: u64) -> Spec { + let spec: Spec = serde_json::from_value(serde_json::json!({ + "use_case": "t", "start_ms": 0, "duration_ms": 100000, "seed": 5, + "metrics": [{"name": "m", "sample_interval_ms": 10, "series": [{ + "labels": {"k": "a"}, + "baseline": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1.0, "seed": baseline_seed}, + "phases": [{"start_offset_ms": 0, "end_offset_ms": 100001, "ramp_ms": 0, + "change": {"mix": {"share": 0.5, "distribution": + {"kind": "uniform", "lower_bound": 10.0, "upper_bound": 11.0, "seed": mix_seed}}}}]}]}], + "queries": [{"id": "q", "promql": "m", "window_ms": 1000, "interval_ms": 1000, "unit": "x"}] + })) + .unwrap(); + spec.check().unwrap(); + spec +} + +fn values(spec: &Spec) -> Vec { + let series = generate(spec, Path::new(".")).unwrap(); + assert_eq!(series.len(), 1); + series[0].points.iter().map(|&(_, v)| v).collect() +} + +fn uniform_draws(lower_bound: f64, upper_bound: f64, seed: u64, count: usize) -> Vec { + let sampler = DataDistribution::Uniform(UniformParameter { + lower_bound, + upper_bound, + seed, + }) + .sampler() + .unwrap(); + let mut rng = Xoshiro256PlusPlus::seed_from_u64(series_stream_seed(seed, 0)); + (0..count).map(|_| sampler.sample(&mut rng)).collect() +} + +#[test] +fn phase_choices_do_not_replay_a_baseline_stream_seeded_like_the_spec() { + let drawn = values(&spec(5, 99)); + let mut stream = Xoshiro256PlusPlus::seed_from_u64(series_stream_seed(5, 0)); + let choices_from_the_baseline_stream: Vec = drawn + .iter() + .map(|_| stream.random::() >= 0.5) + .collect(); + let baseline_picks: Vec = drawn.iter().map(|&v| v < 10.0).collect(); + assert_ne!(baseline_picks, choices_from_the_baseline_stream); + let baseline: Vec = drawn.iter().copied().filter(|&v| v < 10.0).collect(); + assert_eq!(baseline, uniform_draws(0.0, 1.0, 5, baseline.len())); + let at_least_half = baseline.iter().filter(|&&v| v >= 0.5).count() as f64; + assert!((0.45..0.55).contains(&(at_least_half / baseline.len() as f64))); +} + +#[test] +fn a_mix_distribution_with_the_baselines_seed_draws_its_own_values() { + let drawn = values(&spec(13, 13)); + let baseline: Vec = drawn.iter().copied().filter(|&v| v < 10.0).collect(); + let mixed: Vec = drawn.iter().copied().filter(|&v| v >= 10.0).collect(); + assert_eq!(baseline, uniform_draws(0.0, 1.0, 13, baseline.len())); + let replayed = uniform_draws(10.0, 11.0, 13, mixed.len()); + assert!(mixed.iter().zip(&replayed).all(|(a, b)| a != b)); +} diff --git a/aqpbm-usecase/tests/uc1.rs b/aqpbm-usecase/tests/uc1.rs index fbf1b0e3..2c08f9a7 100644 --- a/aqpbm-usecase/tests/uc1.rs +++ b/aqpbm-usecase/tests/uc1.rs @@ -57,7 +57,7 @@ fn the_use_case_1_spec_draws_a_fixed_sample_stream() { } } assert_eq!(series[0].points.len(), 11_340_033); - assert_eq!(hash, 0xd704_cd23_c966_dead); + assert_eq!(hash, 0xca5a_35a0_1056_68dc); } #[test] From f49317f035cdda0c38b564919cc88934c3734553 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:10:29 +0000 Subject: [PATCH 18/51] harness: WorkloadSpec carries the use cases' generated and imported metrics, and each query's threshold, unit and accuracy metric WorkloadSpec gains, all optional and under the use-case Spec's names: start_ms, duration_ms and seed, and metrics (series groups with phases, floor, non_negative, label_from_value, planned_series_count, max_distinct_per_evaluation, and tables to import). WorkloadQuery gains threshold, unit and accuracy_metric. data may be left out. Every existing field keeps its name and meaning, so existing workloads read unchanged. The use-case sample generator moves into aqpbm-core (harness::data, metric_series and workload_series), with the random streams of the #254 fix, so it draws the same samples. Importing a table needs aqpbm-core's new import feature, which approxbench turns on. The harness reads both kinds of data: the schedule, run_arm's refresh chunks (workload_sample_chunks), the declared-truth report and the victoriametrics and clickhouse adapters. benchmark-external run and report take --data-root (ASAP_DATASETS, default datasets), as planeval does, for the tables a workload imports; run_arm and report take the data root. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-cli/Cargo.toml | 2 +- aqpbm-cli/src/benchmark_external_cmd.rs | 17 +- aqpbm-cli/tests/benchmark_external_cli.rs | 3 + aqpbm-core/Cargo.toml | 1 + aqpbm-core/src/harness/arm_run.rs | 39 +- aqpbm-core/src/harness/benchmark_external.rs | 13 +- aqpbm-core/src/harness/conformance.rs | 3 + aqpbm-core/src/harness/data.rs | 615 +++++++++++++++++- aqpbm-core/src/harness/engine.rs | 151 ++++- .../tests/harness_arm_run_answer_drops.rs | 1 + aqpbm-core/tests/harness_arm_schedule.rs | 3 + .../tests/harness_benchmark_external.rs | 66 +- aqpbm-core/tests/harness_cgroup.rs | 5 + aqpbm-core/tests/harness_fake.rs | 7 + aqpbm-core/tests/harness_workload_metrics.rs | 161 +++++ .../src/engines_external/clickhouse_server.rs | 7 +- .../victoriametrics_server.rs | 13 +- system-bench/tests/clickhouse_conformance.rs | 5 + system-bench/tests/clickhouse_server.rs | 6 + system-bench/tests/end_to_end_adapters.rs | 3 + .../tests/victoriametrics_conformance.rs | 3 + system-bench/tests/victoriametrics_server.rs | 3 + 22 files changed, 1069 insertions(+), 58 deletions(-) create mode 100644 aqpbm-core/tests/harness_workload_metrics.rs diff --git a/aqpbm-cli/Cargo.toml b/aqpbm-cli/Cargo.toml index b10009d5..4064b287 100644 --- a/aqpbm-cli/Cargo.toml +++ b/aqpbm-cli/Cargo.toml @@ -28,7 +28,7 @@ planeval = ["system-bench/planeval"] [dependencies] aqpbm-datagen = { workspace = true, features = ["import"] } -aqpbm-core.workspace = true +aqpbm-core = { workspace = true, features = ["import"] } sketch-bench.workspace = true system-bench.workspace = true clap.workspace = true diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs index fbbaad97..259d4c60 100644 --- a/aqpbm-cli/src/benchmark_external_cmd.rs +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -80,6 +80,13 @@ pub struct RunArgs { /// A core busier than this fraction before a step refuses it. #[arg(long, default_value_t = Protocol::default().max_core_busy_fraction)] pub max_core_busy: f64, + #[arg( + long, + env = "ASAP_DATASETS", + default_value = "datasets", + help = "Directory that imported tables' dataset paths are relative to" + )] + pub data_root: PathBuf, #[command(flatten)] pub systems: SystemOptions, } @@ -161,6 +168,13 @@ pub struct ReportArgs { /// `/`. #[arg(long)] pub truth: String, + #[arg( + long, + env = "ASAP_DATASETS", + default_value = "datasets", + help = "Directory that imported tables' dataset paths are relative to" + )] + pub data_root: PathBuf, } pub fn run(args: BenchmarkExternalArgs) -> Result<()> { @@ -332,6 +346,7 @@ fn run_engine_cmd(args: RunArgs) -> Result<()> { engine.as_ref(), only, EngineRunSetup { + data_root: &args.data_root, protocol: &protocol, core: args.core, probe: probe.as_mut(), @@ -351,7 +366,7 @@ fn report_cmd(args: ReportArgs) -> Result<()> { if truth == ReportTruth::Declared { workloads(&run_directory)?; } - let report = report(&run_directory, &truth)?; + let report = report(&run_directory, &truth, &args.data_root)?; write_report(&run_directory, &report)?; print!("{}", report.summary_markdown()); Ok(()) diff --git a/aqpbm-cli/tests/benchmark_external_cli.rs b/aqpbm-cli/tests/benchmark_external_cli.rs index 134291ee..d27bce30 100644 --- a/aqpbm-cli/tests/benchmark_external_cli.rs +++ b/aqpbm-cli/tests/benchmark_external_cli.rs @@ -21,6 +21,9 @@ fn workload(name: &str) -> WorkloadSpec { window_ms: 10_000, evaluation_interval_ms: 10_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }], vec![DataRecord { metric: "m".into(), diff --git a/aqpbm-core/Cargo.toml b/aqpbm-core/Cargo.toml index 7d024554..4980f100 100644 --- a/aqpbm-core/Cargo.toml +++ b/aqpbm-core/Cargo.toml @@ -29,6 +29,7 @@ heap-track = [] # of the embedded build: nothing at runtime needs it. Forwards to # aqpbm-datagen, whose `TableDescription` is the record's `workload`. schema = ["dep:schemars", "aqpbm-datagen/schema"] +import = ["aqpbm-datagen/import"] [dependencies] aqpbm-datagen.workspace = true diff --git a/aqpbm-core/src/harness/arm_run.rs b/aqpbm-core/src/harness/arm_run.rs index b313c6be..cdd27679 100644 --- a/aqpbm-core/src/harness/arm_run.rs +++ b/aqpbm-core/src/harness/arm_run.rs @@ -2,8 +2,10 @@ //! refresh chunk, evaluate at every time, and record the costs the harness //! measured. +use std::path::Path; + use crate::harness::cgroup::CgroupSource; -use crate::harness::data::{workload_chunks, DataError}; +use crate::harness::data::{workload_sample_chunks, DataError}; use crate::harness::engine::{ Answers, ArmSpec, CpuAccounting, EngineError, EngineUnderTest, InstalledArm, MeasuredUsage, WorkloadSpec, @@ -60,20 +62,10 @@ impl ArmSchedule { .map(|q| q.window_ms) .max() .unwrap_or(0); - let start_ms = workload - .data - .iter() - .map(|record| record.description.start_ms) - .min() - .ok_or(ScheduleError::NoData { - workload: workload.name.clone(), - })?; - let end_ms = workload - .data - .iter() - .map(|record| record.description.start_ms + record.description.duration_ms as i64) - .max() - .unwrap_or(start_ms); + let start_ms = workload.data_start_ms().ok_or(ScheduleError::NoData { + workload: workload.name.clone(), + })?; + let end_ms = workload.data_end_ms().unwrap_or(start_ms); let interval = interval_ms as i64; // Chunks end at `start + k * refresh`; with an unaligned start an // evaluation would run after a chunk holding later samples. @@ -180,6 +172,7 @@ pub enum ScheduleError { pub fn run_arm( engine: &dyn EngineUnderTest, workload: &WorkloadSpec, + data_root: &Path, arm: &ArmSpec, schedule: &ArmSchedule, protocol: &Protocol, @@ -188,12 +181,7 @@ pub fn run_arm( clocks: &MeasurementClocks, ) -> Result { protocol.check_run_count()?; - let data_ms = workload - .data - .iter() - .map(|record| record.description.duration_ms) - .max() - .unwrap_or(0); + let data_ms = workload.data_duration_ms(); if data_ms == 0 { return Err(ArmRunError::NoData { workload: workload.name.clone(), @@ -231,6 +219,7 @@ pub fn run_arm( steps_one_install_at_a_time( engine, workload, + data_root, arm, schedule, protocol, @@ -242,7 +231,7 @@ pub fn run_arm( )? } else { steps_on_every_install_at_once( - engine, workload, arm, schedule, protocol, core, probe, &clock, + engine, workload, data_root, arm, schedule, protocol, core, probe, &clock, )? }; @@ -301,6 +290,7 @@ struct Steps { fn steps_on_every_install_at_once( engine: &dyn EngineUnderTest, workload: &WorkloadSpec, + data_root: &Path, arm: &ArmSpec, schedule: &ArmSchedule, protocol: &Protocol, @@ -340,7 +330,7 @@ fn steps_on_every_install_at_once( answers.push((at_ms, last_answers)); Ok(()) }; - for chunk in workload_chunks(&workload.data, schedule.refresh_ms)? { + for chunk in workload_sample_chunks(workload, data_root, schedule.refresh_ms)? { let chunk = chunk?; ingested_samples += chunk.samples.len() as u64; let mut call = 0; @@ -373,6 +363,7 @@ fn steps_on_every_install_at_once( fn steps_one_install_at_a_time( engine: &dyn EngineUnderTest, workload: &WorkloadSpec, + data_root: &Path, arm: &ArmSpec, schedule: &ArmSchedule, protocol: &Protocol, @@ -435,7 +426,7 @@ fn steps_one_install_at_a_time( answers.push((at_ms, step_answers.expect("one measured call"))); Ok(()) }; - for chunk in workload_chunks(&workload.data, schedule.refresh_ms)? { + for chunk in workload_sample_chunks(workload, data_root, schedule.refresh_ms)? { let chunk = chunk?; ingested_samples += chunk.samples.len() as u64; let job = diff --git a/aqpbm-core/src/harness/benchmark_external.rs b/aqpbm-core/src/harness/benchmark_external.rs index 107c4349..7260dd82 100644 --- a/aqpbm-core/src/harness/benchmark_external.rs +++ b/aqpbm-core/src/harness/benchmark_external.rs @@ -31,7 +31,7 @@ use serde::{Deserialize, Serialize}; use crate::accuracy::declared_truth::{without_name, AnswerAt, QueryTruth, Series, Statistic}; use crate::harness::arm_run::{run_arm, ArmSchedule}; -use crate::harness::data::{workload_chunks, SeriesLabels}; +use crate::harness::data::{workload_sample_chunks, SeriesLabels}; use crate::harness::engine::{ ArmSpec, CpuAccounting, EngineDescription, EngineUnderTest, WorkloadSpec, }; @@ -244,6 +244,7 @@ pub fn read_variants( /// How one engine run measures. pub struct EngineRunSetup<'a> { + pub data_root: &'a Path, pub protocol: &'a Protocol, pub core: usize, pub probe: &'a mut dyn LoadProbe, @@ -372,6 +373,7 @@ fn run_cell( let result = run_arm( engine, workload, + setup.data_root, &arm, &schedule, setup.protocol, @@ -611,6 +613,7 @@ fn errors_against( pub fn report( run_directory: &RunDirectory, truth: &ReportTruth, + data_root: &Path, ) -> Result { let results = run_directory.path().join("results"); let mut cells: Vec<(EngineRunCell, Option)> = Vec::new(); @@ -717,7 +720,10 @@ pub fn report( )) })?; if !series_of.contains_key(&cell.workload) { - series_of.insert(cell.workload.clone(), series_of_workload(workload)?); + series_of.insert( + cell.workload.clone(), + series_of_workload(workload, data_root)?, + ); } let (series, generated) = &series_of[&cell.workload]; if *generated != result.ingested_samples { @@ -786,13 +792,14 @@ pub fn report( fn series_of_workload( workload: &WorkloadSpec, + data_root: &Path, ) -> Result<(Vec, u64), BenchmarkExternalError> { let refresh_ms = ArmSchedule::for_workload(workload) .map_err(|e| BenchmarkExternalError::Report(format!("workload {}: {e}", workload.name)))? .refresh_ms; let mut points: BTreeMap> = BTreeMap::new(); let mut generated = 0u64; - let chunks = workload_chunks(&workload.data, refresh_ms) + let chunks = workload_sample_chunks(workload, data_root, refresh_ms) .map_err(|e| BenchmarkExternalError::Report(format!("workload {}: {e}", workload.name)))?; for chunk in chunks { let chunk = chunk.map_err(|e| { diff --git a/aqpbm-core/src/harness/conformance.rs b/aqpbm-core/src/harness/conformance.rs index 962b7653..b1cc4c17 100644 --- a/aqpbm-core/src/harness/conformance.rs +++ b/aqpbm-core/src/harness/conformance.rs @@ -457,6 +457,9 @@ pub fn probe_workloads() -> Vec { window_ms: PROBE_STEP_MS, evaluation_interval_ms: PROBE_STEP_MS, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }], vec![data.clone()], ) diff --git a/aqpbm-core/src/harness/data.rs b/aqpbm-core/src/harness/data.rs index 89ca76b8..c8b2f8f2 100644 --- a/aqpbm-core/src/harness/data.rs +++ b/aqpbm-core/src/harness/data.rs @@ -6,11 +6,20 @@ //! `TimeSeriesDescription` on the left-open grid `(start, start + duration]`. use std::collections::BTreeMap; +use std::path::Path; use std::sync::Arc; -use aqpbm_datagen::{OwnedTimeSeriesSamples, TimeSeriesDescription}; +use aqpbm_datagen::{ + sample_offsets_ms, series_stream_seed, splitmix64, DataDistribution, OwnedTimeSeriesSamples, + Sampler, TimeSeriesDescription, +}; +use rand::{Rng, SeedableRng}; +use rand_xoshiro::Xoshiro256PlusPlus; use serde::{Deserialize, Serialize}; +use crate::accuracy::declared_truth::Series; +use crate::harness::engine::WorkloadSpec; + /// A series' labels, `__name__` included, such as /// `{__name__: "m", job: "job_0"}`. pub type SeriesLabels = BTreeMap; @@ -186,14 +195,133 @@ pub fn workload_chunks( records: &[DataRecord], refresh_ms: u64, ) -> Result>, DataError> { - let mut per_record = Vec::with_capacity(records.len()); + let mut per_record: Vec = Vec::with_capacity(records.len()); for record in records { - let chunks: Box>> = - Box::new(refresh_chunks(record, refresh_ms)?); - per_record.push(chunks.peekable()); + per_record.push(Box::new(refresh_chunks(record, refresh_ms)?)); + } + Ok(merged_by_end(per_record)) +} + +pub fn workload_sample_chunks( + workload: &WorkloadSpec, + data_root: &Path, + refresh_ms: u64, +) -> Result>, DataError> { + let mut sources: Vec = Vec::with_capacity(workload.data.len() + 1); + for record in &workload.data { + sources.push(Box::new(refresh_chunks(record, refresh_ms)?)); + } + if !workload.metrics.is_empty() { + if refresh_ms == 0 { + return Err(DataError::ZeroRefresh); + } + let series = metric_series(workload, data_root)?; + let start_ms = workload.start_ms.unwrap_or(0); + let duration_ms = workload.duration_ms.unwrap_or(0).max(0) as u64; + sources.push(Box::new(SeriesChunks::new( + series, + start_ms, + refresh_ms, + duration_ms.div_ceil(refresh_ms), + ))); + } + Ok(merged_by_end(sources)) +} + +pub fn workload_series( + workload: &WorkloadSpec, + data_root: &Path, +) -> Result, DataError> { + let mut out = Vec::new(); + for record in &workload.data { + let generator = |error: aqpbm_datagen::DataGenError| DataError::Generator { + metric: record.metric.clone(), + message: error.to_string(), + }; + let generated = record.description.generate().map_err(generator)?; + let label_pairs = generated.labels.clone(); + let mut points: Vec> = vec![Vec::new(); label_pairs.len()]; + for sample in generated.into_samples() { + let (index, ts_ms, value) = sample.map_err(generator)?; + points[index].push((ts_ms, value)); + } + for (pairs, points) in label_pairs.iter().zip(points) { + let mut labels: SeriesLabels = pairs.iter().cloned().collect(); + labels.insert("__name__".into(), record.metric.clone()); + out.push(Series { labels, points }); + } + } + out.extend(metric_series(workload, data_root)?); + Ok(out) +} + +type ChunkSource = Box>>; + +struct SeriesChunks { + labels: Vec>, + points: Vec>, + next_point: Vec, + start_ms: i64, + refresh_ms: u64, + chunk_count: u64, + next_chunk: u64, +} + +impl SeriesChunks { + fn new(series: Vec, start_ms: i64, refresh_ms: u64, chunk_count: u64) -> SeriesChunks { + let next_point = vec![0; series.len()]; + let (labels, points) = series + .into_iter() + .map(|series| (Arc::new(series.labels), series.points)) + .unzip(); + SeriesChunks { + labels, + points, + next_point, + start_ms, + refresh_ms, + chunk_count, + next_chunk: 0, + } + } +} + +impl Iterator for SeriesChunks { + type Item = Result; + + fn next(&mut self) -> Option { + if self.next_chunk >= self.chunk_count { + return None; + } + self.next_chunk += 1; + let end_ms = self.start_ms + (self.next_chunk * self.refresh_ms) as i64; + let mut drawn: Vec<(i64, usize, f64)> = Vec::new(); + for (index, points) in self.points.iter().enumerate() { + let from = self.next_point[index]; + let to = from + points[from..].partition_point(|&(t, _)| t <= end_ms); + drawn.extend(points[from..to].iter().map(|&(t, v)| (t, index, v))); + self.next_point[index] = to; + } + drawn.sort_by_key(|&(t, index, _)| (t, index)); + let samples = drawn + .into_iter() + .map(|(ts_ms, index, value)| Sample { + labels: Arc::clone(&self.labels[index]), + ts_ms, + value, + }) + .collect(); + Some(Ok(SampleChunk { end_ms, samples })) } +} + +fn merged_by_end( + sources: Vec, +) -> impl Iterator> { + let mut per_record: Vec> = + sources.into_iter().map(Iterator::peekable).collect(); let mut finished = false; - Ok(std::iter::from_fn(move || { + std::iter::from_fn(move || { if finished { return None; } @@ -220,7 +348,7 @@ pub fn workload_chunks( } } Some(Ok(SampleChunk { end_ms, samples })) - })) + }) } /// Data that cannot be generated or cut. @@ -233,3 +361,476 @@ pub enum DataError { #[error("refresh_ms must be > 0")] ZeroRefresh, } + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct MetricSpec { + pub name: String, + pub sample_interval_ms: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_distinct_per_evaluation: Option, + #[serde(default, skip_serializing_if = "is_false")] + pub floor: bool, + #[serde(default, skip_serializing_if = "is_false")] + pub non_negative: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label_from_value: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub planned_series_count: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub series: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub import: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Import { + pub table: serde_json::Value, + #[serde(default = "unit_scale")] + pub time_scale: f64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub origin_ns: Option, +} + +fn unit_scale() -> f64 { + 1.0 +} + +fn is_false(value: &bool) -> bool { + !*value +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SeriesGroup { + #[serde(default = "one")] + pub count: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub sample_interval_ms: Option, + pub labels: BTreeMap, + pub baseline: DataDistribution, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub phases: Vec, +} + +fn one() -> usize { + 1 +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Phase { + pub start_offset_ms: i64, + pub end_offset_ms: i64, + pub ramp_ms: i64, + #[serde(default)] + pub stagger_ms: i64, + pub change: Change, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields, rename_all = "snake_case")] +pub enum Change { + Mix { + share: f64, + distribution: DataDistribution, + }, + Scale { + factor: f64, + }, + /// Multiplies how often the series samples: factor 25 writes 25 samples where the baseline writes one. + Rate { + factor: f64, + }, +} + +impl MetricSpec { + pub fn series_count(&self) -> u64 { + self.planned_series_count + .unwrap_or_else(|| self.series.iter().map(|g| g.count as u64).sum()) + } + + pub fn planned_sample_interval_ms(&self) -> i64 { + match self.label_from_value { + Some(_) => self.sample_interval_ms * self.series_count() as i64, + None => self.sample_interval_ms, + } + } + + pub fn sample_interval_of(&self, group: &SeriesGroup) -> i64 { + group.sample_interval_ms.unwrap_or(self.sample_interval_ms) + } + + pub fn rows_per_second(&self) -> f64 { + if self.import.is_some() { + let streams = match self.label_from_value { + Some(_) => 1, + None => self.series_count(), + }; + return streams as f64 * 1000.0 / self.sample_interval_ms as f64; + } + self.series + .iter() + .map(|g| { + let streams = match self.label_from_value { + Some(_) => 1, + None => g.count, + }; + streams as f64 * 1000.0 / self.sample_interval_of(g) as f64 + }) + .sum() + } + + pub fn check(&self) -> Result<(), String> { + if self.import.is_some() != self.series.is_empty() { + return Err(format!( + "metric {} needs either series to generate or a table to import, not both", + self.name + )); + } + if self.import.is_some() && self.planned_series_count.is_none() { + return Err(format!( + "metric {} is imported, so it needs planned_series_count", + self.name + )); + } + if self.import.as_ref().is_some_and(|i| i.time_scale <= 0.0) { + return Err(format!("metric {} needs a positive time_scale", self.name)); + } + if self.sample_interval_ms <= 0 + || self.series.iter().any(|g| self.sample_interval_of(g) <= 0) + { + return Err(format!( + "metric {} needs a positive sample_interval_ms", + self.name + )); + } + if self.label_from_value.is_some() && self.planned_series_count.is_none() { + return Err(format!( + "metric {} draws its series from values, so it needs planned_series_count", + self.name + )); + } + for phase in self.series.iter().flat_map(|g| &g.phases) { + let share = match phase.change { + Change::Mix { share, .. } => share, + Change::Scale { .. } => 0.0, + Change::Rate { factor } if factor > 0.0 => 0.0, + Change::Rate { .. } => { + return Err(format!( + "a rate phase of {} needs a positive factor", + self.name + )) + } + }; + if !(0.0..=1.0).contains(&share) + || phase.start_offset_ms >= phase.end_offset_ms + || phase.ramp_ms < 0 + { + return Err(format!( + "phase {phase:?} of {} is not a span with a share in [0, 1]", + self.name + )); + } + } + Ok(()) + } +} + +pub fn intensity(phase: &Phase, offset_ms: i64, shift_ms: i64) -> f64 { + let start = phase.start_offset_ms + shift_ms; + let end = phase.end_offset_ms + shift_ms; + if offset_ms < start || offset_ms >= end { + return 0.0; + } + if phase.ramp_ms == 0 { + return 1.0; + } + let rise = (offset_ms - start + 1) as f64 / phase.ramp_ms as f64; + let fall = (end - offset_ms) as f64 / phase.ramp_ms as f64; + rise.min(fall).min(1.0) +} + +const PHASE_CHOICE_TAG: u64 = u64::MAX; + +fn tagged_seed(seed: u64, tag: u64) -> u64 { + match tag { + 0 => seed, + tag => seed ^ splitmix64(tag), + } +} + +struct GroupStream<'a> { + metric: &'a MetricSpec, + group: &'a SeriesGroup, + index: i64, + distributions: Vec<(Sampler, Xoshiro256PlusPlus)>, + phase_distribution: Vec>, + choice: Xoshiro256PlusPlus, +} + +impl<'a> GroupStream<'a> { + fn new( + seed: u64, + metric: &'a MetricSpec, + group: &'a SeriesGroup, + stream: u64, + index: i64, + ) -> Result, DataError> { + let mut known: Vec<&DataDistribution> = vec![&group.baseline]; + let mut phase_distribution = Vec::new(); + for phase in &group.phases { + phase_distribution.push(match &phase.change { + Change::Mix { distribution, .. } => Some( + known + .iter() + .position(|d| *d == distribution) + .unwrap_or_else(|| { + known.push(distribution); + known.len() - 1 + }), + ), + Change::Scale { .. } | Change::Rate { .. } => None, + }); + } + let distributions = known + .iter() + .zip(0u64..) + .map(|(d, tag)| { + let sampler = d.sampler().map_err(|error| DataError::Generator { + metric: metric.name.clone(), + message: error.to_string(), + })?; + Ok(( + sampler, + Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( + tagged_seed(d.seed(), tag), + stream, + )), + )) + }) + .collect::>()?; + Ok(GroupStream { + metric, + group, + index, + distributions, + phase_distribution, + choice: Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( + tagged_seed(seed, PHASE_CHOICE_TAG), + stream, + )), + }) + } + + fn draw(&mut self, offset_ms: i64) -> f64 { + let u = self.choice.random::(); + let mut chosen = None; + let mut cumulative = 0.0; + let mut scale = 1.0; + for (phase, distribution) in self.group.phases.iter().zip(&self.phase_distribution) { + let w = intensity(phase, offset_ms, self.index * phase.stagger_ms); + if w == 0.0 { + continue; + } + match (&phase.change, distribution) { + (Change::Mix { share, .. }, Some(index)) => { + cumulative += share * w; + if chosen.is_none() && u < cumulative { + chosen = Some(*index); + } + } + (Change::Scale { factor }, _) => scale *= 1.0 + w * (factor - 1.0), + _ => {} + } + } + let (sampler, rng) = &mut self.distributions[chosen.unwrap_or(0)]; + let mut value = sampler.sample(rng) * scale; + if self.metric.floor { + value = value.floor(); + } + if self.metric.non_negative { + value = value.max(0.0); + } + value + } +} + +/// Offsets in ms of one stream's samples: one every `interval_ms` on `aqpbm-datagen`'s grid +/// (`sample_offsets_ms`, the first one interval after the start), more often while a rate phase holds. +fn group_offsets(group: &SeriesGroup, interval_ms: i64, duration_ms: i64, index: i64) -> Vec { + let rates: Vec<(&Phase, f64)> = group + .phases + .iter() + .filter_map(|phase| match phase.change { + Change::Rate { factor } => Some((phase, factor)), + _ => None, + }) + .collect(); + if rates.is_empty() { + return sample_offsets_ms(interval_ms as u64, duration_ms as u64) + .map(|offset| offset as i64) + .collect(); + } + let mut out = Vec::new(); + let mut offset = 0.0f64; + loop { + let at = offset.round() as i64; + let rate: f64 = rates + .iter() + .map(|(phase, factor)| { + 1.0 + intensity(phase, at, index * phase.stagger_ms) * (factor - 1.0) + }) + .product(); + offset += interval_ms as f64 / rate; + if offset > duration_ms as f64 { + return out; + } + out.push(offset.round() as i64); + } +} + +fn group_labels(metric: &MetricSpec, group: &SeriesGroup, index: usize) -> SeriesLabels { + let mut labels: SeriesLabels = group + .labels + .iter() + .map(|(k, v)| (k.clone(), v.replace("{i}", &index.to_string()))) + .collect(); + labels.insert("__name__".into(), metric.name.clone()); + labels +} + +#[cfg(feature = "import")] +fn imported( + start_ms: i64, + duration_ms: i64, + metric: &MetricSpec, + import: &Import, + data_root: &Path, +) -> Result, DataError> { + use aqpbm_datagen::{ColumnData, ExternalTableDescription}; + let failed = |message: String| DataError::Generator { + metric: metric.name.clone(), + message, + }; + let description: ExternalTableDescription = serde_json::from_value(import.table.clone()) + .map_err(|error| failed(format!("the table to import: {error}")))?; + let table = description + .load(data_root) + .map_err(|error| failed(format!("loading the table: {error}")))? + .ok_or_else(|| failed("the table has no records".into()))?; + let groups = description.group_columns.len(); + let first_group = table.column_num as usize - 1 - groups; + let times = table + .column(0) + .and_then(ColumnData::as_i64) + .map_err(|error| failed(error.to_string()))?; + let values = table + .column(table.column_num as usize - 1) + .and_then(ColumnData::as_f64) + .map_err(|error| failed(error.to_string()))?; + let labels_of: Vec<&[String]> = (first_group..first_group + groups) + .map(|i| table.column(i).and_then(ColumnData::as_string)) + .collect::>() + .map_err(|error| failed(error.to_string()))?; + let first = import + .origin_ns + .unwrap_or_else(|| times.iter().copied().min().unwrap_or(0)); + let mut by_labels: BTreeMap> = BTreeMap::new(); + for row in 0..times.len() { + let offset_ms = 1 + ((times[row] - first) as f64 / 1e6 * import.time_scale) as i64; + if offset_ms < 1 || offset_ms > duration_ms { + continue; + } + let mut labels = BTreeMap::from([("__name__".to_string(), metric.name.clone())]); + for (column, values) in description.group_columns.iter().zip(&labels_of) { + labels.insert(column.clone(), values[row].clone()); + } + let mut value = values[row]; + if let Some(label) = &metric.label_from_value { + labels.insert(label.clone(), (value as u64).to_string()); + value = 1.0; + } + by_labels + .entry(labels) + .or_default() + .push((start_ms + offset_ms, value)); + } + Ok(by_labels + .into_iter() + .map(|(labels, mut points)| { + points.sort_by_key(|&(t, _)| t); + Series { labels, points } + }) + .collect()) +} + +#[cfg(not(feature = "import"))] +fn imported( + _start_ms: i64, + _duration_ms: i64, + metric: &MetricSpec, + _import: &Import, + _data_root: &Path, +) -> Result, DataError> { + Err(DataError::Generator { + metric: metric.name.clone(), + message: "importing a table needs aqpbm-core's import feature".into(), + }) +} + +pub fn metric_series(workload: &WorkloadSpec, data_root: &Path) -> Result, DataError> { + if workload.metrics.is_empty() { + return Ok(Vec::new()); + } + workload.check().map_err(|message| DataError::Generator { + metric: workload.name.clone(), + message, + })?; + let start_ms = workload.start_ms.unwrap_or(0); + let duration_ms = workload.duration_ms.unwrap_or(0); + let seed = workload.seed.unwrap_or(0); + let mut out = Vec::new(); + let mut stream = 0u64; + for metric in &workload.metrics { + if let Some(import) = &metric.import { + out.extend(imported(start_ms, duration_ms, metric, import, data_root)?); + continue; + } + for group in &metric.series { + let interval_ms = metric.sample_interval_of(group); + if let Some(label) = &metric.label_from_value { + let mut drawn = GroupStream::new(seed, metric, group, stream, 0)?; + stream += 1; + let mut by_value: BTreeMap> = BTreeMap::new(); + for offset_ms in group_offsets(group, interval_ms, duration_ms, 0) { + let value = drawn.draw(offset_ms) as u64; + by_value + .entry(value) + .or_default() + .push((start_ms + offset_ms, 1.0)); + } + for (value, points) in by_value { + let mut labels = group_labels(metric, group, 0); + labels.insert(label.clone(), value.to_string()); + out.push(Series { labels, points }); + } + continue; + } + for index in 0..group.count { + let mut drawn = GroupStream::new(seed, metric, group, stream, index as i64)?; + stream += 1; + let points = group_offsets(group, interval_ms, duration_ms, index as i64) + .into_iter() + .map(|offset_ms| (start_ms + offset_ms, drawn.draw(offset_ms))) + .collect(); + out.push(Series { + labels: group_labels(metric, group, index), + points, + }); + } + } + } + Ok(out) +} diff --git a/aqpbm-core/src/harness/engine.rs b/aqpbm-core/src/harness/engine.rs index 18c7286e..d73231dd 100644 --- a/aqpbm-core/src/harness/engine.rs +++ b/aqpbm-core/src/harness/engine.rs @@ -10,7 +10,9 @@ use std::collections::BTreeMap; use serde::{Deserialize, Serialize}; -pub use crate::harness::data::{DataRecord, Sample, SampleChunk, SeriesLabels}; +pub use crate::harness::data::{ + Change, DataRecord, Import, MetricSpec, Phase, Sample, SampleChunk, SeriesGroup, SeriesLabels, +}; /// An engine the harness can measure: the Planner's executor, a fake, or an /// external server such as ClickHouse. @@ -83,11 +85,20 @@ pub struct ArmSpec { pub struct WorkloadSpec { pub name: String, pub queries: Vec, + #[serde(default)] pub data: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub tables: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub one_shot_queries: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub start_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub duration_ms: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seed: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub metrics: Vec, } impl WorkloadSpec { @@ -102,6 +113,10 @@ impl WorkloadSpec { data, tables: Vec::new(), one_shot_queries: Vec::new(), + start_ms: None, + duration_ms: None, + seed: None, + metrics: Vec::new(), } } @@ -116,7 +131,119 @@ impl WorkloadSpec { data: Vec::new(), tables, one_shot_queries, + start_ms: None, + duration_ms: None, + seed: None, + metrics: Vec::new(), + } + } + + pub fn data_start_ms(&self) -> Option { + self.data + .iter() + .map(|record| record.description.start_ms) + .chain(self.metrics_span().map(|(start_ms, _)| start_ms)) + .min() + } + + pub fn data_end_ms(&self) -> Option { + self.data + .iter() + .map(|record| record.description.start_ms + record.description.duration_ms as i64) + .chain(self.metrics_span().map(|(_, end_ms)| end_ms)) + .max() + } + + pub fn data_duration_ms(&self) -> u64 { + self.data + .iter() + .map(|record| record.description.duration_ms) + .chain( + self.metrics_span() + .map(|(start_ms, end_ms)| (end_ms - start_ms).max(0) as u64), + ) + .max() + .unwrap_or(0) + } + + fn metrics_span(&self) -> Option<(i64, i64)> { + if self.metrics.is_empty() { + return None; + } + let start_ms = self.start_ms.unwrap_or(0); + Some((start_ms, start_ms + self.duration_ms.unwrap_or(0))) + } + + pub fn metric_names(&self) -> Vec { + let mut names: Vec = Vec::new(); + for name in self + .data + .iter() + .map(|record| &record.metric) + .chain(self.metrics.iter().map(|metric| &metric.name)) + { + if !names.contains(name) { + names.push(name.clone()); + } + } + names + } + + pub fn query(&self, id: &str) -> Option<&WorkloadQuery> { + self.queries.iter().find(|query| query.id == id) + } + + pub fn evaluation_times(&self, query: &WorkloadQuery) -> Vec { + let (Some(start_ms), Some(end_ms)) = (self.data_start_ms(), self.data_end_ms()) else { + return Vec::new(); + }; + let interval_ms = query.evaluation_interval_ms as i64; + if interval_ms <= 0 { + return Vec::new(); + } + let first = start_ms + query.window_ms as i64; + let first = first + (interval_ms - first.rem_euclid(interval_ms)) % interval_ms; + (0..) + .map(|i| first + i * interval_ms) + .take_while(|&t| t <= end_ms) + .collect() + } + + pub fn check(&self) -> Result<(), String> { + for query in &self.queries { + if query.window_ms == 0 || query.evaluation_interval_ms == 0 { + return Err(format!( + "query {} needs a positive window and interval", + query.id + )); + } + } + if self.metrics.is_empty() { + return Ok(()); + } + let (Some(start_ms), Some(duration_ms), Some(_)) = + (self.start_ms, self.duration_ms, self.seed) + else { + return Err(format!( + "workload {} has metrics, so it needs start_ms, duration_ms and seed", + self.name + )); + }; + if duration_ms <= 0 { + return Err("duration_ms must be positive".into()); + } + for metric in &self.metrics { + metric.check()?; } + for query in &self.queries { + if start_ms.rem_euclid(query.evaluation_interval_ms as i64) != 0 { + return Err(format!( + "start_ms is not on query {}'s interval grid", + query.id + )); + } + } + Ok(()) } pub fn dialects(&self) -> impl Iterator { @@ -213,6 +340,28 @@ pub struct WorkloadQuery { pub evaluation_interval_ms: u64, #[serde(default, skip_serializing_if = "Option::is_none")] pub truth: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub threshold: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub unit: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub accuracy_metric: Option, +} + +impl WorkloadQuery { + pub fn text_in(&self, language: QueryLanguage) -> Option<&str> { + self.texts + .iter() + .find(|text| text.language == language) + .map(|text| text.text.as_str()) + } + + pub fn declared_truth(&self) -> Option { + Some(crate::accuracy::declared_truth::QueryTruth::new( + self.truth.as_ref()?, + self.window_ms as i64, + )) + } } /// A query text in one language. diff --git a/aqpbm-core/tests/harness_arm_run_answer_drops.rs b/aqpbm-core/tests/harness_arm_run_answer_drops.rs index 60286bd9..d1267612 100644 --- a/aqpbm-core/tests/harness_arm_run_answer_drops.rs +++ b/aqpbm-core/tests/harness_arm_run_answer_drops.rs @@ -173,6 +173,7 @@ fn answers_are_freed_outside_the_timed_window() { let result = run_arm( &MarkerEngine, &workload, + std::path::Path::new("."), &arm, &schedule, &Protocol::default(), diff --git a/aqpbm-core/tests/harness_arm_schedule.rs b/aqpbm-core/tests/harness_arm_schedule.rs index 950d622e..d69ddc98 100644 --- a/aqpbm-core/tests/harness_arm_schedule.rs +++ b/aqpbm-core/tests/harness_arm_schedule.rs @@ -16,6 +16,9 @@ fn query(id: &str, window_ms: u64, evaluation_interval_ms: u64) -> WorkloadQuery window_ms, evaluation_interval_ms, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, } } diff --git a/aqpbm-core/tests/harness_benchmark_external.rs b/aqpbm-core/tests/harness_benchmark_external.rs index 59e6ab8d..8aefe7df 100644 --- a/aqpbm-core/tests/harness_benchmark_external.rs +++ b/aqpbm-core/tests/harness_benchmark_external.rs @@ -68,6 +68,9 @@ fn workload(name: &str) -> WorkloadSpec { window_ms: 10_000, evaluation_interval_ms: 10_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }], vec![DataRecord { metric: "m".into(), @@ -145,6 +148,7 @@ fn run_fake(run: &RunDirectory, only: Option<&[String]>) -> Result String { engine: engine.into(), variant: variant.into(), }, + std::path::Path::new("."), ) .unwrap_err() .to_string() @@ -822,7 +828,7 @@ fn answers_are_scored_against_each_queries_declared_statistic() { let mut w2 = result("e", "w2", "v", vec![(10_000, answers_of_sum())]); w2.ingested_samples = generated; put(&run, "e", "w2", "v", CellOutcome::Ran, Some(w2)); - let report = report(&run, &ReportTruth::Declared).unwrap(); + let report = report(&run, &ReportTruth::Declared, std::path::Path::new(".")).unwrap(); assert_eq!(report.truth, "declared"); let distinct: Vec<_> = report .accuracy @@ -863,9 +869,13 @@ fn answers_are_scored_against_each_queries_declared_statistic() { &run.path().join("workloads/w1.json"), &serde_json::to_string(&edited).unwrap(), ); - let error = aqpbm_core::harness::benchmark_external::report(&run, &ReportTruth::Declared) - .unwrap_err() - .to_string(); + let error = aqpbm_core::harness::benchmark_external::report( + &run, + &ReportTruth::Declared, + std::path::Path::new("."), + ) + .unwrap_err() + .to_string(); assert!(error.contains("generates"), "{error}"); assert!(scores.starts_with("workload,engine,variant,query,score,max,median,points\n")); assert!( @@ -923,6 +933,7 @@ fn the_summary_has_a_processes_engine_memory_in_its_own_columns() { engine: "a".into(), variant: "v1".into(), }, + std::path::Path::new("."), ) .unwrap() .summary_csv(); @@ -935,3 +946,50 @@ fn the_summary_has_a_processes_engine_memory_in_its_own_columns() { assert_eq!(row[4], "processes"); assert_eq!(&row[9..15], ["", "", "", "1048576", "3145728", "5242880"]); } + +#[test] +fn a_workload_of_series_groups_runs_and_answers_over_its_generated_samples() { + let temp = TempDir::new("series-groups"); + let run = RunDirectory::create_at(&temp.0.join("run")).unwrap(); + let workload: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "groups", + "start_ms": 0, + "duration_ms": 60000, + "seed": 7, + "metrics": [{"name": "m", "sample_interval_ms": 1000, "series": [ + {"count": 2, "labels": {"s": "s{i}"}, + "baseline": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 10.0, "seed": 1}, + "phases": [{"start_offset_ms": 20000, "end_offset_ms": 40000, "ramp_ms": 0, + "change": {"scale": {"factor": 3.0}}}]}]}], + "queries": [{"id": "sum", "texts": [{"language": "PromQl", "text": "sum_over_time(m[10s])"}], + "window_ms": 10000, "evaluation_interval_ms": 10000}] + })) + .unwrap(); + write( + &run.path().join("workloads/groups.json"), + &serde_json::to_string(&workload).unwrap(), + ); + write( + &run.path().join("plans/text/variant.json"), + r#"{"substitutions_allowed": false, "plans": false}"#, + ); + let cells = run_fake(&run, None).unwrap(); + assert_eq!( + outcomes(&cells), + vec![("groups".into(), "text".into(), CellOutcome::Ran)] + ); + let result = read_result(&run, "groups", "text"); + let series = aqpbm_core::harness::data::metric_series(&workload, Path::new(".")).unwrap(); + assert_eq!(result.ingested_samples, 120); + let times: Vec = result.answers.iter().map(|(t, _)| *t).collect(); + assert_eq!(times, workload.evaluation_times(&workload.queries[0])); + for (t, answers) in &result.answers { + for generated in &series { + let mut labels = generated.labels.clone(); + labels.remove("__name__"); + let sum: f64 = generated.between(t - 10_000, *t).iter().map(|p| p.1).sum(); + let answer = answers.get("sum", &labels).unwrap(); + assert!((answer - sum).abs() < 1e-9, "{t} {labels:?}"); + } + } +} diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs index 468c8a48..ec7aa216 100644 --- a/aqpbm-core/tests/harness_cgroup.rs +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -258,6 +258,9 @@ fn two_series_workload() -> WorkloadSpec { window_ms: 10_000, evaluation_interval_ms: 10_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }], vec![DataRecord { metric: "m".into(), @@ -321,6 +324,7 @@ fn an_arm_on_a_cgroup_server_records_cpu_memory_and_samples() { let result = run_arm( &engine, &workload, + std::path::Path::new("."), &arm, &schedule, &protocol, @@ -409,6 +413,7 @@ fn installs_one_after_another_count_the_server_cpu_from_each_install() { let result = run_arm( &engine, &workload, + std::path::Path::new("."), &arm, &schedule, &protocol, diff --git a/aqpbm-core/tests/harness_fake.rs b/aqpbm-core/tests/harness_fake.rs index bec9af80..f5e1008e 100644 --- a/aqpbm-core/tests/harness_fake.rs +++ b/aqpbm-core/tests/harness_fake.rs @@ -77,6 +77,9 @@ fn sum_query(id: &str, metric: &str, window_s: u64) -> WorkloadQuery { window_ms: window_s * 1_000, evaluation_interval_ms: 10_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, } } @@ -145,6 +148,7 @@ fn run_probe_on( run_arm( engine, &workload, + std::path::Path::new("."), &arm(), &probe_schedule(&workload), &Protocol::default(), @@ -376,6 +380,7 @@ fn consecutive_jobs_share_one_idle_sample() { let result = run_arm( &engine, &workload, + std::path::Path::new("."), &arm(), &probe_schedule(&workload), &Protocol::default(), @@ -436,6 +441,7 @@ fn a_workload_without_data_is_refused() { let error = run_arm( &engine, &workload, + std::path::Path::new("."), &arm(), &ArmSchedule { refresh_ms: 10_000, @@ -569,6 +575,7 @@ fn an_engine_that_holds_one_install_at_a_time_runs_the_arm_once_per_run() { let result = run_arm( &engine, &workload, + std::path::Path::new("."), &arm(), &probe_schedule(&workload), &protocol, diff --git a/aqpbm-core/tests/harness_workload_metrics.rs b/aqpbm-core/tests/harness_workload_metrics.rs new file mode 100644 index 00000000..29077ac5 --- /dev/null +++ b/aqpbm-core/tests/harness_workload_metrics.rs @@ -0,0 +1,161 @@ +use std::path::Path; + +use aqpbm_core::harness::arm_run::ArmSchedule; +use aqpbm_core::harness::data::{metric_series, workload_sample_chunks, workload_series}; +use aqpbm_core::harness::engine::{QueryLanguage, WorkloadSpec}; + +const START_MS: i64 = 1_767_225_600_000; + +fn workload() -> WorkloadSpec { + let workload: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "groups", + "start_ms": START_MS, + "duration_ms": 20000, + "seed": 3, + "metrics": [ + {"name": "latency", "sample_interval_ms": 500, "non_negative": true, "series": [ + {"count": 2, "labels": {"host": "h{i}"}, + "baseline": {"kind": "uniform", "lower_bound": 1.0, "upper_bound": 2.0, "seed": 4}, + "phases": [{"start_offset_ms": 5000, "end_offset_ms": 15000, "ramp_ms": 0, + "change": {"mix": {"share": 0.5, "distribution": + {"kind": "uniform", "lower_bound": 10.0, "upper_bound": 11.0, "seed": 5}}}}]}]}, + {"name": "requests", "sample_interval_ms": 250, "floor": true, "label_from_value": "code", + "planned_series_count": 2, "series": [ + {"labels": {}, "baseline": {"kind": "uniform", "lower_bound": 200, "upper_bound": 202, "seed": 6}}]} + ], + "queries": [ + {"id": "p50", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.5, latency[5s])"}], + "window_ms": 5000, "evaluation_interval_ms": 1000, "threshold": 5.0, "unit": "s", + "accuracy_metric": "rank"} + ] + })) + .unwrap(); + workload.check().unwrap(); + workload +} + +#[test] +fn a_workload_with_metrics_reads_the_use_case_fields() { + let workload = workload(); + let query = &workload.queries[0]; + assert_eq!( + query.text_in(QueryLanguage::PromQl), + Some("quantile_over_time(0.5, latency[5s])") + ); + assert_eq!(query.threshold, Some(5.0)); + assert_eq!(query.unit.as_deref(), Some("s")); + assert_eq!(query.accuracy_metric.as_deref(), Some("rank")); + assert!(workload.data.is_empty()); + assert_eq!(workload.metric_names(), vec!["latency", "requests"]); + assert_eq!(workload.data_start_ms(), Some(START_MS)); + assert_eq!(workload.data_end_ms(), Some(START_MS + 20000)); + assert_eq!(workload.data_duration_ms(), 20000); + let text = serde_json::to_string(&workload).unwrap(); + let back: WorkloadSpec = serde_json::from_str(&text).unwrap(); + assert_eq!(back, workload); +} + +#[test] +fn each_query_is_evaluated_from_one_window_after_the_start_through_the_end() { + let workload = workload(); + let times = workload.evaluation_times(&workload.queries[0]); + assert_eq!(times.first(), Some(&(START_MS + 5000))); + assert_eq!(times.last(), Some(&(START_MS + 20000))); + assert!(times.windows(2).all(|w| w[1] - w[0] == 1000)); + let schedule = ArmSchedule::for_workload(&workload).unwrap(); + assert_eq!(schedule.refresh_ms, 1000); + assert_eq!(schedule.evaluate_at_ms, times); +} + +#[test] +fn the_metrics_generate_their_series_with_names_labels_and_values() { + let workload = workload(); + let series = metric_series(&workload, Path::new(".")).unwrap(); + let drawn = |series: &[aqpbm_core::accuracy::declared_truth::Series]| { + series + .iter() + .map(|s| (s.labels.clone(), s.points.clone())) + .collect::>() + }; + assert_eq!( + drawn(&series), + drawn(&workload_series(&workload, Path::new(".")).unwrap()) + ); + let latency: Vec<_> = series + .iter() + .filter(|s| s.labels["__name__"] == "latency") + .collect(); + assert_eq!(latency.len(), 2); + assert_eq!(latency[1].labels["host"], "h1"); + assert!(latency.iter().all(|s| s.points.len() == 40)); + let mixed = |s: &&aqpbm_core::accuracy::declared_truth::Series| { + s.points + .iter() + .filter(|&&(t, v)| v >= 10.0 && !(START_MS + 5000..START_MS + 15000).contains(&t)) + .count() + }; + assert!(latency.iter().all(|s| mixed(s) == 0)); + let codes: Vec<&str> = series + .iter() + .filter(|s| s.labels["__name__"] == "requests") + .map(|s| s.labels["code"].as_str()) + .collect(); + assert_eq!(codes, vec!["200", "201"]); +} + +#[test] +fn refresh_chunks_hold_every_metric_sample_in_time_order() { + let workload = workload(); + let series = metric_series(&workload, Path::new(".")).unwrap(); + let mut expected: Vec<(i64, usize, u64)> = series + .iter() + .enumerate() + .flat_map(|(i, s)| s.points.iter().map(move |&(t, v)| (t, i, v.to_bits()))) + .collect(); + expected.sort(); + let mut seen = Vec::new(); + let mut ends = Vec::new(); + for chunk in workload_sample_chunks(&workload, Path::new("."), 3000).unwrap() { + let chunk = chunk.unwrap(); + assert!(chunk + .samples + .iter() + .all(|s| s.ts_ms > chunk.end_ms - 3000 && s.ts_ms <= chunk.end_ms)); + for sample in &chunk.samples { + let index = series + .iter() + .position(|s| s.labels == *sample.labels) + .unwrap(); + seen.push((sample.ts_ms, index, sample.value.to_bits())); + } + ends.push(chunk.end_ms - START_MS); + } + assert_eq!(ends, vec![3000, 6000, 9000, 12000, 15000, 18000, 21000]); + assert_eq!(seen, expected); +} + +#[test] +fn metrics_without_their_start_duration_and_seed_are_refused() { + let mut workload = workload(); + workload.seed = None; + let error = workload.check().unwrap_err(); + assert!(error.contains("seed"), "{error}"); + assert!(metric_series(&workload, Path::new(".")).is_err()); +} + +#[test] +fn an_imported_table_that_cannot_be_read_names_its_metric() { + let workload: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "imported", "start_ms": 0, "duration_ms": 1000, "seed": 1, + "metrics": [{"name": "trace", "sample_interval_ms": 10, "planned_series_count": 1, + "import": {"table": {"source": "custom", "dataset": "missing/trace.csv", "mode": "scalar", + "value_column": "v", "timestamp_column": "t", "timestamp_unit": "milliseconds"}}}], + "queries": [] + })) + .unwrap(); + let Err(error) = metric_series(&workload, Path::new("/nonexistent")) else { + panic!("a table that cannot be read generates no series"); + }; + let error = error.to_string(); + assert!(error.contains("trace"), "{error}"); +} diff --git a/system-bench/src/engines_external/clickhouse_server.rs b/system-bench/src/engines_external/clickhouse_server.rs index dbdf134b..29589152 100644 --- a/system-bench/src/engines_external/clickhouse_server.rs +++ b/system-bench/src/engines_external/clickhouse_server.rs @@ -199,12 +199,7 @@ impl EngineUnderTest for ClickHouseEngine { /// interval and the data start. Refused at install, not at the first /// evaluation. fn check_evaluation_times(workload: &WorkloadSpec, steps_ms: &[u64]) -> Result<(), EngineError> { - let data_start_ms = workload - .data - .iter() - .map(|record| record.description.start_ms) - .min() - .unwrap_or(0); + let data_start_ms = workload.data_start_ms().unwrap_or(0); for (query, &step_ms) in workload.queries.iter().zip(steps_ms) { let step = step_ms as i64; if (query.evaluation_interval_ms as i64) % step != 0 || data_start_ms % step != 0 { diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs index 59320fb7..0caf683c 100644 --- a/system-bench/src/engines_external/victoriametrics_server.rs +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -164,11 +164,7 @@ impl VictoriaMetricsEngine { http: self.http.clone(), arm_installed: Arc::clone(&self.arm_installed), queries, - metrics: workload - .data - .iter() - .map(|record| record.metric.clone()) - .collect(), + metrics: workload.metric_names(), data_bytes_at_install: 0, }; installed.delete_series()?; @@ -364,12 +360,7 @@ fn check_time_steps( /// 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) + workload.data_start_ms().unwrap_or(0) } /// The offset from data time to wall time: the smallest multiple of diff --git a/system-bench/tests/clickhouse_conformance.rs b/system-bench/tests/clickhouse_conformance.rs index ded51897..4102dbc0 100644 --- a/system-bench/tests/clickhouse_conformance.rs +++ b/system-bench/tests/clickhouse_conformance.rs @@ -103,6 +103,9 @@ fn workload(plan: &Value, interval_ms: Option) -> WorkloadSpec { window_ms: 60_000, evaluation_interval_ms: interval_ms, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }) .collect(), vec![], @@ -795,6 +798,7 @@ fn the_clickhouse_engine_matches_the_fake_engine() { engine, None, EngineRunSetup { + data_root: std::path::Path::new("."), protocol: &protocol, core: 0, probe: probe.as_mut(), @@ -811,6 +815,7 @@ fn the_clickhouse_engine_matches_the_fake_engine() { engine: "fake".into(), variant: "equivalent-only".into(), }, + std::path::Path::new("."), ) .unwrap(); println!("{}", report.summary_markdown()); diff --git a/system-bench/tests/clickhouse_server.rs b/system-bench/tests/clickhouse_server.rs index efe48945..6d0815cf 100644 --- a/system-bench/tests/clickhouse_server.rs +++ b/system-bench/tests/clickhouse_server.rs @@ -191,6 +191,9 @@ fn workload_of(plan: &str, interval_ms: u64, start_ms: i64) -> WorkloadSpec { window_ms: 60_000, evaluation_interval_ms: interval_ms, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }) .collect(), vec![data_record(start_ms)], @@ -748,6 +751,9 @@ fn only_a_bare_selector_keeps_the_metric_name() { window_ms: 60_000, evaluation_interval_ms: 60_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }], vec![data_record(0)], ); diff --git a/system-bench/tests/end_to_end_adapters.rs b/system-bench/tests/end_to_end_adapters.rs index 579224c8..ec908fc0 100644 --- a/system-bench/tests/end_to_end_adapters.rs +++ b/system-bench/tests/end_to_end_adapters.rs @@ -123,6 +123,9 @@ fn workload() -> WorkloadSpec { window_ms: 60_000, evaluation_interval_ms: 60_000, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }) .collect(), vec![aqpbm_core::harness::data::DataRecord { diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs index 77446b1b..8af0a9d7 100644 --- a/system-bench/tests/victoriametrics_conformance.rs +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -95,6 +95,9 @@ fn workload(plan: &Value, interval_ms: u64) -> WorkloadSpec { window_ms: 60_000, evaluation_interval_ms: interval_ms, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }) .collect(), vec![], diff --git a/system-bench/tests/victoriametrics_server.rs b/system-bench/tests/victoriametrics_server.rs index ed88ce7b..5a342947 100644 --- a/system-bench/tests/victoriametrics_server.rs +++ b/system-bench/tests/victoriametrics_server.rs @@ -290,6 +290,9 @@ fn workload(texts: &[&str], interval_ms: u64) -> WorkloadSpec { window_ms: 60_000, evaluation_interval_ms: interval_ms, truth: None, + threshold: None, + unit: None, + accuracy_metric: None, }) .collect(), vec![], From 8e30d140a6398b435f2dc6186bcdd9a8a690e52c Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:25:55 +0000 Subject: [PATCH 19/51] aqpbm-usecase: the 16 use-case files are WorkloadSpecs; planeval and systemeval read WorkloadSpec; the use-case Spec is removed The files under aqpbm-usecase/workloads keep their names and data; three names change to WorkloadSpec's: use_case is name, interval_ms is evaluation_interval_ms, and promql is a PromQl entry of texts. Every other field keeps the Spec's name. Each file generates the same samples as before (checked file by file, with the import feature planeval and approxbench build with; the real-trace files' imported tables are not on this machine, so only their generated metrics were checked). planeval and systemeval read any WorkloadSpec, including the *.workload.json suites: they generate data records and metrics alike, and plan with the data records as sources too. Their output files keep every field. The Spec and the generator copy in aqpbm-usecase are removed; aqpbm-usecase keeps the scoring, the output layout and read_workload. The Python that reads the use-case files (run_use_case.py through bounds and scenario, run_use_case_on_systems.py, tools/grafana and the uc3 workload writers) reads the new names; the dashboards it generates are unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-usecase/Cargo.toml | 6 +- aqpbm-usecase/src/data.rs | 279 +----------------- aqpbm-usecase/src/lib.rs | 1 - aqpbm-usecase/src/score.rs | 4 +- aqpbm-usecase/src/spec.rs | 256 ---------------- aqpbm-usecase/tests/datagen_conventions.rs | 12 +- aqpbm-usecase/tests/random_streams.rs | 14 +- aqpbm-usecase/tests/uc1.rs | 27 +- aqpbm-usecase/workloads/uc1_syn_flood.json | 12 +- .../workloads/uc1_syn_flood_real.json | 22 +- .../uc1_syn_flood_real_caida_2019.json | 22 +- .../uc1_syn_flood_real_mawi_2019.json | 22 +- aqpbm-usecase/workloads/uc2_autoscaling.json | 14 +- .../workloads/uc2_autoscaling_real.json | 26 +- aqpbm-usecase/workloads/uc3_video.json | 26 +- aqpbm-usecase/workloads/uc3_video_real.json | 26 +- aqpbm-usecase/workloads/uc4_canary.json | 10 +- aqpbm-usecase/workloads/uc4_canary_real.json | 18 +- .../workloads/uc4_canary_real_native.json | 18 +- aqpbm-usecase/workloads/uc5_top_clients.json | 6 +- .../workloads/uc5_top_clients_real.json | 10 +- .../uc5_top_clients_real_caida_2019.json | 10 +- .../uc5_top_clients_real_mawi_2019.json | 10 +- .../workloads/uc5_top_clients_real_nasa.json | 10 +- scripts/dataset_tools/real_data_video.py | 2 +- scripts/dataset_tools/video_spec.py | 22 +- scripts/use_cases/bounds.py | 9 +- scripts/use_cases/cases/__init__.py | 4 + scripts/use_cases/run_use_case_on_systems.py | 12 +- scripts/use_cases/scenario.py | 6 +- scripts/use_cases/test_bounds.py | 7 +- .../use_cases/test_run_use_case_on_systems.py | 4 +- scripts/use_cases/test_scenario.py | 5 +- system-bench/Cargo.toml | 3 +- system-bench/src/bin/planeval.rs | 21 +- system-bench/src/bin/systemeval.rs | 22 +- system-bench/src/planeval/plan.rs | 36 ++- system-bench/src/systemeval/query.rs | 11 +- system-bench/tests/declared_truth.rs | 10 +- system-bench/tests/uc1.rs | 14 +- tools/grafana/generate_dashboards.py | 4 +- 41 files changed, 303 insertions(+), 750 deletions(-) delete mode 100644 aqpbm-usecase/src/spec.rs diff --git a/aqpbm-usecase/Cargo.toml b/aqpbm-usecase/Cargo.toml index 12c378cb..d10c26cd 100644 --- a/aqpbm-usecase/Cargo.toml +++ b/aqpbm-usecase/Cargo.toml @@ -3,13 +3,15 @@ name = "aqpbm-usecase" version.workspace = true edition.workspace = true license.workspace = true -description = "Use-case specs: the recurring queries, the samples they run over, each query's declared truth, and the scoring of answers against it." +description = "Use-case workloads (WorkloadSpec files under workloads/) and the scoring of answers against each query's declared truth and an exact run's answers." [dependencies] aqpbm-core.workspace = true -aqpbm-datagen = { workspace = true, features = ["import"] } anyhow.workspace = true serde.workspace = true serde_json.workspace = true + +[dev-dependencies] +aqpbm-datagen.workspace = true rand.workspace = true rand_xoshiro.workspace = true diff --git a/aqpbm-usecase/src/data.rs b/aqpbm-usecase/src/data.rs index 9930852e..d6713906 100644 --- a/aqpbm-usecase/src/data.rs +++ b/aqpbm-usecase/src/data.rs @@ -1,21 +1,24 @@ -use std::collections::BTreeMap; - -use anyhow::Result; -use aqpbm_datagen::{sample_offsets_ms, series_stream_seed, splitmix64, DataDistribution, Sampler}; -use rand::{Rng, SeedableRng}; -use rand_xoshiro::Xoshiro256PlusPlus; - use std::path::Path; -use anyhow::Context; -use aqpbm_datagen::ColumnData; - -use crate::spec::{Change, Import, MetricSpec, Phase, SeriesGroup, Spec}; +use anyhow::{Context, Result}; +use aqpbm_core::harness::engine::WorkloadSpec; pub use aqpbm_core::accuracy::declared_truth::Series; pub type Slice<'a> = (&'a Series, &'a [(i64, f64)]); +pub fn read_workload(path: &Path) -> Result { + let text = + std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let workload: WorkloadSpec = + serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + workload + .check() + .map_err(anyhow::Error::msg) + .with_context(|| format!("checking {}", path.display()))?; + Ok(workload) +} + pub fn between(series: &[Series], start_exclusive: i64, end_inclusive: i64) -> Vec> { series .iter() @@ -31,257 +34,3 @@ pub fn up_to(series: &[Series], end_inclusive: i64) -> Vec> { .filter(|(_, points)| !points.is_empty()) .collect() } - -pub fn intensity(phase: &Phase, offset_ms: i64, shift_ms: i64) -> f64 { - let start = phase.start_offset_ms + shift_ms; - let end = phase.end_offset_ms + shift_ms; - if offset_ms < start || offset_ms >= end { - return 0.0; - } - if phase.ramp_ms == 0 { - return 1.0; - } - let rise = (offset_ms - start + 1) as f64 / phase.ramp_ms as f64; - let fall = (end - offset_ms) as f64 / phase.ramp_ms as f64; - rise.min(fall).min(1.0) -} - -const PHASE_CHOICE_TAG: u64 = u64::MAX; - -fn tagged_seed(seed: u64, tag: u64) -> u64 { - match tag { - 0 => seed, - tag => seed ^ splitmix64(tag), - } -} - -struct Stream<'a> { - metric: &'a MetricSpec, - group: &'a SeriesGroup, - index: i64, - distributions: Vec<(Sampler, Xoshiro256PlusPlus)>, - phase_distribution: Vec>, - choice: Xoshiro256PlusPlus, -} - -impl<'a> Stream<'a> { - fn new( - spec: &Spec, - metric: &'a MetricSpec, - group: &'a SeriesGroup, - stream: u64, - index: i64, - ) -> Result> { - let mut known: Vec<&DataDistribution> = vec![&group.baseline]; - let mut phase_distribution = Vec::new(); - for phase in &group.phases { - phase_distribution.push(match &phase.change { - Change::Mix { distribution, .. } => Some( - known - .iter() - .position(|d| *d == distribution) - .unwrap_or_else(|| { - known.push(distribution); - known.len() - 1 - }), - ), - Change::Scale { .. } | Change::Rate { .. } => None, - }); - } - let distributions = known - .iter() - .zip(0u64..) - .map(|(d, tag)| { - Ok(( - d.sampler()?, - Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( - tagged_seed(d.seed(), tag), - stream, - )), - )) - }) - .collect::>()?; - Ok(Stream { - metric, - group, - index, - distributions, - phase_distribution, - choice: Xoshiro256PlusPlus::seed_from_u64(series_stream_seed( - tagged_seed(spec.seed, PHASE_CHOICE_TAG), - stream, - )), - }) - } - - fn draw(&mut self, offset_ms: i64) -> f64 { - let u = self.choice.random::(); - let mut chosen = None; - let mut cumulative = 0.0; - let mut scale = 1.0; - for (phase, distribution) in self.group.phases.iter().zip(&self.phase_distribution) { - let w = intensity(phase, offset_ms, self.index * phase.stagger_ms); - if w == 0.0 { - continue; - } - match (&phase.change, distribution) { - (Change::Mix { share, .. }, Some(index)) => { - cumulative += share * w; - if chosen.is_none() && u < cumulative { - chosen = Some(*index); - } - } - (Change::Scale { factor }, _) => scale *= 1.0 + w * (factor - 1.0), - _ => {} - } - } - let (sampler, rng) = &mut self.distributions[chosen.unwrap_or(0)]; - let mut value = sampler.sample(rng) * scale; - if self.metric.floor { - value = value.floor(); - } - if self.metric.non_negative { - value = value.max(0.0); - } - value - } -} - -/// Offsets in ms of one stream's samples: one every `interval_ms` on `aqpbm-datagen`'s grid -/// (`sample_offsets_ms`, the first one interval after the start), more often while a rate phase holds. -fn offsets(group: &SeriesGroup, interval_ms: i64, duration_ms: i64, index: i64) -> Vec { - let rates: Vec<(&Phase, f64)> = group - .phases - .iter() - .filter_map(|phase| match phase.change { - Change::Rate { factor } => Some((phase, factor)), - _ => None, - }) - .collect(); - if rates.is_empty() { - return sample_offsets_ms(interval_ms as u64, duration_ms as u64) - .map(|offset| offset as i64) - .collect(); - } - let mut out = Vec::new(); - let mut offset = 0.0f64; - loop { - let at = offset.round() as i64; - let rate: f64 = rates - .iter() - .map(|(phase, factor)| { - 1.0 + intensity(phase, at, index * phase.stagger_ms) * (factor - 1.0) - }) - .product(); - offset += interval_ms as f64 / rate; - if offset > duration_ms as f64 { - return out; - } - out.push(offset.round() as i64); - } -} - -fn labels(metric: &MetricSpec, group: &SeriesGroup, index: usize) -> BTreeMap { - let mut labels: BTreeMap = group - .labels - .iter() - .map(|(k, v)| (k.clone(), v.replace("{i}", &index.to_string()))) - .collect(); - labels.insert("__name__".into(), metric.name.clone()); - labels -} - -fn imported( - spec: &Spec, - metric: &MetricSpec, - import: &Import, - data_root: &Path, -) -> Result> { - let table = import - .table - .load(data_root) - .with_context(|| format!("loading metric {}", metric.name))? - .with_context(|| format!("metric {}: the table has no records", metric.name))?; - let groups = import.table.group_columns.len(); - let first_group = table.column_num as usize - 1 - groups; - let times = table.column(0)?.as_i64()?; - let values = table.column(table.column_num as usize - 1)?.as_f64()?; - let labels_of: Vec<&[String]> = (first_group..first_group + groups) - .map(|i| table.column(i).and_then(ColumnData::as_string)) - .collect::>()?; - let first = import - .origin_ns - .unwrap_or_else(|| times.iter().copied().min().unwrap_or(0)); - let mut by_labels: BTreeMap, Vec<(i64, f64)>> = BTreeMap::new(); - for row in 0..times.len() { - let offset_ms = 1 + ((times[row] - first) as f64 / 1e6 * import.time_scale) as i64; - if offset_ms < 1 || offset_ms > spec.duration_ms { - continue; - } - let mut labels = BTreeMap::from([("__name__".to_string(), metric.name.clone())]); - for (column, values) in import.table.group_columns.iter().zip(&labels_of) { - labels.insert(column.clone(), values[row].clone()); - } - let mut value = values[row]; - if let Some(label) = &metric.label_from_value { - labels.insert(label.clone(), (value as u64).to_string()); - value = 1.0; - } - by_labels - .entry(labels) - .or_default() - .push((spec.start_ms + offset_ms, value)); - } - Ok(by_labels - .into_iter() - .map(|(labels, mut points)| { - points.sort_by_key(|&(t, _)| t); - Series { labels, points } - }) - .collect()) -} - -pub fn generate(spec: &Spec, data_root: &Path) -> Result> { - let mut out = Vec::new(); - let mut stream = 0u64; - for metric in &spec.metrics { - if let Some(import) = &metric.import { - out.extend(imported(spec, metric, import, data_root)?); - continue; - } - for group in &metric.series { - let interval_ms = metric.sample_interval_of(group); - if let Some(label) = &metric.label_from_value { - let mut drawn = Stream::new(spec, metric, group, stream, 0)?; - stream += 1; - let mut by_value: BTreeMap> = BTreeMap::new(); - for offset_ms in offsets(group, interval_ms, spec.duration_ms, 0) { - let value = drawn.draw(offset_ms) as u64; - by_value - .entry(value) - .or_default() - .push((spec.start_ms + offset_ms, 1.0)); - } - for (value, points) in by_value { - let mut labels = labels(metric, group, 0); - labels.insert(label.clone(), value.to_string()); - out.push(Series { labels, points }); - } - continue; - } - for index in 0..group.count { - let mut drawn = Stream::new(spec, metric, group, stream, index as i64)?; - stream += 1; - let points = offsets(group, interval_ms, spec.duration_ms, index as i64) - .into_iter() - .map(|offset_ms| (spec.start_ms + offset_ms, drawn.draw(offset_ms))) - .collect(); - out.push(Series { - labels: labels(metric, group, index), - points, - }); - } - } - } - Ok(out) -} diff --git a/aqpbm-usecase/src/lib.rs b/aqpbm-usecase/src/lib.rs index 08f7cf6b..d1f8c99c 100644 --- a/aqpbm-usecase/src/lib.rs +++ b/aqpbm-usecase/src/lib.rs @@ -2,4 +2,3 @@ pub mod accuracy; pub mod data; pub mod output; pub mod score; -pub mod spec; diff --git a/aqpbm-usecase/src/score.rs b/aqpbm-usecase/src/score.rs index d1e83dcf..04fc5cb2 100644 --- a/aqpbm-usecase/src/score.rs +++ b/aqpbm-usecase/src/score.rs @@ -8,7 +8,7 @@ use serde_json::Value; use crate::accuracy::{keyed, without_name, AnswerAt, Labels, Scores}; use crate::data::Series; use crate::output::{Answer, TruthCell}; -use crate::spec::QuerySpec; +use aqpbm_core::harness::engine::WorkloadQuery; pub fn read_answers(path: &Path) -> Result>> { let text = @@ -43,7 +43,7 @@ pub struct Scored { } pub fn score( - query: &QuerySpec, + query: &WorkloadQuery, series: &[Series], times: &[i64], answered: &[AnswerAt], diff --git a/aqpbm-usecase/src/spec.rs b/aqpbm-usecase/src/spec.rs deleted file mode 100644 index f1c4db8a..00000000 --- a/aqpbm-usecase/src/spec.rs +++ /dev/null @@ -1,256 +0,0 @@ -use std::collections::BTreeMap; -use std::path::Path; - -use anyhow::{bail, Context, Result}; -use aqpbm_datagen::DataDistribution; -use serde::Deserialize; - -use aqpbm_core::accuracy::declared_truth::QueryTruth; -pub use aqpbm_core::accuracy::declared_truth::{Statistic, Truth}; - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Spec { - pub use_case: String, - pub start_ms: i64, - pub duration_ms: i64, - pub seed: u64, - pub metrics: Vec, - pub queries: Vec, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct MetricSpec { - pub name: String, - pub sample_interval_ms: i64, - #[serde(default)] - pub max_distinct_per_evaluation: Option, - #[serde(default)] - pub floor: bool, - #[serde(default)] - pub non_negative: bool, - #[serde(default)] - pub label_from_value: Option, - #[serde(default)] - pub planned_series_count: Option, - #[serde(default)] - pub series: Vec, - #[serde(default)] - pub import: Option, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Import { - pub table: aqpbm_datagen::ExternalTableDescription, - #[serde(default = "unit_scale")] - pub time_scale: f64, - #[serde(default)] - pub origin_ns: Option, -} - -fn unit_scale() -> f64 { - 1.0 -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct SeriesGroup { - #[serde(default = "one")] - pub count: usize, - #[serde(default)] - pub sample_interval_ms: Option, - pub labels: BTreeMap, - pub baseline: DataDistribution, - #[serde(default)] - pub phases: Vec, -} - -fn one() -> usize { - 1 -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct Phase { - pub start_offset_ms: i64, - pub end_offset_ms: i64, - pub ramp_ms: i64, - #[serde(default)] - pub stagger_ms: i64, - pub change: Change, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields, rename_all = "snake_case")] -pub enum Change { - Mix { - share: f64, - distribution: DataDistribution, - }, - Scale { - factor: f64, - }, - /// Multiplies how often the series samples: factor 25 writes 25 samples where the baseline writes one. - Rate { - factor: f64, - }, -} - -#[derive(Debug, Clone, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct QuerySpec { - pub id: String, - pub promql: String, - pub window_ms: i64, - pub interval_ms: i64, - #[serde(default)] - pub threshold: Option, - pub unit: String, - #[serde(default)] - pub accuracy_metric: Option, - #[serde(default)] - pub truth: Option, -} - -impl QuerySpec { - pub fn declared_truth(&self) -> Option { - Some(QueryTruth::new(self.truth.as_ref()?, self.window_ms)) - } -} - -impl MetricSpec { - pub fn series_count(&self) -> u64 { - self.planned_series_count - .unwrap_or_else(|| self.series.iter().map(|g| g.count as u64).sum()) - } - - pub fn planned_sample_interval_ms(&self) -> i64 { - match self.label_from_value { - Some(_) => self.sample_interval_ms * self.series_count() as i64, - None => self.sample_interval_ms, - } - } - - pub fn sample_interval_of(&self, group: &SeriesGroup) -> i64 { - group.sample_interval_ms.unwrap_or(self.sample_interval_ms) - } - - pub fn rows_per_second(&self) -> f64 { - if self.import.is_some() { - let streams = match self.label_from_value { - Some(_) => 1, - None => self.series_count(), - }; - return streams as f64 * 1000.0 / self.sample_interval_ms as f64; - } - self.series - .iter() - .map(|g| { - let streams = match self.label_from_value { - Some(_) => 1, - None => g.count, - }; - streams as f64 * 1000.0 / self.sample_interval_of(g) as f64 - }) - .sum() - } -} - -impl Spec { - pub fn read(path: &Path) -> Result { - let text = - std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; - let spec: Spec = - serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; - spec.check()?; - Ok(spec) - } - - pub fn check(&self) -> Result<()> { - if self.duration_ms <= 0 { - bail!("duration_ms must be positive"); - } - for metric in &self.metrics { - if metric.import.is_some() != metric.series.is_empty() { - bail!( - "metric {} needs either series to generate or a table to import, not both", - metric.name - ); - } - if metric.import.is_some() && metric.planned_series_count.is_none() { - bail!( - "metric {} is imported, so it needs planned_series_count", - metric.name - ); - } - if metric.import.as_ref().is_some_and(|i| i.time_scale <= 0.0) { - bail!("metric {} needs a positive time_scale", metric.name); - } - if metric.sample_interval_ms <= 0 - || metric - .series - .iter() - .any(|g| metric.sample_interval_of(g) <= 0) - { - bail!("metric {} needs a positive sample_interval_ms", metric.name); - } - if metric.label_from_value.is_some() && metric.planned_series_count.is_none() { - bail!( - "metric {} draws its series from values, so it needs planned_series_count", - metric.name - ); - } - for phase in metric.series.iter().flat_map(|g| &g.phases) { - let share = match phase.change { - Change::Mix { share, .. } => share, - Change::Scale { .. } => 0.0, - Change::Rate { factor } if factor > 0.0 => 0.0, - Change::Rate { .. } => { - bail!("a rate phase of {} needs a positive factor", metric.name) - } - }; - if !(0.0..=1.0).contains(&share) - || phase.start_offset_ms >= phase.end_offset_ms - || phase.ramp_ms < 0 - { - bail!( - "phase {phase:?} of {} is not a span with a share in [0, 1]", - metric.name - ); - } - } - } - for query in &self.queries { - if query.window_ms <= 0 || query.interval_ms <= 0 { - bail!("query {} needs a positive window and interval", query.id); - } - if self.start_ms.rem_euclid(query.interval_ms) != 0 { - bail!("start_ms is not on query {}'s interval grid", query.id); - } - } - Ok(()) - } - - pub fn end_ms(&self) -> i64 { - self.start_ms + self.duration_ms - } - - pub fn query(&self, id: &str) -> Result<&QuerySpec> { - self.queries - .iter() - .find(|q| q.id == id) - .with_context(|| format!("no query {id} in the spec")) - } - - pub fn evaluation_times(&self, query: &QuerySpec) -> Vec { - let first = self.start_ms + query.window_ms; - let first = - first + (query.interval_ms - first.rem_euclid(query.interval_ms)) % query.interval_ms; - (0..) - .map(|i| first + i * query.interval_ms) - .take_while(|&t| t <= self.end_ms()) - .collect() - } -} diff --git a/aqpbm-usecase/tests/datagen_conventions.rs b/aqpbm-usecase/tests/datagen_conventions.rs index 566c3496..7674d7dc 100644 --- a/aqpbm-usecase/tests/datagen_conventions.rs +++ b/aqpbm-usecase/tests/datagen_conventions.rs @@ -4,11 +4,11 @@ use std::path::Path; +use aqpbm_core::harness::data::metric_series as generate; +use aqpbm_core::harness::engine::WorkloadSpec; use aqpbm_datagen::{ series_stream_seed, DataDistribution, NormalParameter, SeriesLabelSpec, TimeSeriesDescription, }; -use aqpbm_usecase::data::generate; -use aqpbm_usecase::spec::Spec; use rand::SeedableRng; use rand_xoshiro::Xoshiro256PlusPlus; @@ -24,9 +24,9 @@ fn normal() -> DataDistribution { /// Three series sampled every 500 ms for 5 s from Normal(0.45, 0.08) with /// seed 22, no phases. -fn spec() -> Spec { - let spec: Spec = serde_json::from_value(serde_json::json!({ - "use_case": "conventions", +fn spec() -> WorkloadSpec { + let spec: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "conventions", "start_ms": START_MS, "duration_ms": 5000, "seed": 1, @@ -40,7 +40,7 @@ fn spec() -> Spec { }] }], "queries": [ - {"id": "q", "promql": "avg_over_time(cpu[1s])", "window_ms": 1000, "interval_ms": 1000, "unit": "ratio"} + {"id": "q", "texts": [{"language": "PromQl", "text": "avg_over_time(cpu[1s])"}], "window_ms": 1000, "evaluation_interval_ms": 1000, "unit": "ratio"} ] })) .unwrap(); diff --git a/aqpbm-usecase/tests/random_streams.rs b/aqpbm-usecase/tests/random_streams.rs index 792bc720..a041e7f9 100644 --- a/aqpbm-usecase/tests/random_streams.rs +++ b/aqpbm-usecase/tests/random_streams.rs @@ -1,28 +1,28 @@ use std::path::Path; +use aqpbm_core::harness::data::metric_series as generate; +use aqpbm_core::harness::engine::WorkloadSpec; use aqpbm_datagen::{series_stream_seed, DataDistribution, UniformParameter}; -use aqpbm_usecase::data::generate; -use aqpbm_usecase::spec::Spec; use rand::{Rng, SeedableRng}; use rand_xoshiro::Xoshiro256PlusPlus; -fn spec(baseline_seed: u64, mix_seed: u64) -> Spec { - let spec: Spec = serde_json::from_value(serde_json::json!({ - "use_case": "t", "start_ms": 0, "duration_ms": 100000, "seed": 5, +fn spec(baseline_seed: u64, mix_seed: u64) -> WorkloadSpec { + let spec: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "t", "start_ms": 0, "duration_ms": 100000, "seed": 5, "metrics": [{"name": "m", "sample_interval_ms": 10, "series": [{ "labels": {"k": "a"}, "baseline": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1.0, "seed": baseline_seed}, "phases": [{"start_offset_ms": 0, "end_offset_ms": 100001, "ramp_ms": 0, "change": {"mix": {"share": 0.5, "distribution": {"kind": "uniform", "lower_bound": 10.0, "upper_bound": 11.0, "seed": mix_seed}}}}]}]}], - "queries": [{"id": "q", "promql": "m", "window_ms": 1000, "interval_ms": 1000, "unit": "x"}] + "queries": [{"id": "q", "texts": [{"language": "PromQl", "text": "m"}], "window_ms": 1000, "evaluation_interval_ms": 1000, "unit": "x"}] })) .unwrap(); spec.check().unwrap(); spec } -fn values(spec: &Spec) -> Vec { +fn values(spec: &WorkloadSpec) -> Vec { let series = generate(spec, Path::new(".")).unwrap(); assert_eq!(series.len(), 1); series[0].points.iter().map(|&(_, v)| v).collect() diff --git a/aqpbm-usecase/tests/uc1.rs b/aqpbm-usecase/tests/uc1.rs index 2c08f9a7..33370f00 100644 --- a/aqpbm-usecase/tests/uc1.rs +++ b/aqpbm-usecase/tests/uc1.rs @@ -1,12 +1,14 @@ use std::path::Path; +use aqpbm_core::accuracy::declared_truth::{Statistic, Truth}; +use aqpbm_core::harness::data::metric_series as generate; +use aqpbm_core::harness::engine::WorkloadSpec; use aqpbm_usecase::accuracy::Labels; -use aqpbm_usecase::data::{generate, Series}; -use aqpbm_usecase::spec::{Spec, Statistic, Truth}; +use aqpbm_usecase::data::{read_workload, Series}; -fn small_spec() -> Spec { - let spec: Spec = serde_json::from_value(serde_json::json!({ - "use_case": "test", +fn small_spec() -> WorkloadSpec { + let spec: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "test", "start_ms": 1767225600000i64, "duration_ms": 60000, "seed": 1, @@ -24,8 +26,8 @@ fn small_spec() -> Spec { }] }], "queries": [ - {"id": "distinct_10s", "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", - "window_ms": 10000, "interval_ms": 5000, "threshold": 300, "unit": "addresses"} + {"id": "distinct_10s", "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], + "window_ms": 10000, "evaluation_interval_ms": 5000, "threshold": 300, "unit": "addresses"} ] })) .unwrap(); @@ -37,8 +39,8 @@ fn small_spec() -> Spec { fn evaluation_times_start_one_window_in_and_stay_on_the_grid() { let spec = small_spec(); let times = spec.evaluation_times(&spec.queries[0]); - assert_eq!(times.first(), Some(&(spec.start_ms + 10000))); - assert_eq!(times.last(), Some(&spec.end_ms())); + assert_eq!(times.first(), Some(&(spec.start_ms.unwrap() + 10000))); + assert_eq!(times.last(), spec.data_end_ms().as_ref()); assert!(times.windows(2).all(|w| w[1] - w[0] == 5000)); } @@ -46,7 +48,7 @@ fn evaluation_times_start_one_window_in_and_stay_on_the_grid() { /// hash pins the values drawn under `aqpbm_datagen::series_stream_seed`. #[test] fn the_use_case_1_spec_draws_a_fixed_sample_stream() { - let spec = Spec::read(Path::new("workloads/uc1_syn_flood.json")).unwrap(); + let spec = read_workload(Path::new("workloads/uc1_syn_flood.json")).unwrap(); let series = generate(&spec, std::path::Path::new(".")).unwrap(); assert_eq!(series.len(), 1); let mut hash: u64 = 0xcbf2_9ce4_8422_2325; @@ -80,7 +82,7 @@ fn a_quantile_answer_is_scored_by_rank_within_its_window_and_series() { ]; let mut spec = small_spec(); spec.metrics[0].name = "m".into(); - spec.queries[0].promql = "quantile_over_time(0.5, m[4ms])".into(); + spec.queries[0].texts[0].text = "quantile_over_time(0.5, m[4ms])".into(); spec.queries[0].window_ms = 4; spec.queries[0].truth = Some(Truth { statistic: Statistic::Quantile(0.5), @@ -114,10 +116,11 @@ fn a_rate_phase_writes_more_samples_while_it_holds_and_none_change_elsewhere() { let points = generate(&spec, std::path::Path::new(".")).unwrap()[0] .points .clone(); + let start_ms = spec.start_ms.unwrap(); let count = |points: &[(i64, f64)], from: i64, to: i64| { points .iter() - .filter(|(t, _)| *t > spec.start_ms + from && *t <= spec.start_ms + to) + .filter(|(t, _)| *t > start_ms + from && *t <= start_ms + to) .count() }; assert_eq!(count(&baseline, 0, 20000), 2000); diff --git a/aqpbm-usecase/workloads/uc1_syn_flood.json b/aqpbm-usecase/workloads/uc1_syn_flood.json index dc401cc8..fbe79991 100644 --- a/aqpbm-usecase/workloads/uc1_syn_flood.json +++ b/aqpbm-usecase/workloads/uc1_syn_flood.json @@ -1,5 +1,5 @@ { - "use_case": "ddos_syn_flood", + "name": "ddos_syn_flood", "start_ms": 1767225600000, "duration_ms": 1800000, "seed": 11, @@ -26,10 +26,10 @@ } ], "queries": [ - {"id": "entropy_10s", "promql": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])", "window_ms": 10000, "interval_ms": 5000, "threshold": 8.5, "unit": "entropy", "truth": {"statistic": "entropy", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, - {"id": "distinct_10s", "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", "window_ms": 10000, "interval_ms": 5000, "threshold": 3000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, - {"id": "distinct_5s", "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])", "window_ms": 5000, "interval_ms": 5000, "threshold": 1700, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, - {"id": "packets_5s", "promql": "count_over_time(src_ip{vm=\"instance1\"}[5s])", "window_ms": 5000, "interval_ms": 5000, "threshold": 100000, "unit": "packets"}, - {"id": "distinct_1m", "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])", "window_ms": 60000, "interval_ms": 5000, "threshold": 18000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}} + {"id": "entropy_10s", "texts": [{"language": "PromQl", "text": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, "evaluation_interval_ms": 5000, "threshold": 8.5, "unit": "entropy", "truth": {"statistic": "entropy", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, + {"id": "distinct_10s", "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, "evaluation_interval_ms": 5000, "threshold": 3000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, + {"id": "distinct_5s", "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, "evaluation_interval_ms": 5000, "threshold": 1700, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}}, + {"id": "packets_5s", "texts": [{"language": "PromQl", "text": "count_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, "evaluation_interval_ms": 5000, "threshold": 100000, "unit": "packets"}, + {"id": "distinct_1m", "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])"}], "window_ms": 60000, "evaluation_interval_ms": 5000, "threshold": 18000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}}} ] } diff --git a/aqpbm-usecase/workloads/uc1_syn_flood_real.json b/aqpbm-usecase/workloads/uc1_syn_flood_real.json index a129099b..9ab277b0 100644 --- a/aqpbm-usecase/workloads/uc1_syn_flood_real.json +++ b/aqpbm-usecase/workloads/uc1_syn_flood_real.json @@ -1,5 +1,5 @@ { - "use_case": "ddos_syn_flood", + "name": "ddos_syn_flood", "start_ms": 1767225600000, "duration_ms": 1800000, "seed": 11, @@ -28,44 +28,44 @@ "queries": [ { "id": "entropy_10s", - "promql": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 8.5, "unit": "entropy", "truth": {"statistic": "entropy", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_10s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 3000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_5s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 1700, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "packets_5s", - "promql": "count_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "count_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 100000, "unit": "packets" }, { "id": "distinct_1m", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])"}], "window_ms": 60000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 18000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} diff --git a/aqpbm-usecase/workloads/uc1_syn_flood_real_caida_2019.json b/aqpbm-usecase/workloads/uc1_syn_flood_real_caida_2019.json index c0ecd076..68cd27c8 100644 --- a/aqpbm-usecase/workloads/uc1_syn_flood_real_caida_2019.json +++ b/aqpbm-usecase/workloads/uc1_syn_flood_real_caida_2019.json @@ -1,5 +1,5 @@ { - "use_case": "ddos_syn_flood", + "name": "ddos_syn_flood", "start_ms": 1767225600000, "duration_ms": 585000, "seed": 11, @@ -28,44 +28,44 @@ "queries": [ { "id": "entropy_10s", - "promql": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 8.5, "unit": "entropy", "truth": {"statistic": "entropy", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_10s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 3000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_5s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 1700, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "packets_5s", - "promql": "count_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "count_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 100000, "unit": "packets" }, { "id": "distinct_1m", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])"}], "window_ms": 60000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 18000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} diff --git a/aqpbm-usecase/workloads/uc1_syn_flood_real_mawi_2019.json b/aqpbm-usecase/workloads/uc1_syn_flood_real_mawi_2019.json index a52742a1..f9531268 100644 --- a/aqpbm-usecase/workloads/uc1_syn_flood_real_mawi_2019.json +++ b/aqpbm-usecase/workloads/uc1_syn_flood_real_mawi_2019.json @@ -1,5 +1,5 @@ { - "use_case": "ddos_syn_flood", + "name": "ddos_syn_flood", "start_ms": 1767225600000, "duration_ms": 895000, "seed": 11, @@ -28,44 +28,44 @@ "queries": [ { "id": "entropy_10s", - "promql": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "entropy_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 8.5, "unit": "entropy", "truth": {"statistic": "entropy", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_10s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], "window_ms": 10000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 3000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "distinct_5s", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 1700, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} }, { "id": "packets_5s", - "promql": "count_over_time(src_ip{vm=\"instance1\"}[5s])", + "texts": [{"language": "PromQl", "text": "count_over_time(src_ip{vm=\"instance1\"}[5s])"}], "window_ms": 5000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 100000, "unit": "packets" }, { "id": "distinct_1m", - "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[1m])"}], "window_ms": 60000, - "interval_ms": 5000, + "evaluation_interval_ms": 5000, "threshold": 18000, "unit": "addresses", "truth": {"statistic": "distinct", "metric": "src_ip", "matchers": {"vm": "instance1"}} diff --git a/aqpbm-usecase/workloads/uc2_autoscaling.json b/aqpbm-usecase/workloads/uc2_autoscaling.json index fbc09bbd..1a09fe42 100644 --- a/aqpbm-usecase/workloads/uc2_autoscaling.json +++ b/aqpbm-usecase/workloads/uc2_autoscaling.json @@ -1,5 +1,5 @@ { - "use_case": "k8s_autoscaling", + "name": "k8s_autoscaling", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 21, @@ -42,11 +42,11 @@ } ], "queries": [ - {"id": "p95_cpu", "promql": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[5m])", "window_ms": 300000, "interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, - {"id": "p95_memory", "promql": "quantile_over_time(0.95, container_memory{dimension=\"used\"}[5m])", "window_ms": 300000, "interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_memory", "matchers": {"dimension": "used"}}}, - {"id": "p50_cpu_1h", "promql": "quantile_over_time(0.5, container_cpu{dimension=\"used\"}[1h])", "window_ms": 3600000, "interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.5}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, - {"id": "p95_cpu_1h", "promql": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[1h])", "window_ms": 3600000, "interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, - {"id": "p99_memory_1h", "promql": "quantile_over_time(0.99, container_memory{dimension=\"used\"}[1h])", "window_ms": 3600000, "interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "container_memory", "matchers": {"dimension": "used"}}}, - {"id": "max_memory_1h", "promql": "max_over_time(container_memory{dimension=\"used\"}[1h])", "window_ms": 3600000, "interval_ms": 60000, "unit": "bytes"} + {"id": "p95_cpu", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[5m])"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, + {"id": "p95_memory", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_memory{dimension=\"used\"}[5m])"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_memory", "matchers": {"dimension": "used"}}}, + {"id": "p50_cpu_1h", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.5, container_cpu{dimension=\"used\"}[1h])"}], "window_ms": 3600000, "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.5}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, + {"id": "p95_cpu_1h", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[1h])"}], "window_ms": 3600000, "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}}}, + {"id": "p99_memory_1h", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, container_memory{dimension=\"used\"}[1h])"}], "window_ms": 3600000, "evaluation_interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "container_memory", "matchers": {"dimension": "used"}}}, + {"id": "max_memory_1h", "texts": [{"language": "PromQl", "text": "max_over_time(container_memory{dimension=\"used\"}[1h])"}], "window_ms": 3600000, "evaluation_interval_ms": 60000, "unit": "bytes"} ] } diff --git a/aqpbm-usecase/workloads/uc2_autoscaling_real.json b/aqpbm-usecase/workloads/uc2_autoscaling_real.json index ef7b7872..48c318e8 100644 --- a/aqpbm-usecase/workloads/uc2_autoscaling_real.json +++ b/aqpbm-usecase/workloads/uc2_autoscaling_real.json @@ -1,5 +1,5 @@ { - "use_case": "k8s_autoscaling", + "name": "k8s_autoscaling", "start_ms": 1767225600000, "duration_ms": 5100000, "seed": 21, @@ -50,54 +50,54 @@ "queries": [ { "id": "p95_cpu", - "promql": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}} }, { "id": "p95_memory", - "promql": "quantile_over_time(0.95, container_memory{dimension=\"used\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_memory{dimension=\"used\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_memory", "matchers": {"dimension": "used"}} }, { "id": "p50_cpu_1h", - "promql": "quantile_over_time(0.5, container_cpu{dimension=\"used\"}[1h])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.5, container_cpu{dimension=\"used\"}[1h])"}], "window_ms": 3600000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.5}, "metric": "container_cpu", "matchers": {"dimension": "used"}} }, { "id": "p95_cpu_1h", - "promql": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[1h])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, container_cpu{dimension=\"used\"}[1h])"}], "window_ms": 3600000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "cores", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "container_cpu", "matchers": {"dimension": "used"}} }, { "id": "p99_memory_1h", - "promql": "quantile_over_time(0.99, container_memory{dimension=\"used\"}[1h])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, container_memory{dimension=\"used\"}[1h])"}], "window_ms": 3600000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "bytes", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "container_memory", "matchers": {"dimension": "used"}} }, { "id": "max_memory_1h", - "promql": "max_over_time(container_memory{dimension=\"used\"}[1h])", + "texts": [{"language": "PromQl", "text": "max_over_time(container_memory{dimension=\"used\"}[1h])"}], "window_ms": 3600000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "bytes" } ] diff --git a/aqpbm-usecase/workloads/uc3_video.json b/aqpbm-usecase/workloads/uc3_video.json index 334644a3..36d498a1 100644 --- a/aqpbm-usecase/workloads/uc3_video.json +++ b/aqpbm-usecase/workloads/uc3_video.json @@ -1,5 +1,5 @@ { - "use_case": "video_experience", + "name": "video_experience", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 31, @@ -5838,48 +5838,48 @@ "queries": [ { "id": "entropy_bitrate", - "promql": "entropy_over_time(bitrate[1m])", + "texts": [{"language": "PromQl", "text": "entropy_over_time(bitrate[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "bits", "truth": {"statistic": "entropy", "metric": "bitrate"} }, { "id": "buffering_l1", - "promql": "sum_over_time(buffering[1m])", + "texts": [{"language": "PromQl", "text": "sum_over_time(buffering[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s" }, { "id": "sessions", - "promql": "count_over_time(bitrate[1m])", + "texts": [{"language": "PromQl", "text": "count_over_time(bitrate[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "sessions" }, { "id": "distinct_devices", - "promql": "distinct_over_time(device_id[1m])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(device_id[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "devices", "truth": {"statistic": "distinct", "metric": "device_id"} }, { "id": "startup_p95", - "promql": "quantile_over_time(0.95, startup_time[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, startup_time[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "startup_time"} }, { "id": "rebuffer_ratio", - "promql": "sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))", + "texts": [{"language": "PromQl", "text": "sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "ratio" } ] diff --git a/aqpbm-usecase/workloads/uc3_video_real.json b/aqpbm-usecase/workloads/uc3_video_real.json index fd9e625f..081cb782 100644 --- a/aqpbm-usecase/workloads/uc3_video_real.json +++ b/aqpbm-usecase/workloads/uc3_video_real.json @@ -1,5 +1,5 @@ { - "use_case": "video_experience", + "name": "video_experience", "start_ms": 1704132000000, "duration_ms": 7200000, "seed": 31, @@ -127,48 +127,48 @@ "queries": [ { "id": "entropy_bitrate", - "promql": "entropy_over_time(bitrate[1m])", + "texts": [{"language": "PromQl", "text": "entropy_over_time(bitrate[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "bits", "truth": {"statistic": "entropy", "metric": "bitrate"} }, { "id": "buffering_l1", - "promql": "sum_over_time(buffering[1m])", + "texts": [{"language": "PromQl", "text": "sum_over_time(buffering[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s" }, { "id": "sessions", - "promql": "count_over_time(bitrate[1m])", + "texts": [{"language": "PromQl", "text": "count_over_time(bitrate[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "sessions" }, { "id": "distinct_devices", - "promql": "distinct_over_time(device_id[1m])", + "texts": [{"language": "PromQl", "text": "distinct_over_time(device_id[1m])"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "devices", "truth": {"statistic": "distinct", "metric": "device_id"} }, { "id": "startup_p95", - "promql": "quantile_over_time(0.95, startup_time[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, startup_time[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "startup_time"} }, { "id": "rebuffer_ratio", - "promql": "sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))", + "texts": [{"language": "PromQl", "text": "sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "ratio" } ] diff --git a/aqpbm-usecase/workloads/uc4_canary.json b/aqpbm-usecase/workloads/uc4_canary.json index 58ad2121..941d4e40 100644 --- a/aqpbm-usecase/workloads/uc4_canary.json +++ b/aqpbm-usecase/workloads/uc4_canary.json @@ -1,5 +1,5 @@ { - "use_case": "canary_release", + "name": "canary_release", "start_ms": 1767225600000, "duration_ms": 15000000, "seed": 41, @@ -58,9 +58,9 @@ } ], "queries": [ - {"id": "p99_canary", "promql": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])", "window_ms": 300000, "interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "canary"}}}, - {"id": "p95_canary", "promql": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])", "window_ms": 300000, "interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "request_latency", "matchers": {"version": "canary"}}}, - {"id": "p99_stable", "promql": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])", "window_ms": 300000, "interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "stable"}}}, - {"id": "success_rate_canary", "promql": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))", "window_ms": 300000, "interval_ms": 60000, "unit": "ratio"} + {"id": "p99_canary", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "canary"}}}, + {"id": "p95_canary", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "request_latency", "matchers": {"version": "canary"}}}, + {"id": "p99_stable", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "stable"}}}, + {"id": "success_rate_canary", "texts": [{"language": "PromQl", "text": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "ratio"} ] } diff --git a/aqpbm-usecase/workloads/uc4_canary_real.json b/aqpbm-usecase/workloads/uc4_canary_real.json index 94a7f12a..bb4d03f8 100644 --- a/aqpbm-usecase/workloads/uc4_canary_real.json +++ b/aqpbm-usecase/workloads/uc4_canary_real.json @@ -1,5 +1,5 @@ { - "use_case": "canary_release", + "name": "canary_release", "start_ms": 1767225600000, "duration_ms": 15000000, "seed": 41, @@ -112,36 +112,36 @@ "queries": [ { "id": "p99_canary", - "promql": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "canary"}} }, { "id": "p95_canary", - "promql": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "request_latency", "matchers": {"version": "canary"}} }, { "id": "p99_stable", - "promql": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "stable"}} }, { "id": "success_rate_canary", - "promql": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))", + "texts": [{"language": "PromQl", "text": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "ratio" } ] diff --git a/aqpbm-usecase/workloads/uc4_canary_real_native.json b/aqpbm-usecase/workloads/uc4_canary_real_native.json index 4f3d904f..2f95b8f7 100644 --- a/aqpbm-usecase/workloads/uc4_canary_real_native.json +++ b/aqpbm-usecase/workloads/uc4_canary_real_native.json @@ -1,5 +1,5 @@ { - "use_case": "canary_release", + "name": "canary_release", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 41, @@ -112,36 +112,36 @@ "queries": [ { "id": "p99_canary", - "promql": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "canary"}} }, { "id": "p95_canary", - "promql": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, request_latency{version=\"canary\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "request_latency", "matchers": {"version": "canary"}} }, { "id": "p99_stable", - "promql": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, request_latency{version=\"stable\"}[5m])"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.99}, "metric": "request_latency", "matchers": {"version": "stable"}} }, { "id": "success_rate_canary", - "promql": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))", + "texts": [{"language": "PromQl", "text": "sum(count_over_time(requests{version=\"canary\", code=\"200\"}[5m])) / sum(count_over_time(requests{version=\"canary\"}[5m]))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "ratio" } ] diff --git a/aqpbm-usecase/workloads/uc5_top_clients.json b/aqpbm-usecase/workloads/uc5_top_clients.json index 65d8efb5..ead3aafa 100644 --- a/aqpbm-usecase/workloads/uc5_top_clients.json +++ b/aqpbm-usecase/workloads/uc5_top_clients.json @@ -1,5 +1,5 @@ { - "use_case": "top_clients", + "name": "top_clients", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 51, @@ -26,7 +26,7 @@ } ], "queries": [ - {"id": "top10_clients", "promql": "topk(10, sum by (client_id) (count_over_time(requests[5m])))", "window_ms": 300000, "interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"}}, - {"id": "top10_clients_1m", "promql": "topk(10, sum by (client_id) (count_over_time(requests[1m])))", "window_ms": 60000, "interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"}} + {"id": "top10_clients", "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[5m])))"}], "window_ms": 300000, "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"}}, + {"id": "top10_clients_1m", "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[1m])))"}], "window_ms": 60000, "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"}} ] } diff --git a/aqpbm-usecase/workloads/uc5_top_clients_real.json b/aqpbm-usecase/workloads/uc5_top_clients_real.json index 951cc1f0..639682d5 100644 --- a/aqpbm-usecase/workloads/uc5_top_clients_real.json +++ b/aqpbm-usecase/workloads/uc5_top_clients_real.json @@ -1,5 +1,5 @@ { - "use_case": "top_clients", + "name": "top_clients", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 51, @@ -25,17 +25,17 @@ "queries": [ { "id": "top10_clients", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[5m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[5m])))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} }, { "id": "top10_clients_1m", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[1m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[1m])))"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} } diff --git a/aqpbm-usecase/workloads/uc5_top_clients_real_caida_2019.json b/aqpbm-usecase/workloads/uc5_top_clients_real_caida_2019.json index f5786ea7..a1bb9e35 100644 --- a/aqpbm-usecase/workloads/uc5_top_clients_real_caida_2019.json +++ b/aqpbm-usecase/workloads/uc5_top_clients_real_caida_2019.json @@ -1,5 +1,5 @@ { - "use_case": "top_clients", + "name": "top_clients", "start_ms": 1767225600000, "duration_ms": 585000, "seed": 51, @@ -25,17 +25,17 @@ "queries": [ { "id": "top10_clients", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[5m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[5m])))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} }, { "id": "top10_clients_1m", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[1m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[1m])))"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} } diff --git a/aqpbm-usecase/workloads/uc5_top_clients_real_mawi_2019.json b/aqpbm-usecase/workloads/uc5_top_clients_real_mawi_2019.json index 91fcaae3..900622cb 100644 --- a/aqpbm-usecase/workloads/uc5_top_clients_real_mawi_2019.json +++ b/aqpbm-usecase/workloads/uc5_top_clients_real_mawi_2019.json @@ -1,5 +1,5 @@ { - "use_case": "top_clients", + "name": "top_clients", "start_ms": 1767225600000, "duration_ms": 895000, "seed": 51, @@ -25,17 +25,17 @@ "queries": [ { "id": "top10_clients", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[5m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[5m])))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} }, { "id": "top10_clients_1m", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[1m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[1m])))"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} } diff --git a/aqpbm-usecase/workloads/uc5_top_clients_real_nasa.json b/aqpbm-usecase/workloads/uc5_top_clients_real_nasa.json index e7b9d798..d5fefa39 100644 --- a/aqpbm-usecase/workloads/uc5_top_clients_real_nasa.json +++ b/aqpbm-usecase/workloads/uc5_top_clients_real_nasa.json @@ -1,5 +1,5 @@ { - "use_case": "top_clients", + "name": "top_clients", "start_ms": 1767225600000, "duration_ms": 7200000, "seed": 51, @@ -26,17 +26,17 @@ "queries": [ { "id": "top10_clients", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[5m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[5m])))"}], "window_ms": 300000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} }, { "id": "top10_clients_1m", - "promql": "topk(10, sum by (client_id) (count_over_time(requests[1m])))", + "texts": [{"language": "PromQl", "text": "topk(10, sum by (client_id) (count_over_time(requests[1m])))"}], "window_ms": 60000, - "interval_ms": 60000, + "evaluation_interval_ms": 60000, "unit": "requests", "truth": {"statistic": {"top_k": {"k": 10, "by": "client_id"}}, "metric": "requests"} } diff --git a/scripts/dataset_tools/real_data_video.py b/scripts/dataset_tools/real_data_video.py index d1ded696..25ab1d54 100644 --- a/scripts/dataset_tools/real_data_video.py +++ b/scripts/dataset_tools/real_data_video.py @@ -108,7 +108,7 @@ def spec(converted, directory, minutes, out_root): "source": "custom", "dataset": os.path.relpath(os.path.join(directory, f"{name}.csv.gz"), out_root), "mode": "grouped", "group_columns": ["city", "isp", "cdn", "device"], "value_column": name, "timestamp_column": "time", "timestamp_unit": "nanoseconds"}}}) - return {"use_case": "video_experience", "start_ms": WINDOW_START_MS, "duration_ms": minutes * MINUTE, + return {"name": "video_experience", "start_ms": WINDOW_START_MS, "duration_ms": minutes * MINUTE, "seed": 31, "metrics": metrics, "queries": video_spec.queries()} diff --git a/scripts/dataset_tools/video_spec.py b/scripts/dataset_tools/video_spec.py index 75ebd6f8..e3bca580 100644 --- a/scripts/dataset_tools/video_spec.py +++ b/scripts/dataset_tools/video_spec.py @@ -75,19 +75,23 @@ def phases_of(labels, metric): def queries(): - every = {"window_ms": MINUTE, "interval_ms": MINUTE} - five = {"window_ms": 5 * MINUTE, "interval_ms": MINUTE} + every = {"window_ms": MINUTE, "evaluation_interval_ms": MINUTE} + five = {"window_ms": 5 * MINUTE, "evaluation_interval_ms": MINUTE} + + def promql(text): + return {"texts": [{"language": "PromQl", "text": text}]} + return [ - {"id": "entropy_bitrate", "promql": "entropy_over_time(bitrate[1m])", **every, "unit": "bits", + {"id": "entropy_bitrate", **promql("entropy_over_time(bitrate[1m])"), **every, "unit": "bits", "truth": {"statistic": "entropy", "metric": "bitrate"}}, - {"id": "buffering_l1", "promql": "sum_over_time(buffering[1m])", **every, "unit": "s"}, - {"id": "sessions", "promql": "count_over_time(bitrate[1m])", **every, "unit": "sessions"}, - {"id": "distinct_devices", "promql": "distinct_over_time(device_id[1m])", **every, "unit": "devices", + {"id": "buffering_l1", **promql("sum_over_time(buffering[1m])"), **every, "unit": "s"}, + {"id": "sessions", **promql("count_over_time(bitrate[1m])"), **every, "unit": "sessions"}, + {"id": "distinct_devices", **promql("distinct_over_time(device_id[1m])"), **every, "unit": "devices", "truth": {"statistic": "distinct", "metric": "device_id"}}, - {"id": "startup_p95", "promql": "quantile_over_time(0.95, startup_time[5m])", **five, "unit": "s", + {"id": "startup_p95", **promql("quantile_over_time(0.95, startup_time[5m])"), **five, "unit": "s", "accuracy_metric": "rank", "truth": {"statistic": {"quantile": 0.95}, "metric": "startup_time"}}, {"id": "rebuffer_ratio", - "promql": "sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))", + **promql("sum_over_time(buffering[5m]) / (sum_over_time(play_time[5m]) + sum_over_time(buffering[5m]))"), **five, "unit": "ratio"}, ] @@ -107,7 +111,7 @@ def spec(duration_minutes): group["phases"] = phases series.append(group) metrics.append({"name": name, "sample_interval_ms": mean_interval, **flags, "series": series}) - return {"use_case": "video_experience", "start_ms": START_MS, "duration_ms": duration_minutes * MINUTE, + return {"name": "video_experience", "start_ms": START_MS, "duration_ms": duration_minutes * MINUTE, "seed": 31, "metrics": metrics, "queries": queries()} diff --git a/scripts/use_cases/bounds.py b/scripts/use_cases/bounds.py index ca54f4e7..7c14a185 100644 --- a/scripts/use_cases/bounds.py +++ b/scripts/use_cases/bounds.py @@ -3,6 +3,8 @@ import math import re +import cases + PLAIN, BOUND, RERUN = "plain", "bound", "rerun" POLICIES = (PLAIN, BOUND, RERUN) LOWER, UPPER = "_lower_bound", "_upper_bound" @@ -133,13 +135,14 @@ def with_bound_queries(spec, max_error): """The spec plus, for each quantile query, the same query at phi - max_error and phi + max_error.""" extra = [] for q in spec["queries"]: - found = QUANTILE.search(q["promql"]) + text = cases.promql(q) + found = QUANTILE.search(text) if not found: continue phi = float(found.group(1)) for suffix, shifted in ((LOWER, max(0.0, phi - max_error)), (UPPER, min(1.0, phi + max_error))): - promql = q["promql"][:found.start(1)] + f"{shifted:g}" + q["promql"][found.end(1):] - shifted_query = {**q, "id": q["id"] + suffix, "promql": promql} + promql = text[:found.start(1)] + f"{shifted:g}" + text[found.end(1):] + shifted_query = {**q, "id": q["id"] + suffix, "texts": [{"language": "PromQl", "text": promql}]} if "truth" in q: shifted_query["truth"] = {**q["truth"], "statistic": {"quantile": float(f"{shifted:g}")}} extra.append(shifted_query) diff --git a/scripts/use_cases/cases/__init__.py b/scripts/use_cases/cases/__init__.py index 145223ac..601253cc 100644 --- a/scripts/use_cases/cases/__init__.py +++ b/scripts/use_cases/cases/__init__.py @@ -18,3 +18,7 @@ def load(): def spec_of(module): with open(os.path.join(WORKLOADS, module.CASE["spec"])) as f: return json.load(f) + + +def promql(query): + return next(text["text"] for text in query["texts"] if text["language"] == "PromQl") diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index 9a3e1916..223fb0cb 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -84,8 +84,8 @@ def workload(spec, queries, max_error, failure_probability): "query_workload": { "language": "promql", "repeating_queries": [{ - "query": q["promql"], - "demand": {"fixed_interval": q["interval_ms"]}, + "query": cases.promql(q), + "demand": {"fixed_interval": q["evaluation_interval_ms"]}, "requirements": requirements(q, max_error, failure_probability), "predictability": {"predictable": {"known_at": None}}, } for q in queries], @@ -516,7 +516,7 @@ def query_report(spec, victoriametrics, approx, unsupported, plans): out = {} for q in spec["queries"]: exact = exact_by_id[q["id"]] - row = {"promql": q["promql"], VICTORIAMETRICS: evaluation_counts(exact)} + row = {"promql": cases.promql(q), VICTORIAMETRICS: evaluation_counts(exact)} if "unsupported" in exact: row[VICTORIAMETRICS]["unsupported"] = exact["unsupported"] if q["id"] in unsupported or q["id"] not in approx_by_id: @@ -526,7 +526,7 @@ def query_report(spec, victoriametrics, approx, unsupported, plans): answered = approx_by_id[q["id"]] expected = returned_by_time(exact) row[BACKEND] = {"supported": True, **evaluation_counts(answered), - "plan": describe_backend_plan(plans[q["id"]], q["promql"]), + "plan": describe_backend_plan(plans[q["id"]], cases.promql(q)), "evaluations returning a different series count": sum(expected.get(t) != n for t, n in returned_by_time(answered).items()), "answers against VictoriaMetrics": agreement.get(q["id"])} @@ -571,7 +571,7 @@ def run_spec_arm(args, spec_path, spec, name, workdir, write_flags, exact_path, groups = (approx.get("groups") or [{"queries": [q["id"] for q in approx["queries"]]}]) if approx else [] report = { "spec": spec_path, - "use_case": spec["use_case"], + "use_case": spec["name"], "start_ms": spec["start_ms"], "duration_ms": spec["duration_ms"], "queries": len(spec["queries"]), @@ -682,7 +682,7 @@ def main(argv=None): if q["id"] not in unsupported}, "unsupported": {q: f"not supported by {BACKEND}: {reason}" for q, reason in unsupported.items()}, "exact_plans": {q: source for q, source in sources.items()}, - "promql": {q["id"]: q["promql"] for q in spec["queries"]}, + "promql": {q["id"]: cases.promql(q) for q in spec["queries"]}, "planner_rev": planner_pin, "backend_rev": rev, "dashboard": case["dashboard"], diff --git a/scripts/use_cases/scenario.py b/scripts/use_cases/scenario.py index 3b8b283d..6083cc7a 100644 --- a/scripts/use_cases/scenario.py +++ b/scripts/use_cases/scenario.py @@ -2,6 +2,7 @@ import re +import cases import decision import rollout import rules @@ -116,7 +117,8 @@ def reads(spec, signals_of): """signal -> (metrics its queries read, its longest query window).""" out = {} for q in spec["queries"]: - metrics = {m["name"] for m in spec["metrics"] if re.search(rf"\b{re.escape(m['name'])}\b", q["promql"])} + metrics = {m["name"] for m in spec["metrics"] + if re.search(rf"\b{re.escape(m['name'])}\b", cases.promql(q))} signals = signals_of(q["id"]) for signal in [signals] if isinstance(signals, str) else signals: read, window = out.get(signal, (set(), 0)) @@ -140,7 +142,7 @@ def derive(run_id, spec, entity_of, derived, signals_of): for arm, acted in by_arm.items(): scored = score(relevant, grace, acted) summary.setdefault(signal, {})[arm] = scored - labels = {"use_case": spec["use_case"], "app": app, "signal": signal, "arm": arm} + labels = {"use_case": spec["name"], "app": app, "signal": signal, "arm": arm} rows += [row(end, "fidelity_summary", run_id, labels, f"scenario_{metric}", value, "seconds" if metric.endswith("seconds") else "count") for metric, value in scored.items()] diff --git a/scripts/use_cases/test_bounds.py b/scripts/use_cases/test_bounds.py index 65da932e..20215460 100644 --- a/scripts/use_cases/test_bounds.py +++ b/scripts/use_cases/test_bounds.py @@ -3,6 +3,7 @@ import unittest import bounds +import cases from bounds import Bounded @@ -51,10 +52,10 @@ def test_rerun_stops_when_history_keeps_a_check_open(self): class WidenTest(unittest.TestCase): def test_quantile_queries_get_both_ends(self): - spec = {"queries": [{"id": "p99", "promql": "quantile_over_time(0.99, m[5m])"}, - {"id": "n", "promql": "count_over_time(m[5m])"}]} + spec = {"queries": [{"id": "p99", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, m[5m])"}]}, + {"id": "n", "texts": [{"language": "PromQl", "text": "count_over_time(m[5m])"}]}]} out = bounds.with_bound_queries(spec, 0.05) - self.assertEqual([(q["id"], q["promql"]) for q in out["queries"][2:]], + self.assertEqual([(q["id"], cases.promql(q)) for q in out["queries"][2:]], [("p99_lower_bound", "quantile_over_time(0.94, m[5m])"), ("p99_upper_bound", "quantile_over_time(1, m[5m])")]) diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index 4bf666a9..f84d2061 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -16,8 +16,8 @@ "series": [{"labels": {}, "baseline": {}}]}, ], } -QUERY = {"id": "p95", "promql": "quantile_over_time(0.95, cpu[5m])", "interval_ms": 60000, - "accuracy_metric": "rank"} +QUERY = {"id": "p95", "texts": [{"language": "PromQl", "text": "quantile_over_time(0.95, cpu[5m])"}], + "evaluation_interval_ms": 60000, "accuracy_metric": "rank"} class WorkloadTest(unittest.TestCase): diff --git a/scripts/use_cases/test_scenario.py b/scripts/use_cases/test_scenario.py index 3fbef65d..4cbe8a5d 100644 --- a/scripts/use_cases/test_scenario.py +++ b/scripts/use_cases/test_scenario.py @@ -7,7 +7,7 @@ from approx_rows import row SPEC = { - "use_case": "uc", "start_ms": 0, "duration_ms": 600000, + "name": "uc", "start_ms": 0, "duration_ms": 600000, "metrics": [ {"name": "cpu", "series": [ {"count": 2, "labels": {"container": "c-{i}"}, @@ -21,7 +21,8 @@ "change": {"mix": {"share": 0.1, "distribution": { "kind": "uniform", "lower_bound": 7, "upper_bound": 9}}}}]}]}, ], - "queries": [{"id": "q", "promql": "max_over_time(cpu[1m])", "window_ms": 60000}], + "queries": [{"id": "q", "texts": [{"language": "PromQl", "text": "max_over_time(cpu[1m])"}], + "window_ms": 60000}], } diff --git a/system-bench/Cargo.toml b/system-bench/Cargo.toml index 81e25d3c..40dba873 100644 --- a/system-bench/Cargo.toml +++ b/system-bench/Cargo.toml @@ -8,9 +8,10 @@ description = "System level: runs ASAPPlanner's plans on its executor (feature p [features] default = ["systemeval"] -systemeval = ["dep:aqpbm-usecase"] +systemeval = ["dep:aqpbm-usecase", "aqpbm-core/import"] planeval = [ "dep:aqpbm-usecase", + "aqpbm-core/import", "dep:asap-planner", "dep:asap-executor", "dep:asap-types", diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index 097208f7..a5846ea0 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -5,14 +5,15 @@ use std::time::Instant; use anyhow::{Context, Result}; use clap::Parser; +use aqpbm_core::harness::data::workload_series; +use aqpbm_core::harness::engine::QueryLanguage; use aqpbm_usecase::accuracy::AnswerAt; -use aqpbm_usecase::data::{generate, Series}; +use aqpbm_usecase::data::{read_workload, Series}; use aqpbm_usecase::output::{ PlanevalCost, PlanevalOutput, PlanevalQuery, PlannedQuery, UnsupportedQuery, OUTPUT_SCHEMA_VERSION, }; use aqpbm_usecase::score::{read_answers, score}; -use aqpbm_usecase::spec::Spec; use system_bench::planeval::plan::{plan, summary, Arm}; use system_bench::planeval::run::Driver; @@ -101,7 +102,7 @@ fn write_samples(path: &Path, series: &[Series]) -> Result<()> { #[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { let args = Args::parse(); - let spec = Spec::read(&args.spec)?; + let spec = read_workload(&args.spec)?; let arm = Arm { max_error: args.max_error, failure_probability: args.failure_probability, @@ -110,7 +111,7 @@ async fn main() -> Result<()> { }; let exact = args.exact.as_deref().map(read_answers).transpose()?; let generated = Instant::now(); - let series = generate(&spec, &args.data_root)?; + let series = workload_series(&spec, &args.data_root)?; let samples: usize = series.iter().map(|s| s.points.len()).sum(); eprintln!( "generated {} samples in {} series in {:.1} s", @@ -126,13 +127,17 @@ async fn main() -> Result<()> { if !args.queries.is_empty() && !args.queries.contains(&query.id) { continue; } + let promql = query + .text_in(QueryLanguage::PromQl) + .unwrap_or_default() + .to_string(); let planned = match plan(&spec, query, &arm).await { Ok(planned) => planned, Err(reason) => { eprintln!("{}: unsupported: {reason}", query.id); queries.push(PlanevalQuery::Unsupported(UnsupportedQuery { id: query.id.clone(), - promql: query.promql.clone(), + promql, unsupported: reason, })); continue; @@ -194,8 +199,8 @@ async fn main() -> Result<()> { ); queries.push(PlanevalQuery::Ran(PlannedQuery { id: query.id.clone(), - promql: query.promql.clone(), - unit: query.unit.clone(), + promql, + unit: query.unit.clone().unwrap_or_default(), threshold: query.threshold, plan: plan_summary, evaluations: times.len(), @@ -209,7 +214,7 @@ async fn main() -> Result<()> { } let document = PlanevalOutput { schema_version: OUTPUT_SCHEMA_VERSION, - use_case: spec.use_case.clone(), + use_case: spec.name.clone(), arm: arm.describe(), planner_rev: env!("ASAP_PLANNER_REV").to_string(), samples, diff --git a/system-bench/src/bin/systemeval.rs b/system-bench/src/bin/systemeval.rs index 85657f33..82a3ef72 100644 --- a/system-bench/src/bin/systemeval.rs +++ b/system-bench/src/bin/systemeval.rs @@ -3,10 +3,11 @@ use std::path::PathBuf; use std::time::Instant; use anyhow::{Context, Result}; -use aqpbm_usecase::data::generate; +use aqpbm_core::harness::data::workload_series; +use aqpbm_core::harness::engine::QueryLanguage; +use aqpbm_usecase::data::read_workload; use aqpbm_usecase::output::{SystemevalOutput, OUTPUT_SCHEMA_VERSION}; use aqpbm_usecase::score::read_answers; -use aqpbm_usecase::spec::Spec; use clap::builder::PossibleValuesParser; use clap::Parser; @@ -76,9 +77,9 @@ fn main() -> Result<()> { let args = Args::parse(); let server = Server::connect(&args.system, &args.url).expect("clap accepts only listed systems"); - let spec = Spec::read(&args.spec)?; + let spec = read_workload(&args.spec)?; let generated = Instant::now(); - let series = generate(&spec, &args.data_root)?; + let series = workload_series(&spec, &args.data_root)?; eprintln!( "generated {} samples in {} series in {:.1} s", series.iter().map(|s| s.points.len()).sum::(), @@ -102,7 +103,9 @@ fn main() -> Result<()> { speed: args.speed, flush_ms: args.flush_ms, }; - let mut writer = Writer::new(&series, &server, spec.start_ms, &options); + let start_ms = spec.data_start_ms().unwrap_or(0); + let end_ms = spec.data_end_ms().unwrap_or(start_ms); + let mut writer = Writer::new(&series, &server, start_ms, &options); let mut collected: Vec = asked.iter().map(|_| Collected::default()).collect(); let started = Instant::now(); writer.start_clock(); @@ -110,11 +113,12 @@ fn main() -> Result<()> { writer.write_through(t)?; writer.make_visible(t)?; for &i in queries { - collected[i].record(t, ask(server.agent(), server.base(), &asked[i].promql, t)); + let promql = asked[i].text_in(QueryLanguage::PromQl).unwrap_or_default(); + collected[i].record(t, ask(server.agent(), server.base(), promql, t)); } } - writer.write_through(spec.end_ms())?; - writer.make_visible(spec.end_ms())?; + writer.write_through(end_ms)?; + writer.make_visible(end_ms)?; let run_seconds = started.elapsed().as_secs_f64(); let write = writer.summary()?; eprintln!( @@ -138,7 +142,7 @@ fn main() -> Result<()> { } let document = SystemevalOutput { schema_version: OUTPUT_SCHEMA_VERSION, - use_case: spec.use_case.clone(), + use_case: spec.name.clone(), system: server.name().to_string(), samples: writer.samples(), run_seconds, diff --git a/system-bench/src/planeval/plan.rs b/system-bench/src/planeval/plan.rs index 7ac41e66..14ba04a2 100644 --- a/system-bench/src/planeval/plan.rs +++ b/system-bench/src/planeval/plan.rs @@ -8,7 +8,7 @@ use asap_planner::{ use serde_json::{json, Value}; use super::sketch_analytics::{analytics, statistics}; -use aqpbm_usecase::spec::{QuerySpec, Spec}; +use aqpbm_core::harness::engine::{QueryLanguage, WorkloadQuery, WorkloadSpec}; #[derive(Debug, Clone, Copy)] pub struct Arm { @@ -29,7 +29,10 @@ impl Arm { } } -pub fn workload(spec: &Spec, query: &QuerySpec, arm: &Arm) -> Result { +pub fn workload(spec: &WorkloadSpec, query: &WorkloadQuery, arm: &Arm) -> Result { + let promql = query + .text_in(QueryLanguage::PromQl) + .with_context(|| format!("query {} has no PromQL text", query.id))?; let requirements = match arm.max_error { None => json!({}), Some(max_error) => { @@ -43,8 +46,25 @@ pub fn workload(spec: &Spec, query: &QuerySpec, arm: &Arm) -> Result Result Result { +pub async fn plan( + spec: &WorkloadSpec, + query: &WorkloadQuery, + arm: &Arm, +) -> Result { let workload = workload(spec, query, arm).map_err(|e| format!("{e:#}"))?; let capabilities = DeploymentCapabilities { raw_data_retained: arm.raw_data_retained, diff --git a/system-bench/src/systemeval/query.rs b/system-bench/src/systemeval/query.rs index 978196c9..a00b9e2c 100644 --- a/system-bench/src/systemeval/query.rs +++ b/system-bench/src/systemeval/query.rs @@ -1,11 +1,11 @@ use std::collections::BTreeMap; use anyhow::{Context, Result}; +use aqpbm_core::harness::engine::{QueryLanguage, WorkloadQuery}; use aqpbm_usecase::accuracy::AnswerAt; use aqpbm_usecase::data::Series; use aqpbm_usecase::output::{Failure, SystemevalCost, SystemevalOutcome, SystemevalQuery}; use aqpbm_usecase::score::score; -use aqpbm_usecase::spec::QuerySpec; use crate::prometheus_api::query::Asked; @@ -56,7 +56,7 @@ impl Collected { pub fn finish( self, - query: &QuerySpec, + query: &WorkloadQuery, series: &[Series], exact: Option<&BTreeMap>>, ) -> Result { @@ -77,8 +77,11 @@ impl Collected { }; Ok(SystemevalQuery { id: query.id.clone(), - promql: query.promql.clone(), - unit: query.unit.clone(), + promql: query + .text_in(QueryLanguage::PromQl) + .unwrap_or_default() + .to_string(), + unit: query.unit.clone().unwrap_or_default(), threshold: query.threshold, evaluations: self.times.len(), failed_evaluations: self.failed, diff --git a/system-bench/tests/declared_truth.rs b/system-bench/tests/declared_truth.rs index 4247b350..7daf968c 100644 --- a/system-bench/tests/declared_truth.rs +++ b/system-bench/tests/declared_truth.rs @@ -1,7 +1,8 @@ use std::collections::BTreeMap; use std::path::Path; -use aqpbm_usecase::spec::{Spec, Statistic, Truth}; +use aqpbm_core::accuracy::declared_truth::{Statistic, Truth}; +use aqpbm_usecase::data::read_workload; use asap_types::ir::operator::{AggIntent, Reduction, Source}; use asap_types::ir::scalar::{CompareOpKind, ScalarValue}; use asap_types::ir::{NonASAPOp, Operator, OperatorNode, QueryRoot, ScalarExpr, TimeRangeKind}; @@ -142,9 +143,12 @@ fn every_workload_declares_the_truth_its_lowered_query_has() { let mut checked = 0; for entry in std::fs::read_dir(Path::new("../aqpbm-usecase/workloads")).unwrap() { let path = entry.unwrap().path(); - let spec = Spec::read(&path).unwrap(); + let spec = read_workload(&path).unwrap(); for query in &spec.queries { - let declared = query.truth.clone().map(|truth| (truth, query.window_ms)); + let declared = query + .truth + .clone() + .map(|truth| (truth, query.window_ms as i64)); assert_eq!( declared, lowered(&workload(&spec, query, &exact).unwrap()), diff --git a/system-bench/tests/uc1.rs b/system-bench/tests/uc1.rs index 5b039700..01929bd9 100644 --- a/system-bench/tests/uc1.rs +++ b/system-bench/tests/uc1.rs @@ -1,13 +1,13 @@ use std::collections::BTreeSet; -use aqpbm_usecase::data::generate; -use aqpbm_usecase::spec::Spec; +use aqpbm_core::harness::data::workload_series as generate; +use aqpbm_core::harness::engine::WorkloadSpec; use system_bench::planeval::plan::{plan, Arm}; use system_bench::planeval::run::Driver; -fn small_spec() -> Spec { - let spec: Spec = serde_json::from_value(serde_json::json!({ - "use_case": "test", +fn small_spec() -> WorkloadSpec { + let spec: WorkloadSpec = serde_json::from_value(serde_json::json!({ + "name": "test", "start_ms": 1767225600000i64, "duration_ms": 60000, "seed": 1, @@ -25,8 +25,8 @@ fn small_spec() -> Spec { }] }], "queries": [ - {"id": "distinct_10s", "promql": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])", - "window_ms": 10000, "interval_ms": 5000, "threshold": 300, "unit": "addresses"} + {"id": "distinct_10s", "texts": [{"language": "PromQl", "text": "distinct_over_time(src_ip{vm=\"instance1\"}[10s])"}], + "window_ms": 10000, "evaluation_interval_ms": 5000, "threshold": 300, "unit": "addresses"} ] })) .unwrap(); diff --git a/tools/grafana/generate_dashboards.py b/tools/grafana/generate_dashboards.py index e96d4431..ec576690 100644 --- a/tools/grafana/generate_dashboards.py +++ b/tools/grafana/generate_dashboards.py @@ -558,7 +558,7 @@ def data_markdown(module): def query_lines(spec): lines = ["| query | PromQL | computed |", "|---|---|---|"] for q in spec["queries"]: - lines.append(f"| {q['id']} | `{cell(q['promql'])}` | every {number(q['interval_ms'] / 1000)} s over " + lines.append(f"| {q['id']} | `{cell(cases.promql(q))}` | every {number(q['evaluation_interval_ms'] / 1000)} s over " f"the last {number(q['window_ms'] / 1000)} s |") return lines @@ -1364,7 +1364,7 @@ def systems_dashboard(uid, use_case): def parts_of(module, phase3=False, figure=True): - use_case = cases.spec_of(module)["use_case"] + use_case = cases.spec_of(module)["name"] board = module.DASHBOARD rule_error = board.get("rule_error", {}) builders = { From c9420ce4fa9112b88daaae0a13eb71029f8e4d65 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:28:07 +0000 Subject: [PATCH 20/51] system-bench: --speed for the victoriametrics and asapquery-backend engines The two engines' arms without a plan file can replay the data at a multiple of its own rate, as systemeval's --speed does: a sample is written no earlier than its time after the data start divided by the speed, counted from the arm's first write, in requests that span at most one second of data time, and each refresh's visibility call (VictoriaMetrics' flush, ASAPQuery-backend's watermark) waits for the refresh's end the same way. Without --speed they write as fast as the server accepts, as before. A VictoriaMetrics arm with a plan file, which is fed in real time, refuses --speed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- .../asapquery_backend_server.rs | 27 +++++++- .../asapquery_precompute_engine_server.rs | 2 +- .../victoriametrics_server.rs | 34 +++++++++- .../src/prometheus_api/query_text_arm.rs | 64 ++++++++++++++++++- system-bench/src/registry.rs | 3 +- system-bench/tests/end_to_end_adapters.rs | 3 + system-bench/tests/replay_pace.rs | 28 ++++++++ .../tests/victoriametrics_conformance.rs | 1 + system-bench/tests/victoriametrics_server.rs | 3 + 9 files changed, 155 insertions(+), 10 deletions(-) create mode 100644 system-bench/tests/replay_pace.rs diff --git a/system-bench/src/engines_external/asapquery_backend_server.rs b/system-bench/src/engines_external/asapquery_backend_server.rs index 299510dd..d5474a7f 100644 --- a/system-bench/src/engines_external/asapquery_backend_server.rs +++ b/system-bench/src/engines_external/asapquery_backend_server.rs @@ -11,15 +11,16 @@ use aqpbm_core::harness::engine::{ use super::restart_command::restart_and_wait; use super::server_cgroup::ServerCgroupOptions; use crate::prometheus_api::query_text_arm::{ - ask_every_query, queries_to_ask, write_chunk, QueryToAsk, + ask_every_query, check_speed, queries_to_ask, write_chunk, QueryToAsk, Replay, }; use aqpbm_core::harness::protocol::Protocol; -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct AsapqueryBackendServer { pub url: String, pub cgroup: CgroupSource, pub request_timeout: Duration, + pub speed: Option, } pub struct AsapqueryBackendEngine { @@ -158,6 +159,10 @@ impl EngineUnderTest for AsapqueryBackendEngine { Ok(Box::new(AsapqueryBackendArm { connection: self.connection.clone(), queries, + replay: self + .server + .speed + .map(|speed| Replay::new(speed, workload.data_start_ms().unwrap_or(0))), })) } } @@ -165,6 +170,7 @@ impl EngineUnderTest for AsapqueryBackendEngine { struct AsapqueryBackendArm { connection: AsapqueryBackendConnection, queries: Vec, + replay: Option, } impl InstalledArm for AsapqueryBackendArm { @@ -173,7 +179,15 @@ impl InstalledArm for AsapqueryBackendArm { } fn ingest(&mut self, chunk: &SampleChunk) -> Result { - write_chunk(&self.connection.agent, &self.connection.base, chunk)?; + write_chunk( + &self.connection.agent, + &self.connection.base, + chunk, + self.replay.as_mut(), + )?; + if let Some(replay) = &mut self.replay { + replay.wait_until(chunk.end_ms); + } self.connection .make_visible(chunk.end_ms) .map_err(|error| EngineError(format!("{error:#}")))?; @@ -204,6 +218,11 @@ pub struct AsapqueryBackendOptions { /// `http://10.0.0.1:8080` (engine `asapquery-backend`). #[arg(long)] pub asapquery_backend_url: Option, + #[arg( + long, + help = "Replay the data at this many times its own rate: a sample is written no earlier than its time after the data start divided by this, counted from the first write (arms without a plan file); omitted writes as fast as the server accepts" + )] + pub speed: Option, #[command(flatten)] pub cgroup: ServerCgroupOptions, #[arg( @@ -230,10 +249,12 @@ pub fn periodic_queries( "engine asapquery-backend runs one arm per server start: pass --warmup 0 --runs 1, or give --asapquery-backend-restart-command" ); } + check_speed(options.speed)?; let mut engine = AsapqueryBackendEngine::new(AsapqueryBackendServer { url, cgroup, request_timeout: Duration::from_secs(600), + speed: options.speed, })?; engine.restart_command = options.asapquery_backend_restart_command; Ok(Box::new(engine)) diff --git a/system-bench/src/engines_external/asapquery_precompute_engine_server.rs b/system-bench/src/engines_external/asapquery_precompute_engine_server.rs index f473560b..4e0386bf 100644 --- a/system-bench/src/engines_external/asapquery_precompute_engine_server.rs +++ b/system-bench/src/engines_external/asapquery_precompute_engine_server.rs @@ -173,7 +173,7 @@ impl InstalledArm for AsapqueryPrecomputeEngineArm { } fn ingest(&mut self, chunk: &SampleChunk) -> Result { - write_chunk(&self.agent, &self.base, chunk)?; + write_chunk(&self.agent, &self.base, chunk, None)?; Ok(StepReport::default()) } diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs index 0caf683c..61629872 100644 --- a/system-bench/src/engines_external/victoriametrics_server.rs +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -69,12 +69,12 @@ use super::victoriametrics::{ }; use super::NodeId; use crate::prometheus_api::query_text_arm::{ - ask_every_query, queries_to_ask, write_chunk, QueryToAsk, + ask_every_query, check_speed, queries_to_ask, write_chunk, QueryToAsk, Replay, }; use aqpbm_core::harness::protocol::Protocol; /// How to reach the server. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq)] pub struct VictoriaMetricsServer { /// The HTTP interface, e.g. `http://10.0.0.1:8428`. pub url: String, @@ -86,6 +86,7 @@ pub struct VictoriaMetricsServer { pub stream_aggregation_config: Option, /// How long one request may take, e.g. 600 s. pub request_timeout: Duration, + pub speed: Option, } /// A VictoriaMetrics server; see the module docs. @@ -166,6 +167,10 @@ impl VictoriaMetricsEngine { queries, metrics: workload.metric_names(), data_bytes_at_install: 0, + replay: self + .server + .speed + .map(|speed| Replay::new(speed, data_start_ms(workload))), }; installed.delete_series()?; installed.http.force_flush()?; @@ -203,6 +208,13 @@ impl EngineUnderTest for VictoriaMetricsEngine { .into(), )); } + if self.server.speed.is_some() { + return Err(EngineError( + "--speed replays an arm without a plan file; an arm with a plan file is fed in \ + real time" + .into(), + )); + } let cgroup = self.server.cgroup.clone(); let Some(stream_aggregation_config) = self.server.stream_aggregation_config.clone() else { return Err(EngineError( @@ -926,6 +938,7 @@ struct VictoriaMetricsQueryTextArm { queries: Vec, metrics: Vec, data_bytes_at_install: u64, + replay: Option, } impl VictoriaMetricsQueryTextArm { @@ -960,7 +973,15 @@ impl InstalledArm for VictoriaMetricsQueryTextArm { } fn ingest(&mut self, chunk: &SampleChunk) -> Result { - write_chunk(&self.http.agent, &self.http.url, chunk)?; + write_chunk( + &self.http.agent, + &self.http.url, + chunk, + self.replay.as_mut(), + )?; + if let Some(replay) = &mut self.replay { + replay.wait_until(chunk.end_ms); + } self.http.force_flush()?; Ok(StepReport::default()) } @@ -1083,6 +1104,11 @@ pub struct VictoriaMetricsOptions { /// for each arm with a plan file (engine `victoriametrics`). #[arg(long)] pub victoriametrics_stream_aggregation_config: Option, + #[arg( + long, + help = "Replay the data at this many times its own rate: a sample is written no earlier than its time after the data start divided by this, counted from the first write (arms without a plan file); omitted writes as fast as the server accepts" + )] + pub speed: Option, #[command(flatten)] pub cgroup: ServerCgroupOptions, } @@ -1097,11 +1123,13 @@ pub fn periodic_queries( "engine victoriametrics needs --victoriametrics-url and --server-cgroup-directory" ); }; + check_speed(options.speed)?; let mut engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { url, cgroup, stream_aggregation_config: options.victoriametrics_stream_aggregation_config, request_timeout: Duration::from_secs(600), + speed: options.speed, })?; engine.runs_per_arm = protocol.warmup_runs + protocol.measured_runs; Ok(Box::new(engine)) diff --git a/system-bench/src/prometheus_api/query_text_arm.rs b/system-bench/src/prometheus_api/query_text_arm.rs index 5c4650d6..bd596c85 100644 --- a/system-bench/src/prometheus_api/query_text_arm.rs +++ b/system-bench/src/prometheus_api/query_text_arm.rs @@ -1,4 +1,5 @@ use std::collections::BTreeMap; +use std::time::{Duration, Instant}; use aqpbm_core::harness::data::SampleChunk; use aqpbm_core::harness::engine::{ @@ -10,6 +11,45 @@ use super::remote_write::{encode, request_of, send_until_accepted}; pub const BATCH_SAMPLES: usize = 10_000; +pub const REPLAY_REQUEST_SPAN_MS: i64 = 1000; + +#[derive(Debug, Clone)] +pub struct Replay { + speed: f64, + data_start_ms: i64, + started: Option, +} + +impl Replay { + pub fn new(speed: f64, data_start_ms: i64) -> Replay { + Replay { + speed, + data_start_ms, + started: None, + } + } + + pub fn wait_until(&mut self, data_ms: i64) { + let started = *self.started.get_or_insert_with(Instant::now); + let due = Duration::from_secs_f64( + (data_ms - self.data_start_ms).max(0) as f64 / 1e3 / self.speed, + ); + let elapsed = started.elapsed(); + if due > elapsed { + std::thread::sleep(due - elapsed); + } + } +} + +pub fn check_speed(speed: Option) -> anyhow::Result<()> { + match speed { + Some(speed) if !(speed.is_finite() && speed > 0.0) => { + anyhow::bail!("--speed must be a positive number, not {speed}") + } + _ => Ok(()), + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct QueryToAsk { pub id: String, @@ -59,12 +99,32 @@ pub fn write_chunk( agent: &ureq::Agent, base: &str, chunk: &SampleChunk, + replay: Option<&mut Replay>, ) -> Result<(), EngineError> { let mut samples = chunk.samples.clone(); samples.sort_by_key(|sample| sample.ts_ms); - for batch in samples.chunks(BATCH_SAMPLES) { + let send = |batch: &[aqpbm_core::harness::data::Sample]| { send_until_accepted(agent, base, &encode(&request_of(batch))) - .map_err(|error| EngineError(format!("{error:#}")))?; + .map(|_| ()) + .map_err(|error| EngineError(format!("{error:#}"))) + }; + let Some(replay) = replay else { + for batch in samples.chunks(BATCH_SAMPLES) { + send(batch)?; + } + return Ok(()); + }; + let mut rest = &samples[..]; + while let Some(first) = rest.first() { + let count = rest + .iter() + .take(BATCH_SAMPLES) + .take_while(|sample| sample.ts_ms - first.ts_ms < REPLAY_REQUEST_SPAN_MS) + .count(); + let (batch, after) = rest.split_at(count); + replay.wait_until(batch[count - 1].ts_ms); + send(batch)?; + rest = after; } Ok(()) } diff --git a/system-bench/src/registry.rs b/system-bench/src/registry.rs index bffd9394..3c3d4f91 100644 --- a/system-bench/src/registry.rs +++ b/system-bench/src/registry.rs @@ -253,12 +253,13 @@ fn fake_engine(matches: &ArgMatches, _: &Protocol) -> Result= Duration::from_millis(100) && elapsed < Duration::from_millis(600), + "{elapsed:?}" + ); + replay.wait_until(2_000); + assert!(started.elapsed() < elapsed + Duration::from_millis(50)); +} + +#[test] +fn a_speed_is_a_positive_number() { + assert!(check_speed(None).is_ok()); + assert!(check_speed(Some(2.5)).is_ok()); + for speed in [0.0, -1.0, f64::NAN, f64::INFINITY] { + assert!(check_speed(Some(speed)).is_err(), "{speed}"); + } +} diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs index 8af0a9d7..fbba1039 100644 --- a/system-bench/tests/victoriametrics_conformance.rs +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -56,6 +56,7 @@ fn engine() -> VictoriaMetricsEngine { .into(), ), request_timeout: Duration::from_secs(60), + speed: None, }) .expect("the server answers") } diff --git a/system-bench/tests/victoriametrics_server.rs b/system-bench/tests/victoriametrics_server.rs index 5a342947..ec7d5e63 100644 --- a/system-bench/tests/victoriametrics_server.rs +++ b/system-bench/tests/victoriametrics_server.rs @@ -317,6 +317,7 @@ fn one_arm_at_a_time_and_its_config_reaches_the_server() { cgroup: fake_cgroup(&dir), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), + speed: None, }) .unwrap(); assert_eq!(engine.description().id, "victoriametrics"); @@ -366,6 +367,7 @@ fn plans_are_checked_against_the_workload_before_anything_loads() { cgroup: fake_cgroup(&dir), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), + speed: None, }) .unwrap(); let plan = fixture_value_public( @@ -407,6 +409,7 @@ fn a_query_time_arm_ingests_then_evaluates() { cgroup: fake_cgroup(&dir), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), + speed: None, }) .unwrap(); let plan = fixture_value_public( From 0f80c457b2a00c40a3738c46ad9ea7b137b7b05b Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:42:18 +0000 Subject: [PATCH 21/51] scripts: run_use_case_on_systems.py runs each system through approxbench benchmark-external run; reference and candidate are options Each server is run by approxbench benchmark-external run instead of systemeval: the script writes a run directory with one workload per query (the use-case WorkloadSpec with that query alone, so each query is evaluated at its own times and a query a system cannot answer fails only its own cell), starts the server, runs the engine with --warmup 0 --runs 1 and reads the answers and per-evaluation wall times from the results. VictoriaMetrics runs every query on one server; ASAPQuery-backend, which keeps every sample written to it, starts once per query with its group's plan. The answers are scored against the exact answers by planeval's new --score-answers (rank errors need the samples), as systemeval scored them. --reference and --candidate (victoriametrics or asapquery-backend; by default VictoriaMetrics is the exact arm and ASAPQuery-backend the approximate one, as ARM_OF had it) replace the fixed roles. --approxbench replaces --systemeval; --batch-samples is gone, since the engines write 10,000 samples per request; --max-core-busy is passed to the run. --spec refuses an arm that keeps raw samples, since no raw store is filled. On Linux each server starts in its own cgroup v2 group (systemd-run --user --scope, no root needed) whose directory is passed as --server-cgroup-directory; the harness reads a group's cores from its nearest ancestor that has cpuset files, as cgroup v2 runs a group without the cpuset controller on its parent's cores. The CPU and memory columns of the summary still come from ps here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-core/src/harness/cgroup.rs | 66 ++- aqpbm-core/src/harness/protocol.rs | 2 +- aqpbm-core/tests/harness_cgroup.rs | 18 + scripts/use_cases/run_use_case_on_systems.py | 500 ++++++++++++------ .../use_cases/test_run_use_case_on_systems.py | 53 +- system-bench/src/bin/planeval.rs | 40 +- 6 files changed, 473 insertions(+), 206 deletions(-) diff --git a/aqpbm-core/src/harness/cgroup.rs b/aqpbm-core/src/harness/cgroup.rs index 91c0cb12..a5c9cb8f 100644 --- a/aqpbm-core/src/harness/cgroup.rs +++ b/aqpbm-core/src/harness/cgroup.rs @@ -56,36 +56,36 @@ impl CgroupSource { if !CGROUP_FILES.contains(&file) && file != PROC_STAT { return Err(CgroupError::NotACgroupFile(file.into())); } + if file == PROC_STAT { + return self.read_path(Path::new("/proc/stat")); + } + self.read_path(&self.directory().join(file)) + } + + fn directory(&self) -> &Path { + match self { + CgroupSource::Local(dir) => dir, + CgroupSource::Remote { + cgroup_directory, .. + } => cgroup_directory, + } + } + + fn read_path(&self, path: &Path) -> Result { match self { - CgroupSource::Local(dir) => { - let path = if file == PROC_STAT { - PathBuf::from("/proc/stat") + CgroupSource::Local(_) => std::fs::read_to_string(path).map_err(|error| { + if error.kind() == std::io::ErrorKind::NotFound { + CgroupError::NotFound(path.display().to_string()) } else { - dir.join(file) - }; - std::fs::read_to_string(&path).map_err(|error| { - if error.kind() == std::io::ErrorKind::NotFound { - CgroupError::NotFound(path.display().to_string()) - } else { - CgroupError::Read { - file: path.display().to_string(), - message: error.to_string(), - } + CgroupError::Read { + file: path.display().to_string(), + message: error.to_string(), } - }) - } + } + }), CgroupSource::Remote { - ssh_program, - host, - cgroup_directory, - } => { - let path = if file == PROC_STAT { - PathBuf::from("/proc/stat") - } else { - cgroup_directory.join(file) - }; - ssh_read(ssh_program, host, &path) - } + ssh_program, host, .. + } => ssh_read(ssh_program, host, path), } } @@ -98,6 +98,20 @@ impl CgroupSource { } } + pub fn cpus_effective(&self) -> Result { + let mut missing = None; + for group in self.directory().ancestors() { + match self.read_path(&group.join("cpuset.cpus.effective")) { + Err(error @ CgroupError::NotFound(_)) => { + missing.get_or_insert(error); + } + found => return found, + } + } + Err(missing + .unwrap_or_else(|| CgroupError::NotFound(self.directory().display().to_string()))) + } + /// `cpu.stat` read once. pub fn cpu(&self) -> Result { CgroupCpu::parse(&self.read("cpu.stat")?) diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index 481bbab2..bde5b34b 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -973,7 +973,7 @@ pub fn load_probe_for( }) } CpuAccounting::Cgroup(source) => Box::new(ServerCoresProbe { - cores: parse_cpu_list(&source.read("cpuset.cpus.effective")?)?, + cores: parse_cpu_list(&source.cpus_effective()?)?, sample_interval, host: ServerHost::Cgroup(source.clone()), }), diff --git a/aqpbm-core/tests/harness_cgroup.rs b/aqpbm-core/tests/harness_cgroup.rs index ec7aa216..5ab4a042 100644 --- a/aqpbm-core/tests/harness_cgroup.rs +++ b/aqpbm-core/tests/harness_cgroup.rs @@ -585,3 +585,21 @@ fn a_file_on_the_server_host_is_replaced_locally_and_over_ssh() { Err(CgroupError::Write { .. }) )); } + +#[test] +fn a_group_without_cpuset_files_runs_on_its_nearest_ancestors_cores() { + let temp = TempDir::new("cpuset-ancestor"); + let parent = temp.0.join("user.slice"); + let scope = parent.join("app.slice").join("run-1.scope"); + std::fs::create_dir_all(&scope).unwrap(); + std::fs::write(parent.join("cpuset.cpus.effective"), "0-7\n").unwrap(); + assert_eq!( + CgroupSource::Local(scope.clone()).cpus_effective().unwrap(), + "0-7\n" + ); + std::fs::write(scope.join("cpuset.cpus.effective"), "2-3\n").unwrap(); + assert_eq!( + CgroupSource::Local(scope).cpus_effective().unwrap(), + "2-3\n" + ); +} diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index 223fb0cb..a4adefe5 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -26,9 +26,10 @@ REPO = in_process.REPO VICTORIAMETRICS = "VictoriaMetrics" BACKEND = "ASAPQuery-backend" -SYSTEM_FLAG = {VICTORIAMETRICS: "victoriametrics", BACKEND: "asapquery-backend"} -ARM_OF = {VICTORIAMETRICS: "exact", BACKEND: "approx"} +NAMES = {"victoriametrics": VICTORIAMETRICS, "asapquery-backend": BACKEND} +PLANNED = {"asapquery-backend"} SPEC_ARM = "noraw" +REFERENCE_ARM = "noraw" BACKEND_ENV = "ASAPQUERY_BACKEND_DIR" READY_SECONDS = 60 @@ -132,9 +133,18 @@ def get(url, timeout=5): return response.status, response.read().decode() +def own_cgroup_available(): + if sys.platform != "linux" or not shutil.which("systemd-run"): + return False + probe = subprocess.run(["systemd-run", "--user", "--scope", "--quiet", "true"], capture_output=True) + return probe.returncode == 0 + + class Server: - def __init__(self, name, cmd, ready_url, log): + def __init__(self, name, cmd, ready_url, log, own_cgroup): self.name, self.ready_url = name, ready_url + if own_cgroup: + cmd = ["systemd-run", "--user", "--scope", "--quiet", "--collect"] + cmd print("$ " + " ".join(cmd), file=sys.stderr) self.log = open(log, "w") self.started = time.monotonic() @@ -155,6 +165,15 @@ def __init__(self, name, cmd, ready_url, log): self.proc.kill() raise RuntimeError(f"{name} was not ready within {READY_SECONDS} s") time.sleep(0.1) + self.cgroup_directory = self.cgroup_of(self.proc.pid) if own_cgroup else None + + @staticmethod + def cgroup_of(pid): + with open(f"/proc/{pid}/cgroup") as f: + for line in f: + if line.startswith("0::"): + return "/sys/fs/cgroup" + line[3:].strip() + raise RuntimeError(f"process {pid} is in no cgroup v2 group") def stop(self): self.proc.send_signal(signal.SIGTERM) @@ -165,14 +184,114 @@ def stop(self): "wall_seconds": time.monotonic() - self.started} -def systemeval(binary, spec, system, url, out, extra): - cmd = [binary, "--spec", spec, "--system", SYSTEM_FLAG[system], "--url", url, "--out", out] + extra +def workload_name(query_id): + name = re.sub(r"[^A-Za-z0-9._-]+", "-", query_id) + return re.sub(r"_{2,}", "_", name).strip("-.") or "query" + + +def run_directory(path, spec, queries, variant): + shutil.rmtree(path, ignore_errors=True) + for sub in ("workloads", "data", "plans", "results"): + os.makedirs(os.path.join(path, sub)) + names = {} + for q in queries: + name = workload_name(q["id"]) + names[q["id"]] = name + with open(os.path.join(path, "workloads", f"{name}.json"), "w") as f: + json.dump({**spec, "name": name, "queries": [q]}, f) + os.makedirs(os.path.join(path, "plans", variant)) + with open(os.path.join(path, "plans", variant, "variant.json"), "w") as f: + json.dump({"substitutions_allowed": True, "plans": False}, f) + return names + + +def benchmark_external(args, engine, path, flags, server): + cmd = [args.approxbench, "benchmark-external", "run", "--run-directory", path, "--engine", engine, + "--warmup", "0", "--runs", "1", "--max-core-busy", str(args.max_core_busy), + "--data-root", args.data_root] + flags + if server.cgroup_directory: + cmd += ["--server-cgroup-directory", server.cgroup_directory] + if args.speed is not None: + cmd += ["--speed", str(args.speed)] print("$ " + " ".join(cmd), file=sys.stderr) - subprocess.run(cmd, check=True) - with open(out) as f: + subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL) + + +def read_json(path): + with open(path) as f: return json.load(f) +def cell_of(path, engine, workload_name_, variant): + results = os.path.join(path, "results", engine) + cell = read_json(os.path.join(results, f"{workload_name_}__{variant}.cell.json")) + outcome = cell["outcome"] + if outcome == "Ran": + return read_json(os.path.join(results, f"{workload_name_}__{variant}.json")), None + if "NoPlan" in outcome: + return None, outcome["NoPlan"]["reason"] + return None, outcome["NotRun"]["error"] + + +def threshold_of(query): + return None if query.get("threshold") is None else float(query["threshold"]) + + +def answered_query(query, result): + answers, costs, not_finite = [], [], 0 + for (time_ms, by_query), job in zip(result["answers"], result["evaluate"]): + pairs = by_query.get(query["id"], []) + for labels, value in pairs: + if value is None: + not_finite += 1 + else: + answers.append({"time": time_ms, "series": labels, "value": value}) + costs.append({"time": time_ms, "query_seconds": job["median"]["wall_ns"] / 1e9, + "series_returned": len(pairs)}) + return {"id": query["id"], "promql": cases.promql(query), "unit": query.get("unit", ""), + "threshold": threshold_of(query), "evaluations": len(costs), "failed_evaluations": 0, + "failures": [], "not_finite_answers": not_finite, "costs": costs, "answers": answers} + + +def unsupported_query(query, reason): + return {"id": query["id"], "promql": cases.promql(query), "unit": query.get("unit", ""), + "threshold": threshold_of(query), "evaluations": 0, "failed_evaluations": 0, + "failures": [], "not_finite_answers": 0, "costs": [], "unsupported": reason} + + +def write_stats(results): + ran = [r for r in results if r] + samples = ran[0]["ingested_samples"] if ran else 0 + ingested = sum(r["ingested_samples"] for r in ran) + seconds = sum(job["median"]["wall_ns"] for r in ran for job in r["ingest"]) / 1e9 + return {"samples": samples, "requests": None, "compressed_bytes": None, "retries": None, + "speed": None, "batch_samples": None, "send_seconds": seconds, "barrier_seconds": None, + "barriers": None, "samples_per_second": ingested / seconds if seconds else None, + "max_lag_seconds": None, "status": None, "cells": len(ran)} + + +def asked_document(spec, system, queries, outcomes, speed): + out = [] + for q in queries: + result, reason = outcomes[q["id"]] + out.append(answered_query(q, result) if result else unsupported_query(q, reason)) + stats = write_stats([outcomes[q["id"]][0] for q in queries]) + stats["speed"] = speed + return {"schema_version": 1, "use_case": spec["name"], "system": system, "samples": stats["samples"], + "run_seconds": None, "write": stats, "queries": out} + + +def scored(args, spec_path, document, exact_path, out): + answers = out.replace(".json", "-answers.json") + with open(answers, "w") as f: + json.dump(document, f) + cmd = [args.planeval, "--spec", spec_path, "--score-answers", answers, "--exact", exact_path, "--out", out, + "--data-root", args.data_root] + print("$ " + " ".join(cmd), file=sys.stderr) + subprocess.run(cmd, check=True) + return read_json(out) + + def latency(document): seconds = [c["query_seconds"] for q in document["queries"] if "unsupported" not in q for c in q["costs"] if c.get("series_returned", 0) is not None] @@ -187,37 +306,34 @@ def latency(document): def system_summary(asked, at_end, process, disk_bytes=None): stats = asked["write"] out = {"insert samples per second": stats["samples_per_second"], "samples": stats["samples"], - "write seconds": stats["send_seconds"] + stats["barrier_seconds"], - "visibility seconds": stats["barrier_seconds"], "write retries": stats["retries"], - "resident bytes at end": at_end["resident_bytes"], + "write seconds": stats["send_seconds"], "visibility seconds": stats["barrier_seconds"], + "write retries": stats["retries"], "resident bytes at end": at_end["resident_bytes"], "peak resident bytes": process["peak_resident_bytes"], "cpu seconds": process["cpu_seconds"], - "disk bytes": disk_bytes, "max replay lag seconds": stats.get("max_lag_seconds")} + "disk bytes": disk_bytes, "max replay lag seconds": stats.get("max_lag_seconds"), + "data writes": stats.get("cells")} out.update(latency(asked)) out["unsupported"] = {q["id"]: q["unsupported"] for q in asked["queries"] if "unsupported" in q} out["failed evaluations"] = {q["id"]: q["failed_evaluations"] for q in asked["queries"] if q["failed_evaluations"] and "unsupported" not in q} - finish = (stats.get("status") or {}).get("precompute") - if finish: - out["samples dropped"] = {k: v for k, v in finish.items() if k.startswith("samples_dropped") and v} return out -def merged_exact(victoriametrics, truth): +def merged_exact(reference, truth, name=VICTORIAMETRICS): truth_by_id = {q["id"]: q for q in truth["queries"]} queries, sources = [], {} - for q in victoriametrics["queries"]: + for q in reference["queries"]: if "unsupported" in q: queries.append({**truth_by_id[q["id"]], "costs": []}) - sources[q["id"]] = "the in-process exact plan: VictoriaMetrics does not support the query" + sources[q["id"]] = f"the in-process exact plan: {name} does not support the query" else: queries.append(q) - sources[q["id"]] = VICTORIAMETRICS - return {**victoriametrics, "queries": queries}, sources + sources[q["id"]] = name + return {**reference, "queries": queries}, sources -def truth_errors(victoriametrics): +def truth_errors(reference): out = {} - for q in victoriametrics["queries"]: + for q in reference["queries"]: errors = [a["exact_plan"]["relative_error"] for a in q.get("answers", []) if "exact_plan" in a] if errors: out[q["id"]] = {"max relative error": max(errors), @@ -313,33 +429,33 @@ def plan_groups(binary, spec, arm, workdir, calls=None): return groups, unsupported -def query_costs(run_id, use_case, signal, query, system): - labels = {"use_case": use_case, "signal": signal, "query": query["id"], "arm": ARM_OF[system]} +def query_costs(run_id, use_case, signal, query, arm): + labels = {"use_case": use_case, "signal": signal, "query": query["id"], "arm": arm} return [row(c["time"], "low_level", run_id, labels, "query_latency", c["query_seconds"], "s") for c in query["costs"] if c.get("series_returned", 0) is not None] -def write_arm(data, case, run_id, exact, approx, unsupported, details, spec): +def write_arm(data, case, run_id, exact, approx, unsupported, details, spec, candidate=BACKEND): use_case = exact["use_case"] exact_by_id = {q["id"]: q for q in exact["queries"]} rows, errors, relative, costs, planned = [], [], [], [], [] for q in approx["queries"]: signal = case["signal"](q["id"]) if q["id"] in unsupported: - costs += query_costs(run_id, use_case, signal, exact_by_id[q["id"]], VICTORIAMETRICS) + costs += query_costs(run_id, use_case, signal, exact_by_id[q["id"]], "exact") continue rows += in_process.query_rows(run_id, use_case, signal, exact_by_id[q["id"]], q) errors += in_process.rank_errors(run_id, use_case, signal, q) relative += in_process.relative_errors(run_id, use_case, signal, q) - costs += query_costs(run_id, use_case, signal, q, BACKEND) - costs += query_costs(run_id, use_case, signal, exact_by_id[q["id"]], VICTORIAMETRICS) + costs += query_costs(run_id, use_case, signal, q, "approx") + costs += query_costs(run_id, use_case, signal, exact_by_id[q["id"]], "exact") planned.append(q) if not rows: if not costs: print(f"{run_id}: no query was asked; nothing written", file=sys.stderr) return write_run(data, run_id, use_case, costs, details, case["split"]) - print(f"{run_id}: no query answered by {BACKEND}; only costs written", file=sys.stderr) + print(f"{run_id}: no query answered by {candidate}; only costs written", file=sys.stderr) return if unsupported: partial = case.get("supported_rules") @@ -349,10 +465,10 @@ def write_arm(data, case, run_id, exact, approx, unsupported, details, spec): else: derived = case["derive"](rows, planned, bounds.PLAIN, None) derived += relative + errors - scored_rows, scored = scenario.derive(run_id, spec, case.get("scenario_entity"), derived, - case.get("signals", case["signal"])) + scored_rows, scored_scenario = scenario.derive(run_id, spec, case.get("scenario_entity"), derived, + case.get("signals", case["signal"])) derived += scored_rows - details["scenario"] = scored + details["scenario"] = scored_scenario details["max_relative_error"] = in_process.max_relative_errors(derived) details["fidelity"] = in_process.headlines(derived) for signal, by_arm in details.get("scenario", {}).items(): @@ -361,7 +477,7 @@ def write_arm(data, case, run_id, exact, approx, unsupported, details, spec): if "stage2" in case and not unsupported: details["stage2"] = case["stage2"](derived, errors) write_run(data, run_id, use_case, rows + derived + costs, details, case["split"]) - print(f"{run_id}: {len(planned)} queries, {len(unsupported)} not supported by {BACKEND}", file=sys.stderr) + print(f"{run_id}: {len(planned)} queries, {len(unsupported)} not supported by {candidate}", file=sys.stderr) def backend_rev(backend_dir): @@ -381,66 +497,74 @@ def default_backend_dir(): "release") -def run_victoriametrics(args, spec_path, workdir, write_flags, truth_path): - data = os.path.join(workdir, "victoriametrics-data") +def start_victoriametrics(args, workdir, name): + data = os.path.join(workdir, f"{name}-data") shutil.rmtree(data, ignore_errors=True) port = free_port() url = f"http://127.0.0.1:{port}" server = Server(VICTORIAMETRICS, [args.victoriametrics, f"-storageDataPath={data}", "-retentionPeriod=100y", f"-httpListenAddr=127.0.0.1:{port}", "-loggerLevel=ERROR"], - url + "/health", os.path.join(workdir, "victoriametrics.log")) - flags = write_flags + (["--exact", truth_path] if truth_path else []) + url + "/health", os.path.join(workdir, f"{name}.log"), args.own_cgroup) + return server, ["--victoriametrics-url", url], data + + +def start_backend(args, workdir, name, spec, plan): + port = free_port() + url = f"http://127.0.0.1:{port}" + server = Server(BACKEND, [os.path.join(args.backend_dir, "data_plane"), "--plan", plan, "--no-forward", + "--stream-start-ms", str(spec["start_ms"]), "--listen", f"127.0.0.1:{port}"], + url + "/-/ready", os.path.join(workdir, f"{name}-data-plane.log"), args.own_cgroup) + return server, ["--asapquery-backend-url", url] + + +def run_unplanned(args, system, spec_path, spec, workdir, truth_path): + engine = system + name = engine + path = os.path.join(workdir, f"{name}-run") + names = run_directory(path, spec, spec["queries"], "query-text") + server, flags, data = start_victoriametrics(args, workdir, name) try: - asked = systemeval(args.systemeval, spec_path, VICTORIAMETRICS, url, - os.path.join(workdir, "victoriametrics.json"), flags) + benchmark_external(args, engine, path, flags, server) at_end = snapshot(server.proc.pid) disk = directory_bytes(data) finally: process = server.stop() - summary = system_summary(asked, at_end, process, max(disk, directory_bytes(data))) + outcomes = {q["id"]: cell_of(path, engine, names[q["id"]], "query-text") for q in spec["queries"]} + document = asked_document(spec, NAMES[system], spec["queries"], outcomes, args.speed) + if truth_path: + document = scored(args, spec_path, document, truth_path, os.path.join(workdir, f"{name}.json")) + else: + with open(os.path.join(workdir, f"{name}.json"), "w") as f: + json.dump(document, f) + summary = system_summary(document, at_end, process, max(disk, directory_bytes(data))) if not args.keep_data: shutil.rmtree(data, ignore_errors=True) - return asked, summary - - -def start_raw_store(args, spec_path, workdir, write_flags): - data = os.path.join(workdir, "raw-store-data") - shutil.rmtree(data, ignore_errors=True) - port = free_port() - url = f"http://127.0.0.1:{port}" - server = Server("raw store", [args.victoriametrics, f"-storageDataPath={data}", "-retentionPeriod=100y", - f"-httpListenAddr=127.0.0.1:{port}", "-loggerLevel=ERROR", - "-search.disableCache"], - url + "/health", os.path.join(workdir, "raw-store.log")) - try: - systemeval(args.systemeval, spec_path, VICTORIAMETRICS, url, os.path.join(workdir, "raw-store.json"), - write_flags + ["--query", "none"]) - except BaseException: - server.stop() - raise - return server, url, data + return document, summary -def run_group(args, spec_path, spec, planned, members, name, workdir, flags, raw_store=None): - port = free_port() - url = f"http://127.0.0.1:{port}" - try: - server = Server(BACKEND, [os.path.join(args.backend_dir, "data_plane"), "--plan", planned, - "--no-forward", "--stream-start-ms", str(spec["start_ms"]), - "--listen", f"127.0.0.1:{port}"] - + (["--prometheus-url", raw_store] if raw_store else []), - url + "/-/ready", os.path.join(workdir, f"{name}-data-plane.log")) - except RuntimeError as refused: - lines = str(refused).strip().splitlines() - return None, f"the data plane did not start with the plan: {lines[-1] if lines else refused}" +def run_group(args, system, spec_path, spec, planned, members, name, workdir, exact_path): + outcomes, at_end, process = {}, {"resident_bytes": 0}, {"peak_resident_bytes": 0, "cpu_seconds": 0.0} for q in members: - flags = flags + ["--query", q["id"]] - try: - asked = systemeval(args.systemeval, spec_path, BACKEND, url, os.path.join(workdir, f"{name}.json"), flags) - at_end = snapshot(server.proc.pid) - finally: - process = server.stop() - return asked, system_summary(asked, at_end, process, 0) + query_name = f"{name}-{workload_name(q['id'])}" + path = os.path.join(workdir, f"{query_name}-run") + names = run_directory(path, spec, [q], name) + try: + server, flags = start_backend(args, workdir, query_name, spec, planned) + except RuntimeError as refused: + lines = str(refused).strip().splitlines() + return None, f"the data plane did not start with the plan: {lines[-1] if lines else refused}" + try: + benchmark_external(args, system, path, flags, server) + ended = snapshot(server.proc.pid) + finally: + stopped = server.stop() + at_end = ended + process = {"peak_resident_bytes": max(process["peak_resident_bytes"], stopped["peak_resident_bytes"]), + "cpu_seconds": process["cpu_seconds"] + stopped["cpu_seconds"]} + outcomes[q["id"]] = cell_of(path, system, names[q["id"]], name) + document = asked_document(spec, NAMES[system], members, outcomes, args.speed) + document = scored(args, spec_path, document, exact_path, os.path.join(workdir, f"{name}.json")) + return document, system_summary(document, at_end, process, 0) def merged_groups(spec, ran): @@ -448,7 +572,7 @@ def merged_groups(spec, ran): return ran[0] by_id = {q["id"]: q for asked, _ in ran for q in asked["queries"]} asked = {**ran[0][0], "queries": [by_id[q["id"]] for q in spec["queries"] if q["id"] in by_id], - "run_seconds": sum(a["run_seconds"] for a, _ in ran), "write": None, + "run_seconds": None, "write": None, "groups": [{"queries": [q["id"] for q in a["queries"]], "write": a["write"], "run_seconds": a["run_seconds"]} for a, _ in ran]} summaries = [s for _, s in ran] @@ -468,16 +592,15 @@ def planner_summary(calls): "largest plan bytes": max((c["plan bytes"] or 0) for c in calls)} -def run_backend(args, spec_path, spec, arm, workdir, write_flags, exact_path, raw_store=None): +def run_planned(args, system, spec_path, spec, arm, workdir, exact_path): calls = [] groups, unsupported = plan_groups(os.path.join(args.backend_dir, "control_plane"), spec, arm, workdir, calls=calls) planner = planner_summary(calls) - flags = write_flags + ["--exact", exact_path] ran, installed = [], [] for planned, plan, members in groups: - name = arm if len(groups) == 1 else f"{arm}-{members[0]['id']}" - asked, summary = run_group(args, spec_path, spec, planned, members, name, workdir, flags, raw_store) + name = arm if len(groups) == 1 else f"{arm}-{workload_name(members[0]['id'])}" + asked, summary = run_group(args, system, spec_path, spec, planned, members, name, workdir, exact_path) if asked is None: for q in members: unsupported[q["id"]] = summary @@ -498,6 +621,14 @@ def run_backend(args, spec_path, spec, arm, workdir, write_flags, exact_path, ra return asked, summary, plans, unsupported +def run_system(args, system, spec_path, spec, arm, workdir, exact_path): + if system in PLANNED: + return run_planned(args, system, spec_path, spec, arm, workdir, exact_path) + asked, summary = run_unplanned(args, system, spec_path, spec, workdir, exact_path) + unsupported = {q["id"]: q["unsupported"] for q in asked["queries"] if "unsupported" in q} + return asked, summary, {}, unsupported + + def returned_by_time(query): return {c["time"]: c.get("series_returned") for c in query.get("costs", [])} @@ -509,31 +640,59 @@ def evaluation_counts(query): "empty evaluations": sum(r == 0 for r in returned)} -def query_report(spec, victoriametrics, approx, unsupported, plans): - exact_by_id = {q["id"]: q for q in victoriametrics["queries"]} +def plan_text(plans, query): + return describe_backend_plan(plans[query["id"]], cases.promql(query)) if query["id"] in plans else "query text" + + +def query_report(spec, reference, approx, unsupported, plans, names): + reference_name, candidate_name = names + exact_by_id = {q["id"]: q for q in reference["queries"]} approx_by_id = {q["id"]: q for q in approx["queries"]} if approx else {} agreement = truth_errors(approx) if approx else {} out = {} for q in spec["queries"]: exact = exact_by_id[q["id"]] - row = {"promql": cases.promql(q), VICTORIAMETRICS: evaluation_counts(exact)} + report_row = {"promql": cases.promql(q), reference_name: evaluation_counts(exact)} if "unsupported" in exact: - row[VICTORIAMETRICS]["unsupported"] = exact["unsupported"] + report_row[reference_name]["unsupported"] = exact["unsupported"] if q["id"] in unsupported or q["id"] not in approx_by_id: - row[BACKEND] = {"supported": False, - "reason": unsupported.get(q["id"], "not asked")} + report_row[candidate_name] = {"supported": False, "reason": unsupported.get(q["id"], "not asked")} else: answered = approx_by_id[q["id"]] expected = returned_by_time(exact) - row[BACKEND] = {"supported": True, **evaluation_counts(answered), - "plan": describe_backend_plan(plans[q["id"]], cases.promql(q)), - "evaluations returning a different series count": - sum(expected.get(t) != n for t, n in returned_by_time(answered).items()), - "answers against VictoriaMetrics": agreement.get(q["id"])} - out[q["id"]] = row + report_row[candidate_name] = { + "supported": True, **evaluation_counts(answered), "plan": plan_text(plans, q), + "evaluations returning a different series count": + sum(expected.get(t) != n for t, n in returned_by_time(answered).items()), + f"answers against {reference_name}": agreement.get(q["id"])} + out[q["id"]] = report_row return out +def candidate_arms(args, case=None): + if args.candidate not in PLANNED: + return [args.candidate] + if case is None: + return args.arm or [SPEC_ARM] + return args.arm or backend_arms(case) + + +def arm_details(args, arm): + if args.candidate not in PLANNED: + return {"max_error": None, "failure_probability": None, "raw_data_retained": True, + "ignore_guarantees": False} + return {"max_error": in_process.max_error_of(arm), "failure_probability": 0.01, + "raw_data_retained": raw_retained(arm), "ignore_guarantees": "ignore" in arm.split("-")} + + +def write_mode(args): + return "as fast as each system accepts" if args.speed is None else f"replay at {args.speed:g}x the data rate" + + +def run_reference(args, spec_path, spec, workdir, truth_path): + return run_system(args, args.reference, spec_path, spec, REFERENCE_ARM, workdir, truth_path) + + def run_spec(args): spec_path = os.path.abspath(args.spec) with open(spec_path) as f: @@ -542,71 +701,60 @@ def run_spec(args): name = os.path.splitext(os.path.basename(spec_path))[0] workdir = os.path.join(args.raw_out, f"{name}-systems-{mode}") os.makedirs(workdir, exist_ok=True) - write_flags = ["--data-root", args.data_root, "--batch-samples", str(args.batch_samples)] - if args.speed is not None: - write_flags += ["--speed", str(args.speed)] - victoriametrics, victoriametrics_summary = run_victoriametrics(args, spec_path, workdir, write_flags, None) - exact_path = os.path.join(workdir, "victoriametrics.json") + reference, reference_summary, _, _ = run_reference(args, spec_path, spec, workdir, None) + exact_path = os.path.join(workdir, f"{args.reference}.json") + with open(exact_path, "w") as f: + json.dump(reference, f) rev, planner_pin = backend_rev(args.backend_dir) - arms = args.arm or [SPEC_ARM] - raw_store = start_raw_store(args, spec_path, workdir, write_flags) if any(map(raw_retained, arms)) else None - try: - for arm in arms: - run_spec_arm(args, spec_path, spec, name, workdir, write_flags, exact_path, victoriametrics, - victoriametrics_summary, rev, planner_pin, arm, - raw_store if raw_retained(arm) else None) - finally: - if raw_store: - raw_store[0].stop() - if not args.keep_data: - shutil.rmtree(raw_store[2], ignore_errors=True) - - -def run_spec_arm(args, spec_path, spec, name, workdir, write_flags, exact_path, victoriametrics, - victoriametrics_summary, rev, planner_pin, arm, raw_store): - approx, backend_summary, plans, unsupported = run_backend(args, spec_path, spec, arm, workdir, - write_flags, exact_path, - raw_store[1] if raw_store else None) - queries = query_report(spec, victoriametrics, approx, unsupported, plans) - groups = (approx.get("groups") or [{"queries": [q["id"] for q in approx["queries"]]}]) if approx else [] - report = { - "spec": spec_path, - "use_case": spec["name"], - "start_ms": spec["start_ms"], - "duration_ms": spec["duration_ms"], - "queries": len(spec["queries"]), - f"supported by {BACKEND}": sum(r[BACKEND]["supported"] for r in queries.values()), - f"{BACKEND} deployment": {"raw_data_retained": raw_retained(arm), "forwards queries": False, - "raw store": f"{VICTORIAMETRICS}, filled with every sample before " - f"{BACKEND} starts" if raw_store else None, - "accuracy requirement": None if in_process.max_error_of(arm) is None - else {"max_error": in_process.max_error_of(arm), - "failure_probability": 0.01}}, - f"{BACKEND} instances": [g["queries"] for g in groups], - "write mode": "as fast as each system accepts" if args.speed is None - else f"replay at {args.speed:g}x the data rate", - "planner_rev": planner_pin, - "backend_rev": rev, - "systems": {VICTORIAMETRICS: victoriametrics_summary, BACKEND: backend_summary}, - "per query": queries, - } - out = os.path.join(workdir, f"{arm}-summary.json") - with open(out, "w") as f: - json.dump(report, f, indent=1) - print(f"{name} {arm}: {report[f'supported by {BACKEND}']} of {len(spec['queries'])} queries supported by " - f"{BACKEND} in {len(groups)} instances; {out}", file=sys.stderr) + names = (NAMES[args.reference], NAMES[args.candidate]) + for arm in candidate_arms(args): + if args.candidate in PLANNED and raw_retained(arm): + sys.exit(f"arm {arm} keeps raw samples, which needs a raw store this script does not fill") + approx, candidate_summary, plans, unsupported = run_system(args, args.candidate, spec_path, spec, arm, + workdir, exact_path) + queries = query_report(spec, reference, approx, unsupported, plans, names) + groups = (approx.get("groups") or [{"queries": [q["id"] for q in approx["queries"]]}]) if approx else [] + report = { + "spec": spec_path, + "use_case": spec["name"], + "start_ms": spec["start_ms"], + "duration_ms": spec["duration_ms"], + "queries": len(spec["queries"]), + f"supported by {names[1]}": sum(r[names[1]]["supported"] for r in queries.values()), + f"{names[1]} deployment": {"raw_data_retained": arm_details(args, arm)["raw_data_retained"], + "forwards queries": False, "raw store": None, + "accuracy requirement": None if arm_details(args, arm)["max_error"] is None + else {"max_error": in_process.max_error_of(arm), + "failure_probability": 0.01}}, + f"{names[1]} instances": [g["queries"] for g in groups], + "write mode": write_mode(args), + "planner_rev": planner_pin, + "backend_rev": rev, + "systems": {names[0]: reference_summary, names[1]: candidate_summary}, + "per query": queries, + } + out = os.path.join(workdir, f"{arm}-summary.json") + with open(out, "w") as f: + json.dump(report, f, indent=1) + print(f"{name} {arm}: {report[f'supported by {names[1]}']} of {len(spec['queries'])} queries supported by " + f"{names[1]} in {len(groups)} instances; {out}", file=sys.stderr) def main(argv=None): parser = argparse.ArgumentParser( - description=f"Run a use case on {VICTORIAMETRICS}, which keeps every raw sample, and on {BACKEND} " - "planned to keep none, then score both" + description="Run a use case on a reference system, by default VictoriaMetrics, which keeps every raw " + "sample, and on a candidate system, by default ASAPQuery-backend planned to keep none, through " + "approxbench benchmark-external run, then score both" ) parser.add_argument("use_case", nargs="?", choices=sorted(in_process.USE_CASES)) - parser.add_argument("--spec", help="run this spec file instead of a use case; VictoriaMetrics answers are the " - f"reference and {BACKEND} is planned to keep no raw samples") + parser.add_argument("--spec", help="run this spec file instead of a use case; the reference system's answers " + "are the reference") + parser.add_argument("--reference", choices=sorted(NAMES), default="victoriametrics", + help="the system whose answers are the exact arm") + parser.add_argument("--candidate", choices=sorted(NAMES), default="asapquery-backend", + help="the system whose answers are the approx arm; asapquery-backend is planned per arm") parser.add_argument("--planeval", default=os.path.join(REPO, "target", "release", "planeval")) - parser.add_argument("--systemeval", default=os.path.join(REPO, "target", "release", "systemeval")) + parser.add_argument("--approxbench", default=os.path.join(REPO, "target", "release", "approxbench")) parser.add_argument("--backend-dir", default=default_backend_dir(), help=f"directory with {BACKEND}'s control_plane and data_plane binaries; default " f"${BACKEND_ENV}, else ../ASAPQuery-backend/target/release beside this repository") @@ -618,7 +766,9 @@ def main(argv=None): parser.add_argument("--speed", type=float, help="replay the data at this many times its own rate; default writes as fast as each " "system accepts") - parser.add_argument("--batch-samples", type=int, default=10_000) + parser.add_argument("--max-core-busy", type=float, default=0.1, + help="passed to approxbench benchmark-external run: a server core busier than this " + "fraction before a step refuses the step") parser.add_argument("--real", nargs="?", const="", metavar="DATASET", help="read the use case's recorded data from --data-root, as run_use_case.py does") parser.add_argument("--data-root", default=data_root.default(), @@ -627,14 +777,18 @@ def main(argv=None): args = parser.parse_args(argv) if (args.use_case is None) == (args.spec is None): parser.error("give either a use case or --spec") + if args.reference == args.candidate: + parser.error("--reference and --candidate name the same system") + args.own_cgroup = own_cgroup_available() if args.spec: run_spec(args) return case = in_process.USE_CASES[args.use_case] - arms = args.arm or backend_arms(case) - for arm in arms: - if arm not in backend_arms(case): - parser.error(f"arm {arm} is not one of {backend_arms(case)}") + arms = candidate_arms(args, case) + if args.candidate in PLANNED: + for arm in arms: + if arm not in backend_arms(case): + parser.error(f"arm {arm} is not one of {backend_arms(case)}") real = args.real is not None suffix = f"real-{args.real}" if args.real else "real" prefix = f"uc{args.use_case}-{suffix}" if real else f"uc{args.use_case}" @@ -644,7 +798,6 @@ def main(argv=None): parser.error(f"use case {args.use_case} has no {spec_name}") with open(spec_path) as f: spec = json.load(f) - args.data_flags = ["--data-root", args.data_root] if real: for metric in spec["metrics"]: table = metric.get("import", {}).get("table") @@ -654,48 +807,43 @@ def main(argv=None): run_prefix = f"{prefix}-systems-{mode}" workdir = os.path.join(args.raw_out, run_prefix) os.makedirs(workdir, exist_ok=True) - write_flags = args.data_flags + ["--batch-samples", str(args.batch_samples)] - if args.speed is not None: - write_flags += ["--speed", str(args.speed)] truth_path = os.path.join(workdir, "truth.json") truth = in_process.run_binary(args.planeval, spec_path, truth_path, - case.get("planeval_flags", []) + args.data_flags) - victoriametrics, victoriametrics_summary = run_victoriametrics(args, spec_path, workdir, write_flags, truth_path) - exact, sources = merged_exact(victoriametrics, truth) + case.get("planeval_flags", []) + ["--data-root", args.data_root]) + reference, reference_summary, _, _ = run_reference(args, spec_path, spec, workdir, truth_path) + names = (NAMES[args.reference], NAMES[args.candidate]) + exact, sources = merged_exact(reference, truth, names[0]) exact_path = os.path.join(workdir, "exact.json") with open(exact_path, "w") as f: json.dump(exact, f) rev, planner_pin = backend_rev(args.backend_dir) for arm in arms: - approx, backend_summary, plans, unsupported = run_backend(args, spec_path, spec, arm, workdir, write_flags, - exact_path) + approx, candidate_summary, plans, unsupported = run_system(args, args.candidate, spec_path, spec, arm, + workdir, exact_path) run_id = f"{run_prefix}-{arm}" if approx is None: - print(f"{run_id}: no query is supported by {BACKEND}: {unsupported}", file=sys.stderr) + print(f"{run_id}: no query is supported by {names[1]}: {unsupported}", file=sys.stderr) continue details = { - "arm": {"max_error": in_process.max_error_of(arm), "failure_probability": 0.01, - "raw_data_retained": False, "ignore_guarantees": "ignore" in arm.split("-")}, + "arm": arm_details(args, arm), "trial": 1, - "plans": {q["id"]: describe_backend_plan(plans[q["id"]], q["promql"]) for q in approx["queries"] - if q["id"] not in unsupported}, - "unsupported": {q: f"not supported by {BACKEND}: {reason}" for q, reason in unsupported.items()}, + "plans": {q["id"]: plan_text(plans, q) for q in spec["queries"] if q["id"] not in unsupported}, + "unsupported": {q: f"not supported by {names[1]}: {reason}" for q, reason in unsupported.items()}, "exact_plans": {q: source for q, source in sources.items()}, "promql": {q["id"]: cases.promql(q) for q in spec["queries"]}, "planner_rev": planner_pin, "backend_rev": rev, "dashboard": case["dashboard"], "signals": {q["id"]: case.get("signals", case["signal"])(q["id"]) for q in spec["queries"]}, - "write mode": "as fast as each system accepts" if args.speed is None - else f"replay at {args.speed:g}x the data rate", - "systems": {VICTORIAMETRICS: victoriametrics_summary, BACKEND: backend_summary}, - "victoriametrics_vs_truth": truth_errors(victoriametrics), + "write mode": write_mode(args), + "systems": {names[0]: reference_summary, names[1]: candidate_summary}, + "victoriametrics_vs_truth": truth_errors(reference), } if "rules" in case: details["rules"] = {name: rule["description"] for name, rule in case["rules"].items()} details["signal_dashboards"] = {name: "rules" for name in case["rules"]} - write_arm(args.data, case, run_id, exact, approx, unsupported, details, spec) + write_arm(args.data, case, run_id, exact, approx, unsupported, details, spec, names[1]) if __name__ == "__main__": diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index f84d2061..06ef472c 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -1,12 +1,16 @@ #!/usr/bin/env python3 +import json +import os +import tempfile import unittest from unittest import mock import run_use_case import run_use_case_on_systems -from run_use_case_on_systems import (backend_arms, cpu_seconds, describe_backend_plan, evaluation_counts, latency, - merged_exact, merged_groups, plan_groups, truth_errors, workload) +from run_use_case_on_systems import (answered_query, backend_arms, cell_of, cpu_seconds, describe_backend_plan, + evaluation_counts, latency, merged_exact, merged_groups, plan_groups, + run_directory, truth_errors, workload, workload_name) SPEC = { "metrics": [ @@ -171,5 +175,50 @@ def test_empty_and_failed_evaluations(self): {"evaluations": 3, "failed evaluations": 1, "empty evaluations": 1}) +class BenchmarkExternalTest(unittest.TestCase): + def test_each_query_is_its_own_workload_of_the_spec(self): + spec = {"name": "uc", "start_ms": 0, "duration_ms": 60000, "seed": 1, "metrics": [], + "queries": [QUERY, {**QUERY, "id": "p99 canary"}]} + with tempfile.TemporaryDirectory() as root: + path = os.path.join(root, "run") + names = run_directory(path, spec, spec["queries"], "noraw-eps0.05") + self.assertEqual(names, {"p95": "p95", "p99 canary": "p99-canary"}) + with open(os.path.join(path, "workloads", "p99-canary.json")) as f: + written = json.load(f) + self.assertEqual((written["name"], [q["id"] for q in written["queries"]]), ("p99-canary", ["p99 canary"])) + self.assertEqual(written["seed"], 1) + with open(os.path.join(path, "plans", "noraw-eps0.05", "variant.json")) as f: + self.assertEqual(json.load(f), {"substitutions_allowed": True, "plans": False}) + self.assertEqual(sorted(os.listdir(path)), ["data", "plans", "results", "workloads"]) + + def test_a_cell_gives_its_result_or_why_it_did_not_run(self): + with tempfile.TemporaryDirectory() as path: + results = os.path.join(path, "results", "victoriametrics") + os.makedirs(results) + for name, outcome in (("a", "Ran"), ("b", {"NotRun": {"error": "query b: unsupported"}})): + with open(os.path.join(results, f"{name}__v.cell.json"), "w") as f: + json.dump({"engine": "victoriametrics", "workload": name, "variant": "v", "outcome": outcome}, f) + with open(os.path.join(results, "a__v.json"), "w") as f: + json.dump({"answers": []}, f) + self.assertEqual(cell_of(path, "victoriametrics", "a", "v"), ({"answers": []}, None)) + self.assertEqual(cell_of(path, "victoriametrics", "b", "v"), (None, "query b: unsupported")) + + def test_an_arm_result_becomes_answers_and_per_evaluation_costs(self): + result = {"answers": [[60000, {"p95": [[{"host": "a"}, 2.0], [{"host": "b"}, None]]}], + [120000, {"p95": []}]], + "evaluate": [{"median": {"wall_ns": 2_000_000}}, {"median": {"wall_ns": 1_000_000}}]} + self.assertEqual(answered_query({**QUERY, "threshold": 3000}, result)["threshold"], 3000.0) + self.assertIsInstance(answered_query({**QUERY, "threshold": 3000}, result)["threshold"], float) + query = answered_query({**QUERY, "unit": "s", "threshold": 1.5}, result) + self.assertEqual(query["answers"], [{"time": 60000, "series": {"host": "a"}, "value": 2.0}]) + self.assertEqual(query["not_finite_answers"], 1) + self.assertEqual(query["costs"], [{"time": 60000, "query_seconds": 0.002, "series_returned": 2}, + {"time": 120000, "query_seconds": 0.001, "series_returned": 0}]) + self.assertEqual((query["promql"], query["unit"], query["threshold"], query["evaluations"]), + ("quantile_over_time(0.95, cpu[5m])", "s", 1.5, 2)) + self.assertEqual(workload_name("a/b__c"), "a-b_c") + self.assertEqual(workload_name("top10_clients"), "top10_clients") + + if __name__ == "__main__": unittest.main() diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index a5846ea0..bb3bd974 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -2,7 +2,7 @@ use std::io::Write; use std::path::{Path, PathBuf}; use std::time::Instant; -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use clap::Parser; use aqpbm_core::harness::data::workload_series; @@ -65,6 +65,12 @@ struct Args { )] executor_max_bytes: Option, + #[arg( + long, + help = "Plan and run nothing: score the answers in this file (planeval's output layout, such as another system's answers) against --exact and the queries' declared truth, and write the file back with the scores" + )] + score_answers: Option, + #[arg( long, env = "ASAP_DATASETS", @@ -122,6 +128,38 @@ async fn main() -> Result<()> { if let Some(path) = &args.samples_out { write_samples(path, &series)?; } + if let Some(path) = &args.score_answers { + let Some(exact) = exact.as_ref() else { + bail!("--score-answers needs --exact"); + }; + let text = + std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?; + let mut document: serde_json::Value = + serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; + let answered = read_answers(path)?; + for entry in document["queries"].as_array_mut().into_iter().flatten() { + if entry.get("unsupported").is_some() { + continue; + } + let Some(id) = entry["id"].as_str().map(str::to_string) else { + continue; + }; + let query = spec.query(&id).with_context(|| { + format!( + "{} answers query {id}, which the spec has not", + path.display() + ) + })?; + let times = spec.evaluation_times(query); + let given = answered.get(&id).map_or(&[][..], Vec::as_slice); + let scored = score(query, &series, ×, given, Some(exact))?; + entry["answers"] = serde_json::to_value(scored.answers)?; + entry["computed_truth"] = serde_json::to_value(scored.computed_truth)?; + } + std::fs::write(&args.out, serde_json::to_string(&document)?) + .with_context(|| format!("writing {}", args.out.display()))?; + return Ok(()); + } let mut queries = Vec::new(); for query in &spec.queries { if !args.queries.is_empty() && !args.queries.contains(&query.id) { From 173001c04f9eb29c9653d7e5fd88e80d21e04dd6 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:46:34 +0000 Subject: [PATCH 22/51] harness, scripts: system CPU and memory come from the harness; a server without a cgroup, or a host off Linux, runs unmeasured and unpinned CpuAccounting gains NotMeasured: the harness reads no CPU or memory for the engine, so its steps carry wall time only, its idle probe reads nothing, and its result's cpu_source is "not measured", with the CPU and memory columns of summary.csv empty. The victoriametrics and asapquery-backend engines run so when no --server-cgroup-directory is given, instead of refusing; a VictoriaMetrics arm with a plan file, which replaces the stream-aggregation config through the cgroup source, still needs one. Off Linux the harness runs its jobs without pinning the thread instead of refusing, and marks each job NotPinned; a job whose idle check read nothing is marked IdleNotChecked. On Linux pinning is unchanged. run_use_case_on_systems.py no longer reads ps or the servers' rusage: each system's cpu seconds, peak resident bytes and resident bytes at end come from the harness results of its cells (the cgroup's cpu.stat over the whole arm, memory.peak and memory.current), and the summary says where they were read and whether the harness thread was pinned. On a host without systemd-run --user (macOS, a container without a user manager) the servers run without a cgroup and these fields are empty. The numbers differ from the ps-based ones: they cover the server's cgroup, and each cell writes the data once. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-core/src/harness/benchmark_external.rs | 13 +-- aqpbm-core/src/harness/engine.rs | 1 + aqpbm-core/src/harness/protocol.rs | 81 ++++++++++++++++--- aqpbm-core/src/harness/run_directory.rs | 2 + aqpbm-core/src/harness/write_throughput.rs | 2 +- .../tests/harness_benchmark_external.rs | 59 ++++++++++++++ scripts/use_cases/run_use_case_on_systems.py | 68 ++++++++-------- .../use_cases/test_run_use_case_on_systems.py | 32 ++++++-- .../asapquery_backend_server.rs | 14 ++-- .../victoriametrics_server.rs | 31 ++++--- system-bench/tests/end_to_end_adapters.rs | 43 +++++++++- .../tests/victoriametrics_conformance.rs | 4 +- system-bench/tests/victoriametrics_server.rs | 6 +- 13 files changed, 275 insertions(+), 81 deletions(-) diff --git a/aqpbm-core/src/harness/benchmark_external.rs b/aqpbm-core/src/harness/benchmark_external.rs index 7260dd82..c47d22d8 100644 --- a/aqpbm-core/src/harness/benchmark_external.rs +++ b/aqpbm-core/src/harness/benchmark_external.rs @@ -407,7 +407,8 @@ pub struct ReportRow { /// `ok`, `no plan: ` or `not run: `. pub status: String, /// `thread` (in-process, the calling thread's CPU), `processes` or - /// `cgroup` (a server's whole process or group, background threads included). + /// `cgroup` (a server's whole process or group, background threads + /// included), or `not measured` (no CPU or memory read). pub cpu_accounting: Option<&'static str>, /// Sum over refresh chunks of the median ingest CPU, per ingested sample. pub ingest_cpu_ns_per_sample: Option, @@ -938,8 +939,10 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { row.cpu_accounting = Some(match result.cpu_source.as_str() { "calling-thread" => "thread", "schedstat" => "processes", + crate::harness::protocol::NOT_MEASURED => crate::harness::protocol::NOT_MEASURED, _ => "cgroup", }); + let measured = result.cpu_source != crate::harness::protocol::NOT_MEASURED; let ingest_ns: u64 = result .ingest .iter() @@ -954,16 +957,16 @@ fn fill_measurements(row: &mut ReportRow, result: &ArmResult) { }) .sum() }; - row.ingest_cpu_ns_per_sample = - (result.ingested_samples > 0).then(|| ingest_ns as f64 / result.ingested_samples as f64); - if result.ingested_samples > 0 { + row.ingest_cpu_ns_per_sample = (measured && result.ingested_samples > 0) + .then(|| ingest_ns as f64 / result.ingested_samples as f64); + if measured && result.ingested_samples > 0 { let per_sample = |ns: u64| Some(ns as f64 / result.ingested_samples as f64); row.ingest_cpu_ns_per_sample_measured_runs = measured_runs(&result.ingest); row.ingest_cpu_ns_per_sample_min = per_sample(sum_of_step(&result.ingest, true)); row.ingest_cpu_ns_per_sample_max = per_sample(sum_of_step(&result.ingest, false)); } let evaluations = result.evaluate.len(); - if evaluations > 0 { + if measured && evaluations > 0 { let query_ns: u64 = result .evaluate .iter() diff --git a/aqpbm-core/src/harness/engine.rs b/aqpbm-core/src/harness/engine.rs index d73231dd..fd30d893 100644 --- a/aqpbm-core/src/harness/engine.rs +++ b/aqpbm-core/src/harness/engine.rs @@ -64,6 +64,7 @@ pub enum CpuAccounting { /// `cpu.stat` and memory files the harness reads, on this host or over /// SSH on the server host ([`crate::harness::cgroup::CgroupSource`]). Cgroup(crate::harness::cgroup::CgroupSource), + NotMeasured, } /// One arm of a workload: how the engine is asked to run it. diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index bde5b34b..7ed627eb 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -541,10 +541,36 @@ impl<'a> MeasurementClocks<'a> { CpuAccounting::Cgroup(source) => { EngineClock::Cgroup(CgroupCpuClock::new(source.clone())?) } + CpuAccounting::NotMeasured => EngineClock::NotMeasured(WallClockOnly::default()), }) } } +#[derive(Debug, Clone, Copy)] +pub struct WallClockOnly { + origin: Instant, +} + +impl Default for WallClockOnly { + fn default() -> Self { + WallClockOnly { + origin: Instant::now(), + } + } +} + +impl CpuClock for WallClockOnly { + fn thread_cpu_ns(&self) -> u64 { + 0 + } + fn process_cpu_ns(&self) -> u64 { + 0 + } + fn wall_ns(&self) -> u64 { + self.origin.elapsed().as_nanos() as u64 + } +} + /// The clock one engine is measured on, and so the CPU its medians are /// taken over: the calling thread's for `CallingThread`, the server /// processes' for `Processes`. @@ -552,6 +578,7 @@ pub enum EngineClock<'a> { CallingThread(&'a dyn CpuClock), Processes(ProcessesCpuClock), Cgroup(CgroupCpuClock), + NotMeasured(WallClockOnly), } impl EngineClock<'_> { @@ -560,6 +587,7 @@ impl EngineClock<'_> { EngineClock::CallingThread(clock) => *clock, EngineClock::Processes(clock) => clock, EngineClock::Cgroup(clock) => clock, + EngineClock::NotMeasured(clock) => clock, } } @@ -581,6 +609,7 @@ impl EngineClock<'_> { cgroup_directory.join("cpu.stat").display() ), }, + EngineClock::NotMeasured(_) => NOT_MEASURED.into(), } } @@ -589,7 +618,9 @@ impl EngineClock<'_> { pub fn engine_cpu_ns(&self, cost: &StepCost) -> u64 { match self { EngineClock::CallingThread(_) => cost.thread_cpu_ns.unwrap_or(0), - EngineClock::Processes(_) | EngineClock::Cgroup(_) => cost.process_cpu_ns, + EngineClock::Processes(_) | EngineClock::Cgroup(_) | EngineClock::NotMeasured(_) => { + cost.process_cpu_ns + } } } } @@ -636,13 +667,11 @@ fn check_core_allowed(core: usize) -> Result<(), ProtocolError> { Ok(()) } -/// Pinning needs Linux's `sched_setaffinity`; elsewhere it is refused. +/// Pinning needs Linux's `sched_setaffinity`; elsewhere the thread runs +/// unpinned, and each job is marked [`JobMark::NotPinned`]. #[cfg(not(target_os = "linux"))] -fn check_core_allowed(core: usize) -> Result<(), ProtocolError> { - Err(ProtocolError::Pin { - core, - message: "thread pinning is supported on Linux only".into(), - }) +fn check_core_allowed(_core: usize) -> Result<(), ProtocolError> { + Ok(()) } /// Pins the calling thread to `core` with `sched_setaffinity`. A core outside @@ -668,12 +697,17 @@ pub fn pin_current_thread(core: usize) -> Result<(), ProtocolError> { Ok(()) } -/// Pinning needs Linux's `sched_setaffinity`; elsewhere it is refused. +/// Pinning needs Linux's `sched_setaffinity`; elsewhere the thread runs +/// unpinned, and each job is marked [`JobMark::NotPinned`]. #[cfg(not(target_os = "linux"))] pub fn pin_current_thread(core: usize) -> Result<(), ProtocolError> { check_core_allowed(core) } +pub const PINS_THREADS: bool = cfg!(target_os = "linux"); + +pub const NOT_MEASURED: &str = "not measured"; + /// Ascending cores as ranges, as `taskset` writes them: `[0, 1, 2, 5]` is `0-2,5`. #[cfg(target_os = "linux")] fn core_ranges(cores: &[usize]) -> String { @@ -742,6 +776,24 @@ pub trait LoadProbe { fn core_busy_fraction(&mut self, core: usize) -> Result; /// The 1-minute load average. fn loadavg(&mut self) -> f64; + fn checks_idle(&self) -> bool { + true + } +} + +#[derive(Debug, Clone, Copy, Default)] +pub struct NoIdleCheck; + +impl LoadProbe for NoIdleCheck { + fn core_busy_fraction(&mut self, _core: usize) -> Result { + Ok(0.0) + } + fn loadavg(&mut self) -> f64 { + f64::NAN + } + fn checks_idle(&self) -> bool { + false + } } /// The OS load probe: two `/proc/stat` reads `sample_interval` apart, and the @@ -972,6 +1024,7 @@ pub fn load_probe_for( }, }) } + CpuAccounting::NotMeasured => Box::new(NoIdleCheck), CpuAccounting::Cgroup(source) => Box::new(ServerCoresProbe { cores: parse_cpu_list(&source.cpus_effective()?)?, sample_interval, @@ -1037,7 +1090,11 @@ impl JobRecord { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum JobMark { /// The core was busier than the limit after the job. - BusyAfter { busy_fraction: f64 }, + BusyAfter { + busy_fraction: f64, + }, + NotPinned, + IdleNotChecked, } /// One idle-check sample of a core: its busy fraction over the sampling @@ -1135,6 +1192,12 @@ impl Protocol { } let after = CoreLoad::sample(probe, core)?; let mut marks = Vec::new(); + if !PINS_THREADS { + marks.push(JobMark::NotPinned); + } + if !probe.checks_idle() { + marks.push(JobMark::IdleNotChecked); + } if after.busy_fraction > self.max_core_busy_fraction { marks.push(JobMark::BusyAfter { busy_fraction: after.busy_fraction, diff --git a/aqpbm-core/src/harness/run_directory.rs b/aqpbm-core/src/harness/run_directory.rs index 1ada56bd..32f9ae2f 100644 --- a/aqpbm-core/src/harness/run_directory.rs +++ b/aqpbm-core/src/harness/run_directory.rs @@ -206,6 +206,8 @@ impl RunDirectory { JobMark::BusyAfter { busy_fraction } => { line.push_str(&format!(" marked busy-after {busy_fraction:.2}")) } + JobMark::NotPinned => line.push_str(" marked not-pinned"), + JobMark::IdleNotChecked => line.push_str(" marked idle-not-checked"), } } line.push('\n'); diff --git a/aqpbm-core/src/harness/write_throughput.rs b/aqpbm-core/src/harness/write_throughput.rs index 6001c2a1..6def4f56 100644 --- a/aqpbm-core/src/harness/write_throughput.rs +++ b/aqpbm-core/src/harness/write_throughput.rs @@ -571,7 +571,7 @@ pub fn run_write_throughput( CpuAccounting::Cgroup(source) => { (Some(source.memory().map_err(ProtocolError::from)?), None) } - CpuAccounting::CallingThread => (None, None), + CpuAccounting::CallingThread | CpuAccounting::NotMeasured => (None, None), }; drop(installed); diff --git a/aqpbm-core/tests/harness_benchmark_external.rs b/aqpbm-core/tests/harness_benchmark_external.rs index 8aefe7df..97dea199 100644 --- a/aqpbm-core/tests/harness_benchmark_external.rs +++ b/aqpbm-core/tests/harness_benchmark_external.rs @@ -993,3 +993,62 @@ fn a_workload_of_series_groups_runs_and_answers_over_its_generated_samples() { } } } + +#[test] +fn an_engine_whose_cpu_is_not_measured_runs_with_empty_cpu_and_memory() { + use aqpbm_core::harness::engine::CpuAccounting; + use aqpbm_core::harness::protocol::{load_probe_for, JobMark, ProcessCpuFiles, PINS_THREADS}; + let temp = TempDir::new("not-measured"); + let run = fixture(&temp, "{}", "{}"); + let engine = FakeEngine { + cpu_accounting: CpuAccounting::NotMeasured, + ..FakeEngine::default() + }; + let clocks = MeasurementClocks::with_calling_thread(&engine.clock); + let mut probe = load_probe_for(&CpuAccounting::NotMeasured, &ProcessCpuFiles::os()).unwrap(); + let protocol = Protocol { + max_core_busy_fraction: 0.1, + ..protocol() + }; + let cells = run_engine( + &run, + &engine, + Some(&["v1".to_string()]), + EngineRunSetup { + data_root: Path::new("."), + protocol: &protocol, + core: 0, + probe: probe.as_mut(), + clocks: &clocks, + args: vec!["test".into()], + }, + ) + .unwrap(); + assert_eq!(cells[0].outcome, CellOutcome::Ran); + let result = read_result(&run, "w1", "v1"); + assert_eq!(result.cpu_source, "not measured"); + assert!(result.server_memory_after.is_none() && result.server_cpu_ns_whole_arm.is_none()); + assert!(result + .ingest + .iter() + .chain(&result.evaluate) + .all(|job| job.marks.contains(&JobMark::IdleNotChecked) + && job.marks.contains(&JobMark::NotPinned) != PINS_THREADS)); + let csv = report( + &run, + &ReportTruth::Cells { + engine: "fake".into(), + variant: "v1".into(), + }, + Path::new("."), + ) + .unwrap() + .summary_csv(); + let row: Vec<&str> = csv + .lines() + .find(|line| line.starts_with("w1,fake,v1,")) + .unwrap() + .split(',') + .collect(); + assert_eq!(&row[4..9], ["not measured", "", "", "", ""]); +} diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index a4adefe5..c9a82c7b 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -28,6 +28,7 @@ BACKEND = "ASAPQuery-backend" NAMES = {"victoriametrics": VICTORIAMETRICS, "asapquery-backend": BACKEND} PLANNED = {"asapquery-backend"} +NOT_MEASURED = "not measured" SPEC_ARM = "noraw" REFERENCE_ARM = "noraw" BACKEND_ENV = "ASAPQUERY_BACKEND_DIR" @@ -104,19 +105,6 @@ def free_port(): return s.getsockname()[1] -def cpu_seconds(text): - parts = [float(p) for p in re.split("[:-]", text.strip())] - seconds = 0.0 - for p in parts: - seconds = seconds * 60 + p - return seconds - - -def snapshot(pid): - out = subprocess.run(["ps", "-o", "rss=,time=", "-p", str(pid)], capture_output=True, text=True).stdout.split() - return {"resident_bytes": int(out[0]) * 1024, "cpu_seconds": cpu_seconds(out[1])} - - def directory_bytes(path): total = 0 for root, _, files in os.walk(path): @@ -177,11 +165,8 @@ def cgroup_of(pid): def stop(self): self.proc.send_signal(signal.SIGTERM) - _, status, usage = os.wait4(self.proc.pid, 0) + self.proc.wait() self.log.close() - return {"peak_resident_bytes": usage.ru_maxrss * (1 if sys.platform == "darwin" else 1024), - "cpu_seconds": usage.ru_utime + usage.ru_stime, - "wall_seconds": time.monotonic() - self.started} def workload_name(query_id): @@ -303,14 +288,28 @@ def latency(document): "evaluations": len(seconds)} -def system_summary(asked, at_end, process, disk_bytes=None): +def harness_measurements(results): + ran = [r for r in results if r] + sources = sorted({r["cpu_source"] for r in ran}) + measured = bool(ran) and NOT_MEASURED not in sources + cpu = [r.get("server_cpu_ns_whole_arm") for r in ran] + after = [r.get("server_memory_after") for r in ran] + peaks = [m.get("lifetime_peak_bytes") for m in after if m] + return {"cpu and memory": ", ".join(sources) if ran else None, + "cpu seconds": sum(cpu) / 1e9 if measured and None not in cpu else None, + "peak resident bytes": max(peaks) if measured and peaks else None, + "resident bytes at end": after[-1]["current_bytes"] if measured and after and after[-1] else None, + "harness thread pinned": not any("NotPinned" in job["marks"] for r in ran + for job in r["ingest"] + r["evaluate"])} + + +def system_summary(asked, results, disk_bytes=None): stats = asked["write"] out = {"insert samples per second": stats["samples_per_second"], "samples": stats["samples"], "write seconds": stats["send_seconds"], "visibility seconds": stats["barrier_seconds"], - "write retries": stats["retries"], "resident bytes at end": at_end["resident_bytes"], - "peak resident bytes": process["peak_resident_bytes"], "cpu seconds": process["cpu_seconds"], - "disk bytes": disk_bytes, "max replay lag seconds": stats.get("max_lag_seconds"), - "data writes": stats.get("cells")} + "write retries": stats["retries"], "disk bytes": disk_bytes, + "max replay lag seconds": stats.get("max_lag_seconds"), "data writes": stats.get("cells")} + out.update(harness_measurements(results)) out.update(latency(asked)) out["unsupported"] = {q["id"]: q["unsupported"] for q in asked["queries"] if "unsupported" in q} out["failed evaluations"] = {q["id"]: q["failed_evaluations"] for q in asked["queries"] @@ -525,10 +524,9 @@ def run_unplanned(args, system, spec_path, spec, workdir, truth_path): server, flags, data = start_victoriametrics(args, workdir, name) try: benchmark_external(args, engine, path, flags, server) - at_end = snapshot(server.proc.pid) disk = directory_bytes(data) finally: - process = server.stop() + server.stop() outcomes = {q["id"]: cell_of(path, engine, names[q["id"]], "query-text") for q in spec["queries"]} document = asked_document(spec, NAMES[system], spec["queries"], outcomes, args.speed) if truth_path: @@ -536,14 +534,15 @@ def run_unplanned(args, system, spec_path, spec, workdir, truth_path): else: with open(os.path.join(workdir, f"{name}.json"), "w") as f: json.dump(document, f) - summary = system_summary(document, at_end, process, max(disk, directory_bytes(data))) + summary = system_summary(document, [outcomes[q["id"]][0] for q in spec["queries"]], + max(disk, directory_bytes(data))) if not args.keep_data: shutil.rmtree(data, ignore_errors=True) return document, summary def run_group(args, system, spec_path, spec, planned, members, name, workdir, exact_path): - outcomes, at_end, process = {}, {"resident_bytes": 0}, {"peak_resident_bytes": 0, "cpu_seconds": 0.0} + outcomes = {} for q in members: query_name = f"{name}-{workload_name(q['id'])}" path = os.path.join(workdir, f"{query_name}-run") @@ -555,16 +554,12 @@ def run_group(args, system, spec_path, spec, planned, members, name, workdir, ex return None, f"the data plane did not start with the plan: {lines[-1] if lines else refused}" try: benchmark_external(args, system, path, flags, server) - ended = snapshot(server.proc.pid) finally: - stopped = server.stop() - at_end = ended - process = {"peak_resident_bytes": max(process["peak_resident_bytes"], stopped["peak_resident_bytes"]), - "cpu_seconds": process["cpu_seconds"] + stopped["cpu_seconds"]} + server.stop() outcomes[q["id"]] = cell_of(path, system, names[q["id"]], name) document = asked_document(spec, NAMES[system], members, outcomes, args.speed) document = scored(args, spec_path, document, exact_path, os.path.join(workdir, f"{name}.json")) - return document, system_summary(document, at_end, process, 0) + return document, system_summary(document, [outcomes[q["id"]][0] for q in members], 0) def merged_groups(spec, ran): @@ -576,9 +571,11 @@ def merged_groups(spec, ran): "groups": [{"queries": [q["id"] for q in a["queries"]], "write": a["write"], "run_seconds": a["run_seconds"]} for a, _ in ran]} summaries = [s for _, s in ran] + cpu = [s["cpu seconds"] for s in summaries] + peaks = [s["peak resident bytes"] for s in summaries if s["peak resident bytes"] is not None] summary = {"instances": len(ran), "per instance": summaries, - "cpu seconds": sum(s["cpu seconds"] for s in summaries), - "peak resident bytes": max(s["peak resident bytes"] for s in summaries)} + "cpu seconds": None if None in cpu else sum(cpu), + "peak resident bytes": max(peaks) if peaks else None} summary.update(latency(asked)) summary["failed evaluations"] = {k: v for s in summaries for k, v in s["failed evaluations"].items()} return asked, summary @@ -780,6 +777,9 @@ def main(argv=None): if args.reference == args.candidate: parser.error("--reference and --candidate name the same system") args.own_cgroup = own_cgroup_available() + if not args.own_cgroup: + print("the servers run without a cgroup v2 group of their own (systemd-run --user is not available " + "here), so their CPU and memory are not measured", file=sys.stderr) if args.spec: run_spec(args) return diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index 06ef472c..7fa7de2e 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -8,9 +8,9 @@ import run_use_case import run_use_case_on_systems -from run_use_case_on_systems import (answered_query, backend_arms, cell_of, cpu_seconds, describe_backend_plan, - evaluation_counts, latency, merged_exact, merged_groups, plan_groups, - run_directory, truth_errors, workload, workload_name) +from run_use_case_on_systems import (answered_query, backend_arms, cell_of, describe_backend_plan, + evaluation_counts, harness_measurements, latency, merged_exact, merged_groups, + plan_groups, run_directory, truth_errors, workload, workload_name) SPEC = { "metrics": [ @@ -47,11 +47,27 @@ def test_only_arms_that_keep_no_raw_samples(self): ["noraw-eps0.1", "noraw-eps0.05", "noraw-eps0.01", "noraw-eps0.005"]) -class CpuSecondsTest(unittest.TestCase): - def test_ps_time_formats(self): - self.assertAlmostEqual(cpu_seconds("0:01.25"), 1.25) - self.assertAlmostEqual(cpu_seconds("2:03.00"), 123.0) - self.assertAlmostEqual(cpu_seconds("1:00:00"), 3600.0) +def arm_result(cpu_source, cpu_ns, memory, marks=()): + job = {"marks": list(marks)} + return {"cpu_source": cpu_source, "server_cpu_ns_whole_arm": cpu_ns, "server_memory_after": memory, + "ingest": [job], "evaluate": [job]} + + +class HarnessMeasurementsTest(unittest.TestCase): + def test_a_cgroup_server_adds_up_its_cells(self): + memory = {"current_bytes": 100, "anon_bytes": 0, "file_bytes": 0, "lifetime_peak_bytes": 300} + out = harness_measurements([arm_result("cgroup /g/cpu.stat", 2_000_000_000, memory), + None, + arm_result("cgroup /g/cpu.stat", 500_000_000, + {**memory, "current_bytes": 150, "lifetime_peak_bytes": 400})]) + self.assertEqual(out, {"cpu and memory": "cgroup /g/cpu.stat", "cpu seconds": 2.5, + "peak resident bytes": 400, "resident bytes at end": 150, + "harness thread pinned": True}) + + def test_a_server_without_a_group_is_not_measured(self): + out = harness_measurements([arm_result("not measured", None, None, ["NotPinned", "IdleNotChecked"])]) + self.assertEqual(out, {"cpu and memory": "not measured", "cpu seconds": None, "peak resident bytes": None, + "resident bytes at end": None, "harness thread pinned": False}) def answers(*values): diff --git a/system-bench/src/engines_external/asapquery_backend_server.rs b/system-bench/src/engines_external/asapquery_backend_server.rs index d5474a7f..89955aca 100644 --- a/system-bench/src/engines_external/asapquery_backend_server.rs +++ b/system-bench/src/engines_external/asapquery_backend_server.rs @@ -18,7 +18,7 @@ use aqpbm_core::harness::protocol::Protocol; #[derive(Debug, Clone, PartialEq)] pub struct AsapqueryBackendServer { pub url: String, - pub cgroup: CgroupSource, + pub cgroup: Option, pub request_timeout: Duration, pub speed: Option, } @@ -120,7 +120,10 @@ impl EngineUnderTest for AsapqueryBackendEngine { } fn cpu_accounting(&self) -> CpuAccounting { - CpuAccounting::Cgroup(self.server.cgroup.clone()) + match &self.server.cgroup { + Some(source) => CpuAccounting::Cgroup(source.clone()), + None => CpuAccounting::NotMeasured, + } } fn holds_one_install_at_a_time(&self) -> bool { @@ -237,11 +240,10 @@ pub fn periodic_queries( protocol: &Protocol, ) -> anyhow::Result> { let options = ::from_arg_matches(matches)?; - let (Some(url), Some(cgroup)) = (options.asapquery_backend_url, options.cgroup.source()) else { - anyhow::bail!( - "engine asapquery-backend needs --asapquery-backend-url and --server-cgroup-directory" - ); + let Some(url) = options.asapquery_backend_url else { + anyhow::bail!("engine asapquery-backend needs --asapquery-backend-url"); }; + let cgroup = options.cgroup.source(); if protocol.warmup_runs + protocol.measured_runs != 1 && options.asapquery_backend_restart_command.is_none() { diff --git a/system-bench/src/engines_external/victoriametrics_server.rs b/system-bench/src/engines_external/victoriametrics_server.rs index 61629872..2dd3b777 100644 --- a/system-bench/src/engines_external/victoriametrics_server.rs +++ b/system-bench/src/engines_external/victoriametrics_server.rs @@ -45,8 +45,10 @@ //! 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. +//! same way the server's `-streamAggr.config` file is replaced; without a +//! cgroup the harness reads no CPU or memory, and an arm with a plan file is +//! refused. VictoriaMetrics keeps no per-query CPU counter, so [`StepReport`] +//! carries none. use std::collections::BTreeMap; use std::path::PathBuf; @@ -78,8 +80,9 @@ use aqpbm_core::harness::protocol::Protocol; 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, + /// Where the server's cgroup is read, e.g. over SSH from `bench@10.0.0.1`; + /// `None` when the harness reads no CPU or memory. + pub cgroup: Option, /// The server's `-streamAggr.config` file on the server host, replaced /// for each arm with a plan file through `cgroup`'s host access; such an /// arm is refused without it. @@ -186,7 +189,10 @@ impl EngineUnderTest for VictoriaMetricsEngine { } fn cpu_accounting(&self) -> CpuAccounting { - CpuAccounting::Cgroup(self.server.cgroup.clone()) + match &self.server.cgroup { + Some(source) => CpuAccounting::Cgroup(source.clone()), + None => CpuAccounting::NotMeasured, + } } fn holds_one_install_at_a_time(&self) -> bool { @@ -215,7 +221,13 @@ impl EngineUnderTest for VictoriaMetricsEngine { .into(), )); } - let cgroup = self.server.cgroup.clone(); + let Some(cgroup) = self.server.cgroup.clone() else { + return Err(EngineError( + "an arm with a plan file replaces the server's stream-aggregation config through \ + its cgroup source: it needs --server-cgroup-directory" + .into(), + )); + }; let Some(stream_aggregation_config) = self.server.stream_aggregation_config.clone() else { return Err(EngineError( "an arm with a plan file replaces the server's stream-aggregation config: it \ @@ -1118,11 +1130,10 @@ pub fn periodic_queries( protocol: &Protocol, ) -> anyhow::Result> { let options = ::from_arg_matches(matches)?; - let (Some(url), Some(cgroup)) = (options.victoriametrics_url, options.cgroup.source()) else { - anyhow::bail!( - "engine victoriametrics needs --victoriametrics-url and --server-cgroup-directory" - ); + let Some(url) = options.victoriametrics_url else { + anyhow::bail!("engine victoriametrics needs --victoriametrics-url"); }; + let cgroup = options.cgroup.source(); check_speed(options.speed)?; let mut engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { url, diff --git a/system-bench/tests/end_to_end_adapters.rs b/system-bench/tests/end_to_end_adapters.rs index 4e13eab2..38d8c177 100644 --- a/system-bench/tests/end_to_end_adapters.rs +++ b/system-bench/tests/end_to_end_adapters.rs @@ -262,7 +262,7 @@ fn asapquery_backend_writes_closes_panes_and_asks_the_promql() { let (url, seen) = recording_server(); let engine = AsapqueryBackendEngine::new(AsapqueryBackendServer { url, - cgroup: cgroup(), + cgroup: Some(cgroup()), request_timeout: Duration::from_secs(5), speed: None, }) @@ -374,7 +374,7 @@ fn two_answers_for_one_series_are_refused() { let (url, _) = recording_server(); let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { url, - cgroup: cgroup(), + cgroup: Some(cgroup()), stream_aggregation_config: None, request_timeout: Duration::from_secs(5), speed: None, @@ -392,7 +392,7 @@ fn victoriametrics_without_a_plan_writes_the_samples_and_asks_the_query_text() { let (url, seen) = recording_server(); let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { url, - cgroup: cgroup(), + cgroup: Some(cgroup()), stream_aggregation_config: None, request_timeout: Duration::from_secs(5), speed: None, @@ -556,3 +556,40 @@ fn asapquery_precompute_engine_refuses_a_metric_its_streaming_config_does_not_ag .unwrap(); assert!(error.0.contains("no aggregation"), "{error}"); } + +#[test] +fn a_server_without_a_cgroup_is_run_with_cpu_and_memory_not_measured() { + use aqpbm_core::harness::engine::CpuAccounting; + let (url, _) = recording_server(); + let victoriametrics = VictoriaMetricsEngine::new(VictoriaMetricsServer { + url: url.clone(), + cgroup: None, + stream_aggregation_config: Some(std::env::temp_dir().join("stream-aggregation.yaml")), + request_timeout: Duration::from_secs(5), + speed: None, + }) + .unwrap(); + assert_eq!(victoriametrics.cpu_accounting(), CpuAccounting::NotMeasured); + let with_plan = ArmSpec { + engine_options: json!({ "plan_file": "p.plan.json" }), + ..query_text_arm() + }; + let error = victoriametrics + .install(&workload(), &with_plan) + .err() + .unwrap(); + assert!(error.0.contains("--server-cgroup-directory"), "{error}"); + let mut arm = victoriametrics + .install(&workload(), &query_text_arm()) + .unwrap(); + arm.ingest(&chunk()).unwrap(); + drop(arm); + let backend = AsapqueryBackendEngine::new(AsapqueryBackendServer { + url, + cgroup: None, + request_timeout: Duration::from_secs(5), + speed: None, + }) + .unwrap(); + assert_eq!(backend.cpu_accounting(), CpuAccounting::NotMeasured); +} diff --git a/system-bench/tests/victoriametrics_conformance.rs b/system-bench/tests/victoriametrics_conformance.rs index fbba1039..5e3ab90a 100644 --- a/system-bench/tests/victoriametrics_conformance.rs +++ b/system-bench/tests/victoriametrics_conformance.rs @@ -37,7 +37,7 @@ 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: { + cgroup: Some({ let cgroup_directory = std::env::var("AQPBM_SERVER_CGROUP_DIRECTORY") .expect("AQPBM_SERVER_CGROUP_DIRECTORY") .into(); @@ -49,7 +49,7 @@ fn engine() -> VictoriaMetricsEngine { }, Err(_) => CgroupSource::Local(cgroup_directory), } - }, + }), stream_aggregation_config: Some( std::env::var("AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG") .expect("AQPBM_VICTORIAMETRICS_STREAM_AGGREGATION_CONFIG") diff --git a/system-bench/tests/victoriametrics_server.rs b/system-bench/tests/victoriametrics_server.rs index ec7d5e63..843376b5 100644 --- a/system-bench/tests/victoriametrics_server.rs +++ b/system-bench/tests/victoriametrics_server.rs @@ -314,7 +314,7 @@ 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), + cgroup: Some(fake_cgroup(&dir)), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), speed: None, @@ -364,7 +364,7 @@ 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), + cgroup: Some(fake_cgroup(&dir)), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), speed: None, @@ -406,7 +406,7 @@ fn a_query_time_arm_ingests_then_evaluates() { let dir = temp_dir("query-time"); let engine = VictoriaMetricsEngine::new(VictoriaMetricsServer { url: fake_server(dir.join("stream-aggregation.yaml")), - cgroup: fake_cgroup(&dir), + cgroup: Some(fake_cgroup(&dir)), stream_aggregation_config: Some(dir.join("stream-aggregation.yaml")), request_timeout: Duration::from_secs(10), speed: None, From 9d4e9b8764ce4977d730561e55766600c3321186 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Sun, 29 Nov 2026 21:55:58 +0000 Subject: [PATCH 23/51] system-bench: remove systemeval run_use_case_on_systems.py runs the systems through approxbench benchmark-external run since the previous commits, and the victoriametrics and asapquery-backend engines replay at a given speed, so nothing runs systemeval. Its binary, system-bench's systemeval module and feature (the default feature, so system-bench now has none) and the systemeval output types in aqpbm-usecase are removed. The system level is approxbench benchmark-external, plus planeval for comparing plans. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nTLXH7ht3wiMWxCGSc --- aqpbm-usecase/src/output.rs | 67 --------- system-bench/Cargo.toml | 10 +- system-bench/src/bin/systemeval.rs | 155 ------------------- system-bench/src/lib.rs | 2 - system-bench/src/prometheus_api/query.rs | 4 - system-bench/src/systemeval/mod.rs | 3 - system-bench/src/systemeval/query.rs | 94 ------------ system-bench/src/systemeval/servers.rs | 71 --------- system-bench/src/systemeval/write.rs | 181 ----------------------- 9 files changed, 2 insertions(+), 585 deletions(-) delete mode 100644 system-bench/src/bin/systemeval.rs delete mode 100644 system-bench/src/systemeval/mod.rs delete mode 100644 system-bench/src/systemeval/query.rs delete mode 100644 system-bench/src/systemeval/servers.rs delete mode 100644 system-bench/src/systemeval/write.rs diff --git a/aqpbm-usecase/src/output.rs b/aqpbm-usecase/src/output.rs index 59237c27..d219c557 100644 --- a/aqpbm-usecase/src/output.rs +++ b/aqpbm-usecase/src/output.rs @@ -71,70 +71,3 @@ pub struct PlanevalCost { pub samples_read_at_query: usize, pub state_bytes: usize, } - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SystemevalOutput { - pub schema_version: u32, - pub use_case: String, - pub system: String, - pub samples: usize, - pub run_seconds: f64, - pub write: WriteSummary, - pub queries: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct WriteSummary { - pub samples: usize, - pub requests: usize, - pub compressed_bytes: usize, - pub retries: u64, - pub speed: Option, - pub batch_samples: usize, - pub send_seconds: f64, - pub barrier_seconds: f64, - pub barriers: usize, - pub samples_per_second: f64, - pub max_lag_seconds: Option, - pub status: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SystemevalQuery { - pub id: String, - pub promql: String, - pub unit: String, - pub threshold: Option, - pub evaluations: usize, - pub failed_evaluations: usize, - pub failures: Vec, - pub not_finite_answers: usize, - pub costs: Vec, - #[serde(flatten)] - pub outcome: SystemevalOutcome, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(untagged)] -pub enum SystemevalOutcome { - Scored { - answers: Vec, - computed_truth: Option>, - }, - Unsupported { - unsupported: String, - }, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct Failure { - pub time: i64, - pub error: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SystemevalCost { - pub time: i64, - pub query_seconds: f64, - pub series_returned: Option, -} diff --git a/system-bench/Cargo.toml b/system-bench/Cargo.toml index 40dba873..984eeb9c 100644 --- a/system-bench/Cargo.toml +++ b/system-bench/Cargo.toml @@ -4,11 +4,10 @@ version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true -description = "System level: runs ASAPPlanner's plans on its executor (feature planeval), translates ASAPPlanner plan files for external engines, and writes a spec's samples to time series systems and asks them its queries." +description = "System level: runs ASAPPlanner's plans on its executor (feature planeval), translates ASAPPlanner plan files for external engines, and adapts external systems (time series servers, one-shot SQL engines, write-only engines) as engines under test for approxbench benchmark-external." [features] -default = ["systemeval"] -systemeval = ["dep:aqpbm-usecase", "aqpbm-core/import"] +default = [] planeval = [ "dep:aqpbm-usecase", "aqpbm-core/import", @@ -26,11 +25,6 @@ name = "planeval" path = "src/bin/planeval.rs" required-features = ["planeval"] -[[bin]] -name = "systemeval" -path = "src/bin/systemeval.rs" -required-features = ["systemeval"] - [[test]] name = "uc1" required-features = ["planeval"] diff --git a/system-bench/src/bin/systemeval.rs b/system-bench/src/bin/systemeval.rs deleted file mode 100644 index 82a3ef72..00000000 --- a/system-bench/src/bin/systemeval.rs +++ /dev/null @@ -1,155 +0,0 @@ -use std::collections::BTreeMap; -use std::path::PathBuf; -use std::time::Instant; - -use anyhow::{Context, Result}; -use aqpbm_core::harness::data::workload_series; -use aqpbm_core::harness::engine::QueryLanguage; -use aqpbm_usecase::data::read_workload; -use aqpbm_usecase::output::{SystemevalOutput, OUTPUT_SCHEMA_VERSION}; -use aqpbm_usecase::score::read_answers; -use clap::builder::PossibleValuesParser; -use clap::Parser; - -use system_bench::prometheus_api::query::ask; -use system_bench::systemeval::query::Collected; -use system_bench::systemeval::servers::{Server, SERVERS}; -use system_bench::systemeval::write::{Options, Writer}; - -#[derive(Parser, Debug)] -#[command( - name = "systemeval", - about = "Write a spec's samples to a time series system by Prometheus Remote Write in time order and, at each \ - evaluation time, make the samples written so far visible and ask the queries due then" -)] -struct Args { - #[arg(long)] - spec: PathBuf, - - #[arg(long, value_parser = PossibleValuesParser::new(SERVERS))] - system: String, - - #[arg(long, help = "Base URL of the system, e.g. http://127.0.0.1:8428")] - url: String, - - #[arg( - long, - default_value_t = 10_000, - help = "Most samples in one Remote Write request" - )] - batch_samples: usize, - - #[arg( - long, - help = "Replay at this many times the data's own rate; omitted writes as fast as the system accepts" - )] - speed: Option, - - #[arg( - long, - default_value_t = 1000, - help = "With --speed, the most data time one request spans, in ms" - )] - flush_ms: i64, - - #[arg( - long, - help = "Output of an exact run of the same spec; each answer is then also scored against it" - )] - exact: Option, - - #[arg(long = "query", help = "Only these query ids; repeatable")] - queries: Vec, - - #[arg( - long, - env = "ASAP_DATASETS", - default_value = "datasets", - help = "Directory that imported tables' dataset paths are relative to" - )] - data_root: PathBuf, - - #[arg(long)] - out: PathBuf, -} - -fn main() -> Result<()> { - let args = Args::parse(); - let server = - Server::connect(&args.system, &args.url).expect("clap accepts only listed systems"); - let spec = read_workload(&args.spec)?; - let generated = Instant::now(); - let series = workload_series(&spec, &args.data_root)?; - eprintln!( - "generated {} samples in {} series in {:.1} s", - series.iter().map(|s| s.points.len()).sum::(), - series.len(), - generated.elapsed().as_secs_f64() - ); - let exact = args.exact.as_deref().map(read_answers).transpose()?; - let asked: Vec<_> = spec - .queries - .iter() - .filter(|q| args.queries.is_empty() || args.queries.contains(&q.id)) - .collect(); - let mut due: BTreeMap> = BTreeMap::new(); - for (i, query) in asked.iter().enumerate() { - for t in spec.evaluation_times(query) { - due.entry(t).or_default().push(i); - } - } - let options = Options { - batch_samples: args.batch_samples, - speed: args.speed, - flush_ms: args.flush_ms, - }; - let start_ms = spec.data_start_ms().unwrap_or(0); - let end_ms = spec.data_end_ms().unwrap_or(start_ms); - let mut writer = Writer::new(&series, &server, start_ms, &options); - let mut collected: Vec = asked.iter().map(|_| Collected::default()).collect(); - let started = Instant::now(); - writer.start_clock(); - for (&t, queries) in &due { - writer.write_through(t)?; - writer.make_visible(t)?; - for &i in queries { - let promql = asked[i].text_in(QueryLanguage::PromQl).unwrap_or_default(); - collected[i].record(t, ask(server.agent(), server.base(), promql, t)); - } - } - writer.write_through(end_ms)?; - writer.make_visible(end_ms)?; - let run_seconds = started.elapsed().as_secs_f64(); - let write = writer.summary()?; - eprintln!( - "{}: {} samples at {:.0} samples/s, {} evaluation times, {:.1} s", - server.name(), - writer.samples(), - write.samples_per_second, - due.len(), - run_seconds - ); - let mut queries = Vec::new(); - for (query, collected) in asked.iter().zip(collected) { - let out = collected - .finish(query, &series, exact.as_ref()) - .with_context(|| format!("answers of {}", query.id))?; - eprintln!( - "{}: {} evaluations, {} failed", - query.id, out.evaluations, out.failed_evaluations - ); - queries.push(out); - } - let document = SystemevalOutput { - schema_version: OUTPUT_SCHEMA_VERSION, - use_case: spec.name.clone(), - system: server.name().to_string(), - samples: writer.samples(), - run_seconds, - write, - queries, - }; - std::fs::write(&args.out, serde_json::to_string(&document)?) - .with_context(|| format!("writing {}", args.out.display()))?; - Ok(()) -} diff --git a/system-bench/src/lib.rs b/system-bench/src/lib.rs index de179edf..f5a2c7c0 100644 --- a/system-bench/src/lib.rs +++ b/system-bench/src/lib.rs @@ -3,5 +3,3 @@ pub mod engines_external; pub mod planeval; pub mod prometheus_api; pub mod registry; -#[cfg(feature = "systemeval")] -pub mod systemeval; diff --git a/system-bench/src/prometheus_api/query.rs b/system-bench/src/prometheus_api/query.rs index cf585c86..b049440c 100644 --- a/system-bench/src/prometheus_api/query.rs +++ b/system-bench/src/prometheus_api/query.rs @@ -33,10 +33,6 @@ fn vector(body: &Value) -> Result> { Ok(out) } -pub fn ask(agent: &ureq::Agent, base: &str, promql: &str, time_ms: i64) -> Asked { - ask_with_parameters(agent, base, promql, time_ms, &[]) -} - pub fn ask_with_parameters( agent: &ureq::Agent, base: &str, diff --git a/system-bench/src/systemeval/mod.rs b/system-bench/src/systemeval/mod.rs deleted file mode 100644 index 22927a1d..00000000 --- a/system-bench/src/systemeval/mod.rs +++ /dev/null @@ -1,3 +0,0 @@ -pub mod query; -pub mod servers; -pub mod write; diff --git a/system-bench/src/systemeval/query.rs b/system-bench/src/systemeval/query.rs deleted file mode 100644 index a00b9e2c..00000000 --- a/system-bench/src/systemeval/query.rs +++ /dev/null @@ -1,94 +0,0 @@ -use std::collections::BTreeMap; - -use anyhow::{Context, Result}; -use aqpbm_core::harness::engine::{QueryLanguage, WorkloadQuery}; -use aqpbm_usecase::accuracy::AnswerAt; -use aqpbm_usecase::data::Series; -use aqpbm_usecase::output::{Failure, SystemevalCost, SystemevalOutcome, SystemevalQuery}; -use aqpbm_usecase::score::score; - -use crate::prometheus_api::query::Asked; - -const KEPT_FAILURES: usize = 5; - -#[derive(Default)] -pub struct Collected { - answered: Vec, - costs: Vec, - failures: Vec, - failed: usize, - not_finite: usize, - times: Vec, -} - -impl Collected { - pub fn record(&mut self, t: i64, asked: Asked) { - self.times.push(t); - let returned = match asked.outcome { - Ok(samples) => { - let count = samples.len(); - for (labels, value) in samples { - if value.is_finite() { - self.answered.push((t, labels, value)); - } else { - self.not_finite += 1; - } - } - Some(count) - } - Err(reason) => { - self.failed += 1; - if self.failures.len() < KEPT_FAILURES { - self.failures.push(Failure { - time: t, - error: reason, - }); - } - None - } - }; - self.costs.push(SystemevalCost { - time: t, - query_seconds: asked.seconds, - series_returned: returned, - }); - } - - pub fn finish( - self, - query: &WorkloadQuery, - series: &[Series], - exact: Option<&BTreeMap>>, - ) -> Result { - let outcome = if self.failed == self.times.len() { - SystemevalOutcome::Unsupported { - unsupported: self - .failures - .first() - .map_or_else(|| "no evaluation answered".to_string(), |f| f.error.clone()), - } - } else { - let scored = score(query, series, &self.times, &self.answered, exact) - .with_context(|| format!("scoring {}", query.id))?; - SystemevalOutcome::Scored { - answers: scored.answers, - computed_truth: scored.computed_truth, - } - }; - Ok(SystemevalQuery { - id: query.id.clone(), - promql: query - .text_in(QueryLanguage::PromQl) - .unwrap_or_default() - .to_string(), - unit: query.unit.clone().unwrap_or_default(), - threshold: query.threshold, - evaluations: self.times.len(), - failed_evaluations: self.failed, - failures: self.failures, - not_finite_answers: self.not_finite, - costs: self.costs, - outcome, - }) - } -} diff --git a/system-bench/src/systemeval/servers.rs b/system-bench/src/systemeval/servers.rs deleted file mode 100644 index 9cf4cf29..00000000 --- a/system-bench/src/systemeval/servers.rs +++ /dev/null @@ -1,71 +0,0 @@ -use std::time::Duration; - -use anyhow::{Context, Result}; -use serde_json::Value; - -use crate::engines_external::asapquery_backend_server::AsapqueryBackendConnection; -use crate::engines_external::victoriametrics_server::VictoriaMetricsConnection; - -pub const SERVERS: [&str; 2] = ["asapquery-backend", "victoriametrics"]; - -const REQUEST_TIMEOUT: Duration = Duration::from_secs(600); - -pub enum Server { - AsapqueryBackend(AsapqueryBackendConnection), - VictoriaMetrics(VictoriaMetricsConnection), -} - -impl Server { - pub fn connect(id: &str, url: &str) -> Option { - match id { - "asapquery-backend" => Some(Server::AsapqueryBackend(AsapqueryBackendConnection::new( - url, - REQUEST_TIMEOUT, - ))), - "victoriametrics" => Some(Server::VictoriaMetrics(VictoriaMetricsConnection::new( - url, - REQUEST_TIMEOUT, - ))), - _ => None, - } - } - - pub fn name(&self) -> &'static str { - match self { - Server::AsapqueryBackend(_) => "ASAPQuery-backend", - Server::VictoriaMetrics(_) => "VictoriaMetrics", - } - } - - pub fn agent(&self) -> &ureq::Agent { - match self { - Server::AsapqueryBackend(connection) => &connection.agent, - Server::VictoriaMetrics(connection) => &connection.agent, - } - } - - pub fn base(&self) -> &str { - match self { - Server::AsapqueryBackend(connection) => &connection.base, - Server::VictoriaMetrics(connection) => &connection.url, - } - } - - pub fn make_visible(&self, through_ms: i64) -> Result<()> { - match self { - Server::AsapqueryBackend(connection) => connection.make_visible(through_ms), - Server::VictoriaMetrics(connection) => connection - .force_flush() - .map(|_| ()) - .map_err(|error| anyhow::anyhow!("{}", error.0)) - .context("flushing VictoriaMetrics"), - } - } - - pub fn status(&self) -> Result> { - match self { - Server::AsapqueryBackend(connection) => connection.status().map(Some), - Server::VictoriaMetrics(_) => Ok(None), - } - } -} diff --git a/system-bench/src/systemeval/write.rs b/system-bench/src/systemeval/write.rs deleted file mode 100644 index e14de716..00000000 --- a/system-bench/src/systemeval/write.rs +++ /dev/null @@ -1,181 +0,0 @@ -use std::collections::HashMap; -use std::time::{Duration, Instant}; - -use anyhow::Result; -use aqpbm_usecase::data::Series; -use aqpbm_usecase::output::WriteSummary; - -use super::servers::Server; -use crate::prometheus_api::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; -use crate::prometheus_api::remote_write::{send, Sent}; - -pub struct Options { - pub batch_samples: usize, - pub speed: Option, - pub flush_ms: i64, -} - -pub struct Writer<'a> { - server: &'a Server, - options: &'a Options, - start_ms: i64, - order: Vec<(i64, u32, f64)>, - labels: Vec>, - next: usize, - started: Instant, - pub requests: usize, - pub compressed_bytes: usize, - pub retries: u64, - pub send_seconds: f64, - pub barrier_seconds: f64, - pub barriers: usize, - pub max_lag_seconds: f64, -} - -fn labels_of(series: &Series) -> Vec