From 653d6a8dbe4d6f9d34c5eafe24c44d9c000746da Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 04:09:25 +0000 Subject: [PATCH 1/2] hydra: interleaved merge split; merge exactness and bound tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `--merge-split contiguous|interleaved` (default contiguous, unchanged) picks how merge runs split the stream into shards. Interleaved reorders the stream so the existing contiguous `partition` deals it round-robin by record, at the contiguous split's shard sizes, so every row's folds take it unchanged. Tests: hydra-cms, hydra-cs and hydra-hll grids folded from 4 and 7 shards, under both splits, answer every probed subpopulation exactly as the single stream; and every scored group on a fixed 20k-record stream lands inside its hydra doc §2.2 bound (CMS also never under). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- README.md | 11 + aqpbm-cli/src/cli.rs | 11 + aqpbm-cli/src/main.rs | 5 + aqpbm-cli/src/rows/mod.rs | 4 +- aqpbm-cli/src/rows/statistic.rs | 13 +- docs/saturation_study.md | 3 +- sketch-bench/src/request.rs | 2 + sketch-bench/src/wrappers/hydra_shared.rs | 295 ++++++++++++++++++++++ sketch-bench/src/wrappers/mod.rs | 60 +++++ 9 files changed, 398 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index f48e88d6..5d2925cd 100644 --- a/README.md +++ b/README.md @@ -447,6 +447,17 @@ approxbench: hydra-cms/lib config={"cell_cols":1024,"cell_rows":3,"cols":1024,"r `--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). +**`--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. + +**`--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 (records +`0, k, 2k, ...` go to the first of `k` shards). The shard sizes are the same +either way. 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. + **`--flat`**: flatten record such that output data of multiple experiments is flatten into one json file. #### General Explanation diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index bd14e42a..6b911613 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -234,6 +234,17 @@ pub struct SketchbenchArgs { /// merge exactly, so a gap is a defect; for KLL it is the result. #[arg(long, default_value_t = 2, help_heading = "Measurement content")] pub merge_shards: usize, + /// How the merge operation splits the stream into its shards: `contiguous` + /// cuts it into stretches, `interleaved` deals it round-robin by record, so + /// each shard is a sample of the whole stream. The shard sizes are the same + /// either way. + #[arg( + long, + default_value = "contiguous", + value_parser = ["contiguous", "interleaved"], + help_heading = "Measurement content" + )] + pub merge_split: String, /// Path to append JSONL records to. `-` or omitted sends them to stdout. #[arg(long, help_heading = "Output")] diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 8334d4dd..6ccef32e 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -50,6 +50,7 @@ use report_sink::ReportSink; // not know the set; it asks. use sketch_bench::registry; use sketch_bench::request::Requirement; +use sketch_bench::wrappers::MergeSplit; /// What is measured. No default and no `all`: a request names the measurements /// it wants, and a shorthand that swept every operation against every metric @@ -357,6 +358,10 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { width, workers: args.workers.max(1), merge_shards: args.merge_shards, + merge_split: match args.merge_split.as_str() { + "interleaved" => MergeSplit::Interleaved, + _ => MergeSplit::Contiguous, + }, comparator: args.comparator.clone(), runs: args.runs, warmup_runs: args.warmup_runs, diff --git a/aqpbm-cli/src/rows/mod.rs b/aqpbm-cli/src/rows/mod.rs index e1f1c59c..5f146a55 100644 --- a/aqpbm-cli/src/rows/mod.rs +++ b/aqpbm-cli/src/rows/mod.rs @@ -7,8 +7,8 @@ use std::rc::Rc; use sketch_bench::request::{Dtype, Requirement}; use sketch_bench::wrappers::{ - BuildError, Folds, InsertBody, InsertStepBody, ParallelInsertBody, PrepareBody, QueryBody, - QueryPass, StepPass, + interleave, BuildError, Folds, InsertBody, InsertStepBody, MergeSplit, ParallelInsertBody, + PrepareBody, QueryBody, QueryPass, StepPass, }; /// A row that cannot be built at the requested config says so in its own words; diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index 3e6c0678..cea3cbf4 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -343,6 +343,7 @@ pub(super) fn scored_row( prepare: Option>, ) -> Result where + I: Clone, G: GroundTruth + 'static, G::Truth: 'static, G::Probe: 'static, @@ -350,6 +351,12 @@ where { let (probes, score) = questions(ground_truth, &table)?; let items = materialise(description, table)?; + // What the folds cut into shards: the stream itself, or reordered so the + // same cut deals it round-robin. + let merged = match req.merge_split { + MergeSplit::Contiguous => items.clone(), + MergeSplit::Interleaved => Rc::new(interleave(&items, shards(req))), + }; let mut bodies = Vec::with_capacity(want.len()); for &(operation, metric) in want { let n = passes(req, metric); @@ -371,7 +378,7 @@ where (Operation::Merge, Metric::Accuracy) => answered( merge.expect(SUPPORTED).2( &req.params, - items.clone(), + merged.clone(), probes.clone(), shards(req), n, @@ -381,11 +388,11 @@ where metric, ), (Operation::Merge, Metric::Latency) => stepped( - merge.expect(SUPPORTED).1(&req.params, items.clone(), shards(req), n) + merge.expect(SUPPORTED).1(&req.params, merged.clone(), shards(req), n) .map_err(cannot_build)?, ), (Operation::Merge, _) => timed( - merge.expect(SUPPORTED).0(&req.params, items.clone(), shards(req), n) + merge.expect(SUPPORTED).0(&req.params, merged.clone(), shards(req), n) .map_err(cannot_build)?, (shards(req) - 1) as u64, ), diff --git a/docs/saturation_study.md b/docs/saturation_study.md index 834f119f..a2ad6f7d 100644 --- a/docs/saturation_study.md +++ b/docs/saturation_study.md @@ -548,7 +548,8 @@ Crossover at theta = 1, K = 1e5 (frequency, top-k, HLL) and Pareto alpha 1.5 - **Accuracy after merging** is now measured (`--operations merge --metrics accuracy --merge-shards m`, or `--merge-shards-list 1,4,16,64` here, into `saturation_merge_curve.csv`): the N-item stream is split into m contiguous - shards, one sketch per shard is folded into one, and it is scored with the + shards (approxbench `--merge-split interleaved` deals it round-robin), one + sketch per shard is folded into one, and it is scored with the query's comparator against the whole-stream truth. A bounded run (first config per sketch, N up to 1e7, 3 seeds, theta 0.5/1.0/1.5, K 1e3/1e5/1e7, alpha 1.1/2) found: diff --git a/sketch-bench/src/request.rs b/sketch-bench/src/request.rs index 1a13d182..ef6f611c 100644 --- a/sketch-bench/src/request.rs +++ b/sketch-bench/src/request.rs @@ -118,6 +118,8 @@ pub struct Requirement { pub workers: usize, /// How many shards a merge measurement folds pub merge_shards: usize, + /// How a merge measurement splits the stream into those shards + pub merge_split: crate::wrappers::MergeSplit, /// A named comparator, or `None` for the row's default. pub comparator: Option, /// Measured runs, and the warm-ups run and discarded before them diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 0521e338..2ccd7250 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -86,3 +86,298 @@ pub(crate) fn check_grid(rows: usize, cols: usize, algorithm: &str) -> Result<() pub(crate) fn grid_overhead_bytes(rows: usize, cols: usize) -> usize { (rows * cols + 1) * std::mem::size_of::() } + +#[cfg(test)] +mod tests { + use crate::params::{HydraCmsParams, HydraCsParams, HydraHllParams, ParamSet}; + use crate::wrappers::hydra_cms::sketchlib::merge_query_hydra_cms; + use crate::wrappers::hydra_cs::sketchlib::merge_query_hydra_cs; + use crate::wrappers::hydra_hll::sketchlib::merge_query_hydra_hll; + use crate::wrappers::{interleave, QueryPass}; + use std::collections::{HashMap, HashSet}; + use std::rc::Rc; + + /// Records over two labels, deterministic: `r0..r5` with weights halving + /// from 32, `s0..s4` uniform, and a value skewed towards 0 over about + /// 2000 distinct values. + fn records(n: usize) -> Vec<(String, i64)> { + let mut state = 0x9e37_79b9_7f4a_7c15u64; + let mut next = move || { + state = state + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1); + state >> 11 + }; + (0..n) + .map(|_| { + let pick = (next() % 63) as u32; + let region = (0..6).find(|&r| pick < 64 - (64 >> (r + 1))).unwrap_or(5); + let service = next() % 5; + let u = (next() % 10_000) as f64 / 10_000.0; + (format!("r{region};s{service}"), (u * u * 2000.0) as i64) + }) + .collect() + } + + /// Every subpopulation the grid answers for: each first label alone and + /// each pair, as the query names them (leading columns). + fn groups(items: &[(String, i64)]) -> Vec> { + let mut out: Vec> = Vec::new(); + for (key, _) in items { + let parts: Vec = key.split(';').map(str::to_string).collect(); + for g in [parts[..1].to_vec(), parts] { + if !out.contains(&g) { + out.push(g); + } + } + } + out + } + + fn in_group(key: &str, group: &[String]) -> bool { + key.split(';').zip(group).all(|(a, b)| a == b) + } + + /// Every (group, value) pair that occurs, the frequency probes. + fn pairs(items: &[(String, i64)]) -> Vec<(Vec, i64)> { + let mut seen = HashSet::new(); + for g in groups(items) { + for (key, v) in items { + if in_group(key, &g) { + seen.insert((g.clone(), *v)); + } + } + } + let mut out: Vec<_> = seen.into_iter().collect(); + out.sort(); + out + } + + fn answers(mut passes: Vec>) -> Vec { + (passes.pop().expect("one pass"))().0 + } + + // ---------- merge exactness (hydra doc §2.3) ---------- + + const SHARDS: [usize; 2] = [4, 7]; + + /// Asks `run` of the stream folded from every shard count, under both + /// splits, and of the single stream: every answer must be equal, because + /// these cells merge exactly and every cell clones one seeded template. + fn merged_equals_single( + items: Vec<(String, i64)>, + run: impl Fn(Rc>, usize) -> Vec, + ) { + let single = run(Rc::new(items.clone()), 1); + for k in SHARDS { + for (split, stream) in [ + ("contiguous", items.clone()), + ("interleaved", interleave(&items, k)), + ] { + assert_eq!( + run(Rc::new(stream), k), + single, + "{k} {split} shards answer differently from one stream" + ); + } + } + } + + /// A small grid, so groups collide and the merge has contamination to + /// carry too. + const SMALL_W: usize = 16; + + #[test] + fn hydra_cms_merged_from_shards_answers_as_one_stream() { + let items = records(3_000); + let probes = Rc::new(pairs(&items)); + let params = ParamSet::of(&HydraCmsParams { + rows: 3, + cols: SMALL_W, + cell_rows: 3, + cell_cols: 64, + }); + merged_equals_single(items, |stream, k| { + answers(merge_query_hydra_cms(¶ms, stream, probes.clone(), k, 1).unwrap()) + }); + } + + #[test] + fn hydra_cs_merged_from_shards_answers_as_one_stream() { + let items = records(3_000); + let probes = Rc::new(pairs(&items)); + let params = ParamSet::of(&HydraCsParams { + rows: 3, + cols: SMALL_W, + cell_rows: 3, + cell_cols: 64, + }); + merged_equals_single(items, |stream, k| { + answers(merge_query_hydra_cs(¶ms, stream, probes.clone(), k, 1).unwrap()) + }); + } + + #[test] + fn hydra_hll_merged_from_shards_answers_as_one_stream() { + let items = records(3_000); + let probes = Rc::new(groups(&items)); + let params = ParamSet::of(&HydraHllParams { + rows: 3, + cols: SMALL_W, + }); + merged_equals_single(items, |stream, k| { + answers(merge_query_hydra_hll(¶ms, stream, probes.clone(), k, 1).unwrap()) + }); + } + + // ---------- the §2.2 bounds, on a fixed stream ---------- + // + // Every scored group must land inside its bound in a good row. `BETA`, the + // Markov factor on the colliders' mass, is generous: the bounds are + // sanity checks on the grid, not a measurement of its confidence. + + const N: usize = 20_000; + const BETA: f64 = 8.0; + /// Subsets every two-label record is inserted under. + const FAN_OUT: f64 = 3.0; + const CELL_COLS: usize = 512; + + /// Each value's fanned-out frequency `F_v`: its count over all subkeys. + fn fanned(items: &[(String, i64)]) -> HashMap { + let mut f = HashMap::new(); + for (_, v) in items { + *f.entry(*v).or_insert(0.0) += FAN_OUT; + } + f + } + + /// Group `g`'s value frequencies `f_q(v)`. + fn frequencies(items: &[(String, i64)], g: &[String]) -> HashMap { + let mut f = HashMap::new(); + for (_, v) in items.iter().filter(|(key, _)| in_group(key, g)) { + *f.entry(*v).or_insert(0.0) += 1.0; + } + f + } + + #[test] + fn hydra_cms_never_under_and_within_its_bound() { + let items = records(N); + let probes = pairs(&items); + let params = ParamSet::of(&HydraCmsParams { + rows: 3, + cols: SMALL_W, + cell_rows: 3, + cell_cols: CELL_COLS, + }); + let got = answers( + merge_query_hydra_cms( + ¶ms, + Rc::new(items.clone()), + Rc::new(probes.clone()), + 1, + 1, + ) + .unwrap(), + ); + let (fv, m, w) = (fanned(&items), FAN_OUT * N as f64, SMALL_W as f64); + let eps = std::f64::consts::E / CELL_COLS as f64; + let mut by_group = HashMap::new(); + for ((g, v), est) in probes.iter().zip(got) { + let f = by_group + .entry(g.clone()) + .or_insert_with(|| frequencies(&items, g)); + let (truth, n_q) = (f[v], f.values().sum::()); + assert!(est >= truth, "{g:?} {v}: {est} under {truth}"); + let bound = truth + eps * n_q + BETA * (fv[v] + eps * m) / w; + assert!(est <= bound, "{g:?} {v}: {est} over its bound {bound}"); + } + } + + #[test] + fn hydra_cs_within_its_bound() { + let items = records(N); + let probes = pairs(&items); + let params = ParamSet::of(&HydraCsParams { + rows: 3, + cols: SMALL_W, + cell_rows: 3, + cell_cols: CELL_COLS, + }); + let got = answers( + merge_query_hydra_cs( + ¶ms, + Rc::new(items.clone()), + Rc::new(probes.clone()), + 1, + 1, + ) + .unwrap(), + ); + let (fv, w) = (fanned(&items), SMALL_W as f64); + let f2: f64 = fv.values().map(|f| f * f).sum(); + let eps = 1.0 / (CELL_COLS as f64).sqrt(); + // The colliders' L2 under the one Markov event `F2_C <= BETA * F2 / W`. + let l2_c = (BETA * f2 / w).sqrt(); + let mut by_group = HashMap::new(); + for ((g, v), est) in probes.iter().zip(got) { + let f = by_group + .entry(g.clone()) + .or_insert_with(|| frequencies(&items, g)); + let truth = f[v]; + let l2_q = f.values().map(|x| x * x).sum::().sqrt(); + let (low, high) = ( + truth - eps * (l2_q + l2_c), + truth + eps * l2_q + BETA * fv[v] / w + eps * l2_c, + ); + assert!( + (low..=high).contains(&est), + "{g:?} {v}: {est} outside [{low}, {high}]" + ); + } + } + + #[test] + fn hydra_hll_within_its_bound() { + let items = records(N); + let probes = groups(&items); + let params = ParamSet::of(&HydraHllParams { + rows: 3, + cols: SMALL_W, + }); + let got = answers( + merge_query_hydra_hll( + ¶ms, + Rc::new(items.clone()), + Rc::new(probes.clone()), + 1, + 1, + ) + .unwrap(), + ); + let distinct = |g: &[String]| frequencies(&items, g).len() as f64; + // `ΣD`: every subkey's distinct count, the first label, the second and + // the pair. + let mut by_subkey: HashMap> = HashMap::new(); + for (key, v) in &items { + let (region, service) = key.split_once(';').unwrap(); + for subkey in [format!("{region};"), format!(";{service}"), key.clone()] { + by_subkey.entry(subkey).or_default().insert(*v); + } + } + let sum_d: f64 = by_subkey.values().map(|s| s.len() as f64).sum(); + // Three standard errors of a 2^14-register HLL. + let eps = 3.0 * 1.04 / ((1u64 << 14) as f64).sqrt(); + for (g, est) in probes.iter().zip(got) { + let d_q = distinct(g); + let (low, high) = ( + (1.0 - eps) * d_q, + (1.0 + eps) * (d_q + BETA * sum_d / SMALL_W as f64), + ); + assert!( + (low..=high).contains(&est), + "{g:?}: {est} outside [{low}, {high}]" + ); + } + } +} diff --git a/sketch-bench/src/wrappers/mod.rs b/sketch-bench/src/wrappers/mod.rs index 39006635..343730ec 100644 --- a/sketch-bench/src/wrappers/mod.rs +++ b/sketch-bench/src/wrappers/mod.rs @@ -148,6 +148,36 @@ pub fn partition(items: &[T], n: usize) -> Vec<&[T]> { items.chunks(chunk).collect() } +/// How a merge run splits the stream into its shards. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum MergeSplit { + /// Each shard a stretch of the stream, as [`partition`] cuts it. + #[default] + Contiguous, + /// Round-robin by record, so each shard is a sample of the whole stream: + /// the stream is first reordered by [`interleave`]. + Interleaved, +} + +/// The stream reordered so that [`partition`] into `n` hands out a round-robin +/// split: record `j` goes to the next shard with room, so each shard holds +/// every `n`-th record, in stream order, and the shard sizes are exactly the +/// contiguous split's. +pub fn interleave(items: &[T], n: usize) -> Vec { + let sizes: Vec = partition(items, n).iter().map(|p| p.len()).collect(); + let mut shards: Vec> = sizes.iter().map(|&len| Vec::with_capacity(len)).collect(); + let mut next = 0; + for item in items { + // Only the last shard can be short, so this skips at most once a round. + while shards[next].len() == sizes[next] { + next = (next + 1) % sizes.len(); + } + shards[next].push(item.clone()); + next = (next + 1) % sizes.len(); + } + shards.concat() +} + // All four helpers below exist for one rule: a row that cannot build at the // requested parameters says so, and never builds at different ones under the // requested label — so `sketch_config` is always the config that ran. @@ -232,3 +262,33 @@ pub fn hh_heap_footprint(capacity: usize) -> usize { std::mem::size_of::(), ) } + +#[cfg(test)] +mod tests { + use super::*; + + /// Cut by [`partition`], the interleaved stream deals record `j` to shard + /// `j mod n` while every shard has room, and keeps the contiguous split's + /// sizes, including its short last shard. + #[test] + fn interleave_deals_round_robin_at_the_contiguous_sizes() { + let items: Vec = (0..10).collect(); + let shards: Vec> = partition(&interleave(&items, 4), 4) + .iter() + .map(|s| s.to_vec()) + .collect(); + // Contiguous: chunks of 3, so sizes 3, 3, 3, 1; record 7 skips the + // full last shard. + assert_eq!( + shards, + vec![vec![0, 4, 7], vec![1, 5, 8], vec![2, 6, 9], vec![3]] + ); + // Divisible: every shard is one residue class. + let shards = partition(&interleave(&items, 5), 5) + .iter() + .map(|s| s.to_vec()) + .collect::>(); + assert_eq!(shards, (0..5).map(|r| vec![r, r + 5]).collect::>()); + assert!(interleave::(&[], 4).is_empty()); + } +} From 6e649de5ea1a76a919237beb1cb41bc49ab3f24b Mon Sep 17 00:00:00 2001 From: zz_y Date: Sat, 10 Oct 2026 05:09:40 +0000 Subject: [PATCH 2/2] hydra: record merge_split; review fixes - `merge_split` (contiguous|interleaved) is a record field next to `merge_shards` (BenchSection and MergeMetrics; schema regenerated). Merge records stamp it; a record without it split contiguously, so existing results parse, and flatten refuses two different splits in one row as it does two shard counts. - `MergeSplit` moves to aqpbm-core (it is a record type) and is parsed by clap directly instead of matching strings. - The interleaved copy of the stream is built only when a merge runs. - README states the round-robin exactly (contiguous shard sizes, so a short last shard shifts the pattern); MergeMetrics docs name the split. - hydra-cs bound test: note its margin (passes from beta ~4.8). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01FhcWJExZcmVqS6r6rEtjis --- README.md | 10 ++++-- aqpbm-cli/src/cli.rs | 7 ++-- aqpbm-cli/src/flatten_record.rs | 36 ++++++++++++++++++-- aqpbm-cli/src/main.rs | 7 ++-- aqpbm-cli/src/repeat.rs | 1 + aqpbm-cli/src/rows/statistic.rs | 9 +++-- aqpbm-core/schema/merged_record.schema.json | 30 ++++++++++++++++- aqpbm-core/src/benchmark_result/mod.rs | 2 +- aqpbm-core/src/benchmark_result/schema.rs | 37 +++++++++++++++++++-- aqpbm-core/src/lib.rs | 4 +-- sketch-bench/src/wrappers/hydra_shared.rs | 5 +++ sketch-bench/src/wrappers/mod.rs | 13 ++------ 12 files changed, 130 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 5d2925cd..b5dd7006 100644 --- a/README.md +++ b/README.md @@ -392,6 +392,7 @@ approxbench: hydra-cms/lib config={"cell_cols":1024,"cell_rows":3,"cols":1024,"r ] }, "merge_shards": 8, + "merge_split": "contiguous", "merge_supported": true, "merge_cpu_time_ms": { "user_ms": { @@ -452,9 +453,12 @@ many ways, one sketch is fed per shard, and the sketches are folded into one. **`--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 (records -`0, k, 2k, ...` go to the first of `k` shards). The shard sizes are the same -either way. CMS, CountSketch and HLL cells (and their Hydra grids) merge +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. diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index 6b911613..cff64dad 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -2,6 +2,8 @@ //! `main.rs`. Option help and grouping track `docs/aqpbm-cli-reference.md`, which //! `scripts/dump_cli_reference.sh` diffs the built binary against. +use aqpbm_core::MergeSplit; +use clap::builder::TypedValueParser; use clap::{Parser, Subcommand}; use crate::atomic_costs_cmd; @@ -241,10 +243,11 @@ pub struct SketchbenchArgs { #[arg( long, default_value = "contiguous", - value_parser = ["contiguous", "interleaved"], + value_parser = clap::builder::PossibleValuesParser::new(["contiguous", "interleaved"]) + .try_map(|s| s.parse::()), help_heading = "Measurement content" )] - pub merge_split: String, + pub merge_split: MergeSplit, /// Path to append JSONL records to. `-` or omitted sends them to stdout. #[arg(long, help_heading = "Output")] diff --git a/aqpbm-cli/src/flatten_record.rs b/aqpbm-cli/src/flatten_record.rs index c69b1004..225b01b0 100644 --- a/aqpbm-cli/src/flatten_record.rs +++ b/aqpbm-cli/src/flatten_record.rs @@ -4,7 +4,8 @@ //! named by both. Grouping records by identity is the caller's job. use aqpbm_core::{ - BenchSection, InsertMetrics, MergeMetrics, MergedRecord, PrepareMetrics, QueryMetrics, Record, + BenchSection, InsertMetrics, MergeMetrics, MergeSplit, MergedRecord, PrepareMetrics, + QueryMetrics, Record, }; /// Which slot a `Record` lands in, per its own `bench.operation` field. Every @@ -84,6 +85,7 @@ pub fn flatten_record(records: &[Record]) -> Result { accuracy, merge_folds_per_sec, merge_shards, + merge_split, merge_supported, } = bench; @@ -113,7 +115,7 @@ pub fn flatten_record(records: &[Record]) -> Result { } }; } - // `merge_shards`/`merge_supported` describe the merge setup, which + // `merge_shards`/`merge_split`/`merge_supported` describe the merge setup, which // every merge square of one invocation stamps — equal values agree, // different ones mean two setups were folded together. macro_rules! keep_same { @@ -183,6 +185,12 @@ pub fn flatten_record(records: &[Record]) -> Result { "merge_folds_per_sec" ); keep_same!(out.merge.merge_shards, *merge_shards, "merge_shards"); + // A record from before `merge_split` existed split contiguously. + keep_same!( + out.merge.merge_split, + merge_split.or(Some(MergeSplit::Contiguous)), + "merge_split" + ); keep_same!( out.merge.merge_supported, *merge_supported, @@ -422,6 +430,30 @@ mod tests { assert!(err.contains("merge_shards"), "{err}"); } + /// Two splits are two setups; a record without the field split + /// contiguously, so it agrees with a contiguous one. + #[test] + fn merge_split_on_two_squares_must_agree() { + let merge = |metric, split| { + record( + "merge", + metric, + BenchSection { + merge_split: split, + ..Default::default() + }, + ) + }; + let out = flatten_record(&[merge("throughput", None)]).expect("one setup"); + assert_eq!(out.merge.merge_split, Some(MergeSplit::Contiguous)); + let err = flatten_record(&[ + merge("throughput", Some(MergeSplit::Interleaved)), + merge("accuracy", None), + ]) + .expect_err("two splits in one row"); + assert!(err.contains("merge_split"), "{err}"); + } + /// `throughput_items_per_sec` is owned by exactly one metric-pass per /// operation — nothing legitimately produces it twice for `insert`. A /// second value here is a genuine duplicate, refused by field name diff --git a/aqpbm-cli/src/main.rs b/aqpbm-cli/src/main.rs index 6ccef32e..84886741 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -50,7 +50,6 @@ use report_sink::ReportSink; // not know the set; it asks. use sketch_bench::registry; use sketch_bench::request::Requirement; -use sketch_bench::wrappers::MergeSplit; /// What is measured. No default and no `all`: a request names the measurements /// it wants, and a shorthand that swept every operation against every metric @@ -358,10 +357,7 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { width, workers: args.workers.max(1), merge_shards: args.merge_shards, - merge_split: match args.merge_split.as_str() { - "interleaved" => MergeSplit::Interleaved, - _ => MergeSplit::Contiguous, - }, + merge_split: args.merge_split, comparator: args.comparator.clone(), runs: args.runs, warmup_runs: args.warmup_runs, @@ -444,6 +440,7 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { // and a record states what ran rather than what was asked for. if operation == Operation::Merge { report.bench.merge_shards = Some(args.merge_shards.max(MIN_MERGE_SHARDS)); + report.bench.merge_split = Some(args.merge_split); } reports.push(report); } diff --git a/aqpbm-cli/src/repeat.rs b/aqpbm-cli/src/repeat.rs index 19ae79e9..8a37f7c0 100644 --- a/aqpbm-cli/src/repeat.rs +++ b/aqpbm-cli/src/repeat.rs @@ -220,6 +220,7 @@ mod tests { accuracy: Some(serde_json::json!({"are_all": 0.01, "accuracy_runs": 5})), merge_folds_per_sec: Some(stats(mean * 0.5)), merge_shards: Some(4), + merge_split: None, merge_supported: Some(true), }); rec diff --git a/aqpbm-cli/src/rows/statistic.rs b/aqpbm-cli/src/rows/statistic.rs index cea3cbf4..ce35a7ef 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -352,10 +352,13 @@ where let (probes, score) = questions(ground_truth, &table)?; let items = materialise(description, table)?; // What the folds cut into shards: the stream itself, or reordered so the - // same cut deals it round-robin. + // same cut deals it round-robin. Copied only when a merge will use it. + let merging = want + .iter() + .any(|&(operation, _)| operation == Operation::Merge); let merged = match req.merge_split { - MergeSplit::Contiguous => items.clone(), - MergeSplit::Interleaved => Rc::new(interleave(&items, shards(req))), + MergeSplit::Interleaved if merging => Rc::new(interleave(&items, shards(req))), + _ => items.clone(), }; let mut bodies = Vec::with_capacity(want.len()); for &(operation, metric) in want { diff --git a/aqpbm-core/schema/merged_record.schema.json b/aqpbm-core/schema/merged_record.schema.json index 4b858a32..251d771e 100644 --- a/aqpbm-core/schema/merged_record.schema.json +++ b/aqpbm-core/schema/merged_record.schema.json @@ -100,7 +100,7 @@ "minimum": 0 }, "merge_accuracy": { - "description": "The same comparator as `query_accuracy`, against the same whole-stream\ntruth, scoring the sketch left by folding `merge_shards` contiguous\nshards. A linear sketch should match `query_accuracy` exactly." + "description": "The same comparator as `query_accuracy`, against the same whole-stream\ntruth, scoring the sketch left by folding `merge_shards` shards split\nas `merge_split` says. A linear sketch should match `query_accuracy`\nexactly under either split." }, "merge_cpu_time_ms": { "anyOf": [ @@ -147,6 +147,18 @@ "format": "uint", "minimum": 0 }, + "merge_split": { + "description": "How the stream was split into the `merge_shards` shards.", + "anyOf": [ + { + "$ref": "#/$defs/MergeSplit" + }, + { + "type": "null" + } + ], + "default": null + }, "merge_supported": { "type": [ "boolean", @@ -322,6 +334,7 @@ "merge_heap_allocated_kb", "merge_rss_peak_kb", "merge_shards", + "merge_split", "merge_supported", "merge_timestamp", "merge_wall_time_ms", @@ -694,6 +707,21 @@ "count" ] }, + "MergeSplit": { + "description": "How a merge run split the stream into its shards.", + "oneOf": [ + { + "description": "Each shard a consecutive stretch of the stream.", + "type": "string", + "const": "contiguous" + }, + { + "description": "Round-robin by record over the contiguous split's shard sizes, so each\nshard is a sample of the whole stream.", + "type": "string", + "const": "interleaved" + } + ] + }, "Mode": { "type": "string", "enum": [ diff --git a/aqpbm-core/src/benchmark_result/mod.rs b/aqpbm-core/src/benchmark_result/mod.rs index f9bcac0b..3fcf7932 100644 --- a/aqpbm-core/src/benchmark_result/mod.rs +++ b/aqpbm-core/src/benchmark_result/mod.rs @@ -11,7 +11,7 @@ pub use bench_report::BenchReport; pub use fold::MemoryMaxima; pub use schema::{ BenchSection, CpuTime, ExternalWorkload, InsertMetrics, Language, LatencySummary, MergeMetrics, - MergedRecord, Mode, PrepareMetrics, QueryMetrics, Record, RunStats, Source, + MergeSplit, MergedRecord, Mode, PrepareMetrics, QueryMetrics, Record, RunStats, Source, WorkloadDescription, SCHEMA_VERSION, }; pub use welford::Welford; diff --git a/aqpbm-core/src/benchmark_result/schema.rs b/aqpbm-core/src/benchmark_result/schema.rs index 6b644160..43bd4cd2 100644 --- a/aqpbm-core/src/benchmark_result/schema.rs +++ b/aqpbm-core/src/benchmark_result/schema.rs @@ -129,6 +129,30 @@ pub enum Source { CppBench, } +/// How a merge run split the stream into its shards. +#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum MergeSplit { + /// Each shard a consecutive stretch of the stream. + #[default] + Contiguous, + /// Round-robin by record over the contiguous split's shard sizes, so each + /// shard is a sample of the whole stream. + Interleaved, +} + +impl std::str::FromStr for MergeSplit { + type Err = String; + fn from_str(s: &str) -> Result { + match s { + "contiguous" => Ok(Self::Contiguous), + "interleaved" => Ok(Self::Interleaved), + other => Err(format!("unknown merge split '{other}'")), + } + } +} + /// MACRO (benchmark) section of a record. Every sub-field is /// `Option`al so N/A metrics don't pollute the JSON with zero /// placeholders. @@ -179,6 +203,11 @@ pub struct BenchSection { /// if the implementation turned out not to support merging. #[serde(skip_serializing_if = "Option::is_none")] pub merge_shards: Option, + /// How the stream was split into those shards. Present whenever merge was + /// measured; absent on records written before the field existed, which + /// all split contiguously. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub merge_split: Option, /// Present, and `true`, whenever a merge was measured. Never `false`: a row /// that provides no merge is refused where the closures are built, before anything /// is timed, so the gap shows up as an error naming the row rather than as a @@ -323,10 +352,14 @@ pub struct MergeMetrics { #[serde(default, skip_serializing_if = "Option::is_none")] pub merge_folds_per_sec: Option, pub merge_shards: Option, + /// How the stream was split into the `merge_shards` shards. + #[serde(default)] + pub merge_split: Option, pub merge_supported: Option, /// The same comparator as `query_accuracy`, against the same whole-stream - /// truth, scoring the sketch left by folding `merge_shards` contiguous - /// shards. A linear sketch should match `query_accuracy` exactly. + /// truth, scoring the sketch left by folding `merge_shards` shards split + /// as `merge_split` says. A linear sketch should match `query_accuracy` + /// exactly under either split. #[serde(rename = "merge_accuracy")] pub accuracy: Option, #[serde(rename = "merge_cpu_time_ms")] diff --git a/aqpbm-core/src/lib.rs b/aqpbm-core/src/lib.rs index b104f323..053a0ccf 100644 --- a/aqpbm-core/src/lib.rs +++ b/aqpbm-core/src/lib.rs @@ -25,8 +25,8 @@ pub use atomic_costs::{ }; pub use benchmark_result::{ BenchReport, BenchSection, CpuTime, ExternalWorkload, InsertMetrics, LatencySummary, - MergeMetrics, MergedRecord, Mode, PrepareMetrics, QueryMetrics, Record, RunStats, Source, - WorkloadDescription, SCHEMA_VERSION, + MergeMetrics, MergeSplit, MergedRecord, Mode, PrepareMetrics, QueryMetrics, Record, RunStats, + Source, WorkloadDescription, SCHEMA_VERSION, }; pub use erp::{ erp_artifact, erp_record, ErpArtifact, ErpRecord, ErpResourceProfile, ERP_SCHEMA_VERSION, diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 2ccd7250..7cd0db7d 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -294,6 +294,11 @@ mod tests { } } + /// The tightest of the three: on this stream it passes from `BETA` about + /// 4.8, so 8 leaves less than 2x, and it fails with `BETA = 0` or `eps = 0`. + /// A wider cell does not buy slack: at `cell_cols` 1024 the worst group + /// needs `BETA` about 14, because `eps` shrinks while the colliders' share + /// of the error does not. #[test] fn hydra_cs_within_its_bound() { let items = records(N); diff --git a/sketch-bench/src/wrappers/mod.rs b/sketch-bench/src/wrappers/mod.rs index 343730ec..49e2049c 100644 --- a/sketch-bench/src/wrappers/mod.rs +++ b/sketch-bench/src/wrappers/mod.rs @@ -148,16 +148,9 @@ pub fn partition(items: &[T], n: usize) -> Vec<&[T]> { items.chunks(chunk).collect() } -/// How a merge run splits the stream into its shards. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum MergeSplit { - /// Each shard a stretch of the stream, as [`partition`] cuts it. - #[default] - Contiguous, - /// Round-robin by record, so each shard is a sample of the whole stream: - /// the stream is first reordered by [`interleave`]. - Interleaved, -} +/// How a merge run splits the stream into its shards: `Contiguous` as +/// [`partition`] cuts it, `Interleaved` reordered first by [`interleave`]. +pub use aqpbm_core::MergeSplit; /// The stream reordered so that [`partition`] into `n` hands out a round-robin /// split: record `j` goes to the next shard with room, so each shard holds