From 7cb5ee810a3eccd0ae252aed42d876ed843a4e63 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Tue, 24 Nov 2026 00:27:53 -0500 Subject: [PATCH 1/3] docs: interface design for the operator and system levels Describes what the benchmark's interfaces should be: the sketch registry entry and wrapper functions at operator level; the EngineUnderTest and InstalledArm traits, workload and arm inputs, run directory outputs, and measurement, accuracy and error rules at system level; which parts are public; and the open questions. Co-Authored-By: Claude Opus 5.5 --- docs/interface-design.md | 442 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 442 insertions(+) create mode 100644 docs/interface-design.md diff --git a/docs/interface-design.md b/docs/interface-design.md new file mode 100644 index 00000000..4824de7c --- /dev/null +++ b/docs/interface-design.md @@ -0,0 +1,442 @@ +# ASAPBench interface design + +## Who reads what + +| Reader | Implements | Calls | Read | +|---|---|---|---| +| Adds a sketch library | a registry entry and wrapper functions | — | [Scope and overview](#scope-and-overview), [Terms](#terms), [Operator level](#operator-level), [Measurement, accuracy and errors](#measurement-accuracy-and-errors) | +| Adds a system | an adapter: `EngineUnderTest` and `InstalledArm` | the conformance check | [Scope and overview](#scope-and-overview), [Terms](#terms), [System level](#system-level), [Measurement, accuracy and errors](#measurement-accuracy-and-errors) | +| Runs the benchmark | — | the command line | [Scope and overview](#scope-and-overview), [Terms](#terms), [Inputs and outputs](#inputs-and-outputs) | +| A crate that uses ASAPBench as a library (for example ASAPPlanner) | as needed | the public modules | [System level](#system-level), [Public and internal](#public-and-internal) | + +## Scope and overview + +ASAPBench measures at two levels: + +- **Operator level**: one sketch algorithm implementation. It measures throughput, latency, memory and accuracy across insert, query and merge operations. +- **System level**: one system running a set of recurring queries over a stream of time-series data. It measures ingest cost, query cost, stored state size and accuracy. A system is an in-process executor or an external server. If the system uses sketches, they are measured as part of the system. + +``` + ┌────────────────┐ + data description ──► │ data generator │── samples ──┬────────────────────────┐ + └────────────────┘ │ │ + ▼ ▼ + ┌─────────────────────────────────────┐ ┌──────────────┐ + │ under test │ │ exact answer │ + │ operator level: wrapper functions │ └──────┬───────┘ + │ system level: adapter │ │ + └──────────────────┬──────────────────┘ │ + the harness times every call │ + ▼ ▼ + answers + cost ─────────────────► scoring ──► results +``` + +Out of scope: + +- how a plan is produced; +- how a system or a sketch works inside; +- turning answers into use-case decisions. + +## Terms + +| Term | Meaning | +|---|---| +| harness | the code that calls what is under test, reads the clocks and writes the results; it lives in the crate `aqpbm-core` | +| `approxbench` | the command-line program | +| system | what runs the queries at system level; the code calls it an engine (`EngineUnderTest`, `engine_options`, the `engine` field of a result) | +| adapter | the code that implements `EngineUnderTest` and `InstalledArm` for one system | +| workload | a set of queries and the time-series data they run over; all its queries use the same evaluation interval | +| arm | one way to run a workload: same data and queries, different configuration | +| sample chunk | the samples in `(end_ms − interval, end_ms]`, where interval is the workload's evaluation interval; a system ingests one chunk at a time | +| repetition | one timed pass of a measurement; the first `warmup_runs` are discarded, the next `measured_runs` are kept | +| run | everything one command measures | + +## Operator level + +### Interface + +A sketch under test is a registry entry, one sketch implementation the benchmark can measure, plus one wrapper function per operation. A wrapper function prepares one operation for timing. Both live in the `sketch-bench` crate. Wrapper functions are plain functions, not a trait: libraries take different input shapes, and a shared trait would put the conversion cost inside the timed region. + +The registry entry: + +```rust +pub struct SketchId { + pub algorithm: &'static str, // algorithm family, e.g. "cms"; entries in one family take the same parameters + pub variant: &'static str, // e.g. "cms-fastpath-vector2d" + pub library: &'static str, // e.g. "oxide", "datasketches", "lib" + pub description: &'static str, + pub capability: Capability, // the statistic it answers: frequency, quantile, cardinality, ... + pub comparator: Option<&'static str>, // the accuracy scorer for this entry, e.g. "frequency"; `--comparator` must name it + pub operations: OperationMask, // which of Insert, Query, Merge, Prepare it supports + pub metrics: MetricsMask, // which of Throughput, Latency, Accuracy it supports +} +``` + +The operations: `Insert` adds items. `Query` reads an estimate from the sketch. `Merge` folds several sketches, called shards, into one. `Prepare` is the step some sketches need between inserting and querying, such as sorting. + +A wrapper function returns one closure per repetition. Calling the closure is the timed work. The harness provides these closure types: + +```rust +pub type Pass = Box usize>; // one repetition; returns the sketch's memory in bytes +pub type QueryPass = Box (Vec, usize)>; // one repetition; returns the estimates and the memory in bytes + +pub struct StepPass { // one repetition for latency: each call does one unit of work + pub steps: usize, // calls in one repetition + pub step: Box, + pub footprint: Box usize>, // memory in bytes, read after the last call +} +``` + +The wrapper function shapes. `I` is the item type, `P` the query input type, `A` the estimate type. + +```rust +// Throughput and accuracy. +// (parameters, items, repetitions) +pub type InsertBody = + fn(&ParamSet, Rc>, usize) -> Result, BuildError>; +// (parameters, items, query inputs, repetitions) +pub type QueryBody = + fn(&ParamSet, Rc>, Rc>, usize) -> Result>, BuildError>; +// (parameters, items, shards, repetitions) +pub type MergeBody = + fn(&ParamSet, Rc>, usize, usize) -> Result, BuildError>; +// (parameters, items, repetitions) +pub type PrepareBody = + fn(&ParamSet, Rc>, usize) -> Result, BuildError>; + +// Latency: the same insert and merge, one unit of work per call. +pub type InsertStepBody = + fn(&ParamSet, Rc>, usize) -> Result, BuildError>; +pub type MergeStepBody = + fn(&ParamSet, Rc>, usize, usize) -> Result, BuildError>; +``` + +Preconditions: + +- Every shard in a merge is built with the same parameters. +- A closure has everything it needs before it is called. + +### Call order + +1. Find the requested registry entry. Stop with an error if it does not exist. +2. Call the wrapper function. It returns one closure per repetition, each holding a sketch and data already built. +3. Call the closures in order. The timer covers only the closure. +4. After the timer stops, read memory and score the estimates. +5. Write one result record for the command. + +### Adding a sketch library + +In the `sketch-bench` crate: + +1. Add a `SketchId` entry to the registry. +2. Write one wrapper function per supported operation. +3. Bind the entry to its wrapper functions. +4. Run `approxbench sketchbench --list-impls`, which lists every registry entry, and check that the new entry is there. Then measure each operation once. + +## System level + +### Interface + +A system plugs in through an adapter. The adapter implements two traits: `EngineUnderTest` describes the system and installs an arm; `InstalledArm` is one installed arm that the harness feeds and queries. + +```rust +pub trait EngineUnderTest { + /// Id, version and build; written into every run. + fn description(&self) -> EngineDescription; + /// Where the harness reads this system's CPU time. + fn cpu_accounting(&self) -> CpuAccounting; + /// Install one arm of one workload. Not timed. + fn install(&self, workload: &WorkloadSpec, arm: &ArmSpec) + -> Result, EngineError>; +} + +pub trait InstalledArm { + /// What was installed: the plan text, the kinds of its operators, its stored outputs. + fn plan_summary(&self) -> PlanSummary; + /// Ingest one sample chunk. The harness times the call. + fn ingest(&mut self, chunk: &SampleChunk) -> Result; + /// The answers of every query at `at_ms`. The harness times the call. + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>; + /// Bytes of state held after the last chunk. + fn footprint(&self) -> Result; +} + +pub enum CpuAccounting { + CallingThread, // in-process system: the work runs on the calling thread + Processes(Vec), // external server: read the CPU of these process ids + Cgroup(CgroupSource), // external server in its own cgroup v2 group: read the group's files +} +``` + +What the harness passes in: the workload, the arm, and the samples chunk by chunk. + +```rust +pub struct WorkloadSpec { + pub name: String, + pub queries: Vec, + pub data: Vec, +} + +pub struct WorkloadQuery { + pub id: String, + pub texts: Vec, // the same query in several languages; the system picks one it supports + pub window_ms: u64, // each evaluation at t covers (t − window_ms, t] + pub evaluation_interval_ms: u64, // the same for every query of a workload; a workload that mixes them is rejected +} + +pub struct QueryText { + pub language: QueryLanguage, + pub text: String, +} + +pub enum QueryLanguage { + PromQl, + Sql, +} + +pub struct DataRecord { + pub metric: String, + pub description: TimeSeriesDescription, +} + +pub struct ArmSpec { + pub name: String, + pub raw_data_retained: bool, // whether the system keeps raw samples + pub engine_options: serde_json::Value, // read only by the adapter; an adapter that runs a given plan reads the plan file path here +} + +pub struct SampleChunk { + pub end_ms: i64, + pub samples: Vec, +} + +pub struct Sample { + pub labels: Arc, + pub ts_ms: i64, + pub value: f64, +} +``` + +What the adapter returns: answers, step reports, the footprint and a plan summary. + +```rust +/// Query id → output series labels → value: one value per (query, output series) pair. +pub struct Answers(pub BTreeMap>); + +/// What the system reports about one step. The harness does not use it for timing. +pub struct StepReport { + pub scanned_bytes: Option, + pub engine_reported_cpu_ns: Option, +} + +pub struct Footprint { + pub view_bytes: u64, // bytes of stored outputs: state kept between evaluations, such as materialized views or sketches + pub raw_retained_bytes: u64, // bytes of raw samples kept + pub peak_bytes: Option, // peak memory during the run, if the system reports it +} + +pub struct PlanSummary { + pub text: String, + pub node_kinds: Vec, // the kind of each operator in the plan, e.g. "scan", "sum" + pub stored_outputs: Vec, +} + +pub struct EngineError(pub String); +``` + +Output series labels follow PromQL: a function or an aggregation drops `__name__`, and only a bare selector keeps it. Every adapter uses this rule so answers from different systems can be matched by label set. For example, `sum_over_time(probe[10s])` with id `sum` over the series `probe{instance="instance_0"}` answers under `"sum" → {instance="instance_0"}`. + +The adapter for an external server runs in the harness process. `ingest` sends the samples to the server, for example by Prometheus Remote Write, and `evaluate` calls the server's query interface. + +### Call order + +The evaluation times are every multiple of the evaluation interval from the data start plus the longest window, through the data end. Example: windows of 30 s and 20 s, every 10 s, data from 0 for 120 s: evaluations at 30 s, 40 s, ..., 120 s. + +1. `install(workload, arm)`. Not timed. +2. For each sample chunk: time `ingest(chunk)`. +3. If the chunk's `end_ms` is an evaluation time `t`: time `evaluate(t)`. +4. After the last chunk: `footprint()`. + +Steps 1–4 are done once per repetition, each on its own install. Each timed step reports the median over the measured repetitions. The answers of the last repetition are scored, and the arm's result is written. + +### Adding a system + +1. Write an adapter: implement `EngineUnderTest` and `InstalledArm`. +2. Choose the `CpuAccounting` that matches where the system runs. +3. Add the system to the list of systems `approxbench benchmark-external` can run. +4. Pass the conformance check, `harness::conformance::check(engine, clocks)`. It installs small probe workloads and checks that: + - two installs with the same data give the same answers; + - the window leaves out a sample exactly at `t − window_ms`; + - for `CallingThread`, the work runs on the calling thread. + +## Inputs and outputs + +### Inputs + +**Workload** + +```json +{ + "name": "http-latency", + "queries": [{ + "id": "p99", + "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, latency[5m])"}], + "window_ms": 300000, + "evaluation_interval_ms": 10000 + }], + "data": [{ + "metric": "latency", + "description": { + "labels": [{"name": "instance", "cardinality": 10}], + "series_num": 10, + "start_ms": 0, + "sample_interval_ms": 1000, + "duration_ms": 3600000, + "value_distribution": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1000.0, "seed": 1}, + "counter": false, + "seed": 42 + } + }] +} +``` + +The data description: + +- `labels`: each label and how many values it takes (`instance_0` to `instance_9` here); +- `series_num`: how many distinct series, at most the product of the label cardinalities; +- `start_ms`, `sample_interval_ms`, `duration_ms`: the first sample is one interval after the start; +- `value_distribution`: what each series draws its values from, with its own seed; +- `counter`: if true, each value is the running sum of the draws, so the series never decreases; +- `seed`: fixes the label sets and, mixed with the distribution's seed, every value. + +**Arm** + +```json +{"name": "noraw", "raw_data_retained": false, "engine_options": {"plan_file": "plans/noraw/http-latency.json"}} +``` + +**Protocol**: the number of repetitions and the load limit. + +```json +{"warmup_runs": 1, "measured_runs": 5, "max_core_busy_fraction": 0.10} +``` + +**System-level command**: run every workload and arm in a run directory on one system, then join the results of every system. + +```sh +approxbench benchmark-external run --run-directory --engine [--variant ] [--core 0] [--warmup 1] [--runs 5] +approxbench benchmark-external report --run-directory --truth / +``` + +**Operator-level command**: names the registry entry, its parameters, the data, and the operations and metrics to measure. + +```sh +approxbench sketchbench \ + --variant cms-fastpath-vector2d --library lib \ + --config 'rows=5 cols=2048' \ + --dataset uniform --size 1000000 --cardinality 100000 \ + --dtype i64 \ + --operations insert,query --metrics throughput \ + --report results.jsonl +``` + +### Outputs + +At system level, one directory per run: + +``` +/runs//--/ + run.json command line, version, machine, systems, protocol + workloads/ the workloads used + data/.datagen.json the data descriptions + plans/ plan files given to systems that take one + results//__.json one result per arm + status.log one line per step: CPU core, how busy it was before and after, load average +``` + +`` names the machine. `` is chosen by whoever starts the run. + +One arm's result (excerpt): + +```json +{ + "engine": "clickhouse", "workload": "http-latency", "arm": "noraw", + "plan": {"text": "...", "node_kinds": ["scan", "quantile"], "stored_outputs": ["mv_p99"]}, + "ingest": [{"median": {"thread_cpu_ns": null, "process_cpu_ns": 812000, "wall_ns": 950000}}], + "evaluate": [{"median": {"thread_cpu_ns": null, "process_cpu_ns": 64000, "wall_ns": 88000}}], + "answers": [[300000, {"p99": {"{instance=\"instance_0\"}": 412.5}}]], + "footprint": {"view_bytes": 18432, "raw_retained_bytes": 0, "peak_bytes": null}, + "ingested_samples": 36000 +} +``` + +- `ingest` has one entry per sample chunk, `evaluate` one per evaluation time. +- `thread_cpu_ns` is the calling thread's CPU time, set only for an in-process system. `process_cpu_ns` is the CPU time of the measured processes. +- Each `answers` entry is `[evaluation time in ms, answers]`. +- `ingested_samples` is the number of samples one install ingested. + +At operator level, the `--report` file gets one JSON line per command: which entry (`sketch`, `algorithm`, `impl`), its parameters (`sketch_config`), the data (`workload`), the number of repetitions (`runs`), and the measured metrics per operation (`bench`). + +## Measurement, accuracy and errors + +### Measurement + +- **The timer**: nothing under test times itself, so every system and sketch is timed the same way and the numbers can be compared. The harness reads the clocks before and after each call. `CpuAccounting` says which clock. +- **CPU time** (ns): for an in-process system, the calling thread's CPU clock. For `Processes`, the processes' own cgroup `cpu.stat`, or their threads' `schedstat`. For `Cgroup`, the group's `cpu.stat`. +- **Wall time** (ns): read before and after each call. +- **Memory** (bytes): at operator level, the value the closure returns; at system level, `footprint`, plus the cgroup's memory readings for an external server. +- **Throughput**: units processed per second of CPU time. Items for insert, query inputs for query, shards for merge. +- **Repetitions**: the first `warmup_runs` repetitions are discarded, then `measured_runs` repetitions (an odd number) are measured and the median is reported. Accuracy is measured once, since it does not change for the same data and parameters. +- **Load check**: the harness pins each step to one CPU core (`--core`). If that core is busier than `max_core_busy_fraction` before a step, the step does not run; if it is busier after the step, the step is recorded as over the limit. Both are recorded in `status.log`. + +### Accuracy + +- The exact answer is the reference an answer is scored against. It comes from one of two sources: + - each query declares the statistic it computes in a use-case spec (crate `aqpbm-usecase`), and the exact answer is computed from the raw samples; + - one system's arm serves as the exact answer: `--truth /`. +- The error is computed per query × series × evaluation time. The default is relative error, `|answer − exact| / |exact|`. + +### Errors + +| Condition | What the harness does | +|---|---| +| `install` fails, for example because the system supports none of the query's languages | the arm is recorded as not run, with the reason; other arms continue | +| `ingest` or `evaluate` fails | the arm stops and is recorded as failed | +| the workload has no data, or mixes evaluation intervals | the arm is recorded as not run | +| the CPU core is too busy before a step | see the load check above | +| the requested registry entry does not exist | the command stops with an error | +| a wrapper function cannot prepare its closures (`BuildError`) | the entry is recorded as failed and not measured | + +## Public and internal + +| Part | Status | +|---|---| +| registry entries and wrapper functions | you add these to the `sketch-bench` crate | +| `Pass`, `QueryPass`, `StepPass` | provided by the harness | +| the system-level traits | you implement these in your own crate | +| the system-level types, the input and output formats | public, versioned | +| the conformance check | public | +| running one arm, the clocks, the run directory | public, callable as a library | +| the data generator's internals, report aggregation, visualization | internal, may change without notice | + +A crate that uses ASAPBench as a library depends on `aqpbm-core`. With `default-features = false` it leaves out the latency histogram. It may use: + +- the system-level interface and types (`harness::engine`, `harness::data`); +- the clocks (`harness::protocol`); +- running one arm (`harness::arm_run`); +- the run directory (`harness::run_directory`); +- the conformance check (`harness::conformance`). + +## Open questions + +1. Should `InstalledArm` gain four optional methods? All four serve a query optimizer, which picks a plan using a cost model (a formula that predicts what a plan costs): + - `predicted`: the cost the system's own cost model predicts; + - `price`: the measured usage, priced by the system's own cost model; + - `node_profiles`: the CPU time each operator used; + - `calibration`: the harness measures a few basic operations so the system can fit the constants of its cost model. +2. Should the declared statistic of a query move from the use-case spec into `WorkloadQuery`, so one workload file carries both the query and how to compute its exact answer? +3. How is a series scored when the exact answer is 0, or when a system returns a series the exact answer does not have, or misses one? +4. Should quantile queries be scored by rank error instead of relative error? +5. Is the arm that runs the exact query directly on a system compared as (a) the same plan on different systems, or (b) each system configured as its users normally would? +6. Should external servers take plans in a format that does not depend on any planner? If not, the planner's format belongs in the adapter. +7. Is the arm with hand-written materialized views compared as the same plan on different systems, or as each system configured as its users normally would? From 52002a6a0f2ffd8258f3a74939980be8147b90b8 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Tue, 24 Nov 2026 00:33:37 -0500 Subject: [PATCH 2/3] docs: spell out sketch and library names in the interface design count-min instead of cms, count-min-fast-path-vector-2d instead of cms-fastpath-vector2d, sketch_oxide instead of oxide, asap_sketchlib instead of lib. Co-Authored-By: Claude Opus 5.5 --- docs/interface-design.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/interface-design.md b/docs/interface-design.md index 4824de7c..c566a430 100644 --- a/docs/interface-design.md +++ b/docs/interface-design.md @@ -61,9 +61,9 @@ The registry entry: ```rust pub struct SketchId { - pub algorithm: &'static str, // algorithm family, e.g. "cms"; entries in one family take the same parameters - pub variant: &'static str, // e.g. "cms-fastpath-vector2d" - pub library: &'static str, // e.g. "oxide", "datasketches", "lib" + pub algorithm: &'static str, // algorithm family, e.g. "count-min"; entries in one family take the same parameters + pub variant: &'static str, // e.g. "count-min-fast-path-vector-2d" + pub library: &'static str, // e.g. "sketch_oxide", "datasketches", "asap_sketchlib" pub description: &'static str, pub capability: Capability, // the statistic it answers: frequency, quantile, cardinality, ... pub comparator: Option<&'static str>, // the accuracy scorer for this entry, e.g. "frequency"; `--comparator` must name it @@ -332,7 +332,7 @@ approxbench benchmark-external report --run-directory --truth / Date: Mon, 30 Nov 2026 20:19:58 +0000 Subject: [PATCH 3/3] docs: interface design follows main, interfaces only, plain wording The document now describes main as it is after #268-#283: the system registry, the one-shot and write-throughput interfaces, the full traits and types, the run directory, and which output formats carry a version. It covers interfaces only (measurement and scoring methods are out), opens with the five interfaces at a glance, and its example is the ASAPQuery-backend 8263b22b vs VictoriaMetrics run of use case 5. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Fj92nP6BDs8xKTsK4ANbnP --- docs/interface-design.md | 711 +++++++++++++++++++++++++-------------- 1 file changed, 451 insertions(+), 260 deletions(-) diff --git a/docs/interface-design.md b/docs/interface-design.md index c566a430..65d23051 100644 --- a/docs/interface-design.md +++ b/docs/interface-design.md @@ -1,208 +1,253 @@ # ASAPBench interface design -## Who reads what +This document describes the interfaces of ASAPBench: what you write to add a sketch or a system, what you give the benchmark to run it, what it writes back, and what another crate can call. How the benchmark measures time and memory, and how it scores answers, are described elsewhere. -| Reader | Implements | Calls | Read | -|---|---|---|---| -| Adds a sketch library | a registry entry and wrapper functions | — | [Scope and overview](#scope-and-overview), [Terms](#terms), [Operator level](#operator-level), [Measurement, accuracy and errors](#measurement-accuracy-and-errors) | -| Adds a system | an adapter: `EngineUnderTest` and `InstalledArm` | the conformance check | [Scope and overview](#scope-and-overview), [Terms](#terms), [System level](#system-level), [Measurement, accuracy and errors](#measurement-accuracy-and-errors) | -| Runs the benchmark | — | the command line | [Scope and overview](#scope-and-overview), [Terms](#terms), [Inputs and outputs](#inputs-and-outputs) | -| A crate that uses ASAPBench as a library (for example ASAPPlanner) | as needed | the public modules | [System level](#system-level), [Public and internal](#public-and-internal) | +ASAPBench measures at two levels: -## Scope and overview +- **Sketch level**: one sketch implementation, for example one library's Count-Min Sketch. It measures the cost of inserting, querying and merging, and how accurate the sketch's estimates are. +- **System level**: one whole system, for example ClickHouse or VictoriaMetrics. A system is run in one of three ways, depending on how the workload uses it: + - **periodic queries**: queries that run again every few seconds while new data keeps arriving. Measured: the cost of taking in the data and of answering, the memory and storage, and how accurate the answers are compared with the exact answers. + - **one-shot queries**: SQL queries over tables that are loaded once. Measured: the time to load and to answer, the CPU and memory, and how accurate the answers are compared with an exact run. + - **write throughput**: data is written and nothing is asked. Measured: how many samples per second the system accepts, and the CPU and memory it uses. With no queries, there is no accuracy to measure. -ASAPBench measures at two levels: +## Interfaces at a glance -- **Operator level**: one sketch algorithm implementation. It measures throughput, latency, memory and accuracy across insert, query and merge operations. -- **System level**: one system running a set of recurring queries over a stream of time-series data. It measures ingest cost, query cost, stored state size and accuracy. A system is an in-process executor or an external server. If the system uses sketches, they are measured as part of the system. +ASAPBench has five interfaces. Two are for extending it, two for running it, and one for calling it from code. -``` - ┌────────────────┐ - data description ──► │ data generator │── samples ──┬────────────────────────┐ - └────────────────┘ │ │ - ▼ ▼ - ┌─────────────────────────────────────┐ ┌──────────────┐ - │ under test │ │ exact answer │ - │ operator level: wrapper functions │ └──────┬───────┘ - │ system level: adapter │ │ - └──────────────────┬──────────────────┘ │ - the harness times every call │ - ▼ ▼ - answers + cost ─────────────────► scoring ──► results -``` +| Interface | Who uses it | What goes in | What comes out | Is the output format versioned? | +|---|---|---|---|---| +| **Adding a sketch** | whoever adds a sketch library | a registry entry and wrapper functions, in the crate `sketch-bench` | the sketch can be measured with `approxbench sketchbench`, which writes one JSON line per command | yes: each line has `schema_version`, now 5 | +| **Adding a system** | whoever adds a database or query engine | an adapter and an entry in the system registry, in the crate `system-bench` | the system can be measured with `approxbench benchmark-external` | not applicable; a change to the adapter traits means every adapter must change | +| **Running one system** (`approxbench benchmark-external`) | whoever measures systems | a run directory with workload files (and plans, for periodic queries), and the command line | each system's results in the run directory, and reports that put the systems side by side | no format version. The files record which ASAPBench build wrote them (`harness_version`) | +| **Running a use case** (`scripts/use_cases/run_use_case_on_systems.py`) | whoever compares two systems on an application | a use case number and an arm name | each system's run directory, plus the answers scored against the reference system and the use case's rules | the scored rows: yes, `schema_version`, now 1. The run index: no | +| **Calling ASAPBench from code** | another crate, for example ASAPPlanner | calls to the public modules of `aqpbm-core` | the same results, in memory | no | + +The use-case script is built on `approxbench`. It plans the queries, starts both systems, runs `approxbench benchmark-external run` once for each system, and then scores the answers with the use case's rules. The example in [Running the benchmark](#running-the-benchmark) uses it. -Out of scope: +Some arms come with a plan file, written by a planner such as ASAPPlanner, that says which sketches each query uses. ASAPBench does not read plan files; it only gives their path to the adapter. -- how a plan is produced; -- how a system or a sketch works inside; -- turning answers into use-case decisions. +## Who reads what + +| You want to | You write | Read | +|---|---|---| +| add a sketch library | a registry entry and one wrapper function per operation | [Terms](#terms), [Adding a sketch](#adding-a-sketch) | +| add a system | an adapter and a system registry entry | [Terms](#terms), [Adding a system](#adding-a-system) | +| run the benchmark, on one system or on a use case | input files and a command line | [Terms](#terms), [Running the benchmark](#running-the-benchmark) | +| use ASAPBench from another crate, for example ASAPPlanner | calls to the public modules | [Adding a system](#adding-a-system), [Using ASAPBench as a library](#using-asapbench-as-a-library) | ## Terms | Term | Meaning | |---|---| -| harness | the code that calls what is under test, reads the clocks and writes the results; it lives in the crate `aqpbm-core` | +| harness | the part of ASAPBench that calls the code under test, times each call and writes the results. It lives in the crate `aqpbm-core` | | `approxbench` | the command-line program | -| system | what runs the queries at system level; the code calls it an engine (`EngineUnderTest`, `engine_options`, the `engine` field of a result) | -| adapter | the code that implements `EngineUnderTest` and `InstalledArm` for one system | -| workload | a set of queries and the time-series data they run over; all its queries use the same evaluation interval | -| arm | one way to run a workload: same data and queries, different configuration | -| sample chunk | the samples in `(end_ms − interval, end_ms]`, where interval is the workload's evaluation interval; a system ingests one chunk at a time | -| repetition | one timed pass of a measurement; the first `warmup_runs` are discarded, the next `measured_runs` are kept | -| run | everything one command measures | - -## Operator level - -### Interface - -A sketch under test is a registry entry, one sketch implementation the benchmark can measure, plus one wrapper function per operation. A wrapper function prepares one operation for timing. Both live in the `sketch-bench` crate. Wrapper functions are plain functions, not a trait: libraries take different input shapes, and a shared trait would put the conversion cost inside the timed region. - -The registry entry: +| system | a database or query engine measured at system level. The code calls it an engine: `EngineUnderTest`, `--engine` | +| adapter | the code that connects one system to the harness. Adapters live in `system-bench/src/engines_external/` | +| system registry | the list of systems the command line knows: `SYSTEMS` in `system-bench/src/registry.rs` | +| sample | one value of one time series at one time, for example the latency of one request | +| workload | some queries plus the data they run over | +| arm | one way to run a workload on a system: same data and queries, different setup, for example with or without sketches. On the command line, an arm of periodic queries is chosen with `--variant` and lives in `plans//`; an arm of one-shot queries is chosen with `--configuration` | +| planner | a program that decides which sketches answer which queries, for example ASAPPlanner or the planner inside ASAPQuery-backend. Its decision is the plan | +| reference system, candidate | in a use case, the reference system's answers are taken as correct, for example VictoriaMetrics, which keeps every sample. The candidate is the system compared with it, for example ASAPQuery-backend | +| query variant | another wording of a one-shot query. For example, the `approximate` variant uses an approximate SQL function such as `approx_count_distinct` instead of `COUNT(DISTINCT ...)` | +| evaluation interval | how often the periodic queries run, for example every 10 s | +| sample chunk | the samples of one evaluation interval. The harness gives the system one chunk at a time | +| repetition | one timed pass over the whole workload. The first few repetitions are a warm-up and are thrown away | +| cost model | a formula some systems use to predict what a plan will cost before running it. Calibration measures the numbers in that formula | +| cgroup | a Linux control group: a set of processes whose CPU and memory Linux counts together. A server in its own cgroup can be measured from outside | +| cold run | a run right after the system restarts and the operating system's file cache is emptied, so nothing is cached | + +## Adding a sketch + +### What you write + +You write two things in the crate `sketch-bench`: a registry entry, and one wrapper function for each operation the sketch supports. + +The registry entry says what the sketch is and what it can do: ```rust pub struct SketchId { - pub algorithm: &'static str, // algorithm family, e.g. "count-min"; entries in one family take the same parameters - pub variant: &'static str, // e.g. "count-min-fast-path-vector-2d" - pub library: &'static str, // e.g. "sketch_oxide", "datasketches", "asap_sketchlib" + pub algorithm: &'static str, // the algorithm, e.g. "count-min-sketch"; all its implementations take the same parameters + pub variant: &'static str, // this implementation's name, e.g. "count-min-sketch-fastpath-vector2d" + pub library: &'static str, // the library it comes from, e.g. "asap_sketchlib", "sketch_oxide", "datasketches" pub description: &'static str, - pub capability: Capability, // the statistic it answers: frequency, quantile, cardinality, ... - pub comparator: Option<&'static str>, // the accuracy scorer for this entry, e.g. "frequency"; `--comparator` must name it - pub operations: OperationMask, // which of Insert, Query, Merge, Prepare it supports - pub metrics: MetricsMask, // which of Throughput, Latency, Accuracy it supports + pub capability: Capability, // what it estimates: frequency, quantile, distinct count, ... + pub comparator: Option<&'static str>, // how its answers are scored, e.g. "frequency" + pub operations: OperationMask, // which operations it supports: Insert, Query, Merge, Prepare + pub metrics: MetricsMask, // whether throughput and latency can be measured + pub row: RowBinding, // the function that links this entry to its wrapper functions + pub takes_seed: bool, // true if the sketch takes a random seed } ``` -The operations: `Insert` adds items. `Query` reads an estimate from the sketch. `Merge` folds several sketches, called shards, into one. `Prepare` is the step some sketches need between inserting and querying, such as sorting. +The four operations: + +- `Insert` adds items to the sketch. +- `Query` asks the sketch for estimates. +- `Merge` combines several sketches, each built from part of the data, into one. +- `Prepare` is a step some sketches need between inserting and querying, such as sorting. + +A wrapper function gets everything ready for one operation and returns one closure per repetition. The harness times only the call to the closure, so building the sketch and converting the data are not timed. Wrapper functions are plain functions, not a trait, because each library takes its input in a different form. -A wrapper function returns one closure per repetition. Calling the closure is the timed work. The harness provides these closure types: +The closures: ```rust -pub type Pass = Box usize>; // one repetition; returns the sketch's memory in bytes -pub type QueryPass = Box (Vec, usize)>; // one repetition; returns the estimates and the memory in bytes +pub type Pass = Box usize>; // does the work once and returns the sketch's size in bytes +pub type QueryPass = Box (Vec, usize)>; // also returns the estimates -pub struct StepPass { // one repetition for latency: each call does one unit of work - pub steps: usize, // calls in one repetition +pub struct StepPass { // for latency: each call does one small piece of the work + pub steps: usize, // how many calls make one repetition pub step: Box, - pub footprint: Box usize>, // memory in bytes, read after the last call + pub footprint: Box usize>, // the sketch's size in bytes after the last call } ``` -The wrapper function shapes. `I` is the item type, `P` the query input type, `A` the estimate type. +The wrapper functions. `I` is the type of an item, `P` the type of a query input, and `A` the type of an estimate. ```rust -// Throughput and accuracy. -// (parameters, items, repetitions) -pub type InsertBody = +// Throughput and accuracy +pub type InsertBody = // (parameters, items, repetitions) fn(&ParamSet, Rc>, usize) -> Result, BuildError>; -// (parameters, items, query inputs, repetitions) -pub type QueryBody = +pub type QueryBody = // (parameters, items, query inputs, repetitions) fn(&ParamSet, Rc>, Rc>, usize) -> Result>, BuildError>; -// (parameters, items, shards, repetitions) -pub type MergeBody = +pub type MergeBody = // (parameters, items, number of sketches to merge, repetitions) fn(&ParamSet, Rc>, usize, usize) -> Result, BuildError>; -// (parameters, items, repetitions) -pub type PrepareBody = +pub type PrepareBody = // (parameters, items, repetitions) fn(&ParamSet, Rc>, usize) -> Result, BuildError>; -// Latency: the same insert and merge, one unit of work per call. +// Latency: the same insert and merge, one small piece of the work per call pub type InsertStepBody = fn(&ParamSet, Rc>, usize) -> Result, BuildError>; pub type MergeStepBody = fn(&ParamSet, Rc>, usize, usize) -> Result, BuildError>; ``` -Preconditions: +Two rules: all the sketches of a merge are built with the same parameters, and a closure must not do any setup when it is called. -- Every shard in a merge is built with the same parameters. -- A closure has everything it needs before it is called. +### What the harness does with it -### Call order +1. It looks up the registry entry. If there is none, the command stops with an error. +2. It calls the wrapper function. If the function returns a `BuildError`, the sketch is recorded as failed and is not measured. +3. It calls the closures one by one and times each call. +4. After each call, it reads the size and scores the estimates. +5. It writes one result line for the command. -1. Find the requested registry entry. Stop with an error if it does not exist. -2. Call the wrapper function. It returns one closure per repetition, each holding a sketch and data already built. -3. Call the closures in order. The timer covers only the closure. -4. After the timer stops, read memory and score the estimates. -5. Write one result record for the command. +### Steps -### Adding a sketch library +1. Write the wrapper functions, and the function that links them to the registry entry, in `sketch-bench/src/rows/`. +2. Add a `SketchId` to `REGISTRY` in `sketch-bench/src/registry.rs`. +3. Run `approxbench sketchbench --list-impls` and check that the new sketch is listed. Then measure each operation once. -In the `sketch-bench` crate: +## Adding a system -1. Add a `SketchId` entry to the registry. -2. Write one wrapper function per supported operation. -3. Bind the entry to its wrapper functions. -4. Run `approxbench sketchbench --list-impls`, which lists every registry entry, and check that the new entry is there. Then measure each operation once. +### Which system does what -## System level +| System (`--engine`) | Periodic queries | One-shot queries | Write throughput | +|---|---|---|---| +| `fake` (a fake system for tests) | yes | — | — | +| `clickhouse` | yes | yes | — | +| `victoriametrics` | yes | — | — | +| `asapquery-backend` | yes | — | — | +| `asapquery-precompute-engine` | — | — | yes (it only takes writes) | +| `duckdb` | — | yes | — | +| `postgresql` | — | yes | — | +| `druid` | — | yes | — | +| `pilotdb` | — | yes | — | -### Interface +### Periodic queries and write throughput -A system plugs in through an adapter. The adapter implements two traits: `EngineUnderTest` describes the system and installs an arm; `InstalledArm` is one installed arm that the harness feeds and queries. +The adapter implements two traits. `EngineUnderTest` describes the system and sets up an arm. `InstalledArm` is one arm after it has been set up: the harness sends it data and asks it the queries. A method with a body is optional. ```rust pub trait EngineUnderTest { - /// Id, version and build; written into every run. + /// Name, version and build, written into every result. fn description(&self) -> EngineDescription; - /// Where the harness reads this system's CPU time. + /// Where the harness reads the system's CPU time (see CpuAccounting below). fn cpu_accounting(&self) -> CpuAccounting; - /// Install one arm of one workload. Not timed. + /// Set up one arm of one workload. Not timed. fn install(&self, workload: &WorkloadSpec, arm: &ArmSpec) -> Result, EngineError>; + /// For a system with a cost model: lets the harness measure the numbers in the model. + fn calibration(&mut self) -> Option<&mut dyn Calibratable> { None } + /// Normally the harness sets up one install per repetition and keeps them all. + /// Return true if the system can keep only one: the harness then sets one up, + /// measures it, and only then sets up the next. + fn holds_one_install_at_a_time(&self) -> bool { false } } pub trait InstalledArm { - /// What was installed: the plan text, the kinds of its operators, its stored outputs. + /// What was set up: the plan, the kind of each plan step, what the plan stores. fn plan_summary(&self) -> PlanSummary; - /// Ingest one sample chunk. The harness times the call. + /// For a system with a cost model: the cost the model predicts. + fn predicted(&self) -> Option { None } + /// Take one sample chunk. Timed. fn ingest(&mut self, chunk: &SampleChunk) -> Result; - /// The answers of every query at `at_ms`. The harness times the call. + /// Answer every query that is due at time `at_ms`. Timed. fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>; - /// Bytes of state held after the last chunk. + /// How many bytes the system holds after the last chunk. fn footprint(&self) -> Result; + /// For a system with a cost model: the CPU each plan step used since the last call. + fn node_profiles(&mut self) -> Option> { None } + /// For a system with a cost model: the measured usage, converted into the model's cost. + fn price(&self, usage: &MeasuredUsage) -> Option { None } + /// For write throughput: `count` writers that send samples at the same time. + fn sample_writers(&mut self, count: usize) -> Option>> { None } +} + +pub trait SampleWriter: Send { + fn write(&mut self, samples: &[Sample]) -> Result<(), EngineError>; } pub enum CpuAccounting { - CallingThread, // in-process system: the work runs on the calling thread - Processes(Vec), // external server: read the CPU of these process ids - Cgroup(CgroupSource), // external server in its own cgroup v2 group: read the group's files + CallingThread, // the system runs inside the harness process, on the thread that calls it + Processes(Vec), // a server: the harness reads the CPU of these process ids + Cgroup(CgroupSource), // a server in its own cgroup: the harness reads that cgroup's CPU and memory } ``` -What the harness passes in: the workload, the arm, and the samples chunk by chunk. +What the harness gives the adapter: ```rust pub struct WorkloadSpec { pub name: String, - pub queries: Vec, - pub data: Vec, + pub queries: Vec, // the periodic queries + pub data: Vec, // generated time series, one entry per metric + pub tables: Vec, // for one-shot queries, see below + pub one_shot_queries: Vec, // see below + pub start_ms: Option, // when the data starts + pub duration_ms: Option, // how long the data lasts + pub seed: Option, // the random seed for the data + pub metrics: Vec, // how each metric's series are made + pub each_query_from_own_window: bool, // see "Order of calls" below } pub struct WorkloadQuery { pub id: String, - pub texts: Vec, // the same query in several languages; the system picks one it supports - pub window_ms: u64, // each evaluation at t covers (t − window_ms, t] - pub evaluation_interval_ms: u64, // the same for every query of a workload; a workload that mixes them is rejected -} - -pub struct QueryText { - pub language: QueryLanguage, - pub text: String, + pub texts: Vec, // the same query in several languages; the system uses one it understands + pub window_ms: u64, // a query at time t looks at the data in (t − window_ms, t] + pub evaluation_interval_ms: u64, // must be the same for every query of a workload + pub truth: Option, // what the query computes, so the exact answer can be computed from the data + pub threshold: Option, // the threshold the application compares the answer with + pub unit: Option, // the unit of the answer + pub accuracy_metric: Option, // how the planner measures the answer's error, e.g. "rank" } -pub enum QueryLanguage { - PromQl, - Sql, +pub struct Truth { + pub statistic: Statistic, // Quantile(q), Entropy, Distinct, TopK { k, by }, ... + pub metric: String, + pub matchers: BTreeMap, } -pub struct DataRecord { - pub metric: String, - pub description: TimeSeriesDescription, +pub struct QueryText { + pub language: QueryLanguage, // PromQl, MetricsQl or Sql + pub text: String, + pub dialect: Option, // set when this SQL text is for one system only } pub struct ArmSpec { pub name: String, - pub raw_data_retained: bool, // whether the system keeps raw samples - pub engine_options: serde_json::Value, // read only by the adapter; an adapter that runs a given plan reads the plan file path here + pub raw_data_retained: bool, // whether the system keeps the raw samples + pub engine_options: serde_json::Value, // only the adapter reads this; for an arm with a plan, {"plan_file": } } pub struct SampleChunk { @@ -217,226 +262,372 @@ pub struct Sample { } ``` -What the adapter returns: answers, step reports, the footprint and a plan summary. +There are two ways to describe the data. A workload made of generated series uses `data`. A use-case workload uses `start_ms`, `duration_ms`, `seed` and `metrics` instead: each metric has groups of series, each group has a normal pattern, and phases are time spans when the pattern changes, for example when extra traffic is mixed in. A metric can also be read from a recorded real trace. `accuracy_metric` `"rank"` means that the error of a quantile is measured as how far the answer's position in sorted order is from the requested position, instead of how far its value is. + +What the adapter gives back: ```rust -/// Query id → output series labels → value: one value per (query, output series) pair. +/// For each query id, for each output series (identified by its labels), the value. pub struct Answers(pub BTreeMap>); -/// What the system reports about one step. The harness does not use it for timing. +/// Numbers the system itself reports about one call. The harness stores them, +/// but its own timings come from its own clocks. pub struct StepReport { pub scanned_bytes: Option, pub engine_reported_cpu_ns: Option, + pub query_wall_ns: BTreeMap, // for each query, the time the system says it took } pub struct Footprint { - pub view_bytes: u64, // bytes of stored outputs: state kept between evaluations, such as materialized views or sketches - pub raw_retained_bytes: u64, // bytes of raw samples kept - pub peak_bytes: Option, // peak memory during the run, if the system reports it + pub view_bytes: u64, // bytes the system keeps between queries, such as materialized views or sketches + pub raw_retained_bytes: u64, // bytes of raw samples it keeps + pub peak_bytes: Option, // its peak memory, if it reports one } pub struct PlanSummary { pub text: String, - pub node_kinds: Vec, // the kind of each operator in the plan, e.g. "scan", "sum" + pub node_kinds: Vec, // the kind of each plan step, e.g. "scan", "sum" pub stored_outputs: Vec, + pub substitutions: Vec, // functions the system replaced with a similar but not identical one + pub sharing_lost: Vec, // results the plan shares between queries but the system could not share } pub struct EngineError(pub String); ``` -Output series labels follow PromQL: a function or an aggregation drops `__name__`, and only a bare selector keeps it. Every adapter uses this rule so answers from different systems can be matched by label set. For example, `sum_over_time(probe[10s])` with id `sum` over the series `probe{instance="instance_0"}` answers under `"sum" → {instance="instance_0"}`. +Answers are labelled the way PromQL labels them, so answers from different systems can be matched. A query that applies a function or an aggregation removes the metric name from the labels; a query that only selects a metric keeps it. Example: the query `sum_over_time(probe[10s])`, with id `sum`, over the series `probe{instance="instance_0"}`, gives one answer for query `sum` with the labels `{instance="instance_0"}`. -The adapter for an external server runs in the harness process. `ingest` sends the samples to the server, for example by Prometheus Remote Write, and `evaluate` calls the server's query interface. +An adapter for a server runs inside the harness process. `ingest` sends the samples to the server, for example with Prometheus Remote Write. `evaluate` calls the server's query API. -### Call order +#### Order of calls: periodic queries -The evaluation times are every multiple of the evaluation interval from the data start plus the longest window, through the data end. Example: windows of 30 s and 20 s, every 10 s, data from 0 for 120 s: evaluations at 30 s, 40 s, ..., 120 s. +The queries run at every multiple of the evaluation interval. They start when the longest window is full and stop at the end of the data. Example: windows of 30 s and 20 s, every 10 s, data from 0 to 120 s: the queries run at 30 s, 40 s, ..., 120 s. With `each_query_from_own_window`, each query starts as soon as its own window is full: the 20 s query at 20 s, the 30 s query at 30 s. -1. `install(workload, arm)`. Not timed. -2. For each sample chunk: time `ingest(chunk)`. -3. If the chunk's `end_ms` is an evaluation time `t`: time `evaluate(t)`. -4. After the last chunk: `footprint()`. +For each repetition: -Steps 1–4 are done once per repetition, each on its own install. Each timed step reports the median over the measured repetitions. The answers of the last repetition are scored, and the arm's result is written. +1. The harness calls `install(workload, arm)`. This is not timed. +2. For each sample chunk, it calls `ingest(chunk)` and times it. +3. If the chunk ends at a query time `t`, it calls `evaluate(t)` and times it. +4. After the last chunk, it calls `footprint()`. -### Adding a system +The result keeps the median over the measured repetitions, and the answers of the last repetition. -1. Write an adapter: implement `EngineUnderTest` and `InstalledArm`. -2. Choose the `CpuAccounting` that matches where the system runs. -3. Add the system to the list of systems `approxbench benchmark-external` can run. -4. Pass the conformance check, `harness::conformance::check(engine, clocks)`. It installs small probe workloads and checks that: - - two installs with the same data give the same answers; - - the window leaves out a sample exactly at `t − window_ms`; - - for `CallingThread`, the work runs on the calling thread. +#### Order of calls: write throughput -## Inputs and outputs +1. The harness calls `install(workload, arm)`, then `sample_writers(n)`. A system that returns `None` cannot be measured. +2. The `n` writers write at the same time. Each sends one request and waits for the reply before sending the next. Each writes its series in timestamp order, and no writer's timestamps may get more than `--max-event-time-lead-ms` ahead of the slowest writer's. +3. They write as fast as the system accepts, or at a target rate: first a warm-up, then the measured period. +4. The result is the number of samples per second the system accepted, the CPU used by the system and by the harness, and the system's memory afterwards. -### Inputs +### One-shot queries -**Workload** +The adapter implements one trait, `OneShotQueryEngine`. The harness loads the tables once and then runs each query a few times. -```json -{ - "name": "http-latency", - "queries": [{ - "id": "p99", - "texts": [{"language": "PromQl", "text": "quantile_over_time(0.99, latency[5m])"}], - "window_ms": 300000, - "evaluation_interval_ms": 10000 - }], - "data": [{ - "metric": "latency", - "description": { - "labels": [{"name": "instance", "cardinality": 10}], - "series_num": 10, - "start_ms": 0, - "sample_interval_ms": 1000, - "duration_ms": 3600000, - "value_distribution": {"kind": "uniform", "lower_bound": 0.0, "upper_bound": 1000.0, "seed": 1}, - "counter": false, - "seed": 42 - } - }] +```rust +pub trait OneShotQueryEngine { + fn description(&self) -> EngineDescription; + /// The SQL dialect this system takes, e.g. "DuckDb". + fn dialect(&self) -> SqlDialect; + /// A short note on what the time the system reports covers, written into the result. + /// Example (DuckDB): "the duckdb shell's .timer: running the statement and printing + /// its result, without starting the shell or opening the database". + fn engine_time_covers(&self) -> Option<&'static str>; + /// The settings of this run, written into the result. + fn configuration(&self) -> serde_json::Value { serde_json::Value::Null } + /// For an approximate system such as PilotDB: the error it aims for. + fn error_target(&self) -> Option { None } + /// How many rows a table has, or None if the table does not exist. + fn table_rows(&mut self, table: &str) -> Result, EngineError>; + /// Run the load statements. A system that reads another system's database, + /// as PilotDB reads DuckDB's, loads nothing. + fn load_table(&mut self, statements: &[String]) -> Result<(), EngineError>; + fn data_size_bytes(&mut self, table: &str) -> Result, EngineError> { Ok(None) } + /// Restart the system before a cold run. + fn restart(&mut self) -> Result<(), EngineError>; + /// Run one query. Timed. + fn run_query(&mut self, sql: &str) -> Result; + fn last_query_cpu_seconds(&mut self) -> Option { None } + /// Wait until the system's background work, such as merging data after a load, is done. + fn wait_until_idle(&mut self) -> Result<(), EngineError> { Ok(()) } + /// Where the harness reads CPU and memory: the server's cgroup, or the + /// processes the adapter started. + fn cpu_accounting(&self) -> Option { None } +} + +pub struct TableSource { + pub name: String, + pub file_name: String, // the file in the data directory + pub url: Option, // where to download the file + pub rows: u64, // the number of rows, checked after loading + pub load_statements: Vec, // one list per dialect; {file} is replaced by the file's path +} + +pub struct LoadStatements { + pub dialect: SqlDialect, + pub statements: Vec, +} + +pub struct OneShotQuery { + pub id: String, + pub texts: Vec, // a system uses the text marked with its dialect if there is one, else the text with no dialect + pub group_by_column_positions: Vec, // which result columns are the group key; read from the query if left out + pub variants: BTreeMap>, // other wordings, e.g. "approximate" } + +pub struct SqlDialect(String); // "DuckDb", "ClickHouse", "PostgreSql", "Druid", or a new system's own ``` -The data description: +#### Order of calls: one-shot queries + +1. For each table, the harness calls `table_rows`. If the table does not exist, it calls `load_table` with the statements for the system's dialect and times that call. Then it calls `table_rows` again; the number must equal `rows`. +2. For each query, it calls `run_query` as many times as asked and times each call. Before a cold first run, it calls `restart` and empties the operating system's file cache. +3. For each run, it records the time it measured, the time and CPU the system reported, the CPU and peak memory it measured, and the result table. + +### When something fails + +| What fails | What the harness does | +|---|---| +| for periodic queries: `install`, `ingest` or `evaluate` returns an error; the workload has no data or mixes evaluation intervals; the arm's plan uses a substitution the arm does not allow; or the CPU core was busier than allowed before a step | that arm stops and is recorded as not run, with the error. The other arms still run | +| a one-shot table exists with a different number of rows, or its file or its load statements are missing | the run stops with an error | +| a one-shot query fails | the error is recorded and that query's remaining runs are skipped. The other queries still run | +| a one-shot query has no text for the system's dialect, or for the requested query variant | the query is recorded as skipped, with the reason | +| the named system does not exist | the command stops with an error | + +### Steps + +1. Write the adapter in `system-bench/src/engines_external/`: `EngineUnderTest` and `InstalledArm` for periodic queries or write throughput, `OneShotQueryEngine` for one-shot queries. +2. Choose the `CpuAccounting` (or `OneShotCpuAccounting`) that fits where the system runs. +3. Add the file to `engines_external/mod.rs`. Add one entry to `SYSTEMS` in `system-bench/src/registry.rs` that lists the measurements the system supports (periodic queries, one-shot queries, write throughput). For each measurement, the entry gives the command-line options it takes and a function that builds the adapter from those options. Every option needs help text; a test fails if one has none. +4. For periodic queries, pass the conformance check, `harness::conformance::check(engine, clocks)`. It runs small test workloads and checks that: + - two installs with the same data give the same answers; + - a sample exactly at `t − window_ms` is left out of the window; + - each calibration step does the work the cost model assumes; + - for `CallingThread`, all the work runs on the calling thread. + + A server adapter also has tests against a real server, one for each row of `system-bench/capabilities/README.md`. + +## Running the benchmark + +There are two ways in: + +- `approxbench benchmark-external` measures one system over a run directory and writes its results there. You prepare the run directory yourself or with a script. Then `report` or `one-shot-report` puts the systems' results side by side. +- `scripts/use_cases/run_use_case_on_systems.py` runs a whole use case on two systems. It prepares the run directories, calls `approxbench benchmark-external run` for each system, and scores the answers with the use case's rules. Its outputs are described under [Outputs of the use-case script](#outputs-of-the-use-case-script). -- `labels`: each label and how many values it takes (`instance_0` to `instance_9` here); -- `series_num`: how many distinct series, at most the product of the label cardinalities; -- `start_ms`, `sample_interval_ms`, `duration_ms`: the first sample is one interval after the start; -- `value_distribution`: what each series draws its values from, with its own seed; -- `counter`: if true, each value is the running sum of the draws, so the series never decreases; -- `seed`: fixes the label sets and, mixed with the distribution's seed, every value. +### Example: ASAPQuery-backend against VictoriaMetrics (preliminary) -**Arm** +The question: in a real application, how does a system that keeps only sketches compare with one that keeps every sample? The first is ASAPQuery-backend, at commit `8263b22b` (the commit `scripts/extbench-up-asapquery-backend.sh` builds). The second is VictoriaMetrics v1.154.1. The application is use case 5: rate limiting, which needs the clients that send the most requests. + +**The workload** is `usecase-study/workloads/uc5_top_clients.json`. Its first query: ```json -{"name": "noraw", "raw_data_retained": false, "engine_options": {"plan_file": "plans/noraw/http-latency.json"}} +{ + "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"} +} ``` -**Protocol**: the number of repetitions and the load limit. +The second query, `top10_clients_1m`, asks the same over 1 minute. The data is one metric, `requests`: one sample every 2 ms for 2 hours, 3.6 million samples in all. Each sample is one request, and its value is the id of the client that sent it. Client ids follow a Zipf distribution over 100,000 clients. During two time spans, a few clients send far more requests than usual; these are the incidents the rules below should catch. ```json -{"warmup_runs": 1, "measured_runs": 5, "max_core_busy_fraction": 0.10} +"start_ms": 1767225600000, "duration_ms": 7200000, "seed": 51, +"metrics": [{"name": "requests", "sample_interval_ms": 2, "label_from_value": "client_id", ..., + "series": [{"baseline": {"kind": "zipf", "skewness": 1.0, "population_size": 100000, "seed": 52}, + "phases": [{"start_offset_ms": 1800000, "end_offset_ms": 4200000, ...}, ...]}]}] ``` -**System-level command**: run every workload and arm in a run directory on one system, then join the results of every system. +Three rules act on the answers. Each follows a real product: + +- AWS WAF: a top-10 client with more than 2,000 requests in 5 minutes is limited for as long as it stays over. +- Google Cloud Armor: a top-10 client with more than 500 requests in 1 minute is banned for the rest of that minute and 600 s more. +- Fastly: a top-10 client with more than 20 requests per second over 1 minute is blocked for at least 2 minutes. + +**The arm** is `noraw-ignore-eps0.01`: ASAPQuery-backend keeps no raw samples; each query asks for at most 1% error, allowed to fail 1% of the time; and the planner is told to plan even when it cannot guarantee that error (`--ignore-accuracy-guarantees`). For this arm the planner chose, for both queries, a Count-Min Sketch with a list of the top clients, 28 counters wide and 5 rows deep. + +**The commands:** ```sh -approxbench benchmark-external run --run-directory --engine [--variant ] [--core 0] [--warmup 1] [--runs 5] -approxbench benchmark-external report --run-directory --truth / +scripts/extbench-up-asapquery-backend.sh build +python3 scripts/use_cases/run_use_case_on_systems.py 5 --arm noraw-ignore-eps0.01 --trials 2 \ + --backend-dir /target/release --victoriametrics ``` -**Operator-level command**: names the registry entry, its parameters, the data, and the operations and metrics to measure. +The first command builds ASAPQuery-backend. The second plans the queries with ASAPQuery-backend's planner (its `control_plane` program), starts each system as its own process, and writes a run directory for each system. The arm's `plans//variant.json` is `{"substitutions_allowed": true, "plans": false}`: ASAPQuery-backend already got its plan when it started. Then the script calls, for each system: ```sh -approxbench sketchbench \ - --variant count-min-fast-path-vector-2d --library asap_sketchlib \ - --config 'rows=5 cols=2048' \ - --dataset uniform --size 1000000 --cardinality 100000 \ - --dtype i64 \ - --operations insert,query --metrics throughput \ - --report results.jsonl +approxbench benchmark-external run --run-directory --engine victoriametrics \ + --victoriametrics-url http://127.0.0.1: --warmup 0 --runs 1 --max-core-busy 0.1 \ + --data-root --server-cgroup-directory +approxbench benchmark-external run --run-directory --engine asapquery-backend \ + --asapquery-backend-url http://127.0.0.1: --warmup 0 --runs 1 --max-core-busy 0.1 \ + --data-root --server-cgroup-directory ``` -### Outputs +Both systems get the same 3.6 million samples, each as fast as it accepts them. The script then scores ASAPQuery-backend's answers against VictoriaMetrics' answers, and runs the three rules on the answers of both. A trial is one such pass: both systems start afresh and get all the data again, with one repetition each (`--runs 1`). `--trials 2` does it twice. + +**The result** (trial 1; trial 2 gave the same answers, and costs in the same range): + +| | VictoriaMetrics | ASAPQuery-backend | +|---|---|---| +| time to write 3.6 million samples | 51.5 s (140,000 samples/s) | 67.4 s (107,000 samples/s) | +| CPU | 181 s | 51 s | +| peak memory | 741 MiB | 166 MiB | +| disk | 53 MB | 15 KB | +| query time, median / 99th percentile | 256 / 396 ms | 1.0 / 3.2 ms | +| answers | all 2,360 equal to the exact answers | the top-10 lists share 4.1 of 10 clients on average | +| rule decisions that agree with VictoriaMetrics | — | AWS WAF 86%, Cloud Armor 77%, Fastly 95% | + +ASAPQuery-backend used less CPU, memory and disk and answered about 250 times faster, but with this small sketch it often named the wrong clients. This is one arm, run twice. The other arms of use case 5 (`eps0.05`, `eps0.005`, `eps0.001`) and the other use cases have not been run on this version yet. + +### Workload file -At system level, one directory per run: +A workload is one JSON file in the format of `WorkloadSpec`. It describes its data in one of two ways: + +- like the use case above: `start_ms`, `duration_ms`, `seed` and `metrics`. Each query may add `truth`, `threshold`, `unit` and `accuracy_metric`. +- as generated series: one entry in `data` for each metric, with these fields in its `description`: + - `labels`: each label and how many values it takes. + - `series_num`: how many series, at most the product of the numbers of label values. + - `start_ms`, `sample_interval_ms`, `duration_ms`: when the data starts, how often each series has a sample, and for how long. The first sample comes one interval after the start. + - `value_distribution`: the distribution each series draws its values from, with its own seed. + - `counter`: if true, each value is added to the previous one, so the series only goes up. + - `seed`: fixes the label values and, together with the distribution's seed, every value. + +A workload for one-shot queries has `tables` and `one_shot_queries` instead of `queries` and `data`; their fields are described under [One-shot queries](#one-shot-queries). `scripts/one-shot-clickbench.sh` builds one from ClickBench. + +### Arms + +Each arm of periodic queries is a directory under `plans/` in the run directory: ``` -/runs//--/ - run.json command line, version, machine, systems, protocol - workloads/ the workloads used - data/.datagen.json the data descriptions - plans/ plan files given to systems that take one - results//__.json one result per arm - status.log one line per step: CPU core, how busy it was before and after, load average +plans//variant.json {"substitutions_allowed": false}; optionally "plans": false, "run_by_default": false +plans//.plan.json the plan for that workload; the harness gives its path to the adapter +plans//.no-plan.json why there is no plan, e.g. {"reason": "ExcludedByDeployment"} ``` -`` names the machine. `` is chosen by whoever starts the run. +`substitutions_allowed: false` means the plan may only use functions that compute exactly what the planner asked for. `"plans": false` means the arm has no plan files, as in the example above. `"run_by_default": false` means the arm runs only when `--variant` names it. -One arm's result (excerpt): +### Commands -```json -{ - "engine": "clickhouse", "workload": "http-latency", "arm": "noraw", - "plan": {"text": "...", "node_kinds": ["scan", "quantile"], "stored_outputs": ["mv_p99"]}, - "ingest": [{"median": {"thread_cpu_ns": null, "process_cpu_ns": 812000, "wall_ns": 950000}}], - "evaluate": [{"median": {"thread_cpu_ns": null, "process_cpu_ns": 64000, "wall_ns": 88000}}], - "answers": [[300000, {"p99": {"{instance=\"instance_0\"}": 412.5}}]], - "footprint": {"view_bytes": 18432, "raw_retained_bytes": 0, "peak_bytes": null}, - "ingested_samples": 36000 -} +Each command runs one system over a run directory. The report commands then put the results of all systems side by side. By default each arm runs 1 warm-up repetition and 5 measured ones. Before each timed step, the harness checks the CPU core it runs on; if that core was more than 10% busy, the step does not run and the arm is recorded as not run (`--max-core-busy` changes the limit). + +```sh +# periodic queries +approxbench benchmark-external run --run-directory --engine [--variant ] \ + [--core 0] [--warmup 1] [--runs 5] [--max-core-busy 0.10] [--data-root ] [system options] +approxbench benchmark-external report --run-directory --truth /|declared [--data-root ] + +# one-shot queries +approxbench benchmark-external one-shot-queries --run-directory --engine \ + --workload --configuration [--query ]... [--query-variant ] [--runs 3] \ + [--cold-first-run] [--data-directory ] [system options] +approxbench benchmark-external one-shot-report --run-directory [--truth /] [--baseline /]... + +# write throughput +approxbench benchmark-external write-throughput --run-directory --engine --workload [--arm write-only] \ + --writers --max-event-time-lead-ms [--samples-per-request 2000] [--target-samples-per-second ] \ + [--warmup-seconds 15] [--measure-seconds 30] [system options] + +# sketch level: one sketch, its parameters, the data, the operations and what to measure +approxbench sketchbench --variant --library --config '' \ + --dataset --size --cardinality --dtype \ + --operations --metrics \ + --report .jsonl +``` + +`--truth declared` scores against exact answers computed from each query's `truth`. `approxbench benchmark-external --engine --help` lists the system's own options, for example `--server-cgroup-directory`, `--victoriametrics-url`, `--asapquery-backend-url` and `--duckdb-program`. + +### Outputs of `approxbench` + +At system level, `approxbench` writes into the run directory: + +``` +/ + workloads/.json the workloads used + data/ the data + plans// the arms, see above + results//engine-run-