diff --git a/crates/accuracy/src/guarantee/hll/mod.rs b/crates/accuracy/src/guarantee/hll/mod.rs index 62db84dc7..2b4e13967 100644 --- a/crates/accuracy/src/guarantee/hll/mod.rs +++ b/crates/accuracy/src/guarantee/hll/mod.rs @@ -37,6 +37,38 @@ pub(super) fn guarantee( }) } +/// HLL's guarantee at `precision` over groups of at most +/// `max_distinct_per_group` distinct items per evaluation, when its sparse +/// state holds them all: the state is the set of distinct 64-bit item +/// hashes while it holds at most `m/8` of them (`m = 2^precision`; +/// `asap_sketchlib::HyperLogLogSparse`), and merging states keeps the +/// union, so its count is exact unless two of the `n` item hashes collide: +/// relative error 0, failing with probability at most `n(n − 1) / 2^65` +/// (the `n(n − 1)/2` pairs, each colliding with probability `2^-64`). +/// `None` above `m/8`. +/// +/// Example: precision 16 (`m/8` = 8,192) over at most 7,200 distinct items +/// per host fails with probability at most 1.4e-12; precision 15 (4,096) +/// certifies nothing. +pub(super) fn sparse_exact_guarantee( + precision: u8, + max_distinct_per_group: u64, +) -> Option { + let sparse_threshold = 1u64.checked_shl(u32::from(precision))? / 8; + if max_distinct_per_group > sparse_threshold { + return None; + } + let n = max_distinct_per_group as f64; + let collision_probability = n * (n - 1.0).max(0.0) / 2f64.powi(65); + Some(super::bounded_guarantee( + AccuracyMetric::Relative, + 0.0, + ProbabilityExpr::Constant { + value: collision_probability, + }, + )) +} + /// HLL's relative standard error, `1.04 / √m` for `m = 2^precision` buckets. fn relative_standard_error(precision: u8) -> f64 { 1.04 / 2f64.powi(i32::from(precision)).sqrt() diff --git a/crates/accuracy/src/guarantee/mod.rs b/crates/accuracy/src/guarantee/mod.rs index c26786881..a84d57d15 100644 --- a/crates/accuracy/src/guarantee/mod.rs +++ b/crates/accuracy/src/guarantee/mod.rs @@ -90,6 +90,28 @@ pub(crate) fn guarantee_before_failure_probability_check( ) } +/// The guarantee of a distinct count (`statistic`) read from a state with +/// `parameters` that is exact while each state holds few distinct items, +/// over groups of at most `max_distinct_per_group()` distinct items per +/// evaluation (`Memo::max_distinct_per_group_per_evaluation`, computed only +/// for such a state): HLL's sparse state, exact up to a 64-bit hash +/// collision at every precision whose sparse threshold `2^precision / 8` +/// is at least the bound ([`hll::sparse_exact_guarantee`]). It holds down +/// to a collision's failure probability, so it is checked before a +/// measured or theoretical guarantee. `None` without the bound, above the +/// threshold, or for any other state or statistic. +pub(crate) fn sparse_exact_guarantee( + parameters: &SketchParams, + statistic: &SketchStatistic, + max_distinct_per_group: impl FnOnce() -> Option, +) -> Option { + let (SketchParams::Hll { precision }, SketchStatistic::Cardinality) = (parameters, statistic) + else { + return None; + }; + hll::sparse_exact_guarantee(*precision, max_distinct_per_group()?) +} + /// The guarantee of an error at most `bound` in `metric`, failing with /// probability at most `failure_probability`. fn bounded_guarantee( diff --git a/crates/accuracy/src/guarantee/tests.rs b/crates/accuracy/src/guarantee/tests.rs index 4becf0028..87476c601 100644 --- a/crates/accuracy/src/guarantee/tests.rs +++ b/crates/accuracy/src/guarantee/tests.rs @@ -137,3 +137,33 @@ fn a_ddsketch_quantile_is_certified_only_over_values_of_one_sign() { assert_eq!(before_check.spec.accuracy_metric, AccuracyMetric::Relative); } } + +/// HLL's sparse state is the set of distinct item hashes while it holds at +/// most `m/8` of them, so over groups declared to hold at most that many +/// distinct items per evaluation its count is exact but for a 64-bit hash +/// collision: relative error 0, failing with probability at most +/// `n(n − 1) / 2^65`. One item more than `m/8` (or no bound, a state other +/// than HLL, or a statistic other than the distinct count) certifies +/// nothing. +#[test] +fn hll_is_exact_while_the_group_bound_keeps_it_sparse() { + let p16 = SketchParams::Hll { precision: 16 }; + let distinct = SketchStatistic::Cardinality; + let threshold = (1u64 << 16) / 8; + let guarantee = sparse_exact_guarantee(&p16, &distinct, || Some(threshold)) + .expect("8,192 distinct items keep a precision-16 state sparse"); + assert_eq!(guarantee.spec.accuracy_metric, AccuracyMetric::Relative); + assert_eq!(guarantee.spec.error.evaluate(), Some(0.0)); + let collision = (threshold * (threshold - 1)) as f64 / 2f64.powi(65); + let delta = guarantee.spec.failure_probability.evaluate().unwrap(); + assert!(delta > 0.0 && delta <= collision * (1.0 + 1e-9), "{delta}"); + assert!(delta < 5e-6, "below a δ split over 10,000 hosts: {delta}"); + assert!(sparse_exact_guarantee(&p16, &distinct, || Some(threshold + 1)).is_none()); + assert!(sparse_exact_guarantee(&p16, &distinct, || None).is_none()); + let p15 = SketchParams::Hll { precision: 15 }; + assert!(sparse_exact_guarantee(&p15, &distinct, || Some(7_200)).is_none()); + let k = SketchParams::Kmv { k: 4323 }; + assert!(sparse_exact_guarantee(&k, &distinct, || Some(1)).is_none()); + let entropy = SketchStatistic::FrequencyEntropy; + assert!(sparse_exact_guarantee(&p16, &entropy, || Some(1)).is_none()); +} diff --git a/crates/accuracy/src/logical_edge/mod.rs b/crates/accuracy/src/logical_edge/mod.rs index 9036f1aef..b99d05cef 100644 --- a/crates/accuracy/src/logical_edge/mod.rs +++ b/crates/accuracy/src/logical_edge/mod.rs @@ -12,7 +12,8 @@ use asap_types::stages::{ use asap_types::summary_type::{MergedError, SketchParams, SketchStatistic, SummaryTypeCapability}; use crate::guarantee::{ - guarantee_before_failure_probability_check, holds_at_failure_probability, theoretical_guarantee, + guarantee_before_failure_probability_check, holds_at_failure_probability, + sparse_exact_guarantee, theoretical_guarantee, }; use crate::readout::sketch_readout; use crate::{AccuracyEvidence, ErrorMetricsOfMemo}; @@ -54,8 +55,10 @@ impl ErrorMetricsOfMemo { /// guarantee's failure probability is unknown, as HLL's), and the /// guarantee of the producer's θ for the readout's statistic, at the /// required failure probability, is within the required error - /// ([`within_limit`]) and in its metric: the deployment's measurement - /// (`evidence`) when it has one, else the theoretical guarantee over + /// ([`within_limit`]) and in its metric: HLL's sparse-exact guarantee + /// over the declared per-group distinct bound + /// ([`sparse_exact_guarantee`]), else the deployment's + /// measurement (`evidence`) when it has one, else the theoretical guarantee over /// the sign of the state's values (`GroupProperties::state_column_sign`, /// DDSketch's sign condition) and, for a distinct count, the scanned /// sources' declared distinct bound @@ -121,8 +124,15 @@ impl ErrorMetricsOfMemo { } let required = consumer_candidate.input_requirements[input].required_accuracy; let failure_probability = required.map_or(1.0, |required| required.failure_probability); - let measured = - evidence.measured_guarantee(summary_type, parameters, statistic, failure_probability); + let measured = exact_or_measured_guarantee( + memo, + summary_input, + summary_type, + parameters, + statistic, + failure_probability, + evidence, + ); let allowed = self.error_metrics_allowed_on_input_edge(consumer, input); // The theoretical guarantee before its failure-probability check, // computed once for both checks below, over the sign of the values @@ -189,9 +199,10 @@ impl ErrorMetricsOfMemo { /// Whether a state of `summary_type` built with `parameters` meets readout /// level `required` for `statistic`, as the edge from the build checks it /// ([`ErrorMetricsOfMemo::edge_meets_logical_requirements`]): its guarantee -/// at the required failure probability (`evidence`'s measurement, else the -/// theoretical one over the sign and distinct bound of the state group -/// `summary_input`) is in the required metric and within the required +/// at the required failure probability (HLL's sparse-exact one over the +/// state group `summary_input`'s per-group distinct bound, else +/// `evidence`'s measurement, else the theoretical one over the sign and +/// distinct bound of that group) is in the required metric and within the required /// error. A KLL build of k = 1404 meets rank error 0.0025 at δ = 0.01, not /// at δ = 0.00125. pub(crate) fn build_meets_level( @@ -203,28 +214,56 @@ pub(crate) fn build_meets_level( required: RequiredAccuracy, evidence: &dyn AccuracyEvidence, ) -> bool { - let guarantee = evidence - .measured_guarantee( + let guarantee = exact_or_measured_guarantee( + memo, + summary_input, + summary_type, + parameters, + statistic, + required.failure_probability, + evidence, + ) + .or_else(|| { + theoretical_guarantee( summary_type, parameters, statistic, required.failure_probability, + memo.groups()[summary_input.0 as usize] + .group_properties + .state_column_sign(), + memo.max_distinct_per_evaluation(summary_input), ) - .or_else(|| { - theoretical_guarantee( - summary_type, - parameters, - statistic, - required.failure_probability, - memo.groups()[summary_input.0 as usize] - .group_properties - .state_column_sign(), - memo.max_distinct_per_evaluation(summary_input), - ) - }); + }); guarantee_meets(guarantee.as_ref(), required) } +/// The guarantee of θ that takes precedence over its theoretical one, at +/// `failure_probability`: a state exact over the per-group distinct bound +/// declared for the state group `summary_input` (HLL's sparse state, +/// [`sparse_exact_guarantee`]) when it fails at most that rarely, else the +/// deployment's measurement (`evidence`). A measured table records failure +/// probabilities only down to 3 / trials; the sparse-exact guarantee holds +/// down to a hash collision's (about 1e-12), so it serves a target whose δ +/// is split over many values (0.05 over 10,000 hosts is 5e-6 each). +fn exact_or_measured_guarantee( + memo: &Memo, + summary_input: MemoGroupId, + summary_type: &FieldDataType, + parameters: &SketchParams, + statistic: &SketchStatistic, + failure_probability: f64, + evidence: &dyn AccuracyEvidence, +) -> Option { + sparse_exact_guarantee(parameters, statistic, || { + memo.max_distinct_per_group_per_evaluation(summary_input) + }) + .filter(|guarantee| holds_at_failure_probability(guarantee, failure_probability)) + .or_else(|| { + evidence.measured_guarantee(summary_type, parameters, statistic, failure_probability) + }) +} + /// Whether `guarantee`, a θ's at the required failure probability, meets /// `required`: in its metric, with an error within its error. fn guarantee_meets(guarantee: Option<&AccuracyGuarantee>, required: RequiredAccuracy) -> bool { diff --git a/crates/frontend-sil/src/lib.rs b/crates/frontend-sil/src/lib.rs index f0236d29d..f404eced3 100644 --- a/crates/frontend-sil/src/lib.rs +++ b/crates/frontend-sil/src/lib.rs @@ -54,7 +54,8 @@ pub struct IntentQuery { pub sql_template: String, /// Each hole reading a variable, in text order (`$now` is not one). pub holes: Vec, - /// `REQUIRE EXACT` or `REQUIRE ERROR m <= ε [DELTA δ]`. + /// `REQUIRE EXACT` or `REQUIRE ERROR m <= ε [DELTA δ] [SCOPE scope]` + /// (`per_value` or the default `whole_result`). pub accuracy: AccuracyTarget, /// `LATENCY <= d`, in milliseconds; `None` when not given. pub max_latency_ms: Option, diff --git a/crates/frontend-sil/src/parse.rs b/crates/frontend-sil/src/parse.rs index 5b361ab57..9ac618d8c 100644 --- a/crates/frontend-sil/src/parse.rs +++ b/crates/frontend-sil/src/parse.rs @@ -7,6 +7,7 @@ //! sql REQUIRE accuracy [ ',' LATENCY '<=' duration ] //! binder ::= '$' name | '_' //! accuracy::= EXACT | ERROR (abs | rel | rank) '<=' number [ DELTA number ] +//! [ SCOPE (per_value | whole_result) ] //! group ::= GROUP '(' id (',' id)* ')' LATENCY '<=' duration //! duration::= number ('ms' | 's' | 'm' | 'h') //! ``` @@ -17,7 +18,7 @@ use std::collections::{BTreeMap, BTreeSet}; -use asap_types::accuracy::{AccuracyMetric, AccuracyTarget}; +use asap_types::accuracy::{AccuracyMetric, AccuracyScope, AccuracyTarget}; use crate::lex::{statement_ends, tokens, Token, TokenKind, COMPARISONS}; use crate::{Hole, HolePosition, Intent, IntentGroupLatencyBound, IntentQuery, SilError}; @@ -281,6 +282,11 @@ fn parse_require(statement: &str, toks: &[Token]) -> Result<(AccuracyTarget, Opt .map_err(|_| format!("{text} is not a number")) }; let (accuracy, rest) = match texts.as_slice() { + [exact, scope, ..] + if exact.eq_ignore_ascii_case("EXACT") && scope.eq_ignore_ascii_case("SCOPE") => + { + return Err("EXACT takes no SCOPE: its failure probability is 0".into()); + } [exact, rest @ ..] if exact.eq_ignore_ascii_case("EXACT") => { (AccuracyTarget::exact(), rest) } @@ -292,14 +298,31 @@ fn parse_require(statement: &str, toks: &[Token]) -> Result<(AccuracyTarget, Opt other => return Err(format!("unknown error metric {other} (abs, rel, rank)")), }; let target = AccuracyTarget::max_error(number(epsilon)?).accuracy_metric(metric); - match rest { + let (target, rest) = match rest { [delta, value, rest @ ..] if delta.eq_ignore_ascii_case("DELTA") => { (target.failure_probability(number(value)?), rest) } rest => (target, rest), + }; + // The values one (ε, δ) statement covers: each value separately, + // or the whole result (the default, δ split over its values). + match rest { + [scope, name, rest @ ..] if scope.eq_ignore_ascii_case("SCOPE") => { + let scope = match name.to_ascii_lowercase().as_str() { + "per_value" => AccuracyScope::PerValue, + "whole_result" => AccuracyScope::WholeResult, + other => { + return Err(format!( + "unknown accuracy scope {other} (per_value, whole_result)" + )) + } + }; + (target.accuracy_scope(scope), rest) + } + rest => (target, rest), } } - _ => return Err("expected EXACT or ERROR metric <= ε [DELTA δ]".into()), + _ => return Err("expected EXACT or ERROR metric <= ε [DELTA δ] [SCOPE scope]".into()), }; let latency = match rest { [] => None, diff --git a/crates/frontend-sil/tests/sil.rs b/crates/frontend-sil/tests/sil.rs index 640ca8983..1e058f439 100644 --- a/crates/frontend-sil/tests/sil.rs +++ b/crates/frontend-sil/tests/sil.rs @@ -5,7 +5,7 @@ use std::collections::BTreeMap; use asap_frontend_sil::{parse_intents, HolePosition, Intent, SilError}; -use asap_types::accuracy::{AccuracyMetric, AccuracyTarget}; +use asap_types::accuracy::{AccuracyMetric, AccuracyScope, AccuracyTarget}; /// The contract's two-query drill-down: q1 binds the top hosts, q2 counts /// users over them. @@ -256,6 +256,55 @@ fn rejects_bad_rates_when_without_rate_and_bad_groups() { assert!(matches!(error(&text), SilError::InvalidGroup { .. })); } +/// `SCOPE per_value` states the guarantee for each grouped value +/// separately (no failure probability split over the values); +/// `SCOPE whole_result` is the default written out. Any other scope, or a +/// scope on `EXACT` (whose δ is 0 whatever the scope), is a syntax error. +#[test] +fn parses_the_accuracy_scope() { + let accuracy = |require: &str| { + one(&intent(&format!( + "q1: SELECT host, count(DISTINCT dst) FROM flows GROUP BY host REQUIRE {require};" + ))) + .queries[0] + .accuracy + .clone() + }; + let target = AccuracyTarget::max_error(0.05) + .failure_probability(0.05) + .accuracy_metric(AccuracyMetric::Relative); + assert_eq!( + accuracy("ERROR rel <= 0.05 DELTA 0.05 SCOPE per_value, LATENCY <= 1000ms"), + target.clone().accuracy_scope(AccuracyScope::PerValue) + ); + assert_eq!( + accuracy("ERROR rel <= 0.05 DELTA 0.05 scope PER_VALUE"), + target.clone().accuracy_scope(AccuracyScope::PerValue) + ); + assert_eq!( + accuracy("ERROR rel <= 0.05 DELTA 0.05 SCOPE whole_result"), + target + ); + assert_eq!(accuracy("ERROR rel <= 0.05 DELTA 0.05"), target); + assert_eq!( + accuracy("ERROR rel <= 0.05 SCOPE per_value"), + AccuracyTarget::max_error(0.05) + .accuracy_metric(AccuracyMetric::Relative) + .accuracy_scope(AccuracyScope::PerValue) + ); + for bad in [ + "ERROR rel <= 0.05 DELTA 0.05 SCOPE per_group", + "ERROR rel <= 0.05 DELTA 0.05 SCOPE", + "EXACT SCOPE per_value", + "ERROR rel <= 0.05 SCOPE per_value DELTA 0.05", + ] { + let text = intent(&format!( + "q1: SELECT host, count(DISTINCT dst) FROM flows GROUP BY host REQUIRE {bad};" + )); + assert!(matches!(error(&text), SilError::Syntax { .. }), "{bad}"); + } +} + #[test] fn rejects_a_duplicate_query_id() { assert!(matches!( diff --git a/crates/integration-tests/tests/hll_distinct_ingest.rs b/crates/integration-tests/tests/hll_distinct_ingest.rs index ea7bcde7e..40a6bcc33 100644 --- a/crates/integration-tests/tests/hll_distinct_ingest.rs +++ b/crates/integration-tests/tests/hll_distinct_ingest.rs @@ -642,3 +642,84 @@ fn ranked_distinct_keeps_estimates() { ); } } + +// --------------------------------------------------------------------------- +// A declared per-host distinct bound: HLL's sparse state exact +// --------------------------------------------------------------------------- + +/// The E6 x1 facts with `flows` declaring at most 7,200 distinct values per +/// host per evaluation (one row every 500 ms for 1 h). +fn e6_x1_sources_with_host_bound() -> Value { + let mut sources = e6_x1_sources(); + sources["flows"]["max_distinct_per_group_per_evaluation"] = json!({"host": 7200}); + sources +} + +/// The least precision whose sparse state holds 7,200 distinct items: +/// m/8 = 8,192 at 16. +const SPARSE_EXACT_PRECISION: u8 = 16; + +/// W1 over the whole result (δ 0.05 split over 10,000 hosts) with the +/// per-host bound declared. +fn w1_whole_result_with_host_bound() -> PlanningWorkload { + workload( + sql(), + &[(W1, 10_000)], + (0.05, 0.05, WHOLE_RESULT), + 30_000.0, + e6_x1_sources_with_host_bound(), + ) +} + +/// The kept Pass 1 θ of W1's `SummaryAgg HLL` group in `pass2`. +fn kept_hll_thetas(pass2: &str) -> Vec<&str> { + group_block(pass2, "SummaryAgg HLL") + .lines() + .filter(|line| line.contains("Pass1") && line.contains("SummaryAgg HLL <-")) + .filter(|line| !line.contains("pruned") && line.contains("θ=")) + .collect() +} + +/// Over the whole result each host's δ is 0.05 / 10,000 = 5e-6, below the +/// table's smallest δ (0.005): without a per-host bound Pass 2 keeps no HLL +/// θ (today's behaviour). +#[test] +fn whole_result_keeps_no_hll_without_a_host_bound() { + let text = stages_text(&w1_over(WHOLE_RESULT), RunUntil::Pass2); + let hll = group_block(section(&text, PASS2), "SummaryAgg HLL"); + assert!(hll.contains("0 kept"), "{hll}"); +} + +/// With at most 7,200 distinct values per host declared, HLL's sparse state +/// is exact (up to a 64-bit hash collision) from precision 16, so Pass 2 +/// keeps precision 16 over the whole result, without the δ split's +/// measurement. +#[test] +fn host_bound_keeps_sparse_exact_hll_over_the_whole_result() { + let text = stages_text(&w1_whole_result_with_host_bound(), RunUntil::Pass2); + let kept = kept_hll_thetas(section(&text, PASS2)); + assert_eq!(kept.len(), 1, "{text}"); + assert!( + kept[0].contains(&hll_theta(SPARSE_EXACT_PRECISION)), + "{kept:?}" + ); +} + +/// End to end: with the per-host bound the selected plan reads W1's count +/// from HLL at precision 16 (built at query time or kept at ingestion +/// time, whichever its HLL pricing makes cheaper), and its predicted cost +/// is below exact's over raw data (alternative (a)). +#[test] +fn host_bound_selects_sparse_exact_hll_over_exact() { + let w = w1_whole_result_with_host_bound(); + let (exact, _) = selected_cost(&w, &forced('a')).unwrap(); + let (chosen, text) = selected_cost(&w, &capabilities(true, without_other_sketches())).unwrap(); + let stage3 = section(&text, "Stage 3 output"); + assert!( + stage3 + .lines() + .any(|line| line.contains("HLL") && line.contains(&hll_theta(SPARSE_EXACT_PRECISION))), + "{stage3}" + ); + assert!(chosen < exact, "chosen {chosen} vs exact {exact}"); +} diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index 2c09229e6..344f8a017 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -20,6 +20,7 @@ use asap_types::ir::schema::{DataType, Field, Schema}; use asap_types::ir::{NonASAPOp, Operator, OperatorNode}; use asap_types::plan::physical_asap_dag::PhysicalASAPDAG; use asap_types::stages::Lifetime; +use asap_types::summary_type::SketchParams; use asap_types::workload::{DataWorkload, QueryRecurrence, RepeatedDemand, RepetitionInterval}; /// `(ts, host, user, dst, bytes)`. @@ -847,3 +848,116 @@ async fn drill_intent_keeps_hll_at_ingestion_per_mode() { .expect("the executor compiles the full plan"); } } + +// --------------------------------------------------------------------------- +// HLL kept for a distinct count per host at the E6 drill's target (rel 0.05, +// δ 0.05): over the whole result the δ splits over 10,000 hosts (5e-6 per +// host), below every measured failure probability, unless the source +// declares a per-host distinct bound that keeps HLL's sparse state exact; +// over each value (`SCOPE per_value`) each host gets δ 0.05. +// --------------------------------------------------------------------------- + +/// q1 of the drill without its ranking: the distinct `dst` per host over +/// 1 h, at rel 0.05 δ 0.05 over `scope` (`""` for the default). +fn per_host_distinct(scope: &str) -> String { + format!( + "q1: SELECT host, count(DISTINCT dst) AS c FROM flows + WHERE ts > $now - INTERVAL '1 hour' GROUP BY host + REQUIRE ERROR rel <= 0.05 DELTA 0.05{scope}, LATENCY <= 1000ms;" + ) +} + +/// The E6 x1 `flows` facts: 10,000 hosts each sampled every 500 ms (7,200 +/// rows per host in 1 h), at most 100,000 distinct values per evaluation, +/// and `per_host_bound` (`max_distinct_per_group_per_evaluation` for +/// `host`) when given. +fn e6_flows(per_host_bound: Option) -> DataWorkload { + let mut flows = serde_json::json!({"series_count": 10_000, "sample_interval": 500, + "distinct_values_per_label": {"host": 10_000}, "rows_held": 72_000_000, + "max_distinct_per_evaluation": 100_000}); + if let Some(bound) = per_host_bound { + flows["max_distinct_per_group_per_evaluation"] = serde_json::json!({"host": bound}); + } + serde_json::from_value(serde_json::json!({ + "arrival": {"ingesting": {"rows_per_second": 20_000.0, "max_out_of_order_ms": 2000}}, + "sources": {"flows": flows}, + })) + .unwrap() +} + +/// HLL's measured per-value accuracy (`accuracy/measured/hll_distinct.json`). +fn measured_hll() -> asap_planner::MeasuredSketchAccuracy { + asap_planner::MeasuredSketchAccuracy::from_json(include_str!( + "../../accuracy/measured/hll_distinct.json" + )) + .unwrap() +} + +/// `queries` planned query at a time with HLL's measured accuracy. +async fn planned_measured(queries: &str, data: &DataWorkload) -> (IntentPlan, f64) { + let intents = parse_intents(&intent_text(queries)).expect("a well-formed intent"); + let measured = measured_hll(); + let (plan, report) = plan_intents( + &intents, + &catalog(), + data, + PlanningModels::builtin().with_evidence(&measured), + &IntentPlanningOptions::default(), + ) + .await + .expect("the intent plans"); + (plan, report.cost_per_second.expect("cost model 1")) +} + +/// The precisions of the HLL states `query_id` reads, built at query time +/// or kept at ingestion time (whichever the HLL pricing makes cheaper). +fn hll_precisions_read(planned: &IntentPlan, query_id: &str) -> BTreeSet { + let q = round_query_of(planned, query_id); + let dag = &planned.plan.dag; + reached(dag, dag.roots[q.query_index]) + .into_iter() + .filter_map(|n| match n.parameters { + Some(SketchParams::Hll { precision }) => Some(precision), + _ => None, + }) + .collect() +} + +/// Without a per-host bound or a per-value scope, the whole-result δ 0.05 +/// over 10,000 hosts is 5e-6 per host, below the measured table's smallest +/// δ: no HLL precision is certified, and q1 reads no HLL state. +#[tokio::test] +async fn per_host_distinct_over_the_whole_result_reads_no_hll() { + let (planned, _) = planned_measured(&per_host_distinct(""), &e6_flows(None)).await; + assert!(hll_precisions_read(&planned, "q1").is_empty()); +} + +/// With at most 7,200 distinct `dst` per host declared, HLL's sparse state +/// is exact from precision 16 (m/8 = 8,192 ≥ 7,200), so q1 reads a +/// per-host HLL state at precision 16 over the whole result, at a lower +/// predicted cost than the plan without the bound. +#[tokio::test] +async fn per_host_bound_keeps_sparse_exact_hll() { + let (_, unbounded_cost) = planned_measured(&per_host_distinct(""), &e6_flows(None)).await; + let (planned, cost) = planned_measured(&per_host_distinct(""), &e6_flows(Some(7_200))).await; + assert_eq!(hll_precisions_read(&planned, "q1"), BTreeSet::from([16])); + assert!( + cost < unbounded_cost, + "{cost} vs {unbounded_cost} unbounded" + ); +} + +/// With `SCOPE per_value` each host's count gets δ 0.05: q1 reads a +/// per-host HLL state at the least precision measured to meet rel 0.05 at +/// δ 0.05 (13), at a lower predicted cost than over the whole result. +#[tokio::test] +async fn scope_per_value_keeps_measured_hll() { + let (_, whole_result_cost) = planned_measured(&per_host_distinct(""), &e6_flows(None)).await; + let (planned, cost) = + planned_measured(&per_host_distinct(" SCOPE per_value"), &e6_flows(None)).await; + assert_eq!(hll_precisions_read(&planned, "q1"), BTreeSet::from([13])); + assert!( + cost < whole_result_cost, + "{cost} vs {whole_result_cost} whole result" + ); +} diff --git a/crates/types/src/stages/logical/memo/mod.rs b/crates/types/src/stages/logical/memo/mod.rs index 95cbb40ef..5dc90e8d9 100644 --- a/crates/types/src/stages/logical/memo/mod.rs +++ b/crates/types/src/stages/logical/memo/mod.rs @@ -349,6 +349,42 @@ impl Memo { ) } + /// The most distinct items one state (one group) of the distinct-count + /// summary `group` counts in one evaluation, from the per-group bounds + /// the data workload declares + /// (`SourceFacts::max_distinct_per_group_per_evaluation`): the smallest + /// bound the scanned source declares for one of the summary's keys. + /// `None` unless the summary's rows come from one scan of one source + /// (through operators of one input each: no join, union or binary + /// operator, whose rows pair or mix rows the bound says nothing about), + /// and when the source declares no bound for any key or a key is not a + /// source column (a per-series value, a computed key or a time). + /// + /// Example: `SELECT host, count(DISTINCT dst) FROM flows GROUP BY host` + /// with `flows` declaring `{"host": 7200}` gives 7,200 for the + /// `SummaryAgg` group; `GROUP BY dst`, or a self-join grouped by one + /// side's `host`, gives `None`. + pub fn max_distinct_per_group_per_evaluation(&self, group: MemoGroupId) -> Option { + let (KeysOfValues::SourceColumns(keys), input) = self.keys_of_values(group)? else { + return None; + }; + let mut below = input; + let source = loop { + let input_group = &self.groups[below.0 as usize]; + match input_group.expression.children().as_slice() { + [] => break input_group.group_properties.scanned_sources.first()?, + [child] => below = **child, + _ => return None, + } + }; + let (facts, _) = series_facts(&self.source_facts, source_name(source))?; + keys.iter() + .filter(|key| &key.source == source) + .filter_map(|key| facts.max_distinct_per_group_per_evaluation.get(&key.column)) + .min() + .copied() + } + /// What the values of `group` are keyed by, and the group of rows they /// are computed from ([`Self::max_values_per_evaluation`]): the keys of /// the state it is, or reads, or of the aggregate it is, and that diff --git a/crates/types/src/stages/logical/memo/tests.rs b/crates/types/src/stages/logical/memo/tests.rs index 287275140..caf51e0f1 100644 --- a/crates/types/src/stages/logical/memo/tests.rs +++ b/crates/types/src/stages/logical/memo/tests.rs @@ -577,6 +577,85 @@ fn max_distinct_per_evaluation_sums_the_scanned_sources_bounds() { assert_eq!(memo.max_distinct_per_evaluation(both), Some(10_000)); } +/// A distinct count's per-group bound comes from the label its groups are +/// keyed by: over `flows` declaring at most 7,200 distinct items per +/// `host`, a state by `host` (or by `host` and `dst`) counts at most 7,200 +/// per state; by `dst` alone, over everything, or over a self-join of +/// `flows` (whose paired rows the bound says nothing about), no bound. +#[test] +fn max_distinct_per_group_per_evaluation_reads_the_grouping_label() { + use crate::ir::schema::DataType; + let data = crate::workload::DataWorkload { + sources: [( + "flows".to_string(), + crate::workload::SourceFacts { + max_distinct_per_group_per_evaluation: [("host".to_string(), 7_200)].into(), + ..Default::default() + }, + )] + .into(), + ..Default::default() + }; + let mut memo = Memo::new(&data); + // `flows(ts, value, host, dst)`, a SQL table (which a join reads). + let field = |name: &str, dtype| crate::ir::schema::Field::plain(name, dtype, false); + let flows = memo + .find_or_add_group(Operator::NonASAP(NonASAPOp::Scan { + source: Source::Table { + table_ref: "flows".into(), + }, + predicates: vec![], + schema: crate::ir::schema::Schema::with_time_index( + vec![ + field("ts", DataType::Timestamp), + field("value", DataType::Float64), + field("host", DataType::Utf8), + field("dst", DataType::Utf8), + ], + 0, + vec![], + ), + })) + .unwrap(); + let position = |memo: &Memo, group: MemoGroupId, name: &str| { + memo.groups()[group.0 as usize] + .group_properties + .schema + .fields + .iter() + .position(|field| field.name == name) + .unwrap() + }; + let (host, dst) = ( + position(&memo, flows, "host"), + position(&memo, flows, "dst"), + ); + let hll = FieldDataType::Sketch(SketchAlgorithm::HLL); + let bound_by = |memo: &mut Memo, keys: Vec, input: MemoGroupId| { + let state = memo + .find_or_add_group(state_grouped_by(hll.clone(), Reduction::by(keys), input)) + .unwrap(); + memo.max_distinct_per_group_per_evaluation(state) + }; + assert_eq!(bound_by(&mut memo, vec![host], flows), Some(7_200)); + assert_eq!(bound_by(&mut memo, vec![host, dst], flows), Some(7_200)); + assert_eq!(bound_by(&mut memo, vec![dst], flows), None); + assert_eq!(bound_by(&mut memo, vec![], flows), None); + // A self-join pairs each host's rows with every row: grouped by the + // left side's `host`, a state counts the right side's `dst` values too. + let self_join = memo + .find_or_add_group(Operator::NonASAP(NonASAPOp::Join { + kind: crate::ir::operator::arguments::JoinKind::Cross, + pred: crate::ir::Predicate(crate::ir::ScalarExpr::Literal( + crate::ir::scalar::ScalarValue::Boolean(true), + )), + left: flows, + right: flows, + })) + .unwrap(); + assert_eq!(bound_by(&mut memo, vec![host], self_join), None); +} + /// A readout of a state grouped by a computed key or a time has no bound /// from the facts: over `latency` with 1000 series and 20 declared jobs, /// grouped by `date_trunc('minute', ts)` it returns one value per minute diff --git a/crates/types/src/workload/data.rs b/crates/types/src/workload/data.rs index 08f34eec0..3d59b7308 100644 --- a/crates/types/src/workload/data.rs +++ b/crates/types/src/workload/data.rs @@ -195,6 +195,26 @@ pub struct SourceFacts { /// KMV's guarantee needs no bound. #[serde(default)] pub max_distinct_per_evaluation: Option, + /// Upper bound on the distinct items one group's distinct-count + /// summary counts in one complete evaluation (including every merged + /// tumbling window), keyed by the label (PromQL) or column (SQL) whose + /// values form the groups (default: none declared), e.g. `{"host": + /// 7200}` when each host sends at most 7,200 rows in the longest window + /// any query reads. It applies to a distinct count over one scan of the + /// source (no join, union or binary operator below it) whose groups are + /// keyed by that label, alone or with others (a finer group, a filter + /// or a shorter window only lowers it); several declared labels among + /// the keys give the smallest bound. Unlike + /// [`Self::max_distinct_per_evaluation`], which must hold for every + /// distinct count over the source, an ungrouped one included, it says + /// nothing about a coarser grouping. HLL's sparse state is exact up to + /// `2^precision / 8` distinct items, so an HLL distinct count is + /// certified exact (up to a 64-bit hash collision) at every precision + /// whose threshold is at least the bound. The deployment must enforce + /// it; an observed count is not a bound. Each bound is positive. + /// Omitted from JSON when empty. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub max_distinct_per_group_per_evaluation: BTreeMap, /// How many distinct values each label (PromQL) or column (SQL) of the /// source takes, keyed by its name (default: none declared), e.g. /// `{"host": 1000, "job": 10}`. Plan selection prices the groups of a @@ -464,7 +484,12 @@ impl DataWorkload { }); } } - if facts.max_distinct_per_evaluation == Some(0) { + if facts.max_distinct_per_evaluation == Some(0) + || facts + .max_distinct_per_group_per_evaluation + .values() + .any(|&bound| bound == 0) + { return Err(WorkloadError::ZeroMaxDistinct); } if facts @@ -599,6 +624,35 @@ mod tests { assert_eq!(with(0).validate(), Err(WorkloadError::ZeroMaxDistinct)); } + /// A per-group distinct bound is keyed by the label (or column) whose + /// values form the groups, and is positive. + #[test] + fn max_distinct_per_group_per_evaluation_is_per_label_and_positive() { + let facts: SourceFacts = serde_json::from_value(serde_json::json!({ + "max_distinct_per_group_per_evaluation": {"host": 7200} + })) + .unwrap(); + assert_eq!( + facts.max_distinct_per_group_per_evaluation, + BTreeMap::from([("host".to_string(), 7200)]) + ); + let with = |bound: u64| DataWorkload { + sources: BTreeMap::from([( + "flows".to_string(), + SourceFacts { + max_distinct_per_group_per_evaluation: BTreeMap::from([( + "host".to_string(), + bound, + )]), + ..SourceFacts::default() + }, + )]), + ..DataWorkload::default() + }; + assert!(with(1).validate().is_ok()); + assert_eq!(with(0).validate(), Err(WorkloadError::ZeroMaxDistinct)); + } + /// A declared value magnitude has `0 < min_abs <= max_abs`, both /// finite; any other is an input error naming the source and column. #[test] diff --git a/crates/types/src/workload/planning.rs b/crates/types/src/workload/planning.rs index 11ae9d773..96ce169ec 100644 --- a/crates/types/src/workload/planning.rs +++ b/crates/types/src/workload/planning.rs @@ -111,8 +111,12 @@ pub enum WorkloadError { /// finite. #[error("a stream norm must be finite and non-negative, got {0}")] InvalidStreamNorm(f64), - /// Bad input: a source's `max_distinct_per_evaluation` of zero. - #[error("a source's max_distinct_per_evaluation must be greater than zero")] + /// Bad input: a source's `max_distinct_per_evaluation`, or a bound in + /// its `max_distinct_per_group_per_evaluation`, of zero. + #[error( + "a source's max_distinct_per_evaluation and max_distinct_per_group_per_evaluation bounds \ + must be greater than zero" + )] ZeroMaxDistinct, /// Bad input: a zero count in a source's `distinct_values_per_label` /// or `distinct_values_per_label_set`. @@ -224,6 +228,10 @@ mod tests { l2: None, }), max_distinct_per_evaluation: Some(100), + max_distinct_per_group_per_evaluation: BTreeMap::from([( + "instance".to_string(), + 10, + )]), distinct_values_per_label: BTreeMap::from([ ("job".to_string(), 10), ("instance".to_string(), 1_000), @@ -251,6 +259,7 @@ mod tests { "sample_interval": 15000, "stream_norms": {"l1": 1e9, "l2": null}, "max_distinct_per_evaluation": 100, + "max_distinct_per_group_per_evaluation": {"instance": 10}, "distinct_values_per_label": {"instance": 1000, "job": 10}, "distinct_values_per_label_set": [ {"labels": ["job", "instance"], "distinct_values": 1000} diff --git a/docs/design_docs/architecture/input-output-workflow.md b/docs/design_docs/architecture/input-output-workflow.md index 4b26b0936..ad46f42af 100644 --- a/docs/design_docs/architecture/input-output-workflow.md +++ b/docs/design_docs/architecture/input-output-workflow.md @@ -201,6 +201,7 @@ struct SourceFacts { sample_interval: Option, stream_norms: Option, max_distinct_per_evaluation: Option, + max_distinct_per_group_per_evaluation: BTreeMap, distinct_values_per_label: BTreeMap, distinct_values_per_label_set: Vec, rows_held: Option, @@ -225,6 +226,7 @@ struct LabelSetDistinctValues { | `column_magnitudes` | Optional; default none; each `0 < min_abs <= max_abs`, both finite | Bounds on the magnitude of each column's non-zero values, keyed by column name, e.g. `{"value": {"min_abs": 0.001, "max_abs": 10000.0}}` for a latency in seconds. Read per series name: a `histogram` or `summary` family's range does not apply to its `_sum`, `_count` or `_bucket` series. A DDSketch state built from a column its producer passes on unchanged from sources that all declare it is costed at the bins that range spans (over several sources, the widest range among them): the bucket indices from ⌊log_γ min_abs⌋ to ⌊log_γ max_abs⌋, at least one, for γ = (1 + α) / (1 − α), instead of an assumed range of nine decades. The same column's declared `column_signs` decides whether the sketch keeps a negative store. The deployment must ensure the range: one that is too narrow can make Stage 3 pick a finer and much larger sketch than the default range would. Any other value is an input error naming the source and column. | | `sample_interval` | PromQL and MetricsQL; nonzero | How often each series of the metric is sampled. Bare instant selectors over it use it as their selection horizon; without it, such a query fails to lower. | | `stream_norms`, `max_distinct_per_evaluation` | Optional | Bounds that Count-Min/Count Sketch and HLL/UnivMon guarantees are bound with. | +| `max_distinct_per_group_per_evaluation` | Optional; default empty; each bound nonzero | Distinct items one group's distinct count holds in one complete evaluation, keyed by the label (or column) whose values form the groups, e.g. `{"host": 7200}`. It applies to a distinct count over one scan of the source (no join, union or binary operator below it) whose groups are keyed by that label (alone or with others), and says nothing about a coarser grouping. HLL's sparse state is exact up to `2^p / 8` items, so an HLL distinct count over such groups is certified exact (relative error 0, failing only on a 64-bit hash collision, at most `n(n − 1) / 2^65`) at every precision `p` with `2^p / 8` at least the bound, whatever failure probability a whole-result target splits down to. Without it, HLL keeps its measured or theoretical guarantee. | | `distinct_values_per_label` | Optional; default empty; each count nonzero | Distinct values each label (PromQL) or column (SQL) takes, e.g. `{"host": 1000, "job": 10}`. Plan selection prices a `by (k1, k2, ...)` aggregate or summary, and a partitioned sort or limit, at the product of its keys' counts, at most the `series_count` (series, or groups of rows) of the sources it reads and the rows it reads per evaluation. Over several sources a key's counts add. No count is assumed for a key some source read does not declare: the grouping is priced at the smaller of that `series_count` and those rows. Each count must be an upper bound, counting a missing label (or a NULL) as one more value: when every key of a grouped result declares one, their product (at most the series read) also bounds `G`, which sizes per-group sketches for a whole-result target; otherwise `G` keeps its series bound, or none for SQL. | | `distinct_values_per_label_set` | Optional; default empty; each set two or more distinct labels, its count nonzero and at most the product of its labels' declared counts | Distinct combinations a set of labels (or columns) takes together, for labels that depend on each other, e.g. `[{"labels": ["service", "endpoint"], "distinct_values": 625}]` when each of 625 endpoints is in one of 25 services. For a grouping over one source whose keys are one row's unchanged labels, the per-label product above becomes the smallest product of declared set and label counts whose labels cover the keys: `by (service, endpoint)` is 625 groups, not 25 x 625, and `by (region, service, endpoint)` at most 4 x 625. A set covering more labels than the keys also bounds them. Nothing is inferred from the per-label counts (no functional dependency is assumed). Over several sources, or for keys a join or binary operator pairs from different rows, only the per-label counts apply; a key a relabeling rewrites is not bounded by any declared set. The same bound gives `G` for a whole-result target. A count above its labels' product is an input error naming the source. | | `rows_held` | Optional; nonzero | Rows the source holds at rest. A query-time scan reads at most these; a scan with no window above it (a SQL query without a time predicate) reads all of them. | diff --git a/docs/design_docs/concepts/accuracy-models.md b/docs/design_docs/concepts/accuracy-models.md index c0e572f9f..d690fdca3 100644 --- a/docs/design_docs/concepts/accuracy-models.md +++ b/docs/design_docs/concepts/accuracy-models.md @@ -242,7 +242,7 @@ The built-in models currently include: | Exact computation | Exact over exact inputs under the supported operation's semantics; approximate inputs still require error propagation | | KLL | Normalized rank error from the empirical 99% calibration `2.296 / k^0.9723`, fitted on Apache DataSketches' C++ KLL (`a9b42755072b`); below a failure probability of 0.01 that error is scaled by the Gaussian quantile ratio `z(1 − δ/2) / z(1 − 0.01/2)`, a model rather than a measurement, and the guarantee names that contract apart | | DDSketch | Relative value error from alpha under the supported estimator/domain contract; a quantile's bound holds only over values of one sign (the state column's `column_signs` non-negative or non-positive, "Sign conditions"), else its failure probability is unknown and the readout serves no query with an accuracy target | -| Classic HLL | Relative error certified at the required failure probability over a source declaring at most `max_distinct_per_evaluation` distinct items (summed over the sources scanned below the state), from the linear-counting collision bound under independent uniform bucket hashes; without such a bound, or above the contract's range (`m/2` items at precision `p`), only the RSE magnitude with unknown failure probability | +| Classic HLL | Relative error certified at the required failure probability over a source declaring at most `max_distinct_per_evaluation` distinct items (summed over the sources scanned below the state), from the linear-counting collision bound under independent uniform bucket hashes; without such a bound, or above the contract's range (`m/2` items at precision `p`), only the RSE magnitude with unknown failure probability. Exact (relative error 0, failing only on a 64-bit hash collision) over groups declaring at most `m/8` distinct items (`max_distinct_per_group_per_evaluation`), where the sparse state holds every item hash; this comes before a measured table | | CMS | L1-normalized frequency bound from width and depth; does not by itself certify TopK membership | | CountSketch | L2-normalized frequency bound and median concentration bound, requiring valid odd depth | | KMV | Provable distinct-count bound from the `k` smallest hashes |