diff --git a/Cargo.lock b/Cargo.lock index 6bd5f07c..843aae1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -158,19 +158,6 @@ dependencies = [ "thiserror 2.0.18", ] -[[package]] -name = "aqpbm-usecase" -version = "0.1.0" -dependencies = [ - "anyhow", - "aqpbm-core", - "aqpbm-datagen", - "rand 0.9.4", - "rand_xoshiro", - "serde", - "serde_json", -] - [[package]] name = "ar_archive_writer" version = "0.5.2" @@ -4181,7 +4168,6 @@ dependencies = [ "anyhow", "aqpbm-core", "aqpbm-datagen", - "aqpbm-usecase", "asap-executor", "asap-frontend-promql", "asap-planner", @@ -4197,6 +4183,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "ureq", + "usecase-study", ] [[package]] @@ -4522,6 +4509,19 @@ dependencies = [ "serde", ] +[[package]] +name = "usecase-study" +version = "0.1.0" +dependencies = [ + "anyhow", + "aqpbm-core", + "aqpbm-datagen", + "rand 0.9.4", + "rand_xoshiro", + "serde", + "serde_json", +] + [[package]] name = "utf8_iter" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 89e9732f..af850117 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,12 +6,10 @@ members = [ "aqpbm-core", "sketch-bench", "aqpbm-cli", - "aqpbm-usecase", + "usecase-study", "system-bench", ] -exclude = ["sketch-runtime"] - [workspace.package] version = "0.1.0" edition = "2021" @@ -63,9 +61,8 @@ asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = aqpbm-datagen = { path = "aqpbm-datagen" } aqpbm-core = { path = "aqpbm-core", default-features = false } sketch-bench = { path = "sketch-bench" } -aqpbm-usecase = { path = "aqpbm-usecase" } +usecase-study = { path = "usecase-study" } system-bench = { path = "system-bench" } -# sketch-runtime = { path = "sketch-runtime" } # parked; [profile.release] opt-level = 3 diff --git a/README.md b/README.md index a87ad5bb..c88eb634 100644 --- a/README.md +++ b/README.md @@ -1,500 +1,129 @@ -# Approximate Benchmark +# ASAPBench A benchmark to tell how approximation is helping. -Current status: a benchmark over sketch instance. +Current status: a benchmark over sketch instance and over (selected) data processing system. ## Quickstart -### Compile - -At root directory of this project, just run: +The benchmark has two levels: -```sh -% cargo build --release -``` +- **Sketch benchmark**: one sketch instance on data the benchmark generates. It compares sketches, libraries and configurations on throughput, latency, memory and accuracy. +- **System benchmark**: the same queries on real data processing systems, exact and approximate. It compares answers, time, CPU and memory. -### Example: HyperLogLog insertion throughput +### Compile ```sh -./target/release/approxbench sketchbench \ - --variant hll --library lib --config 'lg_k=14' \ - --dataset zipf --size 1000000 --zipf-s 1.1 --cardinality 100000 --dtype i64 \ - --runs 10 --warmup-runs 3 \ - --operations insert --metrics throughput --pretty-print -approxbench: hll/lib config={"lg_k":14} runs=10 warmup=3 -{ - "schema_version": 4, - "sketch": "hll", - "algorithm": "hll", - "impl": "lib", - "language": "rust", - "sketch_config": { - "algorithm": "hll", - "params": { - "lg_k": 14 - } - }, - "workload": { - "column_num": 1, - "column_label": [ - "key" - ], - "column_spec": [ - { - "distribution": { - "kind": "zipf", - "skewness": 1.1, - "population_size": 100000, - "seed": 42 - }, - "special_rule": 0, - "data_type": "i64" - } - ], - "row_num": 1000000 - }, - "mode": "bench", - "runs": 10, - "bench": { - "metric": "throughput", - "operation": "insert", - "throughput_items_per_sec": { - "mean": 649590618.9830792, - "stddev": 14589920.644625586, - "n": 10, - "samples": [ - 653007917.7210023, - 654718062.0345364, - 639829242.3717958, - 655039711.7825269, - 661066114.5442479, - 657912916.0147846, - 653097051.5280511, - 657714298.1168982, - 652227225.5297389, - 611293650.1872087 - ] - }, - "wall_time_ms": { - "mean": 1.5401624, - "stddev": 0.03618442327300518, - "n": 10, - "samples": [ - 1.531375, - 1.527375, - 1.562917, - 1.526625, - 1.512708, - 1.519958, - 1.531166, - 1.520417, - 1.533208, - 1.635875 - ] - }, - "memory_bytes": 16400 - }, - "source": "cli", - "timestamp": "2026-08-25T23:19:34.546016Z" -} +cargo build --release ``` -#### CLI Flag Explanation - -In the example above, there are many CLI flags being used. -Here is a explanation about what they are. - -**`--variant`:** `variant` defines which instance to test against. -In this case, it is a regular HyperLogLog. - -**`--library`:** `library` defines which library the variant is from. -`lib` stands for `asap_sketchlib`. - -**`--config`:** `config` takes user configuration for each sketch instance. -Different variant takes configuration differently. -In this case, `hll` takes a `lg_k` which describes the size of register list. - -**`--dataset`:** A benchmark needs to take different data as input. -`dataset` is the command line argument that takes description of input data. -`zipf` means the input data is under zipf distribution. - -**`--size`:** `size` means how large the dataset is. - -**`--zipf-s`:** Some distribution requires parameter, like `zipf-s`. -`zipf-s` means skewness, a parameter for zipf distribution. -`--dataset pareto` instead takes `--pareto-alpha` (shape) and `--pareto-scale` -(minimum value, default 1.0); it is unbounded, so it needs `--dtype f64` (or -`i64`, which floors each draw) and ignores `--cardinality`. - -**`--cardinality`:** Another parameter required by zipf distribution. -`cardinality` means the size of key-space of this synthesized zipf dataset. - -**`--dtype`:** `dtype` means what data the generated will be. -Possible `dtype` are `i64`, `u64`, `f64` and `string`. -Specially, some `dtype` may not be supported by specific sketch (i.e., quantile related sketch will reject `string` data). -Those command line argument will be rejected. - -**`--runs`:** To get accurate benchmark result, repeating benchmarks will be necessary in many cases. -`runs` is how to specify the number to repeat the benchmark. +The binary is `target/release/approxbench`. -**`--warmup-runs`:** Some benchmark result, like throughput, will be different at a cold start or at middle. -To minimize the difference caused by under-utilized hardware, `warmup-runs` will be helpful and even necessary. +### Sketch benchmark: HyperLogLog -**`--operations`:** There are four operations defined: `insert`, `query`, `merge` and `prepare`. -User can specify which operation they are interested in for benchmark. +Compares: how fast a HyperLogLog from `asap_sketchlib` takes 1M Zipf keys, and how far its distinct count is from the exact count. -**`--metrics`:** To specify which metric to test, user can specify things like `throughput` or `accuracy`. -Not all combinations of `metrics` and `operations` are meaningful. -For exmample, `accuracy` of `insert` is meaningless, thus will be rejected. - -**`--pretty-print`:** just a simple command to print the `json` in multiple lines for readability. - -#### Output Explanaition +```sh +./target/release/approxbench sketchbench \ + --variant hll --library lib --config 'lg_k=14' \ + --dataset zipf --size 1000000 --zipf-s 1.1 --cardinality 100000 --dtype i64 \ + --runs 10 --warmup-runs 3 \ + --operations insert --metrics throughput,memory --flat --pretty-print -```json -"sketch": "hll", -"algorithm": "hll", -"impl": "lib", -"language": "rust", -"sketch_config": { - "algorithm": "hll", - "params": { - "lg_k": 14 - } -} +./target/release/approxbench sketchbench \ + --variant hll --library lib --config 'lg_k=14' \ + --dataset zipf --size 1000000 --zipf-s 1.1 --cardinality 100000 --dtype i64 \ + --operations query --metrics accuracy --flat --pretty-print ``` -Above part describes the sketch instance. -It is read as "a regular hll variant of hll algorithm from asap_sketchlib, with 2^14 registers". - -```json -"workload": { - "column_num": 1, - "column_label": [ - "key" - ], - "column_spec": [ - { - "distribution": { - "kind": "zipf", - "skewness": 1.1, - "population_size": 100000, - "seed": 42 - }, - "special_rule": 0, - "data_type": "i64" - } - ], - "row_num": 1000000 -}, -``` +What to expect: one JSON record per command. The first has `insert_throughput_items_per_sec` (about 3×10^8 items/s on our machine) and `memory_bytes` (16400). The second has `query_accuracy` with `estimate`, `truth` and `relative_error` (about 0.006). -Above is the description of synthetic data for input. -This is following the configuration specified by user. - -```json -"mode": "bench", -"runs": 10, -"bench": { - "metric": "throughput", - "operation": "insert", - "throughput_items_per_sec": { - "mean": 649590618.9830792, - "stddev": 14589920.644625586, - "n": 10, - "samples": [ - 653007917.7210023, - 654718062.0345364, - 639829242.3717958, - 655039711.7825269, - 661066114.5442479, - 657912916.0147846, - 653097051.5280511, - 657714298.1168982, - 652227225.5297389, - 611293650.1872087 - ] - }, - "wall_time_ms": { - "mean": 1.5401624, - "stddev": 0.03618442327300518, - "n": 10, - "samples": [ - 1.531375, - 1.527375, - 1.562917, - 1.526625, - 1.512708, - 1.519958, - 1.531166, - 1.520417, - 1.533208, - 1.635875 - ] - }, - "memory_bytes": 16400 -}, -``` +| Flag | Meaning | +|---|---| +| `--variant`, `--library` | which sketch, from which library (`lib` = `asap_sketchlib`); `--list-impls` lists every pair | +| `--config` | the sketch's parameters; `hll` takes `lg_k`, log2 of the register count | +| `--dataset`, `--size`, `--zipf-s`, `--cardinality` | the generated data: distribution, row count, skew, key space | +| `--dtype` | item type: `i64`, `u64`, `f64` or `string` | +| `--runs`, `--warmup-runs` | measured runs, and runs discarded before them | +| `--operations` × `--metrics` | crossed: every operation is measured on every metric; a pair that means nothing (accuracy of insert) is refused | +| `--flat`, `--pretty-print` | one flat JSON record, printed on several lines | -Above is the actual throughput data. -It describes the `metric` being tested as well as `operation` being tested. -`n` means how many runs are performed. -In this case, 10 runs are performed. -Thus there can be a `mean` and `stddev` of all those 10 runs data. -Raw data are recorded under `samples`. -`wall_time_ms` is the time of each run. -`memory_bytes` is the memory of the `hll` being used in this experiment. +### Sketch benchmark: Hydra over UnivMon -### Example: Hydra merge throughput +Compares: the cost of Hydra with UnivMon cells, which keeps one UnivMon for every subset of a record's labels, on insert and on merging 8 shards. ```sh ./target/release/approxbench sketchbench \ - --variant hydra-cms --library lib \ - --spec configs/datagen/hydra_columns.yaml --dtype i64\ - --config "rows=3 cols=1024 cell_rows=3 cell_cols=1024" \ - --operations insert,merge --metrics throughput,cpu,memory \ + --variant hydra-univmon-cardinality --library lib \ + --spec configs/datagen/hydra_univmon_columns.yaml --dtype i64 \ + --config "rows=2 cols=8 cell_heap_size=1000 cell_sketch_row=5 cell_sketch_col=2048 cell_layer_size=8" \ + --operations insert,merge --metrics throughput \ --merge-shards 8 --runs 5 --warmup-runs 2 --flat --pretty-print -approxbench: hydra-cms/lib config={"cell_cols":1024,"cell_rows":3,"cols":1024,"rows":3} runs=5 warmup=2 -{ - "schema_version": 4, - "sketch": "hydra-cms", - "impl": "lib", - "language": "rust", - "mode": "bench", - "runs": 5, - "source": "cli", - "sketch_config": { - "algorithm": "hydra-cms", - "params": { - "cell_cols": 1024, - "cell_rows": 3, - "cols": 1024, - "rows": 3 - } - }, - "workload": { - "column_num": 3, - "column_label": [ - "key1", - "key2", - "value" - ], - "column_spec": [ - { - "distribution": { - "kind": "uniform", - "lower_bound": 0.0, - "upper_bound": 200.0, - "seed": 1 - }, - "special_rule": 0, - "data_type": "string" - }, - { - "distribution": { - "kind": "zipf", - "skewness": 1.1, - "population_size": 50, - "seed": 2 - }, - "special_rule": 0, - "data_type": "string" - }, - { - "distribution": { - "kind": "zipf", - "skewness": 1.2, - "population_size": 1000, - "seed": 3 - }, - "special_rule": 0, - "data_type": "i64" - } - ], - "row_num": 200000 - }, - "memory_bytes": 38437088, - "heap_bytes_net": null, - "heap_bytes_peak": null, - "insert_timestamp": "2026-08-25T23:19:46.170228Z", - "insert_throughput_items_per_sec": { - "mean": 3362367.724670238, - "stddev": 89256.64220060871, - "n": 5, - "samples": [ - 3465463.7857041755, - 3369347.9567077872, - 3376888.15535374, - 3381360.372674605, - 3218778.3529108823 - ] - }, - "insert_latency_ns": null, - "insert_cpu_time_ms": { - "user_ms": { - "mean": 56.474399999999996, - "stddev": 1.2323211026351892, - "n": 5, - "samples": [ - 55.688, - 56.549, - 55.61, - 55.947, - 58.578 - ] - }, - "sys_ms": { - "mean": 2.9716, - "stddev": 0.5908500655834776, - "n": 5, - "samples": [ - 2.027, - 2.811, - 3.263, - 3.202, - 3.555 - ] - } - }, - "insert_wall_time_ms": { - "mean": 59.5160582, - "stddev": 1.6092466137157788, - "n": 5, - "samples": [ - 57.712333, - 59.358666, - 59.226125, - 59.147792, - 62.135375 - ] - }, - "insert_rss_peak_kb": null, - "insert_heap_allocated_kb": 2270156, - "query_timestamp": null, - "query_throughput_items_per_sec": null, - "query_latency_ns": null, - "query_accuracy": null, - "query_cpu_time_ms": null, - "query_wall_time_ms": null, - "query_rss_peak_kb": null, - "query_heap_allocated_kb": null, - "merge_timestamp": "2026-08-25T23:19:46.170231Z", - "merge_folds_per_sec": { - "mean": 244.1933171842133, - "stddev": 129.27731177919472, - "n": 5, - "samples": [ - 81.74828374441567, - 198.36724487506888, - 211.26866622801256, - 300.797655222118, - 428.78473585145133 - ] - }, - "merge_shards": 8, - "merge_split": "contiguous", - "merge_supported": true, - "merge_cpu_time_ms": { - "user_ms": { - "mean": 13.839599999999999, - "stddev": 0.9072333216984481, - "n": 5, - "samples": [ - 14.453, - 13.201, - 13.126, - 15.138, - 13.28 - ] - }, - "sys_ms": { - "mean": 20.4894, - "stddev": 21.064262491243316, - "n": 5, - "samples": [ - 56.377, - 18.185, - 17.27, - 7.57, - 3.045 - ] - } - }, - "merge_wall_time_ms": { - "mean": 38.7293252, - "stddev": 27.311176532236207, - "n": 5, - "samples": [ - 85.628709, - 35.288084, - 33.133167, - 23.271458, - 16.325208 - ] - }, - "merge_rss_peak_kb": null, - "merge_heap_allocated_kb": 1201747, - "prepare_timestamp": null, - "prepare_cpu_time_ms": null, - "prepare_wall_time_ms": null, - "prepare_rss_peak_kb": null, - "prepare_heap_allocated_kb": null -} ``` -#### CLI Flag Explanation (Alternative) +What to expect: `insert_throughput_items_per_sec` (about 2.3×10^5 records/s), `merge_wall_time_ms` and `merge_folds_per_sec` for folding 8 shards into one. Use `--operations query --metrics accuracy` for the per-group error, and `--library polars` for the exact answer to the same question. + +| Flag | Meaning | +|---|---| +| `--spec` | a YAML table description instead of `--dataset`: label columns, then the value column | +| `--config` | `rows`, `cols`: the Hydra grid; `cell_*`: each UnivMon cell | +| `--merge-shards`, `--merge-split` | how many shards merge folds, and how the stream is cut (`contiguous` or `interleaved`) | +| `--group-columns` | which label columns a group is taken over; default `0` | -**`--spec`**: Alternatively, the input data configuration can be provided with a `yaml` file. -`--spec configs/datagen/hydra_columns.yaml` is how user can define the synthetic table for insertion. -The file can be found [under configs directory](./configs/datagen/hydra_columns.yaml). +### System benchmark: ClickBench on DuckDB, ClickHouse, TimescaleDB, Druid and PilotDB -**`--merge-shards`**: how many shards `merge` folds: the stream is split that -many ways, one sketch is fed per shard, and the sketches are folded into one. +Compares: the 43 queries of [ClickBench](https://github.com/ClickHouse/ClickBench) (each engine's `queries.sql`, one query per line), exact on DuckDB and ClickHouse, and 7 of them approximate through PilotDB's sampling over DuckDB, against DuckDB's exact answers. With `POSTGRESQL_CONNECTION` and `DRUID_URL` set, the same run adds TimescaleDB (exact, and its `COUNT(DISTINCT)` variant) and Druid (exact, and its approximate defaults). -**`--merge-split`**: how the stream is split into those shards. `contiguous` -(the default) cuts it into consecutive stretches; `interleaved` deals it -round-robin by record, so each shard is a sample of the whole stream. The -round-robin runs over the contiguous split's shard sizes (`ceil(N/k)` each, -the last one short), skipping a shard once it is full. So when `k` divides -`N`, shard 0 gets records `0, k, 2k, ...`; with a short last shard the -pattern shifts once that shard fills (N = 10, k = 4: shard 0 gets `0, 4, 7`). -The record's `merge_split` says which split ran. CMS, CountSketch and HLL cells (and their Hydra grids) merge -exactly, so they answer identically under both; KLL and UnivMon merges are -lossy and can differ. +```sh +APPROXBENCH=$PWD/target/release/approxbench \ +ENGINE_CPUS=0-15 THREADS=16 PILOTDB_PYTHON=~/pilotdb/venv/bin/python \ + scripts/one-shot-clickbench.sh ~/ClickBench /data/clickbench runs/clickbench +``` -**`--flat`**: flatten record such that output data of multiple experiments is flatten into one json file. +What to expect: `runs/clickbench/one-shot-summary.md` (and `.csv`), one row per configuration and query, with its accuracy against `duckdb/exact` and its speedup over each exact run. On a 64-core machine with the data in memory, this takes about 15 minutes. -**`--group-columns`** (Hydra rows only): which label columns the subpopulation is taken over, as comma-separated indices into the columns before the value column, e.g. `1` or `0,1`; default `0`. -Any non-empty subset works, since the grid stores every subset of a record's labels; it picks the one the `hydra-*` row (`lib` and `polars`) asks and scores. -With `--metrics accuracy`, the record also summarises each scored group's error in the row's own metric (relative error; mean rank error for `hydra-kll`; mean absolute CDF error for `hydra-kll-cdf`): `err_mean`, `err_p50`, `err_p90`, `err_max`, `groups_scored`, plus `schema_width` (`d`), `records` (`N`) and `fanned_mass` (`N·(2^d − 1)`). +Before the run: -Two Hydra rows ask a second statistic of an existing cell: `hydra-kll-cdf` asks the KLL grid `Cdf(x)`, the share of a group at or below `x`, at each group's own values at `phi` = 0.01..0.99; `hydra-univmon-sum` inserts each value counted by itself (i64 or u64, within an `i32` count), so the UnivMon grid's L1 is the group's sum. -Both have a `polars` exact baseline. +- **Get the data**: clone [ClickBench](https://github.com/ClickHouse/ClickBench), and download [`hits.parquet`](https://datasets.clickhouse.com/hits_compatible/athena/hits.parquet) (about 14 GB) into the data directory. +- **Install DuckDB and PilotDB**: `scripts/install-duckdb.sh ` puts `duckdb` in ``; put it on `PATH` or set `DUCKDB` to it. `scripts/install-pilotdb.sh ` prints the `PILOTDB_PYTHON` to use. PilotDB also needs `libodbc.so.2` (Ubuntu: `apt install libodbc2`). +- **Start ClickHouse**: a ClickHouse server whose `user_files_path` contains the data directory, since it loads `hits.parquet` with `file()`. Set `CLICKHOUSE_URL` if it does not listen on `http://127.0.0.1:8123`. (`scripts/extbench-up.sh clickhouse up` starts one in Docker, but does not mount the data directory, so it cannot read `hits.parquet`.) +- **Druid and TimescaleDB, if measured**: `scripts/extbench-up-druid.sh up ...` or `scripts/extbench-up-timescaledb.sh up ...`, with `DATA_DIRECTORY` set to the data directory so the server can read `hits.parquet`. +- **Point to `approxbench`**: put it on `PATH`, or set `APPROXBENCH` to it, as the command above does. +- **Skip an engine**: set its variable empty, such as `CLICKHOUSE_URL=` or `PILOTDB_PYTHON=`. Druid and TimescaleDB run only when `DRUID_URL` or `POSTGRESQL_CONNECTION` is set. +- **All options**: `scripts/one-shot-workload.sh --help`. That script also runs any other workload file the same way. -**`--per-group-out PATH`** (Hydra rows only): write those per-group errors as a CSV, `group_key,n_q,error`, one row per group (`n_q` is its record count, `group_key` its tagged labels such as `label0:a;label1:x`, with `\`, `:` and `;` in a label escaped by `\`). -Every group is listed, so the `n_q` sum to the stream's records; a group that cannot be scored (its true statistic is zero, e.g. zero entropy) has an empty `error` and is left out of the `err_*` summary. -It takes exactly one accuracy measurement (query or merge). +### System benchmark: a use case on VictoriaMetrics and ASAPQuery-backend -#### General Explanation +The use-case study has five use cases. In each one, an application makes decisions from query answers. The five are: 1 DDoS detection, 2 resource scaling, 3 video experience, 4 canary release, 5 rate limiting ([pages](./docs/phase2-use-cases/)). This example runs use case 5, rate limiting, on VictoriaMetrics and ASAPQuery-backend, and compares their answers and the decisions taken from them. To run another use case, change `5` to its number. + +```sh +python3 scripts/use_cases/run_use_case_on_systems.py 5 \ + --victoriametrics ~/victoriametrics/victoria-metrics-prod \ + --backend-dir ~/asapquery-backend/target/release +``` -Most of the input and output is shared between this hydra example and the previous hll example. +What to expect: one directory per arm under `target/grafana-data/phase3/runs/` (use case 5 has 4 arms, one per error target), which the phase 3 Grafana dashboards read (`tools/grafana/run.sh --phase 3`). It also prints, per arm, how many queries the backend supports and how many failed. Use case 5 takes about 10 minutes. -Thus, here is the read of the hydra experiment: +Before the run: -This example is testing Hydra-over-Count-Min insert throughput and merge cost. -Hydra instance comes from `asap_sketchlib`, with configuration `rows=3 cols=1024` (the outer sketch) and `cell_rows=3 cell_cols=1024` (the inner Count-Min sketch), which takes about 38.4 MB. -Input data is a 200k-row, 3-column table: two label columns (uniform, then zipf) and an i64 value column (zipf) -Warmup the benchmark with 2 runs, and benchmark is run for 5 times. -`merge` folds 8 shards into one. -Data is in field `insert_throughput_items_per_sec` and `merge_time_ms` / `merge_folds_per_sec` (merge/sec). +- **Build planeval**: the script uses `planeval` to compute the exact answers and score both systems. `cargo build --release -p system-bench --features planeval`. +- **Download VictoriaMetrics v1.154.1**: + `mkdir -p ~/victoriametrics && curl -L https://github.com/VictoriaMetrics/VictoriaMetrics/releases/download/v1.154.1/victoria-metrics-linux-amd64-v1.154.1.tar.gz | tar xz -C ~/victoriametrics` +- **Build ASAPQuery-backend**: `scripts/extbench-up-asapquery-backend.sh build ~/asapquery-backend` clones it at the pinned commit and builds it. +- **No servers to start**: the script starts and stops both systems itself. +- **All options**: `python3 scripts/use_cases/run_use_case_on_systems.py --help`. ## How to use -A detailed roadmap (under construction) for sketch instance benchmark can be found at [workflow](./docs/sketch-bench-workflow.md). +The Quickstart above runs one example of each level. For more: + +- Sketch benchmark, step by step: [workflow](./docs/sketch-bench-workflow.md). +- System benchmark: [system-bench](./docs/system-bench.md). +- Use-case study: [usecase-study](./usecase-study/README.md). ## Want to add more? -Check this (under construction) [developer_guide](./docs/developer_guide.md) about how to add a sketch instance to benchmark and how to adjust ground-truth calculation to meet demands. +Check this [developer_guide](./docs/developer_guide.md) about how to add a sketch instance, ground truth, data generation, a system or a use case. +Terms used across the repository are in [terminology](./docs/terminology.md). ## Reference @@ -511,15 +140,24 @@ some concepts can go to one location separate by crates may not be necessary at this moments --> -[Core crate](./docs/aqpbm-core.md) +Shared by both levels: + +- [aqpbm-core](./docs/aqpbm-core.md): metrics, ground truth, result records and the harness. +- [aqpbm-datagen](./docs/aqpbm-datagen.md): data generation. +- [aqpbm-cli](./docs/aqpbm-cli.md): the `approxbench` command. + +Operator level: -[CLI](./docs/aqpbm-cli.md) +- [sketch-bench](./docs/sketch-bench.md): sketch wrappers, rows and the registry. -[Data Generation](./docs/aqpbm-datagen.md) +System level: -[Sketch benchmark wrapper](./docs/sketch-bench.md) +- [system-bench](./docs/system-bench.md): adapters for external systems and the registry of systems. +- [planeval](./docs/planeval.md): part of `system-bench`; runs ASAPPlanner's plans in process. +- [Capability files](./system-bench/capabilities/README.md): part of `system-bench`; what ClickHouse and VictoriaMetrics can run. +- [Harness](./docs/aqpbm-core-harness.md): part of `aqpbm-core`; how every system-level measurement is taken. -[Measurement harness (`aqpbm-core` harness module)](./docs/aqpbm-core-harness.md) +Use-case study: -[End-to-end planning flow: traces to an rqe-optimizer plan](https://github.com/ProjectASAP/ASAPQuery/blob/main/rqe-optimizer/docs/e2e_planning_flow.md) -(rqe-optimizer, its evaluation runner and its results are in ProjectASAP/ASAPQuery) +- [usecase-study](./usecase-study/README.md): the five use cases' workloads and the scoring of answers. +- [Use case pages](./docs/phase2-use-cases/): each use case's queries, rules and results. diff --git a/aqpbm-cli/src/benchmark_external_cmd.rs b/aqpbm-cli/src/benchmark_external_cmd.rs index ac0d1c01..c1e82d7b 100644 --- a/aqpbm-cli/src/benchmark_external_cmd.rs +++ b/aqpbm-cli/src/benchmark_external_cmd.rs @@ -41,7 +41,7 @@ pub struct BenchmarkExternalArgs { pub enum BenchmarkExternalCmd { /// Run every (workload, variant) cell of the run directory on one engine. Run(Box), - /// Join every engine run's cells into summary.csv, summary.md and accuracy.csv. + /// Join every engine run's cells into summary.csv, summary.md, accuracy.csv and scores.csv. Report(ReportArgs), #[command( about = "Load one engine through concurrent sample writers and append its acknowledged samples per second, CPU and memory to results//write-throughput.jsonl" diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index fb88c46b..b64f4cc4 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -1,7 +1,5 @@ //! CLI surface: the clap argument structs; the logic consuming them is in -//! `sketchbench.rs` and the subcommand modules. Option help and grouping track -//! `docs/aqpbm-cli-reference.md`, which `scripts/sketch_runs/dump_cli_reference.sh` -//! diffs the built binary against. +//! `sketchbench.rs` and the subcommand modules. use aqpbm_core::{MergeSplit, TrialMode}; use clap::builder::TypedValueParser; @@ -13,8 +11,7 @@ use crate::flatten_cmd; #[derive(Parser, Debug)] // `max_term_width` is pinned so `--help` renders identically under any -// terminal. `docs/aqpbm-cli-reference.md` is a checked-in expectation, and a -// reference that reflowed with the operator's window could never be diffed. +// terminal. #[command( name = "approxbench", version, diff --git a/configs/workloads/README.md b/configs/workloads/README.md index 73f82eb2..40b06fb8 100644 --- a/configs/workloads/README.md +++ b/configs/workloads/README.md @@ -2,15 +2,16 @@ These specs select one bounded workload from the external trace trees used by the metrics-observability benchmark. They contain logical paths only; pass the -root of the data tree with `--data-root`. +root of the data tree with `--data-root` (default: `$ASAP_DATASETS`, else +`datasets` in the current directory). For example: ```sh approxbench sketchbench \ --workload-spec configs/workloads/google/task-usage-cpu.yaml \ - --data-root ../../benchmarks/metrics_observability/data \ - --variant cms --library oxide --dtype f64 \ + --data-root \ + --variant cms --library oxide --config 'rows=5 cols=2048' --dtype f64 \ --metrics throughput --operations insert ``` @@ -22,14 +23,16 @@ rows, missing selected fields, NaN, and infinities fail the invocation. For complete one-minute tumbling windows, use the standard-library sweep driver. It invokes one benchmark process per window and appends JSONL records: -\`\`\`sh -python3 scripts/run_external_sweep.py \ +```sh +python3 scripts/dataset_tools/run_external_sweep.py \ --workload-spec configs/workloads/google/task-usage-cpu.yaml \ - --data-root ../../benchmarks/metrics_observability/data \ + --data-root \ --start 1970-01-16T04:52:15Z --end 1970-01-16T05:52:15Z \ -- --variant hll --library oxide --config lg_k=12 --dtype f64 \ --metrics throughput --operations insert -\`\`\` +``` + +The sweep runs `approxbench` from `PATH`; `--binary` names another one. Keyed external workloads are intentionally separate from this first slice and are tracked in issue #122. @@ -47,9 +50,11 @@ end_timestamp_column: end_ms timestamp_unit: milliseconds group_columns: [service] value_column: key -window: {start: "0", end: "60000"} +window: {start: "1970-01-01T00:00:00Z", end: "1970-01-01T00:01:00Z"} min_records: 10000 ``` +A window bound is an RFC 3339 time or a bare integer, and a bare integer is read +as Unix nanoseconds whatever `timestamp_unit` says. `dataset` remains a logical path resolved below `--data-root`; it and the selected window are recorded in the report's workload descriptor. diff --git a/docs/approx-bench-use-cases.md b/docs/approx-bench-use-cases.md index 14cf1f95..80d9cbb0 100644 --- a/docs/approx-bench-use-cases.md +++ b/docs/approx-bench-use-cases.md @@ -10,6 +10,10 @@ We measure the query result's error and the cost: latency, insert throughput, me The input is stage 1's approx results, over every configuration and trial. We measure the decision fidelity against the measured result error. +Beyond the assumed rule of each use case below, ASAPBench implements rules from industry for each use case in `scripts/use_cases/cases/*.py`; the pages under [phase2-use-cases](phase2-use-cases/) list them with their sources ([DDoS detection](phase2-use-cases/ddos.md), [resource scaling](phase2-use-cases/resource-scaling.md), [video experience](phase2-use-cases/video-experience.md), [canary release](phase2-use-cases/canary.md), [rate limiting](phase2-use-cases/rate-limiting.md)). +A rule can read an approximate answer as a point, or as the interval its error bound gives, taking no action or rerunning the exact plan when the interval leaves the check open (`run_use_case.py --policy plain|bound|rerun`, `scripts/use_cases/bounds.py`); rate limiting runs the plain policy only. +Each rule's decisions are also scored against the incidents injected into the data (`scripts/use_cases/scenario.py`). + ## 1. DDoS detection A TCP SYN flood is a DDoS attack. @@ -40,7 +44,8 @@ It also uses synthetic data: 10M Zipf-distributed samples, 10M uniform samples i Every 5 seconds, the alerting rule receives the entropy of source IPs over the past 10 seconds, and the number of distinct source IPs over the past 10 and 5 seconds, for instance1. **Application.** -An alert fires while any rule's condition holds. +Each rule has its own alert, which fires while that rule's condition holds. +ASAPBench also has a rule that fires when any of the three conditions holds at 4 evaluations in a row (`promsketch_for_15s`). The paper uses the alert to find the start and the end of an attack. ### Stage 1 @@ -82,6 +87,7 @@ A cloud platform scales resources up and down to save cost, for example the numb A scheduler decides when to scale. It decides from statistics of CPU, memory and pod count over a recent window. For example, every minute, recording rules compute each container's p95 CPU and p95 memory over the past 5 minutes, and the average pod count, as below. +ASAPBench's workload (`uc2_autoscaling.json`) has no pod count metric, so it does not run the third query. The rules store the results. The scheduler reads the stored results and decides whether to scale each container. A standard Google Cloud cluster can have up to 256 pods per node and 100 nodes. @@ -102,7 +108,7 @@ PromSketch evaluates `quantile_over_time` and `avg_over_time` on Google Cluster It also uses the synthetic data of use case 1. **Application input data.** -Every minute, the scheduler receives each container's p95 CPU and p95 memory over the past 5 minutes, and the average pod count. +Every minute, the scheduler receives each container's p95 CPU and p95 memory over the past 5 minutes. **Application.** The scheduler reads the results every minute. @@ -113,7 +119,7 @@ It acts once per crossing. ### Stage 1 **Error.** -Rank error of p95 CPU and p95 memory, and relative error of the average pod count. +Rank error of p95 CPU and p95 memory. **Result.** Whether the error stays within the guarantee, and at what cost. @@ -166,16 +172,17 @@ The trace is about 5 GB and clusters into up to 700K subpopulations. It also uses synthetic multidimensional data drawn from Zipf distributions with skewness from 0.7 to 0.99. **Application input data.** -Every minute, the anomaly detector receives each city's entropy of bitrate and L1 norm of buffering ratio. +ASAPBench's queries (`uc3_video.json`) do not filter or group by city: each returns one answer per subpopulation, one combination of city, ISP, CDN and device (named city.isp.cdn.device). +Every minute, the anomaly detector receives each subpopulation's entropy of bitrate and L1 norm of buffering. **Application.** An anomaly detector reads the result every minute. -It flags a city when its L1 norm of buffering is more than 3 standard deviations above its mean over the previous 30 minutes (assumed rule). +It flags a subpopulation when its L1 norm of buffering is more than 3 standard deviations above its mean over the previous 30 minutes (assumed rule). ### Stage 1 **Error.** -Relative error of each city's entropy and L1 norm. +Relative error of each subpopulation's entropy and L1 norm. **Result.** Whether the error stays within the guarantee, and at what cost. @@ -183,29 +190,29 @@ Whether the error stays within the guarantee, and at what cost. ### Stage 2 **Question.** -Does the detector flag the same cities, at the same evaluations, on approx results as on exact results? +Does the detector flag the same subpopulations, at the same evaluations, on approx results as on exact results? **Fidelity metrics.** -- TP / FP / FN / TN per city per evaluation. -- Onset delay: evaluations from a city's exact flag starting to its approx flag starting. -- Gaps in a city's approx flag while its exact flag stays on. +- TP / FP / FN / TN per subpopulation per evaluation. +- Onset delay: evaluations from a subpopulation's exact flag starting to its approx flag starting. +- Gaps in a subpopulation's approx flag while its exact flag stays on. **Example graph.** ```text -evaluation 1 2 3 4 5 6 7 8 -city A flag exact . . █ █ █ █ █ . - approx . . . █ █ . █ . - a b -city B flag exact . . . . . . . . - approx . . . . █ . . . +evaluation 1 2 3 4 5 6 7 8 +subpopulation A flag exact . . █ █ █ █ █ . + approx . . . █ █ . █ . + a b +subpopulation B flag exact . . . . . . . . + approx . . . . █ . . . c a: onset delay b: gap c: FP ``` **Result.** -Whether the detector on approx results flags the cities with a buffering problem and no others, how many evaluations late, and up to which measured error. +Whether the detector on approx results flags the subpopulations with a buffering problem and no others, how many evaluations late, and up to which measured error. ## 4. Canary release analysis @@ -229,8 +236,8 @@ quantile_over_time(0.99, request_latency{version="canary"}[5m]) **Query input data.** Real: no public data labels latency as canary or stable. The Alibaba microservices trace 2021 has real response times for each call. -We split one service's calls into canary and stable by Flagger's traffic shares, and raise the canary's latency during chosen periods. -Synthetic (in sketch-bench): both versions draw latency from the same Pareto distribution, and the canary gets a fixed 5% of the samples. +We hash each call of one service into a fixed 5% canary share, the rest stable, and raise the canary's latency during the same periods as the synthetic data (`scripts/dataset_tools/real_data.py`). +Synthetic (in ASAPBench): both versions draw latency from the same Pareto distribution, and the canary gets a fixed 5% of the samples. The canary's latency rises by 8%, which stays under the 10% tolerance, and later by 25%. **Application input data.** @@ -240,6 +247,7 @@ Every minute, the rollout controller receives the p99 latency of the canary and A rollout controller reads the result every minute. It rolls back after the canary is judged slower in 3 consecutive checks (assumed rule). It promotes the canary after 10 checks with no 3 consecutive slower ones (assumed rule). +ASAPBench also implements the rules of Flagger, Argo Rollouts, AWS CloudWatch and Keptn; they also read the canary's success rate and p95 latency (`success_rate_canary`, `p95_canary`). ### Stage 1 @@ -296,9 +304,10 @@ LIMIT 10 ``` **Query input data.** -Real: the NASA-HTTP logs from 1995 have 3.46M requests, each with the client host and a 1-second timestamp, and may be freely redistributed. +Real: source IP addresses of packets from CAIDA traces of 2016 and 2019 and a MAWI trace of 2019, taken as client IDs. +The NASA-HTTP logs from 1995 have 3.46M requests, each with the client host and a 1-second timestamp, and may be freely redistributed. They average under 1 request per second, so a 5-minute window holds about 200 requests. -Synthetic (in sketch-bench): 100K clients send requests following a Zipf distribution. +Synthetic (in ASAPBench): 100K clients send requests following a Zipf distribution. Two groups of heavy clients appear in turn, sending 3% and then 2% of all requests. **Application input data.** @@ -355,7 +364,7 @@ Use case 3 can also feed a dashboard: when exact results show a city's buffering **Open items.** -- Use case 3 has no synthetic workload in sketch-bench yet. +- None. Use case 3's synthetic workload is in ASAPBench (`usecase-study/workloads/uc3_video.json`). |"5:generated data"| cli cli --->|"6: necessary components"| aqpbm-core aqpbm-core --->|"7: benchmark result"| cli -aqpbm-usecase["`**aqpbm-usecase** -- use case spec: data, queries, declared truth -- sample generation +usecase-study["`**usecase-study** +- use case workloads: data, queries, declared truth - answer scoring`"] -aqpbm-planeval["`**aqpbm-planeval** +planeval["`**system-bench: planeval** - ASAPPlanner planner and executor in process - recurring queries at every evaluation time`"] -aqpbm-systemeval["`**aqpbm-systemeval** -- Prometheus Remote Write to a time series system -- recurring queries at every evaluation time`"] +system-bench["`**system-bench** +- registry of external systems +- adapters: ClickHouse, VictoriaMetrics, DuckDB, ...`"] -aqpbm-usecase --->|"data generation requirement"| aqpbm-datagen -aqpbm-usecase --->|"necessary components"| aqpbm-core +usecase-study --->|"declared truth scoring"| aqpbm-core +aqpbm-core --->|"time series generation"| aqpbm-datagen -aqpbm-planeval ---> aqpbm-usecase -aqpbm-systemeval ---> aqpbm-usecase +planeval ---> usecase-study -class aqp-bench,runtime future +cli --->|"benchmark-external"| system-bench +system-bench --->|"harness: timing, CPU, memory"| aqpbm-core spacer~~~cli end -commandline_input --->|"benchmark setup"| aqpbm-planeval -commandline_input --->|"benchmark setup"| aqpbm-systemeval +commandline_input --->|"benchmark setup"| planeval -aqpbm-planeval ---->|"result"| output -aqpbm-systemeval ---->|"result"| output +planeval ---->|"result"| output +system-bench ---->|"result: run directory"| output classDef future stroke-dasharray: 5 5 classDef invisible fill:none,stroke:none,color:transparent diff --git a/docs/concepts.md b/docs/concepts.md deleted file mode 100644 index e864c618..00000000 --- a/docs/concepts.md +++ /dev/null @@ -1,135 +0,0 @@ -# Concepts - -Concepts or terminology used across this project is aggregated here. -Ideally, this document can help reduce potential confusion in other docs. - -## Terminologies - -This section defines some terminologies adopted across this projects. - -### Metrics - -Metrics is defined in `aqpbm-core` to describe what can be tested. - -Primary metrics are following: - -- `throughput`: how many item can be processed by an operation in a certain amount of time (per sec) -- `latency`: how long one operation can take -- `accuracy`: how accurate one operation is, comparing to ground-truth - -Secondary metrics that are helpful includes: - -- memory usage - - `rss_peak_kb`: process RSS peak, Linux only - - `heap_allocated_kb`: jemalloc `stats.allocated` - - `memory_bytes`: reported by sketch itself - - `heap_bytes_net`: reported by `heap-track`, a cargo feature - - `heap_bytes_peak`: reported by `heap-track`, a cargo feature - - the `heap-track` cargo feature may affect throughput number -- cpu time - - unix-only: user and sys ns delta from `getrusage` - -### Operations - -Operation is a general group of operations. -There are four operations considered at this moment: - -- `insert`: ingest data -- `prepare`: to better serve a query, `prepare` is necessary sometimes -- `query`: answer a request, get a result -- `merge`: if two objects can be combined into one, which is common for sketch - -Not all metrics is applicable to all operations. -`accuracy` is only meaningful against `query`. -`query` doesn't have `latency`. -`prepare` only have `latency`. - -### Capabilities - -Capability is defined as the general, high-level target of an operation. -Current capabilites includes: - -```text -cardinality how many distinct items are there -frequency how many times did this key occur -quantile which value sits at this fraction -topk which k keys are heaviest, and how heavy -heavy-hitter heavy items and how heavy -subpop-cardinality cardinality, within the records carrying a set of labels -subpop-frequency frequency, within the records carrying a set of labels -subpop-quantile quantile, within the records carrying a set of labels -subpop-cdf share at or below a value, within the records carrying a set of labels -subpop-l1-norm L1-norm of values, within the records carrying a set of labels -subpop-l2-norm L2-norm of values, within the records carrying a set of labels -subpop-entropy entropy of values, within the records carrying a set of labels -subpop-sum sum of values, within the records carrying a set of labels -keyed-cardinality how many distinct items for a specific key -keyed-entropy entropy of values for a specific key -keyed-l1-norm L1-norm of values for a specific key -keyed-l2-norm L2-norm of values for a specific key -none no capability and thus no score -``` - -Capabilities are defined in `sketch-bench`. -Capability-related ground-truth and comparators are defined in `aqpbm-core`. - -### Ground Truth - -Ground-truth is defined based on capabilities. -Ground-truth will take necessary arguments. -For example, `k` value for `top-k`. -For example, `&GeneratedTable` that a benchmark target will receive. - -However, sometime capabilities are hard to be deterministic. -For example, quantile is a capability doesn't take specific argument. -Quantile is currently set to be 101 quantile query. -Thus, this is something user can change by modifying the source code. -It's user's job to ensure these operations (from `wrapper` and in GroundTruth) are doing the same job. -If the operation doesn't match, the accuracy will be inaccurate. -Also, quantile error is calculated based on Rank-error instead of relative error. -Such difference can be outstanding sometime. - -Ground-truth is calculated by exact data structure. -For example, `cardinality` is calculated based on hash-set. -For example, `frequency` and `heavy-hitter` are both supported by a hash-map. - -### SketchId - -`SketchId` is a descriptive entry of one sketch instance. -The struct definition is defined as follow: - -```rust -pub struct SketchId { - pub algorithm: &'static str, - pub variant: &'static str, - pub library: &'static str, - pub description: &'static str, - pub capability: Capability, - pub comparator: Option<&'static str>, - pub operations: OperationMask, - pub metrics: MetricsMask, -} -``` - -Whether a full name is essential (i.e., `CountMin Sketch` vs `cms`) is undecided yet: - -- example: HyperLogLog vs HyperLogLog-MLE - - HyperLogLog: the classic algorithm - - HyperLogLog-MLE: adopted in data-fusion and Redis, identical to classical HyperLogLog except a special query algorithm to achieve cardinality estimation - - reason as a `variance`: both claim themselves to be "HyperLogLog" -- another example: CountMin vs CountMin-FixedMatrix-FastPath - - FixedMatrix: the matrix is bounded in a `Box<[T]>` such that the size is pre-determined at compile time; thus there is no row/col configuration possible - - FastPath: hash reuse optimization such that hash elment once and insert to multiple rows (instead of independent hash at each row, in a regular CountMin sketch algorithm) - - reason as a `variance`: the same algorithm with some optimization techniques - -`description`: one-line description about what this instance is - -`capability`: what this sketch is used for, with [capability](./concepts.md#capabilities) defined above - -`comparator`: what this sketch should be compared against - -- sometimes a sketch can have multiple capabilities, so this sketch can be registered multiple times, with different comparators - -`operations`: what operation this sketch provides - -`metrics`: what metrics can this sketch be benchmarked against diff --git a/docs/developer_guide.md b/docs/developer_guide.md index ba359d36..d80b4509 100644 --- a/docs/developer_guide.md +++ b/docs/developer_guide.md @@ -2,15 +2,51 @@ The target audience is who wants to add functionality to the benchmark. +## Architecture + +The benchmark has two levels. +The sketch benchmark (operator level) measures one sketch on generated data. +The system benchmark (system level) measures a whole data processing system. +Every change belongs to one crate: + +| Crate | What it holds | Change it to add | +|---|---|---| +| `aqpbm-datagen` | data generation | a distribution, a column rule, a dataset format | +| `aqpbm-core` | metrics, ground truth, result records, the harness | a ground truth, a way of measuring | +| `sketch-bench` | wrappers, rows, the registry of sketches | a sketch | +| `aqpbm-cli` | the `approxbench` command | a command line flag | +| `system-bench` | adapters, the registry of systems, `planeval` | a system | +| `usecase-study` and `scripts/use_cases/` | the five use cases | a use case | + +A sketch benchmark runs through these crates in order: + +1. `aqpbm-cli` reads the command line. +2. `sketch-bench` finds the sketch in its registry and checks the request. +3. `aqpbm-datagen` generates the data. +4. `sketch-bench` (the row) builds the closures: one set per (operation, metric) measurement, one closure per run. +5. `aqpbm-core` times the closures and folds the runs into one record. + +A system benchmark runs through these crates in order: + +1. `aqpbm-cli` reads the command line (`approxbench benchmark-external`). +2. `system-bench` finds the system in its registry and builds its adapter. +3. The harness in `aqpbm-core` feeds the data and asks the queries through the adapter, and times every call. +4. The results go to a run directory, and a report joins them. + +[sketch-bench-workflow](./sketch-bench-workflow.md) follows one sketch benchmark through these steps. + ## Pre-requirement Rust toolchain is necessary. Modification will require a re-compile of benchmark. -To get correct number, `cargo build -release` is necessary. +To get correct number, `cargo build --release` is necessary. + +Terms used below are in [terminology](./terminology.md). ## Wire New Sketch -To add a new sketch, either from a new library or just a new algorithm / variance, will need to touch `wrappers`. +To add a new sketch, either from a new library or just a new algorithm / variance, will need to touch `wrappers`, `rows` and the `registry`. +All three are in `sketch-bench`. ### Location @@ -21,23 +57,214 @@ Add algorithm name as necessary. For each operation of that sketch, make a closure for that operation. Other existing wrappers can be used as examples. +A wrapper function builds one sketch per run before the clock starts, and returns one closure per run. +Calling the closure does the work and returns the sketch's size in bytes: + +```rust +pub type Pass = Box usize>; // insert, merge +pub type QueryPass = Box (Vec, usize)>; // query: the answers, and the size + +// For example, the insert of HyperLogLog from asap_sketchlib: +pub fn insert_hll_lib(params: &ParamSet, items: Rc>, passes: usize) + -> Result, BuildError>; +``` + +### Row + +A row builds the wrapper and runs the asked operations on it. +Add one under [rows](../sketch-bench/src/rows/), next to the rows of the same algorithm. +Every row has the same signature: + +```rust +pub type RowBinding = fn( + &Requirement, // what the command line asked for + &ValueColumn, // which column of the table goes into the sketch + GeneratedTable, // the data + &[(Operation, Metric)], // the measurements asked for +) -> Result; // one closure per measurement +``` + +Most rows only pick the item type and call a helper that already exists for their capability, such as `cardinality_row` in `rows/statistic.rs`. + +### Parameters + +A new algorithm also needs a parameter struct in [params.rs](../sketch-bench/src/params.rs), one struct per algorithm. +The struct implements `SketchParams`: `ALGORITHM` names the algorithm, and `canonical()` gives one configuration that builds. +`--config` is parsed through this struct, so it decides which keys `--config` accepts. +A new library of an existing algorithm reuses the algorithm's struct. + ### Registry To register the wrapper (such that `cli` is aware of it), add an entry to [registry](../sketch-bench/src/registry.rs). +The entry names its row (`row: rows::row_...`), its capability, its comparator, and the operations and metrics it supports. +`takes_seed` says whether its configuration has a `seed` field; `--trial-mode reseed` only runs on entries where it is true. +`approxbench sketchbench --list-impls` shows whether it is registered. ## Ground Truth Accuracy comparison needs ground-truth to compare against. -All ground-truth are defined under [accuracy](../aqpbm-core/src/accuracy/). +All ground-truth are defined under [accuracy](../aqpbm-core/src/accuracy/), in `aqpbm-core`. +`sketch-bench` then connects each sketch to one of them. Ground-truth is categorized by functionality. ### Adjustment of existing functionality Some functionalities (like `quantile`) require a parameter. -At this moment, there is no place for user to specify the parameter. -Thus, the ground-truth logic is hard-coded. -For example, `quantile` ground truth means 101 quereis from `p0` `p1` to `p100`. -If user need to know `quantile` accuracy under different meaning (i.e., `p50` only), user need to re-write the ground-truth file and adjust the wrapper accordingly. +`--quantiles` gives the fractions a quantile sketch is asked at, for example `--quantiles 0.5,0.99`. +Without it, `quantile` ground truth means 101 queries from `p0` `p1` to `p100`. +`quantile` error is rank error for most sketches; DDSketch is scored by relative value error (`relative-value-error`). + +### Add a new ground-truth + +1. Implement the `GroundTruth` trait in [accuracy](../aqpbm-core/src/accuracy/): the exact answer (`truth`), what to ask the sketch (`probes`), and the error metrics (`score`). + + ```rust + pub trait GroundTruth { + type Truth; // the exact answer + type Probe; // one question for the sketch + type Answer; // one answer from the sketch + fn truth(&self, table: &GeneratedTable) -> Result; + fn probes(&self, truth: &Self::Truth) -> Vec; + fn score(&self, truth: &Self::Truth, probes: &[Self::Probe], answers: &[Self::Answer]) + -> BTreeMap; // error name -> value, such as "relative_error" + // per_group: only for subpopulation comparators; empty by default + } + ``` + +2. In `sketch-bench`, add a row helper that scores with it, next to the existing ones in [statistic.rs](../sketch-bench/src/rows/statistic.rs). +3. Name it as the `comparator` of the registry entries it scores, and add the name to the list the registry test checks (`every_declared_comparator_is_one_core_ships`). +4. If it answers a new kind of question, add a `Capability` in [request.rs](../sketch-bench/src/request.rs). + +## Wire New Data Generation + +Data generation is in [aqpbm-datagen](../aqpbm-datagen/src/), which depends on no other crate of this workspace. +A distribution goes in `dist.rs`, a column rule in `rule.rs`, and time series in `timeseries.rs`. +Imported datasets are read by `import.rs`. +A new distribution in `DataDistribution` (`dist.rs`) is readable from a `--spec` YAML file; to also name it with `--dataset`, add it to the match in `aqpbm-cli/src/sketchbench.rs`, next to `zipf`, and to the `--dataset` help text in `aqpbm-cli/src/cli.rs`. + +## Wire New System + +A system is an external engine the system level measures, such as ClickHouse or VictoriaMetrics. +The adapter and the registry entry are in `system-bench`; the traits they implement are in the harness of `aqpbm-core`. + +### Adapter + +Adapters are under [engines_external](../system-bench/src/engines_external/). +An adapter implements one of the harness traits of `aqpbm-core`: + +- `EngineUnderTest` (`aqpbm-core/src/harness/engine.rs`) for periodic queries and write throughput: install an arm, ingest data, evaluate queries. +- `OneShotQueryEngine` (`aqpbm-core/src/harness/one_shot.rs`) for one-shot queries: load tables, run one query. + +The methods an adapter must write (the others have defaults): + +```rust +pub trait EngineUnderTest { + fn description(&self) -> EngineDescription; // id, version, build + fn cpu_accounting(&self) -> CpuAccounting; // where the harness reads its CPU + fn install(&self, workload: &WorkloadSpec, arm: &ArmSpec) + -> Result, EngineError>; +} + +pub trait InstalledArm { + fn plan_summary(&self) -> PlanSummary; + fn ingest(&mut self, chunk: &SampleChunk) -> Result; + fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>; + fn footprint(&self) -> Result; +} + +pub trait OneShotQueryEngine { + fn description(&self) -> EngineDescription; + fn dialect(&self) -> SqlDialect; + fn engine_time_covers(&self) -> Option<&'static str>; // what the engine's own time includes + fn table_rows(&mut self, table: &str) -> Result, EngineError>; + fn restart(&mut self) -> Result<(), EngineError>; + fn run_query(&mut self, sql: &str) -> Result; +} +``` + +Two methods with defaults still need writing in some cases: + +- For write throughput, an installed arm overrides `InstalledArm::sample_writers`; the default returns `None`, and a write-throughput run then fails. + + ```rust + fn sample_writers(&mut self, count: usize) -> Option>>; + ``` + +- A one-shot engine that loads its own tables overrides `OneShotQueryEngine::load_table`; the default returns an error. + + ```rust + fn load_table(&mut self, statements: &[String]) -> Result<(), EngineError>; + ``` + +The engine never times itself; the harness reads the clocks around every call. +The checks every adapter must pass are in `aqpbm-core/src/harness/conformance.rs`. + +### Registry + +To make `approxbench benchmark-external` aware of it, add a `System` entry to [registry](../system-bench/src/registry.rs). +The entry declares which measurements the system takes (periodic queries, write throughput, one-shot queries), the command-line options each one needs, and the function that builds the adapter from them: + +```rust +pub struct System { + pub name: &'static str, + pub periodic_queries: Option, // options + build: -> Box + pub write_throughput: Option, // options + build: -> Box + pub one_shot_queries: Option, // dialect + options + build: -> Box +} +``` + +### Start script + +If the system is a server, add `scripts/extbench-up-.sh` to start and stop it at a pinned version, as the existing ones do. + +## Wire New Use Case + +A use case needs a workload, a module of rules, and a page. +The workload is in `usecase-study`; the rules are Python, in `scripts/use_cases/`. + +- Workload: a `WorkloadSpec` JSON in [usecase-study/workloads](../usecase-study/workloads/), with each query's `truth` declared where it is a quantile, entropy, distinct count or top-k. +- Module: `scripts/use_cases/cases/uc_.py`, with an `ID` and a `CASE` dictionary: the workload file (`spec`), the arms, the rules, and how answers are turned into decisions (`derive`). `scripts/use_cases/cases/__init__.py` loads every module in that directory, so `run_use_case.py ` and `run_use_case_on_systems.py ` pick it up. + - `CASE` also needs `use_case`, `signal`, `split`, `dashboard` and `needs_every_query`; the scripts read them without defaults. + - `rules` in `CASE` is optional: `uc4_canary_release.py` has none. + - `tools/grafana/generate_dashboards.py` reads the module attributes `DASHBOARD` and `RULES`, `DECISION` for a `decision` dashboard (`uc2_autoscaling.py`), and `QUERY_COLORS` for a `rollout` dashboard (`uc4_canary_release.py`). +- Page: `docs/phase2-use-cases/.md`, describing the queries, the rules and where each rule comes from. + +## Read the Output + +A sketch benchmark writes one JSON record per measurement. +What each field means is in [sketch-bench-workflow](./sketch-bench-workflow.md#output). + +A system benchmark writes its results to a run directory, and a report joins them. +For periodic queries, `approxbench benchmark-external report` writes: + +- `summary.csv`: one row per workload, system and variant: `status`, where CPU was read (`cpu_accounting`), ingest CPU per sample, query CPU per evaluation, the server's memory, and the relative error against the truth +- `summary.md`: the same as a table, one row per workload and one column per system and variant, each cell like `q 2.000 ms, i 2000.0 ns/sample, err 0.100 [cgroup]` +- `accuracy.csv`: the same errors, one row per query +- `scores.csv`: the scores against each query's declared ground-truth + +For one-shot queries, `approxbench benchmark-external one-shot-report` writes `one-shot-summary.csv` and `one-shot-summary.md`: one row per configuration and query, with `status`, the first run and the median of the later (hot) runs, the speedup over each baseline, the maximum relative error against the truth, and how many runs went over the error target. +It also writes `one-shot-tables.csv`: one row per system, configuration and table, with its rows, load time and data size in bytes. + +For write throughput, `approxbench benchmark-external write-throughput` appends one line per measurement to `results//write-throughput.jsonl`: the acknowledged samples per second, and the engine's CPU and memory. + +## Plot the Output + +There is no general script that plots the results at this moment. +What exists: + +- `scripts/studies/plot_saturation_*.py`: the figures of the saturation study, from its own CSV files +- `tools/grafana/`: dashboards for the use cases (`tools/grafana/run.sh`) +- `scripts/sketch_runs/`: batch runs of many sketches (`run_throughput_fast.sh`, `run_profiles.sh`) and of the atomic-cost table (`export_atomic_costs.sh`); they write JSONL, not plots + +## Check the Output + +A number that looks fine can still be wrong. +A few checks help: + +- **Run the exact baseline.** The same command with `--library polars` computes the exact answer through the same machinery. Its error should be 0; any error it shows is the benchmark's, not the sketch's. +- **Compare with the theory.** For example, HyperLogLog with `lg_k=14` has a standard error of about `1.04 / sqrt(2^14)` ≈ 0.008. A relative error far above that points to a wrong configuration or a wrong comparator. +- **Check the memory.** `memory_bytes` should match the configuration: `lg_k=14` is 2^14 registers, and the record says 16400 bytes. +- **Check the spread.** `stddev` of throughput should be small next to `mean`, and `n` should equal `--runs`. A large spread usually means something else is running on the machine.