Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions crates/accuracy/src/guarantee/hll/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<AccuracyGuarantee> {
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()
Expand Down
22 changes: 22 additions & 0 deletions crates/accuracy/src/guarantee/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u64>,
) -> Option<AccuracyGuarantee> {
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(
Expand Down
30 changes: 30 additions & 0 deletions crates/accuracy/src/guarantee/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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());
}
83 changes: 61 additions & 22 deletions crates/accuracy/src/logical_edge/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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<AccuracyGuarantee> {
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 {
Expand Down
3 changes: 2 additions & 1 deletion crates/frontend-sil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Hole>,
/// `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<f64>,
Expand Down
29 changes: 26 additions & 3 deletions crates/frontend-sil/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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')
//! ```
Expand All @@ -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};
Expand Down Expand Up @@ -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)
}
Expand All @@ -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,
Expand Down
51 changes: 50 additions & 1 deletion crates/frontend-sil/tests/sil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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!(
Expand Down
Loading