From 23533b3db82225314d91af71dc05a3eb0ce3574e Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 17:15:44 +0000 Subject: [PATCH 1/8] test(cost): failing tests for IN-list selectivity and the compensation filter below the time merge Test-first phase 3 of the IN-list selectivity plan (sil-inlist-selectivity): cost unit tests U1-U16, group_count_bound tests T1-T4, asap_planner end-to-end tests E1-E7 over drill_cnt x1 fixtures, SIL facade tests S1-S3, and Q5 tests (Pass 2 offers Filter below the time merge; forced-lightcone cost; hole guard). Signatures only, current behaviour kept: group_count_bound takes an unread kept_values_per_column; DataFactAssumption::UniformRowsPerValue (never emitted yet). New-behaviour tests fail on assertions; anchors pass. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 1 + crates/cost/src/node/usage/tests.rs | 644 +++++++++++++++++ .../planner-cli/tests/inlist_selectivity.rs | 656 ++++++++++++++++++ .../tests/inlist_selectivity/data.json | 35 + .../inlist_selectivity/query_workload.json | 86 +++ .../tests/inlist_selectivity/tables.json | 49 ++ crates/planner-cli/tests/main.rs | 1 + crates/planner/tests/sil_intents.rs | 219 ++++++ .../types/src/workload/assumed_data_fact.rs | 34 + crates/types/src/workload/bounds.rs | 118 ++++ 10 files changed, 1843 insertions(+) create mode 100644 crates/planner-cli/tests/inlist_selectivity.rs create mode 100644 crates/planner-cli/tests/inlist_selectivity/data.json create mode 100644 crates/planner-cli/tests/inlist_selectivity/query_workload.json create mode 100644 crates/planner-cli/tests/inlist_selectivity/tables.json diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 5b34ea012..9d0ee28ba 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -1093,6 +1093,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }), data, rows_read, + &BTreeMap::new(), )) }; let groups = |reduction: &Reduction| match reduction { diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 1ea07c071..a7f733665 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -4950,3 +4950,647 @@ fn a_negating_projection_drops_the_non_negative_fact() { assert_eq!(negated.rows_per_state(), Some(300)); assert!(projected(ScalarExpr::Column(0)).non_negative); } + +// IN-list selectivity (test plan `sil-inlist-selectivity`, section 4.1): +// a predicate `column IN (k values)` on a source column passed on unchanged +// whose `distinct_values_per_label` the sources declare (N) keeps k/N of +// the rows, wherever it is evaluated; anything else keeps every row. + +/// `auth`: 100,000 series of `(ts, host, user, value)` sampled every 10 s +/// (10,000 rows per second, 10 per ms), 10,000 hosts and 100,000 users; +/// `host` declared only when `host_declared`. +fn auth_data(host_declared: bool) -> DataWorkload { + let labels = match host_declared { + true => serde_json::json!({"host": 10_000, "user": 100_000}), + false => serde_json::json!({"user": 100_000}), + }; + serde_json::from_value(serde_json::json!({ + "arrival": {"ingesting": {"rows_per_second": 10_000.0}}, + "sources": {"auth": {"series_count": 100_000, "sample_interval": 10_000, + "distinct_values_per_label": labels}} + })) + .unwrap() +} + +/// `auth`'s rows: `(ts, host, user, value)`. +fn auth_schema() -> Schema { + use asap_types::ir::schema::DataType; + Schema::new(vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("host", DataType::Utf8, false), + Field::plain("user", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ]) +} + +/// `auth`'s column `host`, `user` or `value` in [`auth_schema`]. +const HOST: usize = 1; +const USER: usize = 2; +const VALUE: usize = 3; + +/// The literal `'{prefix}{i}'`. +fn text(prefix: &str, i: usize) -> ScalarExpr { + ScalarExpr::Literal(asap_types::ir::scalar::ScalarValue::Utf8(format!( + "{prefix}{i}" + ))) +} + +/// `column IN ('{prefix}0', …)` of `values` values. +fn in_list(column: usize, prefix: &str, values: usize) -> ScalarExpr { + ScalarExpr::InList { + expr: Box::new(ScalarExpr::Column(column)), + list: (0..values).map(|i| text(prefix, i)).collect(), + negated: false, + } +} + +/// `column = '{prefix}i'`. +fn equals(column: usize, prefix: &str, i: usize) -> ScalarExpr { + ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(column)), + op: asap_types::ir::scalar::CompareOpKind::Eq, + right: Box::new(text(prefix, i)), + semantics: asap_types::ir::scalar::ExprSemantics::Sql, + } +} + +/// `column = '{prefix}0' OR …` of `values` equalities: Pass 2's +/// compensation shape (`rules/rollup/compensation.rs`). +fn or_of_equalities(column: usize, prefix: &str, values: usize) -> ScalarExpr { + ScalarExpr::BoolOr((0..values).map(|i| equals(column, prefix, i)).collect()) +} + +/// A query-time `Filter(pred)` with output schema `schema`. +fn filter_node(pred: ScalarExpr, schema: Schema) -> PhysicalASAPDAGNode { + PhysicalASAPDAGNode { + output_schema: schema, + ..node(Payload::NonASAP(NonASAPOp::Filter { + pred: asap_types::ir::scalar::Predicate(pred), + child: 0, + })) + } +} + +/// A `Scan` of `auth` under `predicates`, at `timing`. +fn auth_scan(predicates: Vec>, timing: ExecutionTiming) -> PhysicalASAPDAGNode { + PhysicalASAPDAGNode { + output_state: match timing { + ExecutionTiming::IngestionTime => ExecutionDataState::INGESTION_ROWS, + ExecutionTiming::QueryTime => ExecutionDataState::QUERY_ROWS, + }, + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::Scan { + source: Source::Table { + table_ref: "auth".into(), + }, + predicates: predicates + .into_iter() + .map(asap_types::ir::scalar::Predicate) + .collect(), + schema: auth_schema(), + })) + } +} + +/// `rows` raw rows of `auth` spanning 10 s, as `producer` (of +/// [`auth_schema`]) outputs them: `host`, `user` and `value` unchanged. +fn auth_rows(producer: &PhysicalASAPDAGNode, rows: u64) -> ProducerOutput<'_> { + let mut output = raw_rows(producer, "auth", rows, 10_000); + output.output_facts.unchanged_columns = ["host", "user", "value"].into(); + output +} + +/// The usage of `filter` over `input` (query time) under `data`. +fn filtered<'a>( + filter: &'a PhysicalASAPDAGNode, + input: ProducerOutput<'a>, + data: &DataWorkload, + settings: &'a CostInputs, +) -> NodeResourceUsageAndCost<'a> { + node_resource_usage_and_cost(filter, &[input], (1, 1.0), None, None, data, settings).unwrap() +} + +/// U1. A query-time `host IN (10 values)` over 100,000 raw rows of `auth` +/// (10,000 hosts declared) keeps 10/10,000 of them, 100, and evaluates its +/// predicate on each of the 100,000 it reads, as a `TRUE` filter does. +#[test] +fn a_filter_keeps_its_in_list_share_of_rows() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..rows + }; + let selecting = filter_node(in_list(HOST, "h", 10), auth_schema()); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 100); + assert!( + usage + .cost + .detail + .starts_with("filter: keep 100 of 100000 rows"), + "{}", + usage.cost.detail + ); + let all = filter_node( + ScalarExpr::Literal(asap_types::ir::scalar::ScalarValue::Boolean(true)), + auth_schema(), + ); + let all = filtered(&all, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.cpu_ops_per_second, all.cpu_ops_per_second); +} + +/// U2. Pass 2's compensation `host = 'h0' OR … OR host = 'h9'` is the same +/// 10-value IN-list: it keeps 100 of 100,000 rows. +#[test] +fn an_or_of_equalities_keeps_the_share_of_its_in_list() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(or_of_equalities(HOST, "h", 10), auth_schema()); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 100); +} + +/// U3. `host = 'h1'` keeps one host of 10,000: 10 of 100,000 rows. +#[test] +fn an_equality_keeps_one_value() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(equals(HOST, "h", 1), auth_schema()); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 10); +} + +/// U4. A query-time scan of 10 min of `auth` under `host IN (10 values)` +/// selects the 10 hosts' series before reading their samples (Q1: a label +/// IN-list is a series selection): it reads and outputs 6,000 of the +/// 6,000,000 rows, which still span 10 min, at 0.01 rows per ms. +#[test] +fn a_query_time_scan_keeps_its_predicates_share() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = |predicates| { + let scan = auth_scan(predicates, ExecutionTiming::QueryTime); + let usage = node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + Some(600_000), + None, + &data, + &settings, + ) + .unwrap(); + ( + usage.output_facts.statistics.rows, + usage.output_facts.raw_rows_span_ms, + usage.output_facts.raw_rows_per_ms, + usage.scanned_bytes_per_second, + ) + }; + let (all_rows, _, _, all_scanned) = scan(vec![]); + assert_eq!(all_rows, 6_000_000); + let (rows, span_ms, rows_per_ms, scanned) = scan(vec![in_list(HOST, "h", 10)]); + assert_eq!(rows, 6_000); + assert_eq!(span_ms, Some(600_000)); + assert_eq!(rows_per_ms, Some(0.01)); + // Q1: it reads the selected rows only. + assert_eq!(scanned * 1_000.0, all_scanned); +} + +/// U5. An ingestion-time scan under `host IN (10 values)` sees every +/// arriving row (10,000 a second, the CPU of an unfiltered scan) and +/// passes on the 10 a second of the selected hosts, at 0.01 rows per ms. +#[test] +fn an_ingestion_time_scan_reads_every_arriving_row() { + let settings = CostInputs::default(); + let data = auth_data(true); + let all = auth_scan(vec![], ExecutionTiming::IngestionTime); + let all = + node_resource_usage_and_cost(&all, &[], (1, 1.0), None, None, &data, &settings).unwrap(); + assert_eq!(all.output_facts.statistics.rows, 10_000); + let selecting = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::IngestionTime); + let usage = + node_resource_usage_and_cost(&selecting, &[], (1, 1.0), None, None, &data, &settings) + .unwrap(); + assert_eq!(usage.output_facts.statistics.rows, 10); + assert_eq!(usage.output_facts.raw_rows_per_ms, Some(0.01)); + assert_eq!(usage.cpu_ops_per_second, all.cpu_ops_per_second); +} + +/// U6. A 10 s count-by-user chain at ingestion time over U5's scan counts +/// the selected hosts' rows: 100 a window (0.01 rows per ms), into at most +/// 100 users' states, not 100,000. +#[test] +fn an_ingestion_time_chain_over_a_filtered_scan_counts_the_kept_rows_and_groups() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::IngestionTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), None, None, &data, &settings).unwrap(); + let chain = PhysicalASAPDAGNode { + output_state: ExecutionDataState::INGESTION_SUMMARY, + retention_ms: Some(600_000), + output_schema: Schema::new(vec![ + Field::new( + "state", + FieldDataType::ExactAggregate(ExactKind::Count, ExactParams::Count), + false, + ), + Field::plain("user", asap_types::ir::schema::DataType::Utf8, false), + ]), + ..node(Payload::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: 0, + summary_type: FieldDataType::ExactAggregate(ExactKind::Count, ExactParams::Count), + input: SummaryUpdate::column(ColumnRef::Wildcard), + reduction: Reduction::by(vec![USER]), + filter: None, + tumbling_window_width_ms: 10_000, + })) + }; + let usage = node_resource_usage_and_cost( + &chain, + &[produced(&scan, &scan_usage)], + (1, 1.0), + Some(10_000), + None, + &data, + &settings, + ) + .unwrap(); + assert_eq!(usage.output_facts.statistics.rows, 100); + assert!( + usage.cost.detail.contains("for 100 groups"), + "{}", + usage.cost.detail + ); +} + +/// The usage of a query-time `count(*) GROUP BY key` over U4's scan (10 +/// min of `auth` under `host IN (10 values)`). +fn count_by_over_selected_hosts(key: usize) -> u64 { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::QueryTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), Some(600_000), None, &data, &settings) + .unwrap(); + let aggregate = node(Payload::NonASAP(NonASAPOp::Aggregate { + reduction: Reduction::by(vec![key]), + measures: vec![asap_types::ir::operator::AggIntent::Count], + output_names: vec!["c".into()], + filters: vec![], + having: None, + child: 0, + })); + let usage = node_resource_usage_and_cost( + &aggregate, + &[produced(&scan, &scan_usage)], + (1, 1.0), + None, + None, + &data, + &settings, + ) + .unwrap(); + let detail = &usage.cost.detail; + let groups = detail + .split(" groups") + .next() + .and_then(|head| head.rsplit(' ').next()) + .and_then(|groups| groups.parse().ok()); + groups.unwrap_or_else(|| panic!("no group count in {detail}")) +} + +/// U7. `GROUP BY host` under `host IN (10 values)` has the 10 kept hosts +/// as its groups, not min(10,000 hosts, 6,000 rows). +#[test] +fn a_restricted_group_key_has_its_kept_values_as_groups() { + assert_eq!(count_by_over_selected_hosts(HOST), 10); +} + +/// U8. `GROUP BY user` under `host IN (10 values)`: each series has one +/// host, so the selected series are 100,000 x 10/10,000 = 100, which bound +/// the users, not min(100,000 users, 6,000 rows). +#[test] +fn a_grouping_on_another_label_is_bounded_by_the_selected_series() { + assert_eq!(count_by_over_selected_hosts(USER), 100); +} + +/// `(state, host, user)` rows of exact count states. +fn host_user_count_states_schema() -> Schema { + use asap_types::ir::schema::DataType; + Schema::new(vec![ + Field::new( + "state", + FieldDataType::ExactAggregate(ExactKind::Count, ExactParams::Count), + false, + ), + Field::plain("host", DataType::Utf8, false), + Field::plain("user", DataType::Utf8, false), + ]) +} + +/// U9. The lightcone's compensation: `host = 'h0' OR …` (10 hosts) over +/// 100,000 `(host, user)` count states of `auth` keeps 100 of them, and a +/// merge by user over those merges 100 states into 100 groups, not +/// 100,000 into 100,000. +#[test] +fn a_merge_by_key_over_a_filtered_state_merges_the_kept_states() { + let settings = CostInputs::default(); + let data = auth_data(true); + let states = PhysicalASAPDAGNode { + output_schema: host_user_count_states_schema(), + ..node(Payload::ASAP(ASAPOp::SummaryMerge { + children: vec![0], + group_by: None, + })) + }; + let states_output = ProducerOutput { + payload: &states.payload, + output_schema: &states.output_schema, + output_facts: OutputFacts { + statistics: EdgeStatistics { + rows: 100_000, + bytes: 100_000 * 40, + }, + sources: BTreeSet::from(["auth"]), + family: StateFamily::Exact(&ExactKind::Count), + unchanged_columns: ["host", "user"].into(), + tumbling_windows: 1.0, + chain_tumbling_window_width_ms: None, + raw_rows_span_ms: None, + raw_rows_per_ms: None, + folded_per_row: None, + raw_rows_short_of_range: None, + state_data_span_ms: None, + raw_rows_shifted_back_ms: 0, + states_last_merged: true, + state_input_rows: None, + }, + }; + let compensation = filter_node( + or_of_equalities(HOST, "h", 10), + host_user_count_states_schema(), + ); + let kept = filtered(&compensation, states_output, &data, &settings); + assert_eq!(kept.output_facts.statistics.rows, 100); + let merge = PhysicalASAPDAGNode { + output_schema: Schema::new(vec![ + Field::new( + "state", + FieldDataType::ExactAggregate(ExactKind::Count, ExactParams::Count), + false, + ), + Field::plain("user", asap_types::ir::schema::DataType::Utf8, false), + ]), + ..node(Payload::ASAP(ASAPOp::SummaryMerge { + children: vec![0], + group_by: Some(vec![USER]), + })) + }; + let usage = node_resource_usage_and_cost( + &merge, + &[produced(&compensation, &kept)], + (1, 1.0), + None, + None, + &data, + &settings, + ) + .unwrap(); + assert!( + usage.cost.detail.starts_with("merge 100 states into 100;"), + "{}", + usage.cost.detail + ); +} + +/// U10. `host IN (100 values)` at the scan, then `host IN (10 of them)` +/// above it: the second keeps 10 of the 100 hosts left, not 10 of 10,000, +/// so together they keep 10/10,000 of the 6,000,000 rows, 6,000. +#[test] +fn a_second_in_list_on_the_same_column_narrows_the_kept_values() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![in_list(HOST, "h", 100)], ExecutionTiming::QueryTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), Some(600_000), None, &data, &settings) + .unwrap(); + assert_eq!(scan_usage.output_facts.statistics.rows, 60_000); + let narrower = filter_node(in_list(HOST, "h", 10), auth_schema()); + let usage = filtered(&narrower, produced(&scan, &scan_usage), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 6_000); +} + +/// U11. IN-lists on two independent columns multiply: `host IN (10)` and +/// `user IN (5,000)` keep 10/10,000 x 5,000/100,000 of 6,000,000 rows, +/// 300. (5,000 users rather than the plan's 5, whose 0.3 rows would round +/// to the 1-row floor and hide the product.) +#[test] +fn in_lists_on_two_columns_multiply() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![], ExecutionTiming::QueryTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), Some(600_000), None, &data, &settings) + .unwrap(); + let both = filter_node( + ScalarExpr::BoolAnd(vec![in_list(HOST, "h", 10), in_list(USER, "u", 5_000)]), + auth_schema(), + ); + let usage = filtered(&both, produced(&scan, &scan_usage), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 300); +} + +/// U12 (anchor). An IN-list of more values than the column takes (20,000 +/// of 10,000 hosts) keeps every row. +#[test] +fn more_values_than_the_column_takes_keep_every_row() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(in_list(HOST, "h", 20_000), auth_schema()); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 100_000); +} + +/// U13 (anchor). Without `host` in `distinct_values_per_label`, an IN-list +/// on it keeps every row: a filter, a query-time scan and a grouping cost +/// what they cost without the predicate. +#[test] +fn an_undeclared_column_keeps_every_row() { + let settings = CostInputs::default(); + let data = auth_data(false); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(in_list(HOST, "h", 10), auth_schema()); + let all = filter_node( + ScalarExpr::Literal(asap_types::ir::scalar::ScalarValue::Boolean(true)), + auth_schema(), + ); + let selected = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + let every = filtered(&all, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!( + selected.output_facts.statistics, + every.output_facts.statistics + ); + assert_eq!(selected.cost.cost_per_second, every.cost.cost_per_second); + let scan = |predicates| { + let scan = auth_scan(predicates, ExecutionTiming::QueryTime); + let usage = node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + Some(600_000), + None, + &data, + &settings, + ) + .unwrap(); + ( + usage.output_facts.statistics, + usage.output_facts.raw_rows_per_ms, + usage.cost.cost_per_second, + ) + }; + assert_eq!(scan(vec![in_list(HOST, "h", 10)]), scan(vec![])); +} + +/// U14 (anchor, Q3). Only `In` constraints have a share: `host NOT IN +/// (…)`, `value > 3` and `lower(host) IN (…)` (a computed column) keep +/// every row. +#[test] +fn not_in_ranges_and_computed_columns_keep_every_row() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let not_in = ScalarExpr::InList { + expr: Box::new(ScalarExpr::Column(HOST)), + list: (0..10).map(|i| text("h", i)).collect(), + negated: true, + }; + let range = ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(VALUE)), + op: asap_types::ir::scalar::CompareOpKind::Gt, + right: Box::new(ScalarExpr::Literal( + asap_types::ir::scalar::ScalarValue::Float64(3.0), + )), + semantics: asap_types::ir::scalar::ExprSemantics::Sql, + }; + let computed = ScalarExpr::InList { + expr: Box::new(ScalarExpr::FunctionCall { + name: "lower".into(), + args: vec![ScalarExpr::Column(HOST)], + }), + list: (0..10).map(|i| text("h", i)).collect(), + negated: false, + }; + for pred in [not_in, range, computed] { + let shown = format!("{pred:?}"); + let selecting = filter_node(pred, auth_schema()); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &data, &settings); + assert_eq!(usage.output_facts.statistics.rows, 100_000, "{shown}"); + } +} + +/// U15 (Q7). A share never rounds a non-empty input to no rows: 3 rows +/// under `host IN (10 of 10,000)` keep 1; no rows keep none. +#[test] +fn the_share_never_rounds_rows_to_zero() { + let settings = CostInputs::default(); + let data = auth_data(true); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(in_list(HOST, "h", 10), auth_schema()); + let three = filtered(&selecting, auth_rows(&rows, 3), &data, &settings); + assert_eq!(three.output_facts.statistics.rows, 1); + let mut none = auth_rows(&rows, 0); + none.output_facts.statistics = EdgeStatistics { rows: 0, bytes: 0 }; + let none = filtered(&selecting, none, &data, &settings); + assert_eq!(none.output_facts.statistics.rows, 0); +} + +/// U16 (Q2). Rows per host are assumed uniform: a filter whose IN-list +/// keeps a share of `auth`'s rows names that assumption once, for `auth` +/// and `host`; an IN-list on an undeclared column (share 1) assumes +/// nothing. +#[test] +fn an_in_list_share_names_the_uniform_rows_per_value_assumption() { + let settings = CostInputs::default(); + let rows = PhysicalASAPDAGNode { + output_schema: auth_schema(), + ..node(Payload::NonASAP(NonASAPOp::TimeRange { + range: Duration::from_secs(10), + kind: TimeRangeKind::Range, + child: 0, + })) + }; + let selecting = filter_node(in_list(HOST, "h", 10), auth_schema()); + let declared = auth_data(true); + let usage = filtered(&selecting, auth_rows(&rows, 100_000), &declared, &settings); + assert_eq!( + usage.cost.assumed_data_facts, + [AssumedDataFact { + sources: vec!["auth".into()], + assumption: DataFactAssumption::UniformRowsPerValue { + column: "host".into() + }, + }] + ); + let undeclared = auth_data(false); + let usage = filtered( + &selecting, + auth_rows(&rows, 100_000), + &undeclared, + &settings, + ); + assert!(usage.cost.assumed_data_facts.is_empty()); +} diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs new file mode 100644 index 000000000..4c36749b6 --- /dev/null +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -0,0 +1,656 @@ +//! IN-list selectivity end to end (test plan `sil-inlist-selectivity`, +//! sections 4.2 and Q5): `asap_planner` over E6's `drill_cnt` x1 facts, +//! q1 the top 10 hosts of `flows`, q2 the users of `auth` under `host IN +//! (k values)`, lowered as the SIL frontend lowers them (placeholders +//! `'__sil_Y_i'`, the hole guard as deployment exclusions), with the +//! lightcone query `SELECT host, user, count(*) … GROUP BY host, user` in +//! full mode. Fixtures in `tests/inlist_selectivity/`: `data.json` (E6's +//! `drill_cnt.x1/data.json`), `tables.json`, and `query_workload.json` (the +//! lowered full-mode workload, q2's IN-list as `{in_list}`). + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::PathBuf; +use std::process::Command; + +use serde_json::{json, Value}; + +use crate::asap_planner::TempFile; + +/// A fixture file of `tests/inlist_selectivity/`. +fn fixture(name: &str) -> Value { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/inlist_selectivity") + .join(name); + serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap() +} + +/// `drill_cnt` x1's data facts; without `host` in `auth`'s and `flows`' +/// `distinct_values_per_label` unless `host_declared`. +fn data(host_declared: bool) -> Value { + let mut data = fixture("data.json"); + if !host_declared { + for source in ["flows", "auth"] { + data["sources"][source]["distinct_values_per_label"] + .as_object_mut() + .unwrap() + .remove("host"); + } + } + data +} + +/// The values q2's IN-list holds. +#[derive(Clone, Copy, PartialEq)] +enum Values { + /// The SIL frontend's placeholders `'__sil_Y_0'`, …. + Placeholders, + /// Literal hosts `'h0'`, …. + Literals, +} + +impl Values { + /// Value `i` as an SQL literal's text, without quotes. + fn value(self, i: usize) -> String { + match self { + Values::Placeholders => format!("__sil_Y_{i}"), + Values::Literals => format!("h{i}"), + } + } +} + +/// The workload: q1, q2 with `k` values of `values`, and the lightcone +/// query when `lightcone`, over [`data`]`(host_declared)`. +fn workload(k: usize, values: Values, lightcone: bool, host_declared: bool) -> Value { + let mut queries = fixture("query_workload.json"); + let entries = queries["repeating_queries"].as_array_mut().unwrap(); + let in_list = (0..k) + .map(|i| format!("'{}'", values.value(i))) + .collect::>() + .join(", "); + let q2 = entries[1]["query"] + .as_str() + .unwrap() + .replace("{in_list}", &in_list); + entries[1]["query"] = json!(q2); + if !lightcone { + entries.truncate(2); + } + json!({"query_workload": queries, "data_workload": data(host_declared)}) +} + +/// The deployment capabilities: the hole guard for `values` when `guard` +/// (no ingestion-time candidate and none kept across evaluations reads its +/// first value, as `lower_intents` adds), and `extra` exclusions. +fn capabilities(values: Values, guard: bool, extra: &[Value]) -> Value { + let mut excluded: Vec = Vec::new(); + if guard { + let first = json!({"Utf8": values.value(0)}); + excluded.push(json!({"timing": "ingestion_time", "reads_constant": first})); + excluded.push(json!({"kept_across_evaluations": true, "reads_constant": first})); + } + excluded.extend(extra.iter().cloned()); + json!({"excluded_candidates": excluded}) +} + +/// No query-time scan: q2 can only read the lightcone's state. +fn no_query_time_scan() -> Value { + json!({"timing": "query_time", "operator": "Scan"}) +} + +/// One node of the selected plan with its cost line. +#[derive(Debug, Clone, PartialEq)] +struct NodeLine { + id: u64, + operator: String, + timing: String, + cost_per_second: f64, + detail: String, + /// The payload's JSON (its predicates, keys, …). + payload: String, + producers: Vec, +} + +impl NodeLine { + /// The line without its id, which the plan numbers: comparable across + /// plans. + fn without_id(&self) -> (String, String, String, String) { + ( + self.operator.clone(), + self.timing.clone(), + format!("{:.6e}", self.cost_per_second), + self.detail.clone(), + ) + } +} + +/// The plan Stage 3 selected and its cost. +struct Planned { + cost_per_second: f64, + nodes: BTreeMap, + roots: Vec, +} + +impl Planned { + /// The nodes query `query` (its index in the workload) reaches, its + /// root first. + fn reached(&self, query: usize) -> Vec<&NodeLine> { + let mut seen = BTreeSet::new(); + let mut order = Vec::new(); + let mut stack = vec![self.roots[query]]; + while let Some(id) = stack.pop() { + if seen.insert(id) { + let node = &self.nodes[&id]; + order.push(node); + stack.extend(node.producers.iter().copied()); + } + } + order + } + + /// The nodes `query` reaches of operator `operator`. + fn reached_of(&self, query: usize, operator: &str) -> Vec<&NodeLine> { + self.reached(query) + .into_iter() + .filter(|node| node.operator == operator) + .collect() + } + + /// The ingestion-time nodes of the plan, without ids, sorted. + fn ingestion_lines(&self) -> Vec<(String, String, String, String)> { + let mut lines: Vec<_> = self + .nodes + .values() + .filter(|node| node.timing == "ingestion_time") + .map(NodeLine::without_id) + .collect(); + lines.sort(); + lines + } + + /// The node holding the IN-list's first value `first` in its payload. + fn holding<'a>(&'a self, first: &str) -> Vec<&'a NodeLine> { + self.nodes + .values() + .filter(|node| node.payload.contains(&format!("\"{first}\""))) + .collect() + } +} + +/// `asap_planner --run-until stage3`'s document over `workload` with +/// `capabilities` and the fixture's tables. +fn document(workload: &Value, capabilities: &Value) -> Value { + let workload = TempFile::json(workload); + let capabilities = TempFile::json(capabilities); + let tables: Vec = fixture("tables.json") + .as_array() + .unwrap() + .iter() + .map(Value::to_string) + .collect(); + let mut args = vec![ + "--workload", + workload.path(), + "--deployment-capabilities", + capabilities.path(), + "--run-until", + "stage3", + "--format", + "json", + ]; + for table in &tables { + args.extend(["--sql-catalog-table", table.as_str()]); + } + let output = Command::new(env!("CARGO_BIN_EXE_asap_planner")) + .args(&args) + .output() + .unwrap(); + let stderr = String::from_utf8_lossy(&output.stderr); + assert_eq!(output.status.code(), Some(0), "{stderr}"); + serde_json::from_slice(&output.stdout).unwrap() +} + +/// The plan `asap_planner` selects over `workload` with `capabilities`. +fn plan(workload: &Value, capabilities: &Value) -> Planned { + planned(&document(workload, capabilities)["stage3_plan_selection"]) +} + +/// The selected plan of a `stage3_plan_selection` section. +fn planned(selection: &Value) -> Planned { + let cost = &selection["cost"]; + let per_node = cost["per_node"].as_object().unwrap(); + let plan = &selection["plan"]; + let nodes = plan["nodes"] + .as_array() + .unwrap() + .iter() + .map(|node| { + let id = node["id"].as_u64().unwrap(); + let line = &per_node[&id.to_string()]; + let typed: asap_types::plan::physical_asap_dag::PhysicalASAPDAGNode = + serde_json::from_value(node.clone()).unwrap(); + let node_line = NodeLine { + id, + operator: line["operator"].as_str().unwrap().to_owned(), + timing: line["timing"].as_str().unwrap().to_owned(), + cost_per_second: line["cost_per_second"].as_f64().unwrap(), + detail: line["detail"].as_str().unwrap().to_owned(), + payload: node["payload"].to_string(), + producers: typed.producers().into_iter().map(|p| p as u64).collect(), + }; + (id, node_line) + }) + .collect(); + Planned { + cost_per_second: cost["cost_per_second"].as_f64().unwrap(), + nodes, + roots: plan["roots"] + .as_array() + .unwrap() + .iter() + .map(|root| root.as_u64().unwrap()) + .collect(), + } +} + +/// On-demand holes (mode 2): q1 and q2 with `k` placeholders, the hole +/// guard, no lightcone. +fn on_demand(k: usize) -> Planned { + plan( + &workload(k, Values::Placeholders, false, true), + &capabilities(Values::Placeholders, true, &[]), + ) +} + +/// Full intent: q1, q2 with `k` placeholders and the lightcone query, +/// the hole guard, and `extra` exclusions. +fn full(k: usize, extra: &[Value]) -> Planned { + plan( + &workload(k, Values::Placeholders, true, true), + &capabilities(Values::Placeholders, true, extra), + ) +} + +/// The number `detail` states right after `before` (e.g. `"scan "`). +fn number_after(detail: &str, before: &str) -> u64 { + let start = detail + .find(before) + .unwrap_or_else(|| panic!("no {before:?} in {detail}")) + + before.len(); + detail[start..] + .split(|c: char| !c.is_ascii_digit()) + .next() + .and_then(|digits| digits.parse().ok()) + .unwrap_or_else(|| panic!("no number after {before:?} in {detail}")) +} + +/// Whether `a` is within `tolerance` (relative) of `b`. +fn close(a: f64, b: f64, tolerance: f64) -> bool { + (a - b).abs() <= tolerance * b.abs() +} + +/// E1. In mode 2, q2 reads the selected hosts' rows at query time, so its +/// cost grows with |$Y|: `auth`'s 10,000 rows/s over 10,000 hosts are 600 +/// rows per host in 10 min, so its scan reads 600·k rows (Q1) and its +/// aggregate groups them into at most 10·k users (100,000 series, 10 per +/// host); q1's nodes are the same for every |$Y|. Today every |$Y| costs +/// 177.9132/s (scan 6,000,000 rows into 100,000 groups). +#[test] +fn query_time_cost_grows_with_the_in_list_size() { + let sizes = [1, 10, 100, 1_000]; + let plans: Vec = sizes.iter().map(|&k| on_demand(k)).collect(); + for pair in plans.windows(2) { + assert!( + pair[0].cost_per_second < pair[1].cost_per_second, + "{} !< {}", + pair[0].cost_per_second, + pair[1].cost_per_second + ); + } + let q1_lines = |planned: &Planned| -> Vec<_> { + planned + .reached(0) + .into_iter() + .map(NodeLine::without_id) + .collect() + }; + for planned in &plans[1..] { + assert_eq!(q1_lines(planned), q1_lines(&plans[0])); + } + for (&k, planned) in sizes.iter().zip(&plans) { + let scans = planned.reached_of(1, "Scan"); + assert_eq!(scans.len(), 1, "q2 scans auth once"); + assert_eq!( + number_after(&scans[0].detail, "scan "), + 600 * k as u64, + "{}", + scans[0].detail + ); + let aggregates = planned.reached_of(1, "Aggregate"); + assert_eq!(aggregates.len(), 1); + let detail = &aggregates[0].detail; + assert_eq!( + number_after(detail, "hash aggregate "), + 600 * k as u64, + "{detail}" + ); + assert!( + number_after(detail, " rows into ") <= 10 * k as u64, + "{detail}" + ); + } +} + +/// E2. The lightcone's kept state is built without the IN-list (the hole +/// guard keeps every placeholder at query time), so its ingestion-time +/// nodes cost the same for every |$Y|; only the query-time compensation +/// filter and what reads it shrink with k/N. q2 is forced onto the +/// lightcone (no query-time scan). Today the filter passes 100,000 rows +/// and the merge by user merges 100,000 states for every |$Y|. +#[test] +fn kept_state_cost_does_not_depend_on_the_in_list_size() { + let small = full(10, &[no_query_time_scan()]); + let large = full(1_000, &[no_query_time_scan()]); + assert_eq!(small.ingestion_lines(), large.ingestion_lines()); + let chains: Vec<_> = small + .reached(1) + .into_iter() + .filter(|node| node.timing == "ingestion_time" && node.detail.contains("100000 groups")) + .collect(); + assert!(!chains.is_empty(), "q2 reads the (host, user) lightcone"); + let filter_kept = |planned: &Planned| { + let filters = planned.reached_of(1, "Filter"); + assert_eq!(filters.len(), 1, "one compensation filter"); + let detail = filters[0].detail.clone(); + ( + number_after(&detail, "filter: keep "), + number_after(&detail, " of "), + ) + }; + let (kept_small, read_small) = filter_kept(&small); + let (kept_large, read_large) = filter_kept(&large); + assert_eq!(read_small, read_large); + // 10 and 1,000 of 10,000 hosts. + assert_eq!(kept_small, (read_small as f64 / 1_000.0).round() as u64); + assert_eq!(kept_large, (read_large as f64 / 10.0).round() as u64); + // The merge by user reads the 10 hosts' 100 users' states. + let merges: Vec = small + .reached_of(1, "SummaryMerge") + .into_iter() + .map(|node| node.detail.clone()) + .collect(); + assert!( + merges + .iter() + .any(|detail| detail.starts_with("merge 100 states into 100;")), + "q2's merges at |$Y| = 10: {merges:?}" + ); +} + +/// E3. With 10 of 10,000 hosts bound, reading them at query time (≈28/s) +/// is far cheaper than keeping the (host, user) lightcone (≈68/s of +/// ingestion alone): the full-intent plan reads no (host, user) state for +/// q2 and costs what mode 2 costs, plus the lightcone root's own +/// once-in-49-days evaluation. Today q2 reads the lightcone, 169.2572/s. +#[test] +fn the_lightcone_is_dropped_when_few_keys_are_bound() { + let planned = full(10, &[]); + assert!( + planned + .reached(1) + .iter() + .all(|node| node.timing != "ingestion_time" || !node.detail.contains("100000 groups")), + "q2 reads the lightcone" + ); + let on_demand = on_demand(10); + assert!( + close(planned.cost_per_second, on_demand.cost_per_second, 0.001), + "full {} vs on-demand {}", + planned.cost_per_second, + on_demand.cost_per_second + ); +} + +/// E4. The planner reads k from the plan's IN-list the same way for SIL +/// placeholders and literal hosts: under the same exclusions (each with +/// its own first value), equal costs and per-node lines. Passes today +/// (both ignore the IN-list); kept as the consistency pin. +#[test] +fn placeholders_and_literals_cost_the_same() { + let placeholders = plan( + &workload(10, Values::Placeholders, false, true), + &capabilities(Values::Placeholders, true, &[]), + ); + let literals = plan( + &workload(10, Values::Literals, false, true), + &capabilities(Values::Literals, true, &[]), + ); + assert_eq!(placeholders.cost_per_second, literals.cost_per_second); + let lines = |planned: &Planned| -> Vec<_> { + let mut lines: Vec<_> = planned.nodes.values().map(NodeLine::without_id).collect(); + lines.sort(); + lines + }; + assert_eq!(lines(&placeholders), lines(&literals)); +} + +/// E5. Plain literal SQL without the hole guard folds `host IN ('h0', …)` +/// into an ingestion-time scan, whose chain then holds only the selected +/// hosts' users: 100 groups for 10 hosts (100,000 series x 10/10,000), +/// ≈29/s; 1,000 hosts cost more. Today the chain is priced for 100,000 +/// groups, 140.9361/s. +#[test] +fn a_literal_in_list_shrinks_its_ingestion_time_state() { + let literal = |k| { + plan( + &workload(k, Values::Literals, false, true), + &capabilities(Values::Literals, false, &[]), + ) + }; + let small = literal(10); + let chains: Vec<_> = small + .reached(1) + .into_iter() + .filter(|node| node.operator == "SummaryTumblingWindowChain") + .collect(); + assert_eq!(chains.len(), 1, "q2 keeps an ingestion-time chain"); + assert!( + chains[0].detail.contains("for 100 groups"), + "{}", + chains[0].detail + ); + assert!( + small.cost_per_second < 30.0, + "{} (≈29/s expected)", + small.cost_per_second + ); + let large = literal(1_000); + assert!(small.cost_per_second < large.cost_per_second); +} + +/// E6 (anchor). Without `host` declared, an IN-list on it keeps every row: +/// mode 2, full intent and plain literal SQL cost exactly today's +/// 177.9132, 169.2572 and 140.9361 per second. +#[test] +fn an_undeclared_label_reproduces_todays_costs() { + let rounded = |cost: f64| (cost * 1e4).round() / 1e4; + let mode2 = plan( + &workload(10, Values::Placeholders, false, false), + &capabilities(Values::Placeholders, true, &[]), + ); + assert_eq!(rounded(mode2.cost_per_second), 177.9132); + let lightcone = plan( + &workload(10, Values::Placeholders, true, false), + &capabilities(Values::Placeholders, true, &[]), + ); + assert_eq!(rounded(lightcone.cost_per_second), 169.2572); + let literal = plan( + &workload(10, Values::Literals, false, false), + &capabilities(Values::Literals, false, &[]), + ); + assert_eq!(rounded(literal.cost_per_second), 140.9361); +} + +/// `sum(rate(m{job="a"}[5m]))` once, `m` 1,000 series every 15 s holding +/// 60,000 rows, `job` declared with `jobs` values when given; its plan. +fn promql_rate_of_one_job(jobs: Option, matcher: bool) -> Planned { + let mut facts = json!({"series_count": 1000, "sample_interval": 15000, "rows_held": 60000}); + if let Some(jobs) = jobs { + facts["distinct_values_per_label"] = json!({"job": jobs}); + } + let query = match matcher { + true => r#"sum(rate(m{job="a"}[5m]))"#, + false => "sum(rate(m[5m]))", + }; + let workload = json!({ + "query_workload": {"language": "promql", "query_batch": [{ + "query": query, + "requirements": {"accuracy": {"max_error": 0.0, "failure_probability": 0.0}}, + "predictability": "unknown", + "invocations": 1, + }]}, + "data_workload": {"arrival": "unknown", "sources": {"m": facts}}, + }); + plan(&workload, &json!({})) +} + +/// The rows the plan's one query-time scan outputs. +fn scanned_rows(planned: &Planned) -> u64 { + let scans = planned.reached_of(0, "Scan"); + assert_eq!(scans.len(), 1); + number_after(&scans[0].detail, "scan ") +} + +/// E7. A PromQL label matcher is an `In` of one value: with `job` declared +/// at 10 values, `m{job="a"}` reads a tenth of `m`'s rows; with `job` +/// undeclared it reads all of them, as today. +#[test] +fn a_promql_label_matcher_keeps_its_share() { + let all = scanned_rows(&promql_rate_of_one_job(None, false)); + assert_eq!(scanned_rows(&promql_rate_of_one_job(None, true)), all); + assert_eq!( + scanned_rows(&promql_rate_of_one_job(Some(10), true)), + all / 10 + ); +} + +// Q5: the lightcone's compensation filter applied before the time merge. + +/// Q5-E1. In the forced-lightcone plan the compensation filter reads the +/// windows' states (the `TimeRangeCover` over the (host, user) chain), so +/// the time merge after it merges k/N of the 1,003,333 states: no +/// query-time merge on q2's path merges more than the filter keeps. Today +/// the filter sits above `SummaryMerge` (time), which merges 1,003,333 +/// states for every |$Y|. +#[test] +fn the_compensation_filter_runs_before_the_time_merge() { + let planned = full(10, &[no_query_time_scan()]); + let filters = planned.reached_of(1, "Filter"); + assert_eq!(filters.len(), 1); + let filter = filters[0]; + let inputs: Vec<&str> = filter + .producers + .iter() + .map(|id| planned.nodes[id].operator.as_str()) + .collect(); + assert!( + inputs + .iter() + .all(|operator| matches!(*operator, "TimeRangeCover" | "TimeRange")), + "the filter reads {inputs:?}" + ); + let kept = number_after(&filter.detail, "filter: keep "); + for merge in planned.reached_of(1, "SummaryMerge") { + assert!( + number_after(&merge.detail, "merge ") <= kept, + "{} merges more than the filter keeps ({kept})", + merge.detail + ); + } +} + +/// Q5-E2. Forced onto the lightcone at |$Y| = 10, the plan costs q1 +/// (≈27.85/s) plus the lightcone's ingestion (≈67.87/s) plus q2's query +/// time: the cover (≈1.10/s), the filter over 1,003,333 states (≈0.10/s) +/// and merges and a finalize over ≈1,000 and 100 states (≈0.07/s): +/// ≈97.0/s within 2%. Without Q5 (filter above the time merge) ≈130.9/s; +/// today 169.2572/s. +#[test] +fn filtering_before_the_time_merge_cuts_the_forced_lightcone_cost() { + let planned = full(10, &[no_query_time_scan()]); + assert!( + close(planned.cost_per_second, 97.0, 0.02), + "{} (≈97.0/s expected)", + planned.cost_per_second + ); +} + +/// Q5-E3 (invariants). With the filter below the time merge, every node +/// holding a placeholder still runs at query time (so none is kept across +/// evaluations: only ingestion-time nodes are), and the kept state is the +/// same for |$Y| = 10 and 1,000 (byte-identical ingestion lines). +#[test] +fn the_hole_guard_holds_with_the_filter_below_the_time_merge() { + for k in [10, 1_000] { + let planned = full(k, &[no_query_time_scan()]); + let holding = planned.holding(&Values::Placeholders.value(0)); + assert!(!holding.is_empty(), "k = {k}"); + for node in holding { + assert_eq!(node.timing, "query_time", "k = {k}: {node:?}"); + } + } + assert_eq!( + full(10, &[no_query_time_scan()]).ingestion_lines(), + full(1_000, &[no_query_time_scan()]).ingestion_lines() + ); +} + +/// Q5-M1 (plan space). Pass 2 offers the compensation filter below the +/// time merge: some memo group has a `SummaryMerge` candidate over a group +/// computed by a `Filter` holding the IN-list's placeholders, over a group +/// computed by a `TimeRangeCover` (or `TimeRange`) of the lightcone's chain +/// windows. Today the only compensation `Filter` reads the lightcone's +/// summary state group (a `SummaryMerge` / `SummaryAgg` over the whole +/// window). +#[test] +fn pass2_offers_the_compensation_filter_over_the_windows() { + let document = document( + &workload(10, Values::Placeholders, true, true), + &capabilities(Values::Placeholders, true, &[]), + ); + let pass2 = document["memo"]["steps"] + .as_array() + .unwrap() + .iter() + .find(|step| step["step"] == "pass2") + .unwrap(); + let groups = pass2["groups"].as_array().unwrap(); + let candidates = |group: u64| groups[group as usize]["candidates"].as_array().unwrap(); + let only_child = |candidate: &Value| -> Option { + match candidate["children"].as_array().unwrap().as_slice() { + [child] => child.as_u64(), + _ => None, + } + }; + let placeholder = format!("\"{}\"", Values::Placeholders.value(0)); + let windows_filter = |group: u64| { + candidates(group).iter().any(|filter| { + filter["label"] == "Filter" + && filter["operator"].to_string().contains(&placeholder) + && only_child(filter).is_some_and(|windows| { + candidates(windows).iter().any(|candidate| { + let label = candidate["label"].as_str().unwrap(); + label.starts_with("TimeRangeCover") || label.starts_with("TimeRange ") + }) + }) + }) + }; + let offered = (0..groups.len() as u64).any(|group| { + candidates(group).iter().any(|merge| { + merge["label"] == "SummaryMerge" && only_child(merge).is_some_and(windows_filter) + }) + }); + assert!( + offered, + "no SummaryMerge over Filter(TimeRangeCover) in pass 2" + ); +} diff --git a/crates/planner-cli/tests/inlist_selectivity/data.json b/crates/planner-cli/tests/inlist_selectivity/data.json new file mode 100644 index 000000000..747172cd6 --- /dev/null +++ b/crates/planner-cli/tests/inlist_selectivity/data.json @@ -0,0 +1,35 @@ +{ + "arrival": { + "ingesting": { + "rows_per_second": 30000, + "max_out_of_order_ms": 2000 + } + }, + "sources": { + "flows": { + "series_count": 10000, + "sample_interval": 500, + "distinct_values_per_label": { + "host": 10000 + }, + "rows_held": 72000000, + "column_signs": { + "value": "non_negative" + }, + "max_distinct_per_evaluation": 100000 + }, + "auth": { + "series_count": 100000, + "sample_interval": 10000, + "distinct_values_per_label": { + "host": 10000, + "user": 100000 + }, + "rows_held": 6000000, + "column_signs": { + "value": "non_negative" + }, + "max_distinct_per_evaluation": 100000 + } + } +} \ No newline at end of file diff --git a/crates/planner-cli/tests/inlist_selectivity/query_workload.json b/crates/planner-cli/tests/inlist_selectivity/query_workload.json new file mode 100644 index 000000000..9d39538d6 --- /dev/null +++ b/crates/planner-cli/tests/inlist_selectivity/query_workload.json @@ -0,0 +1,86 @@ +{ + "language": { + "sql": "datafusion_sql" + }, + "query_batch": null, + "repeating_queries": [ + { + "query": "SELECT host, count(*) AS c FROM flows WHERE ts > now() - INTERVAL '1 hour' GROUP BY host ORDER BY c DESC LIMIT 10", + "demand": { + "fixed_interval_at": { + "interval": 10000, + "evaluation_phase": 0 + } + }, + "requirements": { + "accuracy": { + "accuracy_metric": "relative", + "max_error": 0.05, + "failure_probability": 0.05, + "accuracy_scope": "whole_result" + }, + "max_latency_ms": 1000.0 + }, + "predictability": { + "predictable": { + "known_at": null + } + } + }, + { + "query": "SELECT user, count(*) AS c FROM auth WHERE host IN ({in_list}) AND ts > now() - INTERVAL '10 minutes' GROUP BY user", + "demand": { + "fixed_interval_at": { + "interval": 10000, + "evaluation_phase": 0 + } + }, + "requirements": { + "accuracy": { + "accuracy_metric": "relative", + "max_error": 0.05, + "failure_probability": 0.05, + "accuracy_scope": "whole_result" + }, + "max_latency_ms": 1000.0 + }, + "predictability": { + "predictable": { + "known_at": null + } + } + }, + { + "query": "SELECT host, user, count(*) AS c FROM auth WHERE ts > now() - INTERVAL '10 minutes' GROUP BY host, user", + "demand": { + "fixed_interval_at": { + "interval": 4294960000, + "evaluation_phase": 0 + } + }, + "requirements": { + "accuracy": { + "accuracy_metric": "relative", + "max_error": 0.05, + "failure_probability": 0.05, + "accuracy_scope": "whole_result" + }, + "max_latency_ms": null + }, + "predictability": { + "predictable": { + "known_at": null + } + } + } + ], + "group_latency_bounds": [ + { + "query_indices": [ + 0, + 1 + ], + "max_latency_ms": 2000.0 + } + ] +} diff --git a/crates/planner-cli/tests/inlist_selectivity/tables.json b/crates/planner-cli/tests/inlist_selectivity/tables.json new file mode 100644 index 000000000..88af25e76 --- /dev/null +++ b/crates/planner-cli/tests/inlist_selectivity/tables.json @@ -0,0 +1,49 @@ +[ + { + "name": "flows", + "time_index": 0, + "columns": [ + { + "name": "ts", + "type": "timestamp", + "nullable": false + }, + { + "name": "host", + "type": "utf8", + "nullable": false + }, + { + "name": "value", + "type": "float64", + "nullable": false + } + ] + }, + { + "name": "auth", + "time_index": 0, + "columns": [ + { + "name": "ts", + "type": "timestamp", + "nullable": false + }, + { + "name": "host", + "type": "utf8", + "nullable": false + }, + { + "name": "user", + "type": "utf8", + "nullable": false + }, + { + "name": "value", + "type": "float64", + "nullable": false + } + ] + } +] \ No newline at end of file diff --git a/crates/planner-cli/tests/main.rs b/crates/planner-cli/tests/main.rs index 99d74eedd..74ece640a 100644 --- a/crates/planner-cli/tests/main.rs +++ b/crates/planner-cli/tests/main.rs @@ -3,5 +3,6 @@ mod asap_planner; mod asap_planner_acceptance; +mod inlist_selectivity; mod lowest_mean_latency_exactness; mod search_space_pruning; diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index a2369ba88..3ebeeb24b 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -960,3 +960,222 @@ async fn binder_of_an_unnamed_expression_is_refused() { "{result:?}" ); } + +// IN-list selectivity (test plan `sil-inlist-selectivity`, section 4.3): +// the cost of a dependent query reads |$Y| from its IN-list. + +/// `intent` (full statements) planned in `mode` over `data` under the +/// built-in models with `excluded` candidates added: the plan, its report. +async fn planned_excluding( + queries: &str, + data: &DataWorkload, + mode: IntentPlanningMode, + excluded: serde_json::Value, +) -> (IntentPlan, asap_planner::SelectedPlanReport) { + let mut capabilities = PlanningModels::builtin().deployment_capabilities.clone(); + capabilities + .excluded_candidates + .extend(serde_json::from_value::>(excluded).unwrap()); + let intents = parse_intents(&intent_text(queries)).expect("a well-formed intent"); + plan_intents( + &intents, + &catalog(), + data, + PlanningModels::builtin().with_deployment_capabilities(&capabilities), + &IntentPlanningOptions { + mode, + ..Default::default() + }, + ) + .await + .expect("the intent plans") +} + +/// The cost per second of the nodes `query_id` reads that no other query +/// of the intent reads. +fn own_cost(plan: &IntentPlan, report: &asap_planner::SelectedPlanReport, query_id: &str) -> f64 { + let dag = &plan.plan.dag; + let root_of = |q: &asap_planner::intent::IntentRoundQuery| dag.roots[q.query_index]; + let queries = &plan.intent_rounds[0].queries; + let own: BTreeSet = queries + .iter() + .filter(|q| q.query_id == query_id) + .flat_map(|q| reached(dag, root_of(q)).into_iter().map(|n| n.id)) + .collect(); + let others: BTreeSet = queries + .iter() + .filter(|q| q.query_id != query_id) + .flat_map(|q| reached(dag, root_of(q)).into_iter().map(|n| n.id)) + .collect(); + report + .predicted_usage + .per_node + .iter() + .filter(|node| own.contains(&node.node_id) && !others.contains(&node.node_id)) + .map(|node| node.cost_per_second.expect("cost model 1")) + .sum() +} + +/// q1 the top `k` of 1,000 hosts, q2 the users of those hosts' `auth` +/// rows over 10 minutes. +fn top_k_hosts_then_their_users(k: usize) -> String { + format!( + "q1: ($Y, _) := SELECT host, count(*) AS c FROM flows + WHERE ts > $now - INTERVAL '10 minutes' GROUP BY host ORDER BY c DESC LIMIT {k} REQUIRE EXACT; + {Q2_COUNT_BY_USER}" + ) +} + +/// S1. With the hole read at query time (on-demand holes), q2 reads the +/// rows of the |$Y| bound hosts: binding 50 of 1,000 hosts costs it about +/// 10x binding 5 (its per-request cost aside). Today both cost the same. +#[tokio::test] +async fn dependent_query_cost_grows_with_the_binding_size() { + let data = data(1_000, 1_000, 10_000.0); + let q2_cost = |k| { + let queries = top_k_hosts_then_their_users(k); + let data = data.clone(); + async move { + let (plan, report) = planned_excluding( + &queries, + &data, + IntentPlanningMode::IntentOnDemandHoles, + serde_json::json!([]), + ) + .await; + assert_eq!(slot_size_of(&plan, "q2"), k as u64); + own_cost(&plan, &report, "q2") + } + }; + let five = q2_cost(5).await; + let fifty = q2_cost(50).await; + let ratio = fifty / five; + assert!( + (8.0..=10.5).contains(&ratio), + "q2 at |$Y| = 50 costs {fifty}, at 5 {five}: {ratio}x" + ); +} + +/// The planned value count of `query_id`'s only bind slot in a plan. +fn slot_size_of(plan: &IntentPlan, query_id: &str) -> u64 { + plan.intent_rounds[0] + .queries + .iter() + .find(|q| q.query_id == query_id) + .unwrap() + .bind_slots[0] + .planned_value_count +} + +/// S2. The lightcone's state is kept for every host whatever the binding +/// (the hole guard keeps the IN-list at query time): the full-mode +/// workload planned with the hole guard and no query-time scan (so q2 +/// reads the lightcone) has the same ingestion-time nodes at the same costs +/// for |$Y| = 5 and 50. (`plan_intents` cannot force it: its plan without +/// the lightcone must be feasible too.) +#[tokio::test] +async fn the_lightcone_build_does_not_shrink_with_the_binding_size() { + let data = data(60, 1_000, 10_000.0); + let ingestion_costs = |k| { + let queries = top_k_hosts_then_their_users(k); + let data = data.clone(); + async move { + let full = IntentPlanningOptions { + mode: IntentPlanningMode::IntentFull, + ..Default::default() + }; + let lowered = lowered_with(&queries, &data, &full).await.unwrap(); + assert!(!lowered.lightcone_query_indices.is_empty(), "|$Y| = {k}"); + let mut capabilities = PlanningModels::builtin().deployment_capabilities.clone(); + capabilities + .excluded_candidates + .extend(lowered.hole_exclusions.iter().cloned()); + capabilities.excluded_candidates.push( + serde_json::from_value( + serde_json::json!({"timing": "query_time", "operator": "Scan"}), + ) + .unwrap(), + ); + let catalog = catalog(); + let (plan, report) = asap_planner::plan_installable(asap_planner::UserInput::new( + &lowered.workload, + asap_planner::FrontendInput::Sql { catalog: &catalog }, + PlanningModels::builtin().with_deployment_capabilities(&capabilities), + )) + .await + .expect("the full-mode workload plans"); + let q2 = plan.dag.roots[query_index(&lowered, "q2")]; + assert!( + reached(&plan.dag, q2).iter().any(|node| { + node.output_state.timing == ExecutionTiming::IngestionTime + && node.output_schema.fields.iter().any(|f| f.name == "user") + && node.output_schema.fields.iter().any(|f| f.name == "host") + }), + "|$Y| = {k}: q2 reads the (host, user) lightcone" + ); + let mut costs: Vec = report + .predicted_usage + .per_node + .iter() + .filter(|node| node.timing == ExecutionTiming::IngestionTime) + .map(|node| format!("{:?} {:.9e}", node.operator, node.cost_per_second.unwrap())) + .collect(); + costs.sort(); + costs + } + }; + assert_eq!(ingestion_costs(5).await, ingestion_costs(50).await); +} + +/// E6's `drill_cnt` x1 facts: `flows` 20,000 rows/s over 10,000 hosts, +/// `auth` 10,000 rows/s over 10,000 hosts and 100,000 users. +fn drill_cnt_x1_data() -> DataWorkload { + serde_json::from_value(serde_json::json!({ + "arrival": {"ingesting": {"rows_per_second": 30_000, "max_out_of_order_ms": 2_000}}, + "sources": { + "flows": {"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}, + "auth": {"series_count": 100_000, "sample_interval": 10_000, + "distinct_values_per_label": {"host": 10_000, "user": 100_000}, + "rows_held": 6_000_000, "max_distinct_per_evaluation": 100_000}, + }, + })) + .unwrap() +} + +/// E6's `drill_cnt` intent (q1 the top 10 hosts of `flows` over 1 h, q2 +/// their users' `auth` rows over 10 min). +const DRILL_CNT: &str = "q1: ($Y, _) := SELECT host, count(*) AS c FROM flows + WHERE ts > $now - INTERVAL '1 hour' GROUP BY host ORDER BY c DESC LIMIT 10 + REQUIRE ERROR rel <= 0.05 DELTA 0.05; +q2: SELECT user, count(*) AS c FROM auth WHERE host IN $Y AND ts > $now - INTERVAL '10 minutes' + GROUP BY user REQUIRE ERROR rel <= 0.05 DELTA 0.05;"; + +/// S3. At `drill_cnt` x1, 10 of 10,000 hosts bound, q2 reading them at +/// query time (≈0.15/s) is far cheaper than keeping the (host, user) +/// lightcone (≈68/s): the full intent keeps no lightcone query and costs +/// what the on-demand plan costs. Today it keeps the lightcone. +#[tokio::test] +async fn full_intent_drops_the_lightcone_for_a_small_binding() { + let data = drill_cnt_x1_data(); + let (full, full_report) = planned_excluding( + DRILL_CNT, + &data, + IntentPlanningMode::IntentFull, + serde_json::json!([]), + ) + .await; + let (_, on_demand_report) = planned_excluding( + DRILL_CNT, + &data, + IntentPlanningMode::IntentOnDemandHoles, + serde_json::json!([]), + ) + .await; + assert!(full.lightcone_query_indices.is_empty()); + assert_eq!( + full_report.cost_per_second, + on_demand_report.cost_per_second + ); +} diff --git a/crates/types/src/workload/assumed_data_fact.rs b/crates/types/src/workload/assumed_data_fact.rs index 5a20a41e0..37f457671 100644 --- a/crates/types/src/workload/assumed_data_fact.rs +++ b/crates/types/src/workload/assumed_data_fact.rs @@ -50,6 +50,11 @@ pub enum DataFactAssumption { /// order, a counter at 100 after 120 looks like a reset and adds 100 /// to an `increase`), or ingestion may reject the sample and fail. InOrderArrival, + /// The sources declare no per-value row counts for `column`, so an + /// IN-list keeping k of its N declared values is costed as keeping + /// k/N of the rows. A binding chosen by a top-k selects heavy values, + /// which hold more. Cost only. + UniformRowsPerValue { column: String }, } impl AssumedDataFact { @@ -60,6 +65,7 @@ impl AssumedDataFact { match self.assumption { DataFactAssumption::DDSketchValueMagnitudeRange { .. } => false, DataFactAssumption::InOrderArrival => true, + DataFactAssumption::UniformRowsPerValue { .. } => false, } } } @@ -105,6 +111,11 @@ impl fmt::Display for AssumedDataFact { that an ingestion-time rate, increase or irate state reads are taken to arrive \ in timestamp order" )?, + DataFactAssumption::UniformRowsPerValue { column } => write!( + f, + "{sources} declares no per-value row counts for {column}, so an IN-list keeping \ + k of its N values is costed as keeping k/N of the rows" + )?, } if self.accuracy_target_depends_on_it() { write!( @@ -193,4 +204,27 @@ mod tests { [1, 1000000000]; this affects cost only, the accuracy guarantee does not depend on it" ); } + + /// Q2 of the IN-list selectivity plan: the uniform rows-per-value + /// assumption names the column and affects cost only. + #[test] + fn the_uniform_rows_per_value_warning_names_the_column() { + let uniform = AssumedDataFact { + sources: vec!["auth".into()], + assumption: DataFactAssumption::UniformRowsPerValue { + column: "host".into(), + }, + }; + assert!(!uniform.accuracy_target_depends_on_it()); + assert_eq!( + uniform.to_string(), + "assumed data fact: source auth declares no per-value row counts for host, so an \ + IN-list keeping k of its N values is costed as keeping k/N of the rows; this \ + affects cost only, the accuracy guarantee does not depend on it" + ); + assert_eq!( + serde_json::to_value(&uniform.assumption).unwrap(), + serde_json::json!({"uniform_rows_per_value": {"column": "host"}}) + ); + } } diff --git a/crates/types/src/workload/bounds.rs b/crates/types/src/workload/bounds.rs index 3c462c9c6..2331de905 100644 --- a/crates/types/src/workload/bounds.rs +++ b/crates/types/src/workload/bounds.rs @@ -506,6 +506,11 @@ pub fn unchanged_source_columns<'a>( /// sources): each is in one group; /// - `rows_read`, the rows the grouping reads per evaluation: each row is /// in at most one group. +/// +/// `kept_values_per_column` (column -> distinct values left after the +/// IN-lists below the grouping) is not read yet: test-first placeholder of +/// the IN-list selectivity rule (a restricted key counts its kept values; +/// the declared series scale by the restricted columns' shares). pub fn group_count_bound( keys: &GroupKeys, input: Option<&Schema>, @@ -513,6 +518,7 @@ pub fn group_count_bound( unchanged_input_columns: &BTreeSet<&str>, data: &DataWorkload, rows_read: u64, + _kept_values_per_column: &BTreeMap<&str, u64>, ) -> u64 { let labels = || -> Option> { keys.keys() @@ -696,4 +702,116 @@ mod tests { // A node reading no source sees the whole rate. assert_eq!(source_rows_per_ms(&BTreeSet::new(), &data), Some(4.0)); } + + // IN-list selectivity (test plan `sil-inlist-selectivity`, section + // 4.1): a key restricted by IN-lists below the grouping counts its kept + // values, and the declared series scale by the restricted columns' + // shares. + + /// `auth`'s `(host, user, value)` columns, unchanged. + fn auth_columns() -> Schema { + use crate::ir::schema::{DataType, Field}; + Schema::new(vec![ + Field::plain("host", DataType::Utf8, false), + Field::plain("user", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ]) + } + + /// `auth`: 10,000 hosts, 100,000 users, 100,000 series (`series` `None` + /// leaves it undeclared), and the label set `(host, user)` at + /// `host_user` when given. + fn auth(series: Option, host_user: Option) -> DataWorkload { + let mut facts = SourceFacts { + series_count: series, + distinct_values_per_label: BTreeMap::from([ + ("host".to_string(), 10_000), + ("user".to_string(), 100_000), + ]), + ..SourceFacts::default() + }; + if let Some(distinct_values) = host_user { + facts.distinct_values_per_label_set = serde_json::from_value(serde_json::json!([ + {"labels": ["host", "user"], "distinct_values": distinct_values} + ])) + .unwrap(); + } + DataWorkload { + sources: BTreeMap::from([("auth".to_string(), facts)]), + ..DataWorkload::default() + } + } + + /// The bound for `GROUP BY keys` (columns of [`auth_columns`]) over + /// `rows_read` rows of `auth`, with `kept` values per restricted column. + fn bound(keys: &[usize], data: &DataWorkload, rows_read: u64, kept: &[(&str, u64)]) -> u64 { + let schema = auth_columns(); + group_count_bound( + &GroupKeys::by(keys.to_vec()), + Some(&schema), + &BTreeSet::from(["auth"]), + &BTreeSet::from(["host", "user", "value"]), + data, + rows_read, + &kept.iter().copied().collect(), + ) + } + + /// T1. `GROUP BY host` under `host IN (10 values)`: 10 groups, not + /// the 10,000 declared hosts. + #[test] + fn a_restricted_key_counts_its_kept_values() { + assert_eq!( + bound(&[0], &auth(None, None), 1_000_000, &[("host", 10)]), + 10 + ); + } + + /// T2. `GROUP BY host, user` with the set `(host, user)` declared at + /// 100,000, under `host IN (10 of 10,000)`: the set's combinations times + /// the host share, 100,000 x 10/10,000 = 100. + #[test] + fn kept_values_scale_a_declared_label_set() { + assert_eq!( + bound( + &[0, 1], + &auth(None, Some(100_000)), + 1_000_000, + &[("host", 10)] + ), + 100 + ); + } + + /// T3. `GROUP BY user` under `host IN (10 of 10,000)`: each of the + /// 100,000 series has one host, so 100 series are left, which bound the + /// users (100,000 declared). + #[test] + fn kept_values_scale_the_declared_series() { + assert_eq!( + bound(&[1], &auth(Some(100_000), None), 1_000_000, &[("host", 10)]), + 100 + ); + } + + /// T4 (anchor). With no kept values the bound is today's: the smallest + /// of the declared values (or label set), the declared series and the + /// rows read. + #[test] + fn no_kept_values_is_todays_bound() { + assert_eq!(bound(&[0], &auth(None, None), 1_000_000, &[]), 10_000); + assert_eq!(bound(&[0], &auth(None, None), 6_000, &[]), 6_000); + assert_eq!( + bound(&[1], &auth(Some(50_000), None), 1_000_000, &[]), + 50_000 + ); + assert_eq!( + bound(&[0, 1], &auth(None, Some(200_000)), 1_000_000, &[]), + 200_000 + ); + assert_eq!( + bound(&[0, 1], &auth(None, None), 10_000_000_000, &[]), + 1_000_000_000 + ); + } } From bb0fdfaa37629ef9f3979cd7e0544bda8a1d2266 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:05:51 +0000 Subject: [PATCH 2/8] feat(cost): IN-list selectivity, with the top-k share under a declared skew A `Scan`'s predicates and a `Filter`'s keep their IN-lists' share of the rows (`kept_share`): k of a column's N declared values keep k/N (rows per value assumed uniform, warned as `UniformRowsPerValue`), or the heaviest k values' Zipf mass H_k(s)/H_N(s) when the sources declare `zipf_exponent_per_label` and the values stand for a SIL binding from an upstream count-ranked top-k (`DataWorkload::heaviest_value_placeholders`, added by the intent lowering). A query-time scan reads only the selected rows (series selected by label); an ingestion-time scan sees every row. `OutputFacts::kept_values_per_column` carries the restricted columns up; groups and per-series counts use the kept share (`group_count_bound`), and an ingestion-time grouping reads its input's rate. Stage 3's input baseline keeps a column restricted by every candidate. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/state_bytes/mod.rs | 16 +- crates/cost/src/node/usage/kept_share.rs | 173 +++++++++++++++++ crates/cost/src/node/usage/mod.rs | 177 +++++++++++++++++- crates/cost/src/node/usage/tests.rs | 30 +++ .../tests/lowering_semantics.rs | 1 + crates/frontend-promql/src/lib.rs | 3 + crates/integration-tests/src/lib.rs | 1 + .../tests/joint_search_equivalence.rs | 2 + crates/planner/src/intent.rs | 20 +- crates/planner/tests/e2e_plan.rs | 1 + crates/planner/tests/summary_sharing.rs | 1 + crates/stage3-plan-selection/src/cost.rs | 13 ++ crates/types/src/workload/bounds.rs | 55 ++++-- crates/types/src/workload/data.rs | 20 ++ crates/types/src/workload/planning.rs | 2 + 15 files changed, 487 insertions(+), 28 deletions(-) create mode 100644 crates/cost/src/node/usage/kept_share.rs diff --git a/crates/cost/src/node/state_bytes/mod.rs b/crates/cost/src/node/state_bytes/mod.rs index 4ccf54ea8..c5aeb575d 100644 --- a/crates/cost/src/node/state_bytes/mod.rs +++ b/crates/cost/src/node/state_bytes/mod.rs @@ -193,11 +193,19 @@ impl StateInputRows { .map(|rows| ((rows - 1e-9 * rows.abs().max(1.0)).ceil().max(1.0)) as u64) } - /// Whether `other` folds what this does: the same rows once rounded, - /// sign, magnitude range and distinct values. Candidates of one input - /// group computing the same states fold the same. + /// Whether `other` folds what this does: the same rows once rounded up + /// (or to 0.1%: a filter keeping a share of a chain's windows rounds the + /// states it keeps, so a merge over them folds 60.014 rows where one + /// over all windows folds 60), sign, magnitude range and distinct + /// values. Candidates of one input group computing the same states fold + /// the same. pub fn folds_the_same_as(&self, other: &Self) -> bool { - self.rows_per_state() == other.rows_per_state() + let rows_close = self.rows_per_state() == other.rows_per_state() + || match (self.folded_rows_per_state, other.folded_rows_per_state) { + (Some(a), Some(b)) => (a - b).abs() <= 1e-3 * a.abs().max(b.abs()).max(1.0), + _ => false, + }; + rows_close && self.non_negative == other.non_negative && self.value_magnitude_range == other.value_magnitude_range && self.distinct_values == other.distinct_values diff --git a/crates/cost/src/node/usage/kept_share.rs b/crates/cost/src/node/usage/kept_share.rs new file mode 100644 index 000000000..dd40acb4e --- /dev/null +++ b/crates/cost/src/node/usage/kept_share.rs @@ -0,0 +1,173 @@ +//! The share of rows a predicate keeps: each conjunct `column IN (k +//! values)` (also `column = v` and an `OR` of equalities on one column) on a +//! source column passed on unchanged whose distinct values N the sources +//! declare keeps k of the values left: the heaviest k's share under the +//! column's declared Zipf skew when the values stand for the heaviest ones +//! (a SIL binding from an upstream top-k), else k/N (rows per value +//! assumed uniform). Any other conjunct keeps every row. + +use std::collections::{BTreeMap, BTreeSet}; + +use asap_types::ir::properties::selection::{constraint_of, Constraint}; +use asap_types::ir::scalar::ScalarValue; +use asap_types::ir::schema::Schema; +use asap_types::ir::ScalarExpr; + +/// What the sources declare about one column's values. +#[derive(Debug, Clone, Copy, PartialEq)] +pub(super) struct DeclaredValues { + /// Its distinct values N (`distinct_values_per_label`). + pub(super) distinct: u64, + /// The Zipf exponent of rows over them (`zipf_exponent_per_label`), + /// when declared. + pub(super) zipf_exponent: Option, +} + +/// What a predicate keeps of its input rows. +#[derive(Debug, Clone, PartialEq)] +pub(super) struct KeptShare<'a> { + /// The share of rows kept, in (0, 1]. + pub(super) share: f64, + /// Each restricted column's distinct values left: the input's entries + /// with the predicate's IN-lists applied. + pub(super) kept_values_per_column: BTreeMap<&'a str, u64>, + /// The columns this predicate narrows at k/N because their sources + /// declare no skew (the `UniformRowsPerValue` assumption). + pub(super) assumed_uniform_columns: Vec<&'a str>, +} + +/// The share of rows `conjuncts` keep over rows of `input_schema`, whose +/// `unchanged_columns` hold source columns as they are and whose restricted +/// columns have `kept_values_per_column` values left; `declared_values` +/// gives what the sources declare about a column, and +/// `heaviest_value_placeholders` the values standing for a column's +/// heaviest ones. Example: `host IN (10 values)` with N = 10,000 keeps 0.001 +/// of the rows (0.299 when they are the heaviest 10 under Zipf(1)); a +/// second `host IN (5 of them)` above keeps 5 of the 10 left, 0.5. +pub(super) fn share_of_rows_kept<'a, C>( + conjuncts: &[&ScalarExpr], + input_schema: &'a Schema, + unchanged_columns: &BTreeSet<&str>, + kept_values_per_column: &BTreeMap<&'a str, u64>, + declared_values: impl Fn(&str) -> Option, + heaviest_value_placeholders: &[ScalarValue], +) -> KeptShare<'a> { + let mut kept = kept_values_per_column.clone(); + let mut share = 1.0; + let mut assumed_uniform_columns = Vec::new(); + for conjunct in conjuncts.iter().flat_map(|c| flattened(c)) { + let Some((column, Constraint::In(values))) = constraint_of(conjunct) else { + continue; + }; + let Some(field) = input_schema.fields.get(column) else { + continue; + }; + let name = field.name.as_str(); + if !unchanged_columns.contains(name) { + continue; + } + let Some(declared) = declared_values(name) else { + continue; + }; + let before = kept.get(name).copied().unwrap_or(declared.distinct).max(1); + let after = (values.len() as u64).min(before); + let heaviest = values + .iter() + .any(|value| heaviest_value_placeholders.contains(value)); + let zipf_exponent = declared.zipf_exponent.filter(|_| heaviest); + share *= share_of_rows_of_values(after, before, zipf_exponent); + kept.insert(name, after); + if after < before + && declared.zipf_exponent.is_none() + && !assumed_uniform_columns.contains(&name) + { + assumed_uniform_columns.push(name); + } + } + KeptShare { + share, + kept_values_per_column: kept, + assumed_uniform_columns, + } +} + +/// The share of a column's rows that `kept` of its `values` distinct values +/// left hold: under a Zipf exponent s (`zipf_exponent`, given when the +/// values kept are the heaviest), H_kept(s)/H_values(s), the heaviest +/// values' mass (0.299 for 10 of 10,000 at s = 1); else `kept / values`, +/// rows per value uniform. Example: 10 of 10,000 hosts keep 0.001 +/// uniformly. +fn share_of_rows_of_values(kept: u64, values: u64, zipf_exponent: Option) -> f64 { + match zipf_exponent { + Some(exponent) if kept < values => { + generalized_harmonic(kept, exponent) / generalized_harmonic(values, exponent) + } + Some(_) => 1.0, + None => kept as f64 / values.max(1) as f64, + } +} + +/// H_n(s) = Σ_{i=1..n} 1/i^s: exact over the first 1,000 terms, the rest by +/// Euler–Maclaurin (the integral, the end and the first derivative +/// corrections; relative error below 1e-9). +fn generalized_harmonic(n: u64, exponent: f64) -> f64 { + const EXACT_TERMS: u64 = 1_000; + let exact: f64 = (1..=n.min(EXACT_TERMS)) + .map(|i| (i as f64).powf(-exponent)) + .sum(); + if n <= EXACT_TERMS { + return exact; + } + let (m, n) = (EXACT_TERMS as f64, n as f64); + let integral = if (exponent - 1.0).abs() < 1e-12 { + (n / m).ln() + } else { + (n.powf(1.0 - exponent) - m.powf(1.0 - exponent)) / (1.0 - exponent) + }; + let ends = (n.powf(-exponent) - m.powf(-exponent)) / 2.0; + let slopes = exponent * (m.powf(-exponent - 1.0) - n.powf(-exponent - 1.0)) / 12.0; + exact + integral + ends + slopes +} + +/// The conjuncts of `expr`: the items of nested `AND`s, else `expr`. +fn flattened(expr: &ScalarExpr) -> Vec<&ScalarExpr> { + if let ScalarExpr::BoolAnd(items) = expr { + items.iter().flat_map(flattened).collect() + } else { + vec![expr] + } +} + +/// `rows` kept at `share`: none of none, else at least one. +pub(super) fn rows_kept(rows: u64, share: f64) -> u64 { + if rows == 0 { + 0 + } else { + ((rows as f64 * share).round() as u64).clamp(1, rows) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The top 10 of 10,000 values under Zipf(1) hold H_10/H_10000 of the + /// rows, 0.2993 (E6 measured 0.293 on its Zipf data); uniform, 0.001. + #[test] + fn the_heaviest_values_keep_their_zipf_mass() { + let share = share_of_rows_of_values(10, 10_000, Some(1.0)); + assert!((share - 0.299_253).abs() < 1e-5, "{share}"); + assert_eq!(share_of_rows_of_values(10, 10_000, None), 0.001); + assert_eq!(share_of_rows_of_values(10_000, 10_000, Some(1.0)), 1.0); + } + + /// The tail approximation matches the exact sum past 1,000 terms. + #[test] + fn the_harmonic_tail_matches_the_exact_sum() { + for exponent in [0.5, 1.0, 1.2] { + let exact: f64 = (1..=20_000u64).map(|i| (i as f64).powf(-exponent)).sum(); + let approximate = generalized_harmonic(20_000, exponent); + assert!(((approximate - exact) / exact).abs() < 1e-9, "{exponent}"); + } + } +} diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 9d0ee28ba..1fd483079 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -410,6 +410,11 @@ pub struct OutputFacts<'a> { /// them needs rows held this far back plus its range. Example: `m[5m] /// offset 5m` reads the 5 min that end 5 min ago. pub raw_rows_shifted_back_ms: u64, + /// The distinct values left of each source column an IN-list below it + /// restricts (`kept_share`), for the columns it passes on unchanged; a + /// column absent is unrestricted. Example: `host IN (10 values)` over + /// `auth` leaves `{host: 10}`, which a merge or grouping above keeps. + pub kept_values_per_column: BTreeMap<&'a str, u64>, } /// Raw rows fewer than arrive over the range they are read for @@ -825,6 +830,31 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .map(|p| (p.output_schema, &p.output_facts.unchanged_columns)) .collect::>(), ); + // The restricted columns' values left below it: a column restricted in + // every input, at its most values over them. + let input_kept_values: BTreeMap<&'a str, u64> = match producers { + [] => BTreeMap::new(), + [first, rest @ ..] => first + .output_facts + .kept_values_per_column + .iter() + .filter_map(|(&column, &values)| { + rest.iter() + .try_fold(values, |most, producer| { + producer + .output_facts + .kept_values_per_column + .get(column) + .map(|&other| most.max(other)) + }) + .map(|values| (column, values)) + }) + .collect(), + }; + // The share of rows a `Scan`'s predicates or a `Filter`'s keeps, and + // the restricted columns' values it leaves (`kept_share`); `None` for + // any other node. + let mut kept_by_predicate: Option> = None; let operator = OperatorKind::of(&node.payload); let measured_unit_cost = match &node.payload { Payload::NonASAP(NonASAPOp::Aggregate { measures, .. }) => { @@ -945,6 +975,78 @@ pub(crate) fn node_usage_and_cost_terms<'a>( ) }) }; + // The share of the declared series its input keeps: each series has + // one value per label, so a label restricted to k of its N values + // keeps k/N of them. + let kept_series_share: f64 = input_kept_values + .iter() + .filter_map(|(&column, &values)| { + declared_distinct_values(Some(column)) + .map(|declared| (values as f64 / declared.max(1) as f64).min(1.0)) + }) + .product(); + let kept_series = |series: u64| ((series as f64 * kept_series_share).round() as u64).max(1); + // What the sources declare about a column's values: its distinct + // values and, when every source declares the same one, its skew. + let declared_values = |column: &str| -> Option { + let distinct = declared_distinct_values(Some(column))?; + let mut exponents = sources.iter().map(|source| { + data.sources + .get(*source) + .and_then(|facts| facts.zipf_exponent_per_label.get(column).copied()) + }); + let first = exponents.next().flatten(); + let zipf_exponent = first.filter(|&s| exponents.all(|other| other == Some(s))); + Some(kept_share::DeclaredValues { + distinct, + zipf_exponent, + }) + }; + // The predicate's share of its input, for a `Scan` (over its own + // schema) or a `Filter` (over its input's); the restricted columns and + // their values are the input's, IN-lists applied. + match &node.payload { + Payload::NonASAP(NonASAPOp::Scan { + predicates, schema, .. + }) if !predicates.is_empty() => { + let conjuncts: Vec<_> = predicates.iter().map(|p| &p.0).collect(); + kept_by_predicate = Some(kept_share::share_of_rows_kept( + &conjuncts, + schema, + &unchanged_columns, + &BTreeMap::new(), + declared_values, + &data.heaviest_value_placeholders, + )); + } + Payload::NonASAP(NonASAPOp::Filter { pred, .. }) => { + if let Some(producer) = producers.first() { + kept_by_predicate = Some(kept_share::share_of_rows_kept( + &[&pred.0], + producer.output_schema, + &producer.output_facts.unchanged_columns, + &input_kept_values, + declared_values, + &data.heaviest_value_placeholders, + )); + } + } + Payload::NonASAP(_) | Payload::ASAP(_) => {} + } + // Rows per value are assumed uniform where no skew is declared: one + // warning per column a predicate narrows so. + for column in kept_by_predicate + .iter() + .flat_map(|kept| kept.assumed_uniform_columns.iter()) + { + assumed_data_facts.push(AssumedDataFact { + sources: sources.iter().map(|source| source.to_string()).collect(), + assumption: DataFactAssumption::UniformRowsPerValue { + column: column.to_string(), + }, + }); + } + let share_kept = kept_by_predicate.as_ref().map_or(1.0, |kept| kept.share); // The distinct items one output row's state holds at most per // evaluation (`max_distinct_per_evaluation`, summed over the sources). let distinct_items_per_group = || -> Option { @@ -1072,7 +1174,13 @@ pub(crate) fn node_usage_and_cost_terms<'a>( false => Ok(input.rows.max(1)), true => { let window_ms = window_ms.ok_or(AnalyticalCostError::IngestionGroupingWithoutWindow)?; - // Name a source with no rate of its own. + // Its input's rate (a filter below keeps a share of the + // sources'), else the sources'; name a source with no rate of + // its own. + let rows_per_ms = producers + .first() + .and_then(|producer| producer.output_facts.raw_rows_per_ms) + .or(rows_per_ms); let rows_per_ms = rows_per_ms.ok_or_else(|| { let unrated = sources .iter() @@ -1093,7 +1201,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }), data, rows_read, - &BTreeMap::new(), + &input_kept_values, )) }; let groups = |reduction: &Reduction| match reduction { @@ -1103,8 +1211,8 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // most the rows read), else the rows read, each series having at // least one. Reduction::PerEntity => match (ingestion, series) { - (true, Some(series)) => Ok(series.max(1)), - (false, Some(series)) => Ok(series.min(input.rows).max(1)), + (true, Some(series)) => Ok(kept_series(series)), + (false, Some(series)) => Ok(kept_series(series).min(input.rows).max(1)), (_, None) => rows_read(), }, }; @@ -1190,6 +1298,12 @@ pub(crate) fn node_usage_and_cost_terms<'a>( if !ingestion || raw_rows_materialized_at_ingestion { raw_retained_rows = raw_rows_back(node.retention_ms); } + // Raw rows materialized at ingestion keep only the rows its + // predicates select. + if raw_rows_materialized_at_ingestion { + raw_retained_rows = + raw_retained_rows.map(|rows| kept_share::rows_kept(rows, share_kept)); + } let rows = match ingestion { true => raw_rows(lookback).0.ok_or_else(|| missing_rate(source))?, false => raw_rows_back(lookback).ok_or_else(|| { @@ -1206,7 +1320,15 @@ pub(crate) fn node_usage_and_cost_terms<'a>( } })?, }; - let out = edge(rows.max(1))?; + // At ingestion time it sees every arriving row; at query + // time a series store selects the series its label + // predicates name before reading their rows, so it reads + // only the rows they keep. + let selected_rows = kept_share::rows_kept(rows.max(1), share_kept); + let out = edge(match ingestion { + true => rows.max(1), + false => selected_rows, + })?; let estimate = estimate_operator_with_terms( PhysicalOperator::Scan, OperatorStatistics::Scan { @@ -1222,7 +1344,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // read the rows it retains, not one second of them. let out = match raw_rows_materialized_at_ingestion { true => edge(raw_retained_rows.ok_or(retained_without_a_bound(source))?)?, - false => out, + false => edge(selected_rows)?, }; // The time those rows span: one second at ingestion time, // the retention of raw data materialized there, at query @@ -1246,6 +1368,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( (_, true) => node.retention_ms, (true, false) => Some(ONE_SECOND_MS), (false, false) => rows_per_ms + .map(|rows_per_ms| rows_per_ms * share_kept) .filter(|rows_per_ms| *rows_per_ms > 0.0) .map(|rows_per_ms| (out.rows as f64 / rows_per_ms).round() as u64) .or(lookback), @@ -1674,7 +1797,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( _ => input, }; // It reads and passes on the same rows, each as it outputs - // it. + // it; a filter evaluates its predicate on each row it reads. let estimate = estimate_operator_with_terms( PhysicalOperator::PassThrough, OperatorStatistics::PassThrough { @@ -1685,7 +1808,32 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }, }, ); - (out, estimate, format!("operator: pass {} rows", input.rows)) + if share_kept < 1.0 { + // Its raw rows at their exact rate when they are that + // rate over their span (no rounding twice), else its + // input rows at the share. + let exact = input_raw_rows_per_ms + .zip(input_raw_rows_span_ms) + .map(|(rows_per_ms, span_ms)| rows_per_ms * span_ms as f64) + .filter(|rows| out.rows == (rows.round() as u64).max(1)); + let rows = match exact { + Some(rows) if out.rows > 0 => { + ((rows * share_kept).round() as u64).clamp(1, out.rows) + } + _ => kept_share::rows_kept(out.rows, share_kept), + }; + let bytes = match out.rows { + 0 => 0, + all => (out.bytes as f64 * rows as f64 / all as f64).round() as u64, + }; + ( + EdgeStatistics { rows, bytes }, + estimate, + format!("filter: keep {rows} of {} rows", input.rows), + ) + } else { + (out, estimate, format!("operator: pass {} rows", input.rows)) + } } }, Payload::ASAP(ASAPOp::SummaryAgg { @@ -2583,9 +2731,15 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .then_some(input_raw_rows_span_ms) .flatten() }); + // The restricted columns' values left: the predicate's, else its + // inputs', for the columns it passes on unchanged. + let mut kept_values_per_column = + kept_by_predicate.map_or(input_kept_values, |kept| kept.kept_values_per_column); + kept_values_per_column.retain(|column, _| unchanged_columns.contains(column)); // A scan's rows arrive at its sources' rate; a time range and the - // operators that keep each row's window pass on their input's. The - // rate holds while its rows are that rate over their span. + // operators that keep each row's window pass on their input's; a + // scan's or filter's predicates keep their share of it. The rate holds + // while its rows are that rate over their span. let raw_rows_per_ms = if matches!(node.payload, Payload::NonASAP(NonASAPOp::Scan { .. })) { rows_per_ms } else if matches!(node.payload, Payload::NonASAP(NonASAPOp::TimeRange { .. })) @@ -2595,6 +2749,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( } else { None } + .map(|rows_per_ms| rows_per_ms * share_kept) .filter(|&rows_per_ms| { raw_rows_span_ms.is_some_and(|span_ms| { out.rows == ((rows_per_ms * span_ms as f64).round() as u64).max(1) @@ -2673,6 +2828,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( raw_rows_short_of_range, state_data_span_ms, raw_rows_shifted_back_ms, + kept_values_per_column, }, work_ms_per_execution: node_ms, cpu_ops_per_second: estimate.cpu_ops() * per_second, @@ -3068,5 +3224,6 @@ fn split(input: EdgeStatistics, partitions: u64) -> PartitionStatistics { } } +mod kept_share; #[cfg(test)] mod tests; diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index a7f733665..47e8a30e7 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -69,6 +69,7 @@ fn a_merge_over_a_chain_s_windows_outputs_one_state_per_group() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let windows = node(Payload::NonASAP(NonASAPOp::TimeRange { @@ -186,6 +187,7 @@ fn an_operator_keeping_its_input_window_over_a_chain_or_its_windows_selects_what raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; for &step in path { @@ -253,6 +255,7 @@ fn a_merge_over_a_chain_s_windows_is_costed_by_the_chain_s_family() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -334,6 +337,7 @@ fn a_project_or_filter_over_states_passes_their_family_on() { raw_rows_shifted_back_ms: 0, states_last_merged: true, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; for passing in [ @@ -419,6 +423,7 @@ fn a_merge_over_a_rate_chain_s_windows_is_costed_by_the_rate_accumulator() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -499,6 +504,7 @@ fn raw_rows<'a>( raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, } } @@ -774,6 +780,7 @@ fn a_query_time_chain_pays_the_time_range_over_the_rows_it_reads() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let chain = PhysicalASAPDAGNode { @@ -1041,6 +1048,7 @@ fn a_merge_reading_one_state_per_group_passes_it_through() { value_magnitude_range: None, distinct_values: None, }), + kept_values_per_column: BTreeMap::new(), }, }; let merge = PhysicalASAPDAGNode { @@ -1686,6 +1694,7 @@ fn a_kmv_rollup_merge_costs_per_hash_it_inserts() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: Some(rows), + kept_values_per_column: BTreeMap::new(), }, }; let rollup = PhysicalASAPDAGNode { @@ -1766,6 +1775,7 @@ fn a_rollup_merges_its_states_when_its_group_estimate_ties_its_input() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: Some(rows), + kept_values_per_column: BTreeMap::new(), }, }; let merge_ms = |group_by: Option>| { @@ -1839,6 +1849,7 @@ fn query_time_memory_is_held_only_while_the_node_computes() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let merge = PhysicalASAPDAGNode { @@ -1983,6 +1994,7 @@ fn an_ingestion_time_view_of_raw_rows_keeps_the_rows_its_retention_covers() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let row_schema = Schema::new(vec![ @@ -2058,6 +2070,7 @@ fn a_view_without_retention_is_not_costed() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let shift = PhysicalASAPDAGNode { @@ -2141,6 +2154,7 @@ fn a_view_over_an_ingestion_time_chain_keeps_one_output_per_chain_window() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let usage = node_resource_usage_and_cost( @@ -2217,6 +2231,7 @@ fn ddsketch_build_cost( raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let settings = CostInputs::default(); @@ -2449,6 +2464,7 @@ fn ddsketch_assumed_facts_over_sources( state_data_span_ms: None, raw_rows_shifted_back_ms: 0, states_last_merged: false, + kept_values_per_column: BTreeMap::new(), }, }; let settings = CostInputs::default(); @@ -2649,6 +2665,7 @@ fn kll_merge_cpu_ops_over(k: u32, window_ms: u64, range_s: u64) -> f64 { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let mut chain = node(Payload::ASAP(ASAPOp::SummaryTumblingWindowChain { @@ -2778,6 +2795,7 @@ fn a_finalize_charges_each_group_its_measured_time() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let finalize = node(Payload::ASAP(ASAPOp::FinalizeExactAccumulator { @@ -2837,6 +2855,7 @@ fn a_per_series_aggregate_charges_the_labels_it_carries() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let ms_per_row = |labels: &[&str]| { @@ -2962,6 +2981,7 @@ fn a_merge_over_several_inputs_sizes_its_state_for_all_of_them() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: Some(rows), + kept_values_per_column: BTreeMap::new(), }, }; let wider = ProducerOutput { @@ -3069,6 +3089,7 @@ fn kll_estimate_us_per_group(producer: Payload, rows_per_state: u64, state_bytes value_magnitude_range: None, distinct_values: None, }), + kept_values_per_column: BTreeMap::new(), }, }; let estimate = node(Payload::ASAP(ASAPOp::SummaryEstimate { @@ -3542,6 +3563,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: Some(rows_per_state), + kept_values_per_column: BTreeMap::new(), }, }; let windows = PhysicalASAPDAGNode { @@ -3693,6 +3715,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: Some(kmv_rows), + kept_values_per_column: BTreeMap::new(), }, }], None, @@ -3776,6 +3799,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { value_magnitude_range: None, distinct_values: None, }), + kept_values_per_column: BTreeMap::new(), }, }], None, @@ -3812,6 +3836,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }], None, @@ -4065,6 +4090,7 @@ fn rows_of<'a>(producer: &'a PhysicalASAPDAGNode, rows: u64) -> ProducerOutput<' state_data_span_ms: None, raw_rows_shifted_back_ms: 0, states_last_merged: false, + kept_values_per_column: BTreeMap::new(), }, } } @@ -4300,6 +4326,7 @@ fn counter_sketch_charges_ms(shape: &CounterSketchShape) -> CounterSketchCharges raw_rows_shifted_back_ms: 0, states_last_merged: false, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let family = FieldDataType::Sketch(algorithm); @@ -4592,6 +4619,7 @@ fn a_ddsketch_build_holds_open_states_and_keeps_sealed_ones() { state_data_span_ms: None, raw_rows_shifted_back_ms: 0, states_last_merged: false, + kept_values_per_column: BTreeMap::new(), }, }; let rows = StateInputRows { @@ -4678,6 +4706,7 @@ fn a_measured_ddsketch_state_size_replaces_the_estimate() { state_data_span_ms: None, raw_rows_shifted_back_ms: 0, states_last_merged: false, + kept_values_per_column: BTreeMap::new(), }, }; let build = PhysicalASAPDAGNode { @@ -5348,6 +5377,7 @@ fn a_merge_by_key_over_a_filtered_state_merges_the_kept_states() { raw_rows_shifted_back_ms: 0, states_last_merged: true, state_input_rows: None, + kept_values_per_column: BTreeMap::new(), }, }; let compensation = filter_node( diff --git a/crates/frontend-metricsql/tests/lowering_semantics.rs b/crates/frontend-metricsql/tests/lowering_semantics.rs index eec38fce9..045e915bf 100644 --- a/crates/frontend-metricsql/tests/lowering_semantics.rs +++ b/crates/frontend-metricsql/tests/lowering_semantics.rs @@ -40,6 +40,7 @@ fn workload(language: QueryLanguage, query: &str) -> PlanningWorkload { }, )] .into(), + heaviest_value_placeholders: Vec::new(), }), } } diff --git a/crates/frontend-promql/src/lib.rs b/crates/frontend-promql/src/lib.rs index 95fc9511c..16cf32945 100644 --- a/crates/frontend-promql/src/lib.rs +++ b/crates/frontend-promql/src/lib.rs @@ -155,6 +155,7 @@ mod tests { ("other".to_string(), sampled(30_000)), ] .into(), + heaviest_value_placeholders: Vec::new(), }), } } @@ -309,6 +310,7 @@ mod tests { ("u".to_string(), typed(None)), ] .into(), + heaviest_value_placeholders: Vec::new(), }; let warnings = |query: &str| metric_type_warnings(query, &data).unwrap(); assert_eq!( @@ -349,6 +351,7 @@ mod tests { ("g".to_string(), typed(PrometheusMetricType::Gauge)), ] .into(), + heaviest_value_placeholders: Vec::new(), }; let warnings = |query: &str| metric_type_warnings(query, &data).unwrap(); assert_eq!( diff --git a/crates/integration-tests/src/lib.rs b/crates/integration-tests/src/lib.rs index 98af742ba..0718da067 100644 --- a/crates/integration-tests/src/lib.rs +++ b/crates/integration-tests/src/lib.rs @@ -151,6 +151,7 @@ pub mod planning { max_out_of_order_ms: None, }, sources, + heaviest_value_placeholders: Vec::new(), } } diff --git a/crates/integration-tests/tests/joint_search_equivalence.rs b/crates/integration-tests/tests/joint_search_equivalence.rs index cc5106ea3..ecc99d810 100644 --- a/crates/integration-tests/tests/joint_search_equivalence.rs +++ b/crates/integration-tests/tests/joint_search_equivalence.rs @@ -77,6 +77,7 @@ fn workload_of(queries: &[(&str, u32)], accuracy: AccuracyTarget) -> PlanningWor ) }) .collect(), + heaviest_value_placeholders: Vec::new(), }), } } @@ -297,6 +298,7 @@ fn example2() -> (PlanningWorkload, asap_frontend_sql::SqlCatalog) { }, )] .into(), + heaviest_value_placeholders: Vec::new(), }), }; let catalog = asap_frontend_sql::SqlCatalog::new().with_table( diff --git a/crates/planner/src/intent.rs b/crates/planner/src/intent.rs index f1c4fb4a7..af1896a01 100644 --- a/crates/planner/src/intent.rs +++ b/crates/planner/src/intent.rs @@ -246,6 +246,10 @@ struct BinderFacts { output_position: usize, column_type: FieldDataType, requested_fraction: f64, + /// Whether it keeps the top k by count (a count-ranked `ORDER BY … + /// DESC LIMIT k`, lowered to a `TopK`, [`top_k_parts`]): its values are + /// the heaviest of their column. + binds_heaviest_values: bool, } /// Lower `intents` over `catalog`'s tables and `data`'s facts: each query @@ -281,6 +285,8 @@ pub async fn lower_intents( let mut intent_rounds = Vec::new(); let mut group_latency_bounds = Vec::new(); let mut hole_exclusions = Vec::new(); + // The first placeholder of each binding of the heaviest values. + let mut heaviest_value_placeholders = Vec::new(); for intent in intents { // Each variable's binder, by variable name. let mut binders: BTreeMap = BTreeMap::new(); @@ -366,6 +372,12 @@ pub async fn lower_intents( hole_exclusions.push(timing_or_kept); } } + if binder.binds_heaviest_values + && hole.position == HolePosition::InList + && !heaviest_value_placeholders.contains(&placeholder_values[0]) + { + heaviest_value_placeholders.push(placeholder_values[0].clone()); + } placeholder_texts.insert(hole.variable.clone(), texts); if !bind_slots .iter() @@ -423,6 +435,7 @@ pub async fn lower_intents( output_position, column_type: fields[output_position].dtype.clone(), requested_fraction, + binds_heaviest_values: top_k_parts(&root).is_some(), }, ); } @@ -518,7 +531,10 @@ pub async fn lower_intents( repeating_queries: Some(entries), group_latency_bounds, }, - data_workload: Some(data.clone()), + data_workload: Some(DataWorkload { + heaviest_value_placeholders, + ..data.clone() + }), }, lightcone_query_indices, intent_rounds, @@ -822,6 +838,8 @@ async fn plan_query_at_a_time( capabilities: &asap_types::deployment_capabilities::DeploymentCapabilities, ) -> Result<(InstallablePlan, SelectedPlanReport), IntentError> { let capabilities = executor_summaries_when_unrestricted(capabilities); + // The lowered data: the caller's with the heaviest-value bindings. + let data = lowered.workload.data_workload.as_ref().unwrap_or(data); let entries: Vec = lowered .workload .query_workload diff --git a/crates/planner/tests/e2e_plan.rs b/crates/planner/tests/e2e_plan.rs index 63da6a9c8..90a559bd6 100644 --- a/crates/planner/tests/e2e_plan.rs +++ b/crates/planner/tests/e2e_plan.rs @@ -78,6 +78,7 @@ fn sql_workload( }, )] .into(), + heaviest_value_placeholders: Vec::new(), }), } } diff --git a/crates/planner/tests/summary_sharing.rs b/crates/planner/tests/summary_sharing.rs index ce7e77cb3..dc0882958 100644 --- a/crates/planner/tests/summary_sharing.rs +++ b/crates/planner/tests/summary_sharing.rs @@ -111,6 +111,7 @@ async fn plan_sql(queries: &[&str]) -> PlanOutput { }, )] .into(), + heaviest_value_placeholders: Vec::new(), }), }; let catalog = SqlCatalog::new().with_table( diff --git a/crates/stage3-plan-selection/src/cost.rs b/crates/stage3-plan-selection/src/cost.rs index c98cd907e..b1cca2867 100644 --- a/crates/stage3-plan-selection/src/cost.rs +++ b/crates/stage3-plan-selection/src/cost.rs @@ -1171,6 +1171,19 @@ fn logical_output<'a: 'b, 'b, 'c>( .output_facts .unchanged_columns .retain(|column| usage.output_facts.unchanged_columns.contains(column)); + // A column restricted by every candidate, at the most values any + // keeps: the baseline is the most any outputs. + let kept_values = &usage.output_facts.kept_values_per_column; + known + .output_facts + .kept_values_per_column + .retain(|column, values| match kept_values.get(column) { + Some(&other) => { + *values = (*values).max(other); + true + } + None => false, + }); } output } diff --git a/crates/types/src/workload/bounds.rs b/crates/types/src/workload/bounds.rs index 2331de905..2bdd0f58d 100644 --- a/crates/types/src/workload/bounds.rs +++ b/crates/types/src/workload/bounds.rs @@ -420,7 +420,8 @@ pub fn unchanged_source_columns<'a>( | NonASAPOp::Limit { .. } | NonASAPOp::Dedup { .. } | NonASAPOp::TimeRange { .. } - | NonASAPOp::TimeShift { .. } => kept(), + | NonASAPOp::TimeShift { .. } + | NonASAPOp::TimeRangeCover { .. } => kept(), NonASAPOp::Project { cols, .. } => { passed_on(&mut cols.iter().map(|col| match col.expr { ScalarExpr::Column(input) => Some(input), @@ -480,6 +481,7 @@ pub fn unchanged_source_columns<'a>( ASAPOp::SummaryAgg { .. } | ASAPOp::SummaryTumblingWindowChain { .. } | ASAPOp::SummaryMerge { .. } + | ASAPOp::SummaryMergeWindows { .. } | ASAPOp::SummaryEstimate { .. } | ASAPOp::FinalizeExactAccumulator { .. }, ) => kept(), @@ -507,10 +509,11 @@ pub fn unchanged_source_columns<'a>( /// - `rows_read`, the rows the grouping reads per evaluation: each row is /// in at most one group. /// -/// `kept_values_per_column` (column -> distinct values left after the -/// IN-lists below the grouping) is not read yet: test-first placeholder of -/// the IN-list selectivity rule (a restricted key counts its kept values; -/// the declared series scale by the restricted columns' shares). +/// `kept_values_per_column` holds the distinct values left of each column +/// IN-lists below the grouping restrict: a restricted key counts its kept +/// share of its declared values (`GROUP BY host` under `host IN (10 of +/// 10,000)` is 10 groups), and the declared series keep the product of +/// the restricted columns' shares (each series has one value per label). pub fn group_count_bound( keys: &GroupKeys, input: Option<&Schema>, @@ -518,7 +521,7 @@ pub fn group_count_bound( unchanged_input_columns: &BTreeSet<&str>, data: &DataWorkload, rows_read: u64, - _kept_values_per_column: &BTreeMap<&str, u64>, + kept_values_per_column: &BTreeMap<&str, u64>, ) -> u64 { let labels = || -> Option> { keys.keys() @@ -536,11 +539,23 @@ pub fn group_count_bound( Some(total.saturating_add(*count)) }) }; + // A restricted column's share of its declared values, 1 when + // unrestricted or undeclared. + let kept_share = |label: &str| -> f64 { + kept_values_per_column + .get(label) + .zip(label_count(label)) + .map_or(1.0, |(&kept, declared)| { + (kept as f64 / declared.max(1) as f64).min(1.0) + }) + }; + let scaled = |count: u64, share: f64| ((count as f64 * share).round() as u64).max(1); let declared = || -> Option { if keys.is_without() || sources.is_empty() { return None; } let labels = labels()?; + let keys_share: f64 = labels.iter().map(|label| kept_share(label)).product(); // Keys that are one source row's unchanged labels: the source's // declared label sets bound their combinations. if let (1, Some(source)) = (sources.len(), sources.first()) { @@ -551,21 +566,34 @@ pub fn group_count_bound( return data .sources .get(*source)? - .declared_distinct_combinations(&labels); + .declared_distinct_combinations(&labels) + .map(|combinations| scaled(combinations, keys_share)); } } - labels.into_iter().try_fold(1u64, |product, label| { - Some(product.saturating_mul(label_count(label)?)) - }) + labels + .into_iter() + .try_fold(1u64, |product, label| { + Some(product.saturating_mul(label_count(label)?)) + }) + .map(|product| scaled(product, keys_share)) }; // Over several sources a group combines one series (or group of rows) // of each at most, as a join does; a union's groups are fewer. let declared_series = if sources.is_empty() { None } else { - sources.iter().try_fold(1u64, |product, source| { - Some(product.saturating_mul(data.sources.get(*source)?.series_count?)) - }) + sources + .iter() + .try_fold(1u64, |product, source| { + Some(product.saturating_mul(data.sources.get(*source)?.series_count?)) + }) + .map(|series| { + let share: f64 = kept_values_per_column + .keys() + .map(|label| kept_share(label)) + .product(); + scaled(series, share) + }) }; [declared(), declared_series, Some(rows_read)] .into_iter() @@ -690,6 +718,7 @@ mod tests { (metric.to_string(), facts) }) .collect(), + heaviest_value_placeholders: Vec::new(), }; // 1 000 series every 100 ms; 3 000 series every 300 ms. assert_eq!(source_rows_per_ms(&["a"].into(), &data), Some(10.0)); diff --git a/crates/types/src/workload/data.rs b/crates/types/src/workload/data.rs index 08f34eec0..3b3cf5d5b 100644 --- a/crates/types/src/workload/data.rs +++ b/crates/types/src/workload/data.rs @@ -114,6 +114,14 @@ pub struct DataWorkload { /// without an entry has no known facts. #[serde(default)] pub sources: BTreeMap, + /// Values a query is planned with before they are known that stand for + /// the heaviest values of their column (default: none): the first + /// placeholder of each SIL binding filled by an upstream `ORDER BY … + /// DESC LIMIT k`, which the intent lowering adds. An IN-list holding one + /// keeps the top-k share of the rows under the column's declared + /// `zipf_exponent_per_label`. Omitted from JSON when empty. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub heaviest_value_placeholders: Vec, } /// What is known about one source (a PromQL metric or a SQL table). Every @@ -210,6 +218,15 @@ pub struct SourceFacts { /// NULL) as one more value, and positive. Omitted from JSON when empty. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub distinct_values_per_label: BTreeMap, + /// The skew of rows over a label's values (default: none declared): the + /// Zipf exponent s such that the value of rank i holds a share of the + /// rows proportional to 1/i^s, e.g. `{"host": 1.0}`. An IN-list holding + /// the heaviest k of the label's N declared values (a SIL binding from + /// an upstream top-k, `DataWorkload::heaviest_value_placeholders`) + /// keeps H_k(s)/H_N(s) of the rows (0.299 for 10 of 10,000 at s = 1); + /// without it every IN-list keeps k/N. Omitted from JSON when empty. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub zipf_exponent_per_label: BTreeMap, /// How many distinct combinations sets of labels (or columns) take /// together, for labels that depend on each other (default: none /// declared), e.g. `[{"labels": ["service", "endpoint"], @@ -418,6 +435,7 @@ impl DataWorkload { .into_iter() .map(|metric| (metric, sampled.clone())) .collect(), + heaviest_value_placeholders: Vec::new(), } } @@ -833,6 +851,7 @@ mod tests { ..SourceFacts::default() }, )]), + heaviest_value_placeholders: Vec::new(), }; assert!(with(10.0, Some(15_000)).validate().is_ok()); assert!(with(0.0, None).validate().is_ok()); @@ -926,6 +945,7 @@ mod tests { ("c".to_string(), facts(Counter)), ("g_sum".to_string(), facts(Gauge)), ]), + heaviest_value_placeholders: Vec::new(), }; let series_type = |series: &str| data.series_facts(series).map(|(_, t)| t); assert_eq!(series_type("h"), Some(Some(Histogram))); diff --git a/crates/types/src/workload/planning.rs b/crates/types/src/workload/planning.rs index 6060cad51..a3eb64ed1 100644 --- a/crates/types/src/workload/planning.rs +++ b/crates/types/src/workload/planning.rs @@ -237,8 +237,10 @@ mod tests { distinct_values: 1_000, }], rows_held: Some(1_000_000), + zipf_exponent_per_label: BTreeMap::new(), }, )]), + heaviest_value_placeholders: Vec::new(), }), }; From e2c15cba77042b649d2651306fbab733cf681127 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:05:52 +0000 Subject: [PATCH 3/8] feat(pass2): the compensation filter below the window merge A `Filter` on a summary state group's keys gets the candidate `SummaryMerge{group_by: keys}(Filter(p, W))`, `W` the chain windows the group's window merge reads, so the merge reads only the kept keys' states (drill_cnt's lightcone: 10 of 10,000 hosts' states, not 1,003,333). Aggregate coverage derives for a key filter over a chain's windows, and a regrouping merge maps keys past the windows' `window_end`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- .../stage1-pass2-reuse-candidates/src/lib.rs | 1 + .../src/rules/filter_below_window_merge.rs | 113 ++++++++++++++++++ .../src/rules/mod.rs | 1 + .../src/tests/rollup/finest_common_group.rs | 19 ++- .../logical/group/aggregate_coverage.rs | 52 +++++++- 5 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 crates/stage1-pass2-reuse-candidates/src/rules/filter_below_window_merge.rs diff --git a/crates/stage1-pass2-reuse-candidates/src/lib.rs b/crates/stage1-pass2-reuse-candidates/src/lib.rs index f2c43c09f..2ae609f3b 100644 --- a/crates/stage1-pass2-reuse-candidates/src/lib.rs +++ b/crates/stage1-pass2-reuse-candidates/src/lib.rs @@ -123,6 +123,7 @@ pub fn generate_logical_asap_memo_candidates( &candidates_of(&before_chains), &edges_before_chains, )?; + rules::filter_below_window_merge::add_filters_below_window_merges(&mut memo)?; let order = topological_order(&memo)?; let evaluation_grid_of_group = evaluation_grids(&evaluation_period_ms_per_query(&memo, entries)); diff --git a/crates/stage1-pass2-reuse-candidates/src/rules/filter_below_window_merge.rs b/crates/stage1-pass2-reuse-candidates/src/rules/filter_below_window_merge.rs new file mode 100644 index 000000000..6256aabc7 --- /dev/null +++ b/crates/stage1-pass2-reuse-candidates/src/rules/filter_below_window_merge.rs @@ -0,0 +1,113 @@ +//! A `Filter` on the keys of a summary state group, below the merge of its +//! windows: `Filter(p, SummaryMerge(W))` computed as `SummaryMerge{group_by: +//! keys}(Filter(p, W))`, where `W` selects a chain's tumbling windows (a +//! `TimeRange` or `TimeRangeCover` over its levels) and `keys` are the +//! state group's key columns in `W`'s rows (the merge by them drops the +//! windows' `window_end`). Merging states per key and selecting keys +//! commute, so the merge then reads only the selected keys' states. +//! Example: the compensation `host = p0 OR … OR p9` over a (host, user) +//! count kept over 10 min: the merge reads 10/10,000 of the windows' +//! 1,003,333 states, not all of them. + +use crate::rules::candidates::{add_candidates_per_input_parameters, add_group_computing_itself}; +use crate::Pass2RuleError; +use asap_types::ir::schema::FieldDataType; +use asap_types::ir::{ASAPOp, NonASAPOp, Operator, Predicate}; +use asap_types::stages::{Memo, MemoGroupId, OriginOfCandidateForMemoGroup}; + +/// Adds to each group `Filter(p, S)` whose predicate reads only key +/// columns of `S`, and each candidate `SummaryMerge(W)` of `S` (no +/// regrouping), the candidate `SummaryMerge{group_by: keys}(Filter(p', W))`, +/// `p'` and `keys` reading `S`'s key columns by name in `W`'s rows. Runs after the chain groups +/// (`chains::add_chain_groups`), which add the merges of windows. +pub(crate) fn add_filters_below_window_merges(memo: &mut Memo) -> Result<(), Pass2RuleError> { + let mut additions: Vec<(MemoGroupId, Operator, Vec)> = Vec::new(); + for (index, group) in memo.groups().iter().enumerate() { + let Operator::NonASAP(NonASAPOp::Filter { + pred, + child: states, + }) = &group.expression + else { + continue; + }; + let states_group = &memo.groups()[states.0 as usize]; + let state_fields = &states_group.group_properties.schema.fields; + let columns = pred.0.columns_referenced(); + // Only keys: a plain column, never the state. + if columns.is_empty() + || columns.iter().any(|&column| { + state_fields + .get(column) + .is_none_or(|field| !matches!(field.dtype, FieldDataType::Plain(_))) + }) + { + continue; + } + for candidate in &states_group.candidates { + let Operator::ASAP(ASAPOp::SummaryMerge { + children, + group_by: None, + }) = &candidate.expression.operator + else { + continue; + }; + let [windows] = children.as_slice() else { + continue; + }; + if !matches!( + memo.groups()[windows.0 as usize].expression, + Operator::NonASAP(NonASAPOp::TimeRange { .. } | NonASAPOp::TimeRangeCover { .. }) + ) { + continue; + } + let window_fields = &memo.groups()[windows.0 as usize] + .group_properties + .schema + .fields; + let at_windows = |name: &str| window_fields.iter().position(|f| f.name == name); + let mut missing = false; + let pred_over_windows = pred.0.map_columns(&mut |column| { + at_windows(&state_fields[column].name).unwrap_or_else(|| { + missing = true; + column + }) + }); + // `S`'s keys, its plain columns, in its order. + let keys: Option> = state_fields + .iter() + .filter(|field| matches!(field.dtype, FieldDataType::Plain(_))) + .map(|field| at_windows(&field.name)) + .collect(); + let Some(keys) = keys.filter(|_| !missing) else { + continue; + }; + let filter = Operator::NonASAP(NonASAPOp::Filter { + pred: Predicate(pred_over_windows), + child: *windows, + }); + if !additions + .iter() + .any(|(group, known, _)| group.0 as usize == index && *known == filter) + { + additions.push((MemoGroupId(index as u32), filter, keys)); + } + } + } + for (group, filter, keys) in additions { + let filtered = add_group_computing_itself( + memo, + filter, + OriginOfCandidateForMemoGroup::TumblingWindows, + )?; + add_candidates_per_input_parameters( + memo, + group, + Operator::ASAP(ASAPOp::SummaryMerge { + children: vec![filtered], + group_by: Some(keys), + }), + OriginOfCandidateForMemoGroup::TumblingWindows, + )?; + } + Ok(()) +} diff --git a/crates/stage1-pass2-reuse-candidates/src/rules/mod.rs b/crates/stage1-pass2-reuse-candidates/src/rules/mod.rs index b04d231f0..a440edcc8 100644 --- a/crates/stage1-pass2-reuse-candidates/src/rules/mod.rs +++ b/crates/stage1-pass2-reuse-candidates/src/rules/mod.rs @@ -4,5 +4,6 @@ //! consumer, so every consumer of a group sees what a rule adds to it. pub(crate) mod candidates; pub(crate) mod chains; +pub(crate) mod filter_below_window_merge; pub(crate) mod rollup; pub(crate) mod topk; diff --git a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/finest_common_group.rs b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/finest_common_group.rs index c7f8ed74f..3b2f8145d 100644 --- a/crates/stage1-pass2-reuse-candidates/src/tests/rollup/finest_common_group.rs +++ b/crates/stage1-pass2-reuse-candidates/src/tests/rollup/finest_common_group.rs @@ -103,7 +103,24 @@ fn a_finest_common_group_no_query_asks_for_serves_both() { }), ) .expect("Filter(host = \"xxx\", G*)"); - assert_eq!(candidates_of(memo, filter).len(), listed); + // The filter over G* per θ, and per θ the merge by G*'s keys over the + // same filter below G*'s window merge (`filter_below_window_merge`). + let (filters, below_merge): (Vec<_>, Vec<_>) = + candidates_of(memo, filter).iter().partition(|c| { + matches!( + c.expression.operator, + Operator::NonASAP(NonASAPOp::Filter { .. }) + ) + }); + assert_eq!(filters.len(), listed); + assert_eq!(below_merge.len(), listed); + assert!(below_merge.iter().all(|c| matches!( + c.expression.operator, + Operator::ASAP(ASAPOp::SummaryMerge { + group_by: Some(_), + .. + }) + ))); assert_eq!( merges(by_job), vec![ diff --git a/crates/types/src/stages/logical/group/aggregate_coverage.rs b/crates/types/src/stages/logical/group/aggregate_coverage.rs index 54df6e5a0..87f7ccabf 100644 --- a/crates/types/src/stages/logical/group/aggregate_coverage.rs +++ b/crates/types/src/stages/logical/group/aggregate_coverage.rs @@ -204,6 +204,24 @@ pub(super) fn aggregate_coverage<'m>( Operator::ASAP(ASAPOp::SummaryMergeWindows { child, .. }) => stored_coverage(child) .cloned() .ok_or(CoverageError::NoCoverage), + // Key-selecting filter over a chain's windows: their coverage, its + // selection narrowed by the predicate's constraints. + Operator::NonASAP(NonASAPOp::Filter { pred, child }) + if operator.output_kind() == OperatorResultKind::State + && matches!( + child.operator(), + Operator::NonASAP( + NonASAPOp::TimeRange { .. } + | NonASAPOp::TimeShift { .. } + | NonASAPOp::TimeRangeCover { .. } + ) + ) => + { + let coverage = stored_coverage(child) + .cloned() + .ok_or(CoverageError::NoCoverage)?; + narrowed_by(coverage, pred, &child.group_properties().column_lineage) + } Operator::NonASAP(_) => match selected_build(operator)? { Some(build) => of_summary_agg(&build), None => Err(CoverageError::NoCoverage), @@ -281,6 +299,29 @@ pub(super) fn aggregate_coverage<'m>( } } +/// `coverage` with each box narrowed by `pred`'s conjuncts, each a +/// constraint on a source column of the states' rows (`lineage`); no +/// coverage when a conjunct is not one or a box would select nothing it +/// can state. Example: `host IN (h0, h1)` over the windows of a (host, +/// user) count adds `host IN (h0, h1)` to the windows' selection. +fn narrowed_by( + mut coverage: AggregateCoverage, + pred: &Predicate, + lineage: &[ColumnLineage], +) -> Result { + let lineage: Vec> = lineage.iter().cloned().map(Some).collect(); + for conjunct in pred.0.conjuncts() { + let (column, constraint) = constraint_of(conjunct).ok_or(CoverageError::NoCoverage)?; + let column = source_column(&lineage, column).ok_or(CoverageError::NoCoverage)?; + for selection in &mut coverage.selection { + let combined = combined_with(selection.columns.get(&column), constraint.clone()) + .ok_or(CoverageError::NoCoverage)?; + selection.columns.insert(column.clone(), combined); + } + } + Ok(coverage) +} + /// For a `Filter` that keeps whole states of a grouped `SummaryAgg` by /// their key columns, the build that computes exactly the kept states: the /// same build over its input rows filtered by the same predicate on the @@ -426,16 +467,23 @@ fn regrouped( let state = first.group_properties(); let rows = build_input(first).ok_or(CoverageError::NoCoverage)?; let rows_lineage = &rows.group_properties().column_lineage; + // A chain's windows carry `window_end` (column 0) before the build's + // columns: a key's position in the build is one less, and `window_end` + // is no key. + let window_columns = usize::from(state.schema.time_index == Some(0)); // The build's input column each key of the state names: the column of // the key's lineage (a computed key only the column of the same group // and column). let mapped = keys .iter() .map(|&key| { + let built_key = key.checked_sub(window_columns); let column = match reduction { - Reduction::Reduce(by) if !by.is_without() => by.keys().get(key).copied(), + Reduction::Reduce(by) if !by.is_without() => { + built_key.and_then(|built_key| by.keys().get(built_key).copied()) + } // A per-series state keeps its input's columns in place. - Reduction::PerEntity => Some(key), + Reduction::PerEntity => built_key, Reduction::Reduce(_) => None, }; column From 0673ed1db82cdff90258c97985d3f99861d62d32 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:09:08 +0000 Subject: [PATCH 4/8] test: IN-list selectivity definitions that changed, and the skew tests - E2/Q5-E3/S2: the lightcone's chain build is the same for every |$Y|; the wider levels kept over it may differ (they trade off against the query-time merge, which now shrinks with |$Y|), so only the chain lines are compared, and the windows each filter reads may differ. - Q5-E2: the selection finds a cheaper shape than the plan's estimate (one 10 s level filtered before the merge, 89.03/s): at most ~97/s. - S1: q2's time range over the rows read grows 10x from |$Y| = 5 to 50; its scan's kept raw data and per-request cost do not scale. - planner_fuzz (l): the numerator's label matcher keeps its share, so the plain graft may be the cheapest witness. - New: E8 (heaviest bound hosts keep H_10/H_10000 under Zipf(1); literal hosts keep k/N) and the lowering marking a count-ranked binding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/devtools/tests/planner_fuzz.rs | 8 +- .../planner-cli/tests/inlist_selectivity.rs | 75 ++++++++++++----- crates/planner/tests/sil_intents.rs | 84 +++++++++++++++---- 3 files changed, 127 insertions(+), 40 deletions(-) diff --git a/crates/devtools/tests/planner_fuzz.rs b/crates/devtools/tests/planner_fuzz.rs index 6037f5f9d..0271e011c 100644 --- a/crates/devtools/tests/planner_fuzz.rs +++ b/crates/devtools/tests/planner_fuzz.rs @@ -305,8 +305,10 @@ fn smaller_topk_witness_costs_over_the_same_input() { } /// (l): a filtered share of a grouped rate reads the rate from q's result -/// (ASAPWorkloads #12); the plain graft cannot cost (its numerator is an -/// unplanned raw rate), so the witness planned with the operand must. +/// (ASAPWorkloads #12): a witness builds and costs. The numerator's label +/// matcher keeps its share of the rows (IN-list selectivity), so the plain +/// graft over the raw rate of that one label value may now be the +/// cheapest; before, only the witness planned with the operand costed. #[test] fn ratio_witness_costs_over_the_shared_rate() { let q = promql( @@ -316,7 +318,7 @@ fn ratio_witness_costs_over_the_shared_rate() { ); assert!(matches!( witness_of(Relation::BinaryOverResult, generated(q, false)), - Witness::GraftWithOperand { .. } + Witness::GraftWithOperand { .. } | Witness::Graft { .. } )); } diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 4c36749b6..195123da2 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -155,12 +155,19 @@ impl Planned { .collect() } - /// The ingestion-time nodes of the plan, without ids, sorted. - fn ingestion_lines(&self) -> Vec<(String, String, String, String)> { + /// The lightcone's chain builds: the ingestion-time chains over all + /// 100,000 (host, user) groups, without ids, sorted. The wider levels + /// over them are left out: which the selection keeps trades off against + /// the query-time merge, which shrinks with |$Y|. + fn lightcone_chain_lines(&self) -> Vec<(String, String, String, String)> { let mut lines: Vec<_> = self .nodes .values() - .filter(|node| node.timing == "ingestion_time") + .filter(|node| { + node.timing == "ingestion_time" + && node.operator == "SummaryTumblingWindowChain" + && node.detail.contains("for 100000 groups") + }) .map(NodeLine::without_id) .collect(); lines.sort(); @@ -341,8 +348,8 @@ fn query_time_cost_grows_with_the_in_list_size() { } /// E2. The lightcone's kept state is built without the IN-list (the hole -/// guard keeps every placeholder at query time), so its ingestion-time -/// nodes cost the same for every |$Y|; only the query-time compensation +/// guard keeps every placeholder at query time), so its (host, user) chain +/// build costs the same for every |$Y|; only the query-time compensation /// filter and what reads it shrink with k/N. q2 is forced onto the /// lightcone (no query-time scan). Today the filter passes 100,000 rows /// and the merge by user merges 100,000 states for every |$Y|. @@ -350,7 +357,8 @@ fn query_time_cost_grows_with_the_in_list_size() { fn kept_state_cost_does_not_depend_on_the_in_list_size() { let small = full(10, &[no_query_time_scan()]); let large = full(1_000, &[no_query_time_scan()]); - assert_eq!(small.ingestion_lines(), large.ingestion_lines()); + assert!(!small.lightcone_chain_lines().is_empty()); + assert_eq!(small.lightcone_chain_lines(), large.lightcone_chain_lines()); let chains: Vec<_> = small .reached(1) .into_iter() @@ -368,8 +376,8 @@ fn kept_state_cost_does_not_depend_on_the_in_list_size() { }; let (kept_small, read_small) = filter_kept(&small); let (kept_large, read_large) = filter_kept(&large); - assert_eq!(read_small, read_large); - // 10 and 1,000 of 10,000 hosts. + // 10 and 1,000 of 10,000 hosts, of the windows' states each plan + // reads (which levels it keeps trades off against this filter). assert_eq!(kept_small, (read_small as f64 / 1_000.0).round() as u64); assert_eq!(kept_large, (read_large as f64 / 10.0).round() as u64); // The merge by user reads the 10 hosts' 100 users' states. @@ -568,26 +576,27 @@ fn the_compensation_filter_runs_before_the_time_merge() { } } -/// Q5-E2. Forced onto the lightcone at |$Y| = 10, the plan costs q1 -/// (≈27.85/s) plus the lightcone's ingestion (≈67.87/s) plus q2's query -/// time: the cover (≈1.10/s), the filter over 1,003,333 states (≈0.10/s) -/// and merges and a finalize over ≈1,000 and 100 states (≈0.07/s): -/// ≈97.0/s within 2%. Without Q5 (filter above the time merge) ≈130.9/s; -/// today 169.2572/s. +/// Q5-E2. Forced onto the lightcone at |$Y| = 10, the compensation filter +/// below the window merge makes the lightcone cost q1 (≈27.85/s) plus the +/// (host, user) chain (≈53.8/s) plus q2's query time over the kept hosts' +/// windows (≈7.4/s): at most the ≈97.0/s the test plan estimated for a +/// filter over the cover levels (the selection found a cheaper shape: one +/// 10 s level, no wider levels to maintain, 89.03/s). Without Q5 (filter +/// above the time merge) ≈130.9/s; before the IN-list rule 169.2572/s. #[test] fn filtering_before_the_time_merge_cuts_the_forced_lightcone_cost() { let planned = full(10, &[no_query_time_scan()]); assert!( - close(planned.cost_per_second, 97.0, 0.02), - "{} (≈97.0/s expected)", + planned.cost_per_second <= 97.0 && planned.cost_per_second > 27.85 + 53.7, + "{} (at most ≈97.0/s expected)", planned.cost_per_second ); } /// Q5-E3 (invariants). With the filter below the time merge, every node /// holding a placeholder still runs at query time (so none is kept across -/// evaluations: only ingestion-time nodes are), and the kept state is the -/// same for |$Y| = 10 and 1,000 (byte-identical ingestion lines). +/// evaluations: only ingestion-time nodes are), and the lightcone's chain +/// build is the same for |$Y| = 10 and 1,000 (byte-identical lines). #[test] fn the_hole_guard_holds_with_the_filter_below_the_time_merge() { for k in [10, 1_000] { @@ -599,8 +608,8 @@ fn the_hole_guard_holds_with_the_filter_below_the_time_merge() { } } assert_eq!( - full(10, &[no_query_time_scan()]).ingestion_lines(), - full(1_000, &[no_query_time_scan()]).ingestion_lines() + full(10, &[no_query_time_scan()]).lightcone_chain_lines(), + full(1_000, &[no_query_time_scan()]).lightcone_chain_lines() ); } @@ -654,3 +663,29 @@ fn pass2_offers_the_compensation_filter_over_the_windows() { "no SummaryMerge over Filter(TimeRangeCover) in pass 2" ); } + +/// E8 (skew). With a Zipf(1) skew declared on `auth`'s hosts and q2's +/// placeholders marked as the heaviest hosts (`heaviest_value_placeholders`, +/// which the SIL lowering adds for a count-ranked `ORDER BY … DESC LIMIT +/// k`), q2's scan keeps the top 10 hosts' share H_10/H_10000 = 0.2993 of +/// the 6,000,000 rows, not 10/10,000; the same IN-list of literal hosts +/// (arbitrary values, not marked) keeps 10/10,000. +#[test] +fn the_heaviest_bound_values_keep_their_zipf_share() { + let skewed = |values: Values| { + let mut workload = workload(10, values, false, true); + workload["data_workload"]["sources"]["auth"]["zipf_exponent_per_label"] = + json!({"host": 1.0}); + if values == Values::Placeholders { + workload["data_workload"]["heaviest_value_placeholders"] = + json!([{"Utf8": values.value(0)}]); + } + plan(&workload, &capabilities(values, true, &[])) + }; + let heaviest = skewed(Values::Placeholders); + let scans = heaviest.reached_of(1, "Scan"); + assert_eq!(number_after(&scans[0].detail, "scan "), 1_795_517); + let literal = skewed(Values::Literals); + let scans = literal.reached_of(1, "Scan"); + assert_eq!(number_after(&scans[0].detail, "scan "), 6_000); +} diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index 3ebeeb24b..85ae451da 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -991,9 +991,13 @@ async fn planned_excluding( .expect("the intent plans") } -/// The cost per second of the nodes `query_id` reads that no other query -/// of the intent reads. -fn own_cost(plan: &IntentPlan, report: &asap_planner::SelectedPlanReport, query_id: &str) -> f64 { +/// The cost per second of each node `query_id` reads that no other query +/// of the intent reads, with its operator. +fn own_costs( + plan: &IntentPlan, + report: &asap_planner::SelectedPlanReport, + query_id: &str, +) -> Vec<(asap_planner::OperatorKind, f64)> { let dag = &plan.plan.dag; let root_of = |q: &asap_planner::intent::IntentRoundQuery| dag.roots[q.query_index]; let queries = &plan.intent_rounds[0].queries; @@ -1012,8 +1016,8 @@ fn own_cost(plan: &IntentPlan, report: &asap_planner::SelectedPlanReport, query_ .per_node .iter() .filter(|node| own.contains(&node.node_id) && !others.contains(&node.node_id)) - .map(|node| node.cost_per_second.expect("cost model 1")) - .sum() + .map(|node| (node.operator, node.cost_per_second.expect("cost model 1"))) + .collect() } /// q1 the top `k` of 1,000 hosts, q2 the users of those hosts' `auth` @@ -1027,12 +1031,15 @@ fn top_k_hosts_then_their_users(k: usize) -> String { } /// S1. With the hole read at query time (on-demand holes), q2 reads the -/// rows of the |$Y| bound hosts: binding 50 of 1,000 hosts costs it about -/// 10x binding 5 (its per-request cost aside). Today both cost the same. +/// rows of the |$Y| bound hosts: binding 50 of 1,000 hosts costs it more +/// than binding 5, and its time range over the rows read costs 10x as +/// much (the scan's raw data kept on disk, the per-request cost and the +/// aggregate's per-group work do not scale with |$Y|). Before the IN-list +/// rule both cost the same. #[tokio::test] async fn dependent_query_cost_grows_with_the_binding_size() { let data = data(1_000, 1_000, 10_000.0); - let q2_cost = |k| { + let q2_costs = |k| { let queries = top_k_hosts_then_their_users(k); let data = data.clone(); async move { @@ -1044,15 +1051,25 @@ async fn dependent_query_cost_grows_with_the_binding_size() { ) .await; assert_eq!(slot_size_of(&plan, "q2"), k as u64); - own_cost(&plan, &report, "q2") + own_costs(&plan, &report, "q2") } }; - let five = q2_cost(5).await; - let fifty = q2_cost(50).await; - let ratio = fifty / five; + let total = + |costs: &[(asap_planner::OperatorKind, f64)]| costs.iter().map(|(_, c)| c).sum::(); + let range = |costs: &[(asap_planner::OperatorKind, f64)]| { + costs + .iter() + .filter(|(operator, _)| *operator == asap_planner::OperatorKind::TimeRange) + .map(|(_, c)| c) + .sum::() + }; + let five = q2_costs(5).await; + let fifty = q2_costs(50).await; + assert!(total(&fifty) > total(&five), "{fifty:?} vs {five:?}"); + let ratio = range(&fifty) / range(&five); assert!( - (8.0..=10.5).contains(&ratio), - "q2 at |$Y| = 50 costs {fifty}, at 5 {five}: {ratio}x" + (ratio - 10.0).abs() < 0.1, + "time range {ratio}x: {fifty:?} vs {five:?}" ); } @@ -1070,8 +1087,9 @@ fn slot_size_of(plan: &IntentPlan, query_id: &str) -> u64 { /// S2. The lightcone's state is kept for every host whatever the binding /// (the hole guard keeps the IN-list at query time): the full-mode /// workload planned with the hole guard and no query-time scan (so q2 -/// reads the lightcone) has the same ingestion-time nodes at the same costs -/// for |$Y| = 5 and 50. (`plan_intents` cannot force it: its plan without +/// reads the lightcone) builds the same chains at the same costs for +/// |$Y| = 5 and 50 (the wider levels kept over them may differ: they trade +/// off against the query-time merge, which shrinks with |$Y|). (`plan_intents` cannot force it: its plan without /// the lightcone must be feasible too.) #[tokio::test] async fn the_lightcone_build_does_not_shrink_with_the_binding_size() { @@ -1117,7 +1135,10 @@ async fn the_lightcone_build_does_not_shrink_with_the_binding_size() { .predicted_usage .per_node .iter() - .filter(|node| node.timing == ExecutionTiming::IngestionTime) + .filter(|node| { + node.timing == ExecutionTiming::IngestionTime + && node.operator == asap_planner::OperatorKind::SummaryTumblingWindowChain + }) .map(|node| format!("{:?} {:.9e}", node.operator, node.cost_per_second.unwrap())) .collect(); costs.sort(); @@ -1179,3 +1200,32 @@ async fn full_intent_drops_the_lightcone_for_a_small_binding() { on_demand_report.cost_per_second ); } + +/// A count-ranked `ORDER BY … DESC LIMIT k` binds the heaviest hosts: the +/// lowering lists its binding's first placeholder in the data workload's +/// `heaviest_value_placeholders`, which the cost model reads with a +/// declared skew; a `GROUP BY` without a ranking binds no heaviest values. +#[tokio::test] +async fn a_count_ranked_binding_marks_its_placeholders_heaviest() { + use asap_types::ir::scalar::ScalarValue; + let top = lowered(&format!("{Q1_TOP_10_HOSTS}\n{Q2_USERS_OF_Y}")).await; + assert_eq!( + top.workload + .data_workload + .as_ref() + .unwrap() + .heaviest_value_placeholders, + [ScalarValue::Utf8("__sil_Y_0".into())] + ); + let all = lowered(&format!( + "q1: ($Y, _) := SELECT host, count(*) AS c FROM flows WHERE ts > $now - INTERVAL '1 hour' GROUP BY host REQUIRE EXACT;\n{Q2_USERS_OF_Y}" + )) + .await; + assert!(all + .workload + .data_workload + .as_ref() + .unwrap() + .heaviest_value_placeholders + .is_empty()); +} From 1ac977e6c24b4e4ebd052c0eeef74a72bb3985c8 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:02:31 +0000 Subject: [PATCH 5/8] fix(cost): a regrouping merge of filtered windows folds each window's state With one host bound, the compensation filter keeps 10 of the windows' 1,003,333 states, and the merge by the windows' keys counted its states per group as rows / groups (10/1 vs 10.03), so it folded 60.14 rows a state where the merge of all windows folds 60 and Stage 3's same-group check failed. A regrouping merge keeping each window's groups now merges its input's (exact) windows per group. The uniform rows-per-value warning names the missing `zipf_exponent_per_label`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 23 ++++++++++++++----- .../planner-cli/tests/inlist_selectivity.rs | 12 ++++++++++ .../types/src/workload/assumed_data_fact.rs | 17 +++++++------- 3 files changed, 38 insertions(+), 14 deletions(-) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 1fd483079..0330f41c2 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -2158,13 +2158,24 @@ pub(crate) fn node_usage_and_cost_terms<'a>( ) }; // Each input's states per group, every one folding its rows. + // A regrouping merge keeping each window's groups (by all the + // windows' keys, as below a key filter) merges one state per + // window into each: its input's windows, exact, as the merge of + // the unfiltered windows does (the filter rounds its states). let merged_input_rows = StateInputRows::merged(producers.iter().map(|producer| { - producer.output_facts.state_input_rows.map(|rows| { - ( - rows, - producer.output_facts.statistics.rows as f64 / group_count.max(1) as f64, - ) - }) + let rows = producer.output_facts.statistics.rows as f64; + let windows = producer.output_facts.tumbling_windows; + let states_per_group = match group_by.is_some() + && windows > 1.0 + && (rows / windows).round() as u64 == group_count + { + true => windows, + false => rows / group_count.max(1) as f64, + }; + producer + .output_facts + .state_input_rows + .map(|input_rows| (input_rows, states_per_group)) })); built_state_input_rows = merged_input_rows; // A merge target receives its inputs' states: priced open. diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 195123da2..c4d178dcf 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -689,3 +689,15 @@ fn the_heaviest_bound_values_keep_their_zipf_share() { let scans = literal.reached_of(1, "Scan"); assert_eq!(number_after(&scans[0].detail, "scan "), 6_000); } + +/// A single bound host: the filter below the window merge keeps 10 of +/// the windows' 1,003,333 states, which rounds their count far more than +/// the merge of all windows does; the merge still folds what the merge of +/// all windows folds per state (Stage 3 checks candidates of one group +/// fold the same rows), so the forced lightcone plans. +#[test] +fn a_single_bound_host_merges_its_windows_exactly() { + let planned = full(1, &[no_query_time_scan()]); + assert!(planned.cost_per_second.is_finite()); + assert_eq!(planned.reached_of(1, "Filter").len(), 1); +} diff --git a/crates/types/src/workload/assumed_data_fact.rs b/crates/types/src/workload/assumed_data_fact.rs index 37f457671..9d2a80b73 100644 --- a/crates/types/src/workload/assumed_data_fact.rs +++ b/crates/types/src/workload/assumed_data_fact.rs @@ -50,10 +50,11 @@ pub enum DataFactAssumption { /// order, a counter at 100 after 120 looks like a reset and adds 100 /// to an `increase`), or ingestion may reject the sample and fail. InOrderArrival, - /// The sources declare no per-value row counts for `column`, so an - /// IN-list keeping k of its N declared values is costed as keeping - /// k/N of the rows. A binding chosen by a top-k selects heavy values, - /// which hold more. Cost only. + /// The sources declare no skew for `column` + /// (`SourceFacts::zipf_exponent_per_label`), so an IN-list keeping k of + /// its N declared values is costed as keeping k/N of the rows. A + /// binding chosen by a top-k selects heavy values, which hold more. + /// Cost only. UniformRowsPerValue { column: String }, } @@ -113,8 +114,8 @@ impl fmt::Display for AssumedDataFact { )?, DataFactAssumption::UniformRowsPerValue { column } => write!( f, - "{sources} declares no per-value row counts for {column}, so an IN-list keeping \ - k of its N values is costed as keeping k/N of the rows" + "{sources} declares no zipf_exponent_per_label for {column}, so an IN-list \ + keeping k of its N values is costed as keeping k/N of the rows" )?, } if self.accuracy_target_depends_on_it() { @@ -218,8 +219,8 @@ mod tests { assert!(!uniform.accuracy_target_depends_on_it()); assert_eq!( uniform.to_string(), - "assumed data fact: source auth declares no per-value row counts for host, so an \ - IN-list keeping k of its N values is costed as keeping k/N of the rows; this \ + "assumed data fact: source auth declares no zipf_exponent_per_label for host, so \ + an IN-list keeping k of its N values is costed as keeping k/N of the rows; this \ affects cost only, the accuracy guarantee does not depend on it" ); assert_eq!( From 0c51235293ea9006f5dcae31096ea18e1feb8458 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:25:45 +0000 Subject: [PATCH 6/8] fix(cost): a key filter over states keeps its values' share, not its rows' Under a declared skew the heaviest 10 of 10,000 hosts hold 0.2993 of the rows but 10/10,000 of the per-key states (one per key and window). The compensation filter over the lightcone's windows kept 0.2993 of the states, so the merge by key folded ~18,000 rows a state against 60 for the merge of all windows. `KeptShare::value_share` (k/N per column) is what a filter over states keeps; a filter or scan over rows keeps `share`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/kept_share.rs | 7 ++++++ crates/cost/src/node/usage/mod.rs | 9 +++++++ .../planner-cli/tests/inlist_selectivity.rs | 24 +++++++++++++++++++ 3 files changed, 40 insertions(+) diff --git a/crates/cost/src/node/usage/kept_share.rs b/crates/cost/src/node/usage/kept_share.rs index dd40acb4e..1974bfc29 100644 --- a/crates/cost/src/node/usage/kept_share.rs +++ b/crates/cost/src/node/usage/kept_share.rs @@ -28,6 +28,10 @@ pub(super) struct DeclaredValues { pub(super) struct KeptShare<'a> { /// The share of rows kept, in (0, 1]. pub(super) share: f64, + /// The share of the restricted columns' values kept (k/N per column, + /// multiplied), in (0, 1]: what it keeps of per-key states, one per + /// group, whatever rows each folds. Equals `share` without skew. + pub(super) value_share: f64, /// Each restricted column's distinct values left: the input's entries /// with the predicate's IN-lists applied. pub(super) kept_values_per_column: BTreeMap<&'a str, u64>, @@ -54,6 +58,7 @@ pub(super) fn share_of_rows_kept<'a, C>( ) -> KeptShare<'a> { let mut kept = kept_values_per_column.clone(); let mut share = 1.0; + let mut value_share = 1.0; let mut assumed_uniform_columns = Vec::new(); for conjunct in conjuncts.iter().flat_map(|c| flattened(c)) { let Some((column, Constraint::In(values))) = constraint_of(conjunct) else { @@ -76,6 +81,7 @@ pub(super) fn share_of_rows_kept<'a, C>( .any(|value| heaviest_value_placeholders.contains(value)); let zipf_exponent = declared.zipf_exponent.filter(|_| heaviest); share *= share_of_rows_of_values(after, before, zipf_exponent); + value_share *= share_of_rows_of_values(after, before, None); kept.insert(name, after); if after < before && declared.zipf_exponent.is_none() @@ -86,6 +92,7 @@ pub(super) fn share_of_rows_kept<'a, C>( } KeptShare { share, + value_share, kept_values_per_column: kept, assumed_uniform_columns, } diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 0330f41c2..deb5b03e4 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -1808,6 +1808,15 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }, }, ); + // Over states (one per key and window) it keeps its + // values' share of them, however many rows each folds; over + // rows, its rows' share. + let share_kept = match outputs_states(&node.output_schema) { + true => kept_by_predicate + .as_ref() + .map_or(1.0, |kept| kept.value_share), + false => share_kept, + }; if share_kept < 1.0 { // Its raw rows at their exact rate when they are that // rate over their span (no rounding twice), else its diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index c4d178dcf..8d0fc17fd 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -701,3 +701,27 @@ fn a_single_bound_host_merges_its_windows_exactly() { assert!(planned.cost_per_second.is_finite()); assert_eq!(planned.reached_of(1, "Filter").len(), 1); } + +/// E9 (skew, lightcone). The heaviest 10 hosts hold 0.2993 of `auth`'s +/// rows but only 10 of its 10,000 hosts' (host, user) states, one per key +/// and window: forced onto the lightcone, the compensation filter keeps +/// 10/10,000 of the windows' states (its values' share), not 0.2993. +#[test] +fn a_skewed_binding_keeps_its_values_share_of_the_lightcone_states() { + let mut workload = workload(10, Values::Placeholders, true, true); + workload["data_workload"]["sources"]["auth"]["zipf_exponent_per_label"] = json!({"host": 1.0}); + workload["data_workload"]["heaviest_value_placeholders"] = + json!([{"Utf8": Values::Placeholders.value(0)}]); + let planned = plan( + &workload, + &capabilities(Values::Placeholders, true, &[no_query_time_scan()]), + ); + let filters = planned.reached_of(1, "Filter"); + assert_eq!(filters.len(), 1); + let detail = &filters[0].detail; + let (kept, read) = ( + number_after(detail, "filter: keep "), + number_after(detail, " of "), + ); + assert_eq!(kept, (read as f64 / 1_000.0).round() as u64, "{detail}"); +} From 86ea4fde8b8ad725e77dbb6694f3c0033aeca846 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:24:02 +0000 Subject: [PATCH 7/8] fix(cost): under skew each kept state folds its heavier key's rows A key filter over states keeps the values' share of them; under a declared skew each kept state then folds the rows' share over the values' share of the average (0.2993 / 0.001 for the heaviest 10 of 10,000 hosts), as a query-time build over the same selected rows does, so Stage 3's same-group check holds (E6 drill_cnt with `zipf_exponent_per_label {host: 1.0}`). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index deb5b03e4..1ee31446c 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -1812,9 +1812,25 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // values' share of them, however many rows each folds; over // rows, its rows' share. let share_kept = match outputs_states(&node.output_schema) { - true => kept_by_predicate - .as_ref() - .map_or(1.0, |kept| kept.value_share), + true => { + let value_share = kept_by_predicate + .as_ref() + .map_or(1.0, |kept| kept.value_share); + // Each kept state folds the rows of a heavier key: + // the rows' share over the states' (1 without skew). + if share_kept != value_share { + built_state_input_rows = producers + .first() + .and_then(|producer| producer.output_facts.state_input_rows) + .map(|mut rows| { + rows.folded_rows_per_state = rows + .folded_rows_per_state + .map(|folded| folded * share_kept / value_share); + rows + }); + } + value_share + } false => share_kept, }; if share_kept < 1.0 { From dae00dcb4436c07e1e3df2b85dd5415c522f6050 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:49:51 +0000 Subject: [PATCH 8/8] test(planner): the lightcone's key filter over chain windows runs on the executor The Q5 shape the planner picks when the lightcone pays, a `Filter` on the keys over a chain's windows read by a `SummaryMerge` by the chain's keys (then merged by user), planned from SQL and run on the executor's data plane: every view refreshed in ingestion runs, the query answered from the windows, each user's count of the selected service's rows exact. The executor already runs it (the merge groups by its keys whatever window a state is from); this pins it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/planner/tests/sql_table_scans.rs | 102 ++++++++++++++++++++++++ 1 file changed, 102 insertions(+) diff --git a/crates/planner/tests/sql_table_scans.rs b/crates/planner/tests/sql_table_scans.rs index 40df88316..948b0f260 100644 --- a/crates/planner/tests/sql_table_scans.rs +++ b/crates/planner/tests/sql_table_scans.rs @@ -586,3 +586,105 @@ async fn exact_aggregates_of_an_int64_column_are_built_at_ingestion_time() { expected(|ids| *ids.iter().max().unwrap()) ); } + +/// The lightcone shape the planner picks when keeping per-(service, user) +/// state pays (SIL intents, Q5): the dependent count by user over +/// `service IN ('s0')` reads the (service, user) count chain's windows +/// through a key `Filter`, regrouped by a `SummaryMerge` by the chain's +/// keys, then merged by user; the lightcone query itself is evaluated +/// about never. The deployment keeps no raw data, the +/// hole guard keeps `'s0'` at query time and out of kept state, and no +/// `Aggregate` (the rollup of finalized counts) is offered, so that shape +/// answers. The data plane runs the plan and answers each +/// user's count of `s0` rows in the last 5 minutes, as counted directly. +#[tokio::test] +async fn a_key_filter_over_chain_windows_regrouped_answers_exactly() { + let dependent = "SELECT user_id, COUNT(*) AS value FROM http \ + WHERE service IN ('s0') AND ts >= now() - INTERVAL '5 minutes' GROUP BY user_id"; + let lightcone = "SELECT service, user_id, COUNT(*) AS value FROM http \ + WHERE ts >= now() - INTERVAL '5 minutes' GROUP BY service, user_id"; + let guard: Vec = serde_json::from_value(serde_json::json!([ + {"timing": "ingestion_time", "reads_constant": {"Utf8": "s0"}}, + {"kept_across_evaluations": true, "reads_constant": {"Utf8": "s0"}}, + // The rollup of finalized counts (an exact `Aggregate` over the + // finalized lightcone) is the other shape; ruled out so the states' + // shape is the one run. + {"operator": "Aggregate"}, + ])) + .unwrap(); + let deployment = DeploymentCapabilities { + raw_data_retained: false, + excluded_candidates: guard, + ..DeploymentCapabilities::default() + }; + // The lightcone query is evaluated about never (as SIL plans it), so + // the time merge of all its windows is not needed every minute. + let mut workload = serde_json::to_value(workload( + &[dependent, lightcone], + APPROXIMATE, + MINUTE_MS as u64, + )) + .unwrap(); + workload["query_workload"]["repeating_queries"][1]["demand"]["fixed_interval_at"]["interval"] = + serde_json::json!(4_294_920_000u64); + let workload: PlanningWorkload = serde_json::from_value(workload).unwrap(); + let catalog = SqlCatalog::new().with_table("http", http_schema()); + let plan = plan_installable(UserInput::new( + &workload, + FrontendInput::Sql { catalog: &catalog }, + PlanningModels::builtin().with_deployment_capabilities(&deployment), + )) + .await + .expect("the lightcone workload plans") + .0; + // The dependent query reads a key filter over the chain's windows. + let node = |id: usize| plan.dag.nodes.iter().find(|n| n.id == id).unwrap(); + let filter_over_windows = plan.dag.nodes.iter().any(|n| match &n.payload { + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Filter { child, .. }) => matches!( + node(*child).payload, + PhysicalASAPOperatorPayload::NonASAP( + NonASAPOp::TimeRange { .. } | NonASAPOp::TimeRangeCover { .. } + ) + ), + _ => false, + }); + assert!(filter_over_windows, "{:#?}", plan.dag.nodes); + // A merge by the chain's keys reads that filter. + let regrouped_over_filter = plan.dag.nodes.iter().any(|n| match &n.payload { + PhysicalASAPOperatorPayload::ASAP(ASAPOp::SummaryMerge { + children, + group_by: Some(_), + }) => children.iter().any(|&child| { + matches!( + node(child).payload, + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Filter { .. }) + ) + }), + _ => false, + }); + assert!(regrouped_over_filter, "{:#?}", plan.dag.nodes); + let answers = run_data_plane(&plan); + let mut expected: BTreeMap = BTreeMap::new(); + let mut counts: BTreeMap = BTreeMap::new(); + for row in rows() { + let (Value::Timestamp(ts), Value::Utf8(service), Value::Int64(user)) = + (&row[0], &row[1], &row[2]) + else { + unreachable!() + }; + if *ts >= EVALUATION_MS - 5 * MINUTE_MS && &**service == "s0" { + *counts.entry(*user).or_default() += 1; + } + } + for (user, count) in counts { + expected.insert(user.to_string(), shown(&Value::Int64(count))); + } + let got: BTreeMap = answers[0] + .iter() + .map(|row| match &row[0] { + Value::Int64(user) => (user.to_string(), shown(&row[1])), + other => panic!("key {other:?}"), + }) + .collect(); + assert_eq!(got, expected); +}