diff --git a/README.md b/README.md index b4e58fc0..d24ed43a 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": { @@ -447,6 +448,20 @@ 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. 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. + **`--flat`**: flatten record such that output data of multiple experiments is flatten into one json file. **`--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`. diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index 65e02ee4..1caa964a 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; @@ -234,6 +236,18 @@ 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 = clap::builder::PossibleValuesParser::new(["contiguous", "interleaved"]) + .try_map(|s| s.parse::()), + help_heading = "Measurement content" + )] + pub merge_split: MergeSplit, /// Which label columns the `hydra-*` rows group by, comma-separated /// indices into the columns before the value column: any non-empty subset /// (`0`, `1`, `0,1`). The grid stores every subset, so this picks the one diff --git a/aqpbm-cli/src/flatten_record.rs b/aqpbm-cli/src/flatten_record.rs index 00076d05..921b24ec 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, @@ -424,6 +432,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 750b7c3b..2cd85e4b 100644 --- a/aqpbm-cli/src/main.rs +++ b/aqpbm-cli/src/main.rs @@ -374,6 +374,7 @@ fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { width, workers: args.workers.max(1), merge_shards: args.merge_shards, + merge_split: args.merge_split, group_columns, per_group_out: args.per_group_out.as_ref().map(std::path::PathBuf::from), comparator: args.comparator.clone(), @@ -458,6 +459,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 4ebcec1f..d90aaf63 100644 --- a/aqpbm-cli/src/repeat.rs +++ b/aqpbm-cli/src/repeat.rs @@ -222,6 +222,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/mod.rs b/aqpbm-cli/src/rows/mod.rs index f1937bfc..f3b8ac5c 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 232dfff0..5a2eaced 100644 --- a/aqpbm-cli/src/rows/statistic.rs +++ b/aqpbm-cli/src/rows/statistic.rs @@ -400,6 +400,7 @@ pub(super) fn scored_row( prepare: Option>, ) -> Result where + I: Clone, G: GroundTruth + 'static, G::Truth: 'static, G::Probe: 'static, @@ -411,6 +412,15 @@ where None => score, }; let items = materialise(description, table)?; + // What the folds cut into shards: the stream itself, or reordered so the + // 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::Interleaved if merging => Rc::new(interleave(&items, shards(req))), + _ => items.clone(), + }; let mut bodies = Vec::with_capacity(want.len()); for &(operation, metric) in want { let n = passes(req, metric); @@ -432,7 +442,7 @@ where (Operation::Merge, Metric::Accuracy) => answered( merge.expect(SUPPORTED).2( &req.params, - items.clone(), + merged.clone(), probes.clone(), shards(req), n, @@ -442,11 +452,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/aqpbm-core/schema/merged_record.schema.json b/aqpbm-core/schema/merged_record.schema.json index dd09e6e3..eeb150a3 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", @@ -712,6 +725,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 84472aab..1ce5a7df 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/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 478bfc1f..67d89371 100644 --- a/sketch-bench/src/request.rs +++ b/sketch-bench/src/request.rs @@ -122,6 +122,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, /// The label columns a grouped (`hydra-*`) row asks and scores, ascending pub group_columns: Vec, /// Where a grouped row writes each scored group's error, if anywhere diff --git a/sketch-bench/src/wrappers/hydra_shared.rs b/sketch-bench/src/wrappers/hydra_shared.rs index 5f1c3d47..71d0033f 100644 --- a/sketch-bench/src/wrappers/hydra_shared.rs +++ b/sketch-bench/src/wrappers/hydra_shared.rs @@ -101,3 +101,305 @@ 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(|p| Some(p.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: &[Option]) -> bool { + key.split(';') + .zip(group) + .all(|(a, b)| b.as_deref().is_none_or(|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: &[Option]) -> 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}"); + } + } + + /// 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); + 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: &[Option]| 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..49e2049c 100644 --- a/sketch-bench/src/wrappers/mod.rs +++ b/sketch-bench/src/wrappers/mod.rs @@ -148,6 +148,29 @@ pub fn partition(items: &[T], n: usize) -> Vec<&[T]> { items.chunks(chunk).collect() } +/// 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 +/// 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 +255,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()); + } +}