diff --git a/docs/interface-design.md b/docs/interface-design.md new file mode 100644 index 00000000..65d23051 --- /dev/null +++ b/docs/interface-design.md @@ -0,0 +1,633 @@ +# ASAPBench interface design + +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. + +ASAPBench measures at two levels: + +- **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. + +## Interfaces at a glance + +ASAPBench has five interfaces. Two are for extending it, two for running it, and one for calling it from code. + +| 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. + +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. + +## 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 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 | 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, // 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, // 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 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. + +The closures: + +```rust +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 { // 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>, // the sketch's size in bytes after the last call +} +``` + +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 +pub type InsertBody = // (parameters, items, repetitions) + fn(&ParamSet, Rc>, usize) -> Result, BuildError>; +pub type QueryBody = // (parameters, items, query inputs, repetitions) + fn(&ParamSet, Rc>, Rc>, usize) -> Result>, BuildError>; +pub type MergeBody = // (parameters, items, number of sketches to merge, repetitions) + fn(&ParamSet, Rc>, usize, usize) -> Result, BuildError>; +pub type PrepareBody = // (parameters, items, repetitions) + fn(&ParamSet, Rc>, usize) -> Result, BuildError>; + +// 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>; +``` + +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. + +### What the harness does with it + +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. + +### Steps + +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. + +## Adding a system + +### Which system does what + +| 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 | — | + +### Periodic queries and write throughput + +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 { + /// Name, version and build, written into every result. + fn description(&self) -> EngineDescription; + /// Where the harness reads the system's CPU time (see CpuAccounting below). + fn cpu_accounting(&self) -> CpuAccounting; + /// 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 set up: the plan, the kind of each plan step, what the plan stores. + fn plan_summary(&self) -> PlanSummary; + /// 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; + /// Answer every query that is due at time `at_ms`. Timed. + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>; + /// 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, // 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 gives the adapter: + +```rust +pub struct WorkloadSpec { + pub name: String, + 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 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 struct Truth { + pub statistic: Statistic, // Quantile(q), Entropy, Distinct, TopK { k, by }, ... + pub metric: String, + pub matchers: BTreeMap, +} + +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 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 { + pub end_ms: i64, + pub samples: Vec, +} + +pub struct Sample { + pub labels: Arc, + pub ts_ms: i64, + pub value: f64, +} +``` + +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 +/// For each query id, for each output series (identified by its labels), the value. +pub struct Answers(pub BTreeMap>); + +/// 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 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 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); +``` + +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"}`. + +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. + +#### Order of calls: periodic queries + +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. + +For each repetition: + +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()`. + +The result keeps the median over the measured repetitions, and the answers of the last repetition. + +#### Order of calls: write throughput + +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. + +### One-shot queries + +The adapter implements one trait, `OneShotQueryEngine`. The harness loads the tables once and then runs each query a few times. + +```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 +``` + +#### 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). + +### Example: ASAPQuery-backend against VictoriaMetrics (preliminary) + +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 +{ + "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"} +} +``` + +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 +"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, ...}, ...]}]}] +``` + +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 +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 +``` + +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 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 +``` + +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 + +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: + +``` +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"} +``` + +`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. + +### Commands + +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-