Skip to content

Latest commit

 

History

History
297 lines (213 loc) · 15.1 KB

developer_guide.md

File metadata and controls

297 lines (213 loc) · 15.1 KB

Developer Guidance

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 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.

Terms used below are in terminology.

Wire New Sketch

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

wrappers refers to this folder under sketch-bench crate. Currently, the directory is grouped by algorithm name. 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:

pub type Pass = Box<dyn FnOnce() -> usize>;                   // insert, merge
pub type QueryPass<A> = Box<dyn FnOnce() -> (Vec<A>, usize)>; // query: the answers, and the size

// For example, the insert of HyperLogLog from asap_sketchlib:
pub fn insert_hll_lib<R, T>(params: &ParamSet, items: Rc<Vec<T>>, passes: usize)
    -> Result<Vec<Pass>, BuildError>;

Row

A row builds the wrapper and runs the asked operations on it. Add one under rows, next to the rows of the same algorithm. Every row has the same signature:

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<Measurements, RunError>; // 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, 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. 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, 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. --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: the exact answer (truth), what to ask the sketch (probes), and the error metrics (score).

    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<Self::Truth, DataGenError>;
        fn probes(&self, truth: &Self::Truth) -> Vec<Self::Probe>;
        fn score(&self, truth: &Self::Truth, probes: &[Self::Probe], answers: &[Self::Answer])
            -> BTreeMap<String, f64>; // 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.

  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.

Wire New Data Generation

Data generation is in aqpbm-datagen, 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. 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):

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<Box<dyn InstalledArm>, EngineError>;
}

pub trait InstalledArm {
    fn plan_summary(&self) -> PlanSummary;
    fn ingest(&mut self, chunk: &SampleChunk) -> Result<StepReport, EngineError>;
    fn evaluate(&mut self, at_ms: i64) -> Result<(Answers, StepReport), EngineError>;
    fn footprint(&self) -> Result<Footprint, EngineError>;
}

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<Option<u64>, EngineError>;
    fn restart(&mut self) -> Result<(), EngineError>;
    fn run_query(&mut self, sql: &str) -> Result<QueryRun, EngineError>;
}

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.

    fn sample_writers(&mut self, count: usize) -> Option<Vec<Box<dyn SampleWriter>>>;
  • A one-shot engine that loads its own tables overrides OneShotQueryEngine::load_table; the default returns an error.

    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. 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:

pub struct System {
    pub name: &'static str,
    pub periodic_queries: Option<PeriodicQueries>,  // options + build: -> Box<dyn EngineUnderTest>
    pub write_throughput: Option<WriteThroughput>,  // options + build: -> Box<dyn EngineUnderTest>
    pub one_shot_queries: Option<OneShotQueries>,   // dialect + options + build: -> Box<dyn OneShotQueryEngine>
}

Start script

If the system is a server, add scripts/extbench-up-<system>.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, with each query's truth declared where it is a quantile, entropy, distinct count or top-k.
  • Module: scripts/use_cases/cases/uc<N>_<name>.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 <N> and run_use_case_on_systems.py <N> 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/<name>.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.

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/<engine>/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.