From 5cddc747834b7b0ec8b83e09e986fa241bbe175a Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:31:09 +0000 Subject: [PATCH 01/18] test(cost): failing tests for a deployment's measured scan series, named scan/filter constants, raw rows in memory and active groups per window Test-first phase of the cost calibration (items 2-5 of the calibration proposal; item 1's cost file and the e2e tests follow in their own commit): - T2: a measured Scan entry's `ns_per_series` charges each series the scan visits (10 min of `auth`: 6,000,000 rows x 41 ns + 100,000 series x 8,700 ns = 1,116 ms); a negative one is refused. - item 3: a scan charges `ScanOperationsPerRow` per row read and its predicates `FilterOperationsPerRow` + `FilterOperationsPerRowPerComparedValue` per value compared; a Filter the same (reference executor: 1 + 2.4 ns per compared value per row). U1's last assertion now expects the IN-list's compared values on top of a TRUE filter. - T5: `raw_data_medium` Memory charges a query-time scan's retained raw rows as memory at `raw_data_bytes_per_row`, none on disk, objective = plan_cost. - T6: a chain emits and keeps states only for the groups its windows reach (100,000 rows over 100,000 groups: 63,212 per window); a dense chain is unchanged. Signatures only, behaviour kept: `OperatorCost::ns_per_series`, `UnitPrice::ns_per_series`, `DataPlaneExecution::{raw_data_medium, raw_data_bytes_per_row}`, `CostConstant::{ScanOperationsPerRow, FilterOperationsPerRow, FilterOperationsPerRowPerComparedValue}` and their `operations_per_unit` constants are added but not read yet. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/measured.rs | 12 + crates/cost/src/model.rs | 12 + crates/cost/src/node/cost_terms.rs | 8 + crates/cost/src/node/cost_terms/tests.rs | 7 +- crates/cost/src/node/operations_per_unit.rs | 23 ++ crates/cost/src/node/usage/tests.rs | 287 +++++++++++++++++- crates/cost/tests/measured_operation_costs.rs | 4 + crates/devtools/src/rqe_atomic_costs.rs | 1 + crates/integration-tests/src/lib.rs | 1 + .../tests/stage3_objective.rs | 49 +++ 10 files changed, 393 insertions(+), 11 deletions(-) diff --git a/crates/cost/src/measured.rs b/crates/cost/src/measured.rs index d9256ddde..437336d86 100644 --- a/crates/cost/src/measured.rs +++ b/crates/cost/src/measured.rs @@ -148,6 +148,12 @@ pub struct OperatorCost { /// per-group output row as a 360th of it per state; at 5 states per /// group that row is under-charged. pub ns_per_unit: f64, + /// For a `Scan`: CPU nanoseconds per series it visits in one + /// computation, beside `ns_per_unit` per sample: a store holding raw + /// rows by series finds and decodes each series it reads once per + /// read. Default 0. + #[serde(default, skip_serializing_if = "is_zero")] + pub ns_per_series: f64, /// CPU nanoseconds per computation of the node, whatever its units: /// per evaluation at query time, per second of arriving rows at /// ingestion time. Default 0. @@ -203,6 +209,8 @@ pub enum StateFamily<'a> { #[derive(Debug, Clone, Copy, PartialEq)] pub struct UnitPrice { pub ns_per_unit: f64, + /// CPU ns per series a scan visits (`OperatorCost::ns_per_series`). + pub ns_per_series: f64, pub ns_per_invocation: f64, pub memory_bytes_per_state: Option, /// File bytes per state's row (`OperatorCost::stored_bytes_per_state`). @@ -319,6 +327,7 @@ pub fn lookup_at_scale( let mix = |a: f64, b: f64| a + (b - a) * at; Some(UnitPrice { ns_per_unit: mix(low.ns_per_unit, high.ns_per_unit), + ns_per_series: mix(low.ns_per_series, high.ns_per_series), ns_per_invocation: mix(low.ns_per_invocation, high.ns_per_invocation), memory_bytes_per_state: low .memory_bytes_per_state @@ -377,6 +386,7 @@ fn at_series_count(entries: &[&OperatorCost], series: Option) -> Option UnitPrice { UnitPrice { ns_per_unit: entry.ns_per_unit, + ns_per_series: entry.ns_per_series, ns_per_invocation: entry.ns_per_invocation, memory_bytes_per_state: entry.memory_bytes_per_state, stored_bytes_per_state: entry.stored_bytes_per_state, diff --git a/crates/cost/src/model.rs b/crates/cost/src/model.rs index 4a2597da3..63cba33f6 100644 --- a/crates/cost/src/model.rs +++ b/crates/cost/src/model.rs @@ -5,6 +5,7 @@ use crate::node::analytical::AnalyticalCostError; use crate::MeasuredOperationCosts; +use asap_types::stages::StorageMedium; /// [`PlanCost::source`](crate::PlanCost::source) when every node is priced from the formulas. pub const COST_SOURCE: &str = "analytical-cost-v2 (illustrative statistics)"; @@ -290,6 +291,15 @@ pub struct DataPlaneExecution { /// `job`, `region` and `service` holds 4 + 4 × 4 = 20 bytes beside its /// state. pub key_bytes_per_label_column: u64, + /// Where the data plane keeps the raw rows its query-time scans read: + /// `Disk` (default), charged at the disk byte cost, or `Memory`, + /// charged at the memory byte cost. + pub raw_data_medium: StorageMedium, + /// The bytes one raw row takes where the data plane keeps it, as + /// measured on the deployment; `None` (default): the row's decoded + /// width. + #[serde(skip_serializing_if = "Option::is_none")] + pub raw_data_bytes_per_row: Option, } /// The default [`DataPlaneExecution::state_offset_bytes_per_row`]: a `u32`. @@ -369,6 +379,8 @@ impl Default for DataPlaneExecution { answer_cache: None, state_offset_bytes_per_row: DEFAULT_STATE_OFFSET_BYTES_PER_ROW, key_bytes_per_label_column: DEFAULT_KEY_BYTES_PER_LABEL_COLUMN, + raw_data_medium: StorageMedium::Disk, + raw_data_bytes_per_row: None, } } } diff --git a/crates/cost/src/node/cost_terms.rs b/crates/cost/src/node/cost_terms.rs index 3a2eaedba..ff5159b0b 100644 --- a/crates/cost/src/node/cost_terms.rs +++ b/crates/cost/src/node/cost_terms.rs @@ -31,6 +31,9 @@ use crate::{CostInputs, ProducerOutput}; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum CostConstant { + ScanOperationsPerRow, + FilterOperationsPerRow, + FilterOperationsPerRowPerComparedValue, TimeRangeOperationsPerRow, OperationsPerGroupPerRawBatch, ChainOperationsPerArrivingRow, @@ -89,6 +92,11 @@ impl CostConstant { /// the constant of the same name in `operations_per_unit`. pub fn operations_per_unit(self) -> f64 { match self { + CostConstant::ScanOperationsPerRow => built_in::SCAN_OPERATIONS_PER_ROW, + CostConstant::FilterOperationsPerRow => built_in::FILTER_OPERATIONS_PER_ROW, + CostConstant::FilterOperationsPerRowPerComparedValue => { + built_in::FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE + } CostConstant::TimeRangeOperationsPerRow => built_in::TIME_RANGE_OPERATIONS_PER_ROW, CostConstant::OperationsPerGroupPerRawBatch => { built_in::OPERATIONS_PER_GROUP_PER_RAW_BATCH diff --git a/crates/cost/src/node/cost_terms/tests.rs b/crates/cost/src/node/cost_terms/tests.rs index 114296eb8..3101c7c96 100644 --- a/crates/cost/src/node/cost_terms/tests.rs +++ b/crates/cost/src/node/cost_terms/tests.rs @@ -50,7 +50,7 @@ fn every_per_unit_constant_has_a_cost_constant() { .iter() .map(|constant| format!("{constant:?}")) .collect(); - assert_eq!(defined.len(), 51, "{defined:?}"); + assert_eq!(defined.len(), 54, "{defined:?}"); assert_eq!( defined.difference(&variants).collect::>(), Vec::<&String>::new(), @@ -103,7 +103,10 @@ fn cost_constant_json_names_are_the_full_snake_case_list() { } /// Every constant's JSON name, in declaration order. -const JSON_NAMES: [&str; 51] = [ +const JSON_NAMES: [&str; 54] = [ + "scan_operations_per_row", + "filter_operations_per_row", + "filter_operations_per_row_per_compared_value", "time_range_operations_per_row", "operations_per_group_per_raw_batch", "chain_operations_per_arriving_row", diff --git a/crates/cost/src/node/operations_per_unit.rs b/crates/cost/src/node/operations_per_unit.rs index 40757481a..f89faf704 100644 --- a/crates/cost/src/node/operations_per_unit.rs +++ b/crates/cost/src/node/operations_per_unit.rs @@ -68,6 +68,29 @@ use crate::node::cost_terms::{CostConstant, NodeCostTerms}; use crate::node::state_bytes::StateInputRows; use crate::StateFamily; +/// A row a scan reads from the reference executor's store, beside its +/// bytes (priced apart, `ResourceSpeed::ms_per_scanned_byte`): the store +/// hands each batch on whole, so a row costs its batch's share, 0.2 ns in +/// batches of 10,000 rows and 1.9 ns in batches of 1,000 (2,000,000 rows +/// of 1,000 to 100,000 series, median of 5 runs on one idle core; the +/// series count does not change it). A deployment whose store finds and +/// decodes each series pays per row and per series, which its measured +/// cost file gives (`OperatorCost::ns_per_series`). +pub(crate) const SCAN_OPERATIONS_PER_ROW: f64 = 1.0; + +/// Per row a filter, or a scan's predicates, reads: evaluating the +/// predicate and building the kept rows' batch, beside the values it +/// compares (`FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE`). Fitted with +/// it on the reference executor over 2,000,000 rows in batches of 10,000: +/// a one-value IN-list measures 3.5 ns per row, ten values 25.7, a hundred +/// 244 (a filter node and a scan's predicate alike); in batches of 1,000 +/// each costs about 10 ns per row more. +pub(crate) const FILTER_OPERATIONS_PER_ROW: f64 = 1.0; + +/// Per value a filter compares each row with: an IN-list's values, an +/// equality's one (see `FILTER_OPERATIONS_PER_ROW`; fitted 2.4). +pub(crate) const FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE: f64 = 2.4; + /// A row kept by a time range over raw rows, or a state read by a time /// range over a chain's tumbling windows: 9–16 ns per row (median 11) over /// 54 time ranges of 30,000 to 36 M rows at 1 Hz and 10 Hz over 100, 1,000 diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 47e8a30e7..957b3de71 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -3361,20 +3361,20 @@ fn a_quantile_aggregate_keeps_its_rounding_outside_the_constants() { } /// A query-time scan of 5 min of `latency` (1,000 series at 1 Hz) charges -/// one operation per row read, which no named constant multiplies: no -/// units, 300,000 operations without a constant (observed: 300,000). +/// `SCAN_OPERATIONS_PER_ROW` per row read: 300,000 units of +/// `ScanOperationsPerRow` (1 operation each), nothing without a constant; +/// its bytes are priced as scanned bytes, apart. #[test] -fn a_scan_has_no_constant_terms() { +fn a_scan_charges_each_row_it_reads_by_a_named_constant() { let settings = CostInputs::default(); let data = thousand_series_sampled_every(1_000); let scan = node(metric_scan("latency")); let terms = crate::node_cost_terms(&scan, &[], Some(300_000), &data, &settings).unwrap(); - assert!( - terms.units_per_constant.is_empty(), - "{:?}", - terms.units_per_constant + assert_eq!( + terms.units_per_constant, + [(CostConstant::ScanOperationsPerRow, 300_000.0)].into() ); - assert_eq!(terms.operations_without_constant, 300_000.0); + assert_eq!(terms.operations_without_constant, 0.0); assert_close( charged_by_terms(&terms), formula_cpu_per_execution(&scan, &[], Some(300_000), &data, &settings), @@ -3383,6 +3383,77 @@ fn a_scan_has_no_constant_terms() { ); } +/// A scan's predicates are evaluated on each row it reads, as a filter's: +/// `FILTER_OPERATIONS_PER_ROW` per row and +/// `FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE` per value each row is +/// compared with (an IN-list's values, an equality's one). 10 s of `auth` +/// (100,000 rows) under `host IN (10 values)`: 100,000 units of +/// `ScanOperationsPerRow` and of `FilterOperationsPerRow`, 1,000,000 of +/// `FilterOperationsPerRowPerComparedValue`. +#[test] +fn a_scan_charges_its_predicates_per_row_and_compared_value() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::QueryTime); + let terms = crate::node_cost_terms(&scan, &[], Some(10_000), &data, &settings).unwrap(); + assert_eq!( + terms.units_per_constant, + [ + (CostConstant::ScanOperationsPerRow, 100_000.0), + (CostConstant::FilterOperationsPerRow, 100_000.0), + (CostConstant::FilterOperationsPerRowPerComparedValue, 1_000_000.0), + ] + .into() + ); + assert_close( + charged_by_terms(&terms), + formula_cpu_per_execution(&scan, &[], Some(10_000), &data, &settings), + 1e-9, + "the formula", + ); +} + +/// A `Filter` over 100,000 rows of `auth` charges +/// `FILTER_OPERATIONS_PER_ROW` per row it reads and +/// `FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE` per value compared: `host +/// IN (10 values)` 100,000 and 1,000,000 units; `TRUE` (no value +/// compared) 100,000 and none. The reference executor measures 25.7 ns per +/// row for a 10-value IN-list and 3.5 for one value (2,000,000 rows in +/// batches of 10,000), 1 + 2.4 per value. +#[test] +fn a_filter_charges_each_row_and_each_value_it_compares() { + 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 terms_of = |pred: ScalarExpr| { + let filter = filter_node(pred, auth_schema()); + crate::node_cost_terms(&filter, &[auth_rows(&rows, 100_000)], None, &data, &settings) + .unwrap() + .units_per_constant + }; + assert_eq!( + terms_of(in_list(HOST, "h", 10)), + [ + (CostConstant::FilterOperationsPerRow, 100_000.0), + (CostConstant::FilterOperationsPerRowPerComparedValue, 1_000_000.0), + ] + .into() + ); + assert_eq!( + terms_of(ScalarExpr::Literal( + asap_types::ir::scalar::ScalarValue::Boolean(true) + )), + [(CostConstant::FilterOperationsPerRow, 100_000.0)].into() + ); +} + /// The invariant: for every node these tests cost, the terms at the /// built-in values are the formula CPU per execution, so the formula and /// its terms cannot drift. Each case is a fixture of a test above. @@ -3985,6 +4056,7 @@ fn terms_ignore_the_measured_table_and_the_calibration_factor() { exact: None, measure: None, ns_per_unit: 10.0, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: None, stored_bytes_per_state: None, @@ -4122,6 +4194,7 @@ fn node_priced_by_hand() { exact: Some(ExactKind::Sum), measure: None, ns_per_unit: 10.0, + ns_per_series: 0.0, ns_per_invocation: 500.0, memory_bytes_per_state: None, stored_bytes_per_state: None, @@ -4179,6 +4252,7 @@ fn aggregate_needs_every_measure() { exact: None, measure: Some("sum".into()), ns_per_unit: 10.0, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: None, stored_bytes_per_state: None, @@ -4739,6 +4813,7 @@ fn a_measured_ddsketch_state_size_replaces_the_estimate() { exact: None, measure: None, ns_per_unit: 100.0, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: Some(900.0), stored_bytes_per_state: None, @@ -5131,7 +5206,15 @@ fn a_filter_keeps_its_in_list_share_of_rows() { 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); + // Each of the 100,000 rows is compared with the 10 values. + assert_close( + usage.cpu_ops_per_second - all.cpu_ops_per_second, + 100_000.0 + * 10.0 + * crate::node::operations_per_unit::FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE, + 1e-9, + "the IN-list's compared values", + ); } /// U2. Pass 2's compensation `host = 'h0' OR … OR host = 'h9'` is the same @@ -5624,3 +5707,189 @@ fn an_in_list_share_names_the_uniform_rows_per_value_assumption() { ); assert!(usage.cost.assumed_data_facts.is_empty()); } + +// Cost calibration against a deployment's measurements (proposal +// `dev/cost-calibration.md`, section 5): per-series scan unit (T2), named +// scan and filter constants, active groups per window (T6). + +/// A deployment's measured cost file with one query-time `Scan` entry: +/// `ns_per_row` per row read and `ns_per_series` per series visited. +fn measured_scan(ns_per_row: f64, ns_per_series: f64) -> CostInputs { + use crate::{MeasuredOperationCosts, OperatorCost}; + CostInputs { + measured_operation_costs: MeasuredOperationCosts { + operators: vec![OperatorCost { + operator: OperatorKind::Scan, + phase: Some(ExecutionTiming::QueryTime), + sketch: None, + exact: None, + measure: None, + ns_per_unit: ns_per_row, + ns_per_series, + ns_per_invocation: 0.0, + memory_bytes_per_state: None, + stored_bytes_per_state: None, + ns_per_state_emitted: 0.0, + measured_series_count: None, + measures: vec![], + }], + ..MeasuredOperationCosts::default() + }, + ..CostInputs::default() + } +} + +/// `auth` declaring `series` series, 10,000 rows per second. +fn auth_data_with_series(series: u64) -> DataWorkload { + let mut data = auth_data(true); + for facts in data.sources.values_mut() { + facts.series_count = Some(series); + } + data +} + +/// T2. A measured `Scan` entry charges each series the scan visits beside +/// each row it reads: 10 min of `auth` (6,000,000 rows) at 41 ns per row +/// and 8,700 ns per series is 246 + 870 = 1,116 ms over its 100,000 +/// series and 246 + 87 = 333 ms over 10,000. Without `ns_per_series` the +/// two read the same 246 ms. +#[test] +fn a_measured_scan_charges_each_series_it_visits() { + let scan = auth_scan(vec![], ExecutionTiming::QueryTime); + let work_ms = |settings: &CostInputs, series: u64| { + node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + Some(600_000), + None, + &auth_data_with_series(series), + settings, + ) + .unwrap() + .work_ms_per_execution + }; + let with_series = measured_scan(41.0, 8_700.0); + assert_close(work_ms(&with_series, 100_000), 1_116.0, 1e-9, "100,000 series"); + assert_close(work_ms(&with_series, 10_000), 333.0, 1e-9, "10,000 series"); + let rows_only = measured_scan(41.0, 0.0); + assert_close(work_ms(&rows_only, 100_000), 246.0, 1e-9, "per row only"); +} + +/// T2. `ns_per_series` is a number like every other price: a negative one +/// is refused. +#[test] +fn a_negative_ns_per_series_is_refused() { + let settings = measured_scan(41.0, -1.0); + assert!(settings.validate().is_err()); +} + +/// A 10 s count chain at ingestion time over every arriving row of `auth` +/// (10,000 rows per second), grouped by `keys`, retained 10 min. +fn auth_count_chain(keys: Vec) -> PhysicalASAPDAGNode { + PhysicalASAPDAGNode { + output_state: ExecutionDataState::INGESTION_SUMMARY, + retention_ms: Some(600_000), + lifetime: Lifetime::AcrossEvaluations(StorageMedium::Memory), + output_schema: Schema::new(vec![ + Field::new( + "state", + FieldDataType::ExactAggregate(ExactKind::Count, ExactParams::Count), + false, + ), + Field::plain("host", asap_types::ir::schema::DataType::Utf8, 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(keys), + filter: None, + tumbling_window_width_ms: 10_000, + })) + } +} + +/// T6. A window holds a state only for the groups its rows reach: a 10 s +/// window of `auth` holds 100,000 rows over its 100,000 (host, user) +/// groups, of which 100,000 · (1 − e^−1) = 63,212 appear when rows fall +/// uniformly (`expected_distinct_values`). So the chain emits 6,321.2 +/// states per second, not 10,000, and keeps its 60 sealed windows and the +/// one being built at 63,212 states each, not 100,000. +#[test] +fn a_chain_emits_and_keeps_states_only_for_the_groups_its_windows_reach() { + let settings = CostInputs::default(); + let data = auth_data(true); + let scan = auth_scan(vec![], ExecutionTiming::IngestionTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), None, None, &data, &settings).unwrap(); + let chain = auth_count_chain(vec![HOST, USER]); + 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_000, "the groups"); + assert!( + usage.cost.detail.contains("6321.2 states emitted"), + "{}", + usage.cost.detail + ); + let active_share = -(-1.0_f64).exp_m1(); + let window_bytes = usage.output_facts.statistics.bytes as f64; + assert_close( + usage.cost.memory_and_disk.average_memory_bytes, + 61.0 * window_bytes * active_share, + 1e-3, + "61 windows of the groups reached", + ); +} + +/// T6. A dense chain is unchanged: 1,000 series at 1 Hz put 10,000 rows in +/// each 10 s window, so every series appears (1 − e^−10 of them) and +/// the chain emits 100 states per second. +#[test] +fn a_dense_chain_emits_a_state_for_every_group() { + let settings = CostInputs::default(); + let data = thousand_series_sampled_every(1_000); + let scan = PhysicalASAPDAGNode { + output_state: ExecutionDataState::INGESTION_ROWS, + ..node(metric_scan("latency")) + }; + 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: per_series_carrying_job(None), + ..node(Payload::ASAP(ASAPOp::SummaryTumblingWindowChain { + child: 0, + summary_type: FieldDataType::ExactAggregate(ExactKind::Max, ExactParams::Max), + input: SummaryUpdate::column(ColumnRef::SampleValue), + reduction: Reduction::PerEntity, + 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!( + usage.cost.detail.contains("100.0 states emitted"), + "{}", + usage.cost.detail + ); +} diff --git a/crates/cost/tests/measured_operation_costs.rs b/crates/cost/tests/measured_operation_costs.rs index 2e9b147d8..a82502ad8 100644 --- a/crates/cost/tests/measured_operation_costs.rs +++ b/crates/cost/tests/measured_operation_costs.rs @@ -32,6 +32,7 @@ fn kll_entry( exact: None, measure: None, ns_per_unit, + ns_per_series: 0.0, ns_per_invocation, memory_bytes_per_state, stored_bytes_per_state: None, @@ -185,6 +186,7 @@ fn full_table() -> MeasuredOperationCosts { exact: Some(ExactKind::Sum), measure: None, ns_per_unit: 3.75, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: None, stored_bytes_per_state: None, @@ -199,6 +201,7 @@ fn full_table() -> MeasuredOperationCosts { exact: None, measure: Some("quantile".into()), ns_per_unit: 12.0, + ns_per_series: 0.0, ns_per_invocation: 250.0, memory_bytes_per_state: None, stored_bytes_per_state: None, @@ -213,6 +216,7 @@ fn full_table() -> MeasuredOperationCosts { exact: None, measure: None, ns_per_unit: 20.0, + ns_per_series: 0.0, ns_per_invocation: 5_000.0, memory_bytes_per_state: None, stored_bytes_per_state: None, diff --git a/crates/devtools/src/rqe_atomic_costs.rs b/crates/devtools/src/rqe_atomic_costs.rs index 9b8fe13ff..aa41c09a8 100644 --- a/crates/devtools/src/rqe_atomic_costs.rs +++ b/crates/devtools/src/rqe_atomic_costs.rs @@ -111,6 +111,7 @@ pub fn convert_rqe_atomic_costs(rows: &Value) -> Result exact: None, measure: None, ns_per_unit: seconds * 1e9, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: None, stored_bytes_per_state: None, diff --git a/crates/integration-tests/src/lib.rs b/crates/integration-tests/src/lib.rs index 0718da067..8cccd2989 100644 --- a/crates/integration-tests/src/lib.rs +++ b/crates/integration-tests/src/lib.rs @@ -401,6 +401,7 @@ pub mod planning { exact, measure: None, ns_per_unit: 0.0, + ns_per_series: 0.0, ns_per_invocation: 0.0, memory_bytes_per_state: None, stored_bytes_per_state: None, diff --git a/crates/integration-tests/tests/stage3_objective.rs b/crates/integration-tests/tests/stage3_objective.rs index d9d272573..0d048718f 100644 --- a/crates/integration-tests/tests/stage3_objective.rs +++ b/crates/integration-tests/tests/stage3_objective.rs @@ -1209,3 +1209,52 @@ fn the_objective_is_the_plan_cost_on_a_group_left_join_of_two_hour_increases() { objective_and_plan_cost(&w, &CostInputs::default(), true), ); } + +/// Default unit costs for a deployment that keeps the raw rows its +/// query-time scans read in memory, at `raw_data_bytes_per_row` bytes each +/// (`DataPlaneExecution::raw_data_medium`). +fn raw_data_in_memory(raw_data_bytes_per_row: Option) -> CostInputs { + let mut settings = CostInputs::default(); + settings.data_plane_execution.raw_data_medium = asap_types::stages::StorageMedium::Memory; + settings.data_plane_execution.raw_data_bytes_per_row = raw_data_bytes_per_row; + settings +} + +/// The raw-scanning plan of `count_over_time(m[1m])` every minute (raw data +/// kept) and its `plan_cost` usage under `settings`. +fn raw_scanning_plan_usage(settings: &CostInputs) -> (f64, f64, asap_cost::ResourceUsage) { + let w = workload(&[("count_over_time(m[1m])", 60_000, "")]); + let (plan, (objective, plan_cost)) = selected_plan_objective_and_plan_cost(&w, settings, true); + assert!( + plan.nodes.iter().any(|node| { + node.output_state.timing == ExecutionTiming::QueryTime + && matches!(node.payload, PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { .. })) + }), + "the selected plan scans raw data: {plan:#?}" + ); + let entries: Vec<_> = w.query_workload.entries().collect(); + let data = w.data_workload.clone().unwrap(); + let (cost, _) = asap_cost::plan_cost(&plan, &entries, &data, settings).unwrap(); + (objective, plan_cost, cost.usage) +} + +/// T5. A deployment keeping raw rows in memory at 32 bytes per row: the +/// raw-scanning plan of `count_over_time(m[1m])` every minute (1,000 rows +/// per second of `m`) keeps a minute of rows, 60,000 x 32 = 1,920,000 +/// bytes, as memory, none of it on disk, and Stage 3's objective is its +/// `plan_cost`. On disk (the default) the same plan keeps no raw rows in +/// memory. +#[test] +fn raw_data_kept_in_memory_is_charged_as_memory_at_its_bytes_per_row() { + let (_, _, on_disk) = raw_scanning_plan_usage(&CostInputs::default()); + assert!(on_disk.disk_bytes > 0, "{on_disk:?}"); + let in_memory = raw_data_in_memory(Some(32.0)); + let (objective, plan_cost, usage) = raw_scanning_plan_usage(&in_memory); + assert_equal("raw in memory", (objective, plan_cost)); + assert_eq!(usage.disk_bytes, 0, "{usage:?}"); + let raw_bytes = usage.average_memory_bytes - on_disk.average_memory_bytes; + assert!( + (raw_bytes - 1_920_000.0).abs() <= 0.02 * 1_920_000.0, + "raw rows in memory: {raw_bytes} bytes" + ); +} From 1c6e06998ca26c33e06348a0f03dd3f5442aa834 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:31:10 +0000 Subject: [PATCH 02/18] test(planner): failing end-to-end tests for planning with a deployment's measured cost file T1, T3, T4 of the cost calibration over three SIL intents whose runs were measured on one machine (fixtures: SIL text, tables, data facts): - T1: each measured cost file validates; the slower machine's is the measured machine's at 1.25x (every measured time and the formula scale); every node whose operator the file measures is priced from it. - T3: binding-free queries (drill_cnt q1, dash q1, rca q1) predicted within 1.5x of their measured medians; full intent keeps dash's and rca's shared state and predicts its upkeep within 1.5x of measured. - T4 (ignored): drill_cnt keeps the lightcone once a top-k binding is costed at its heavy values' rows (needs item 6, IN-list branch). The cost files themselves come with item 1's commit. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/planner/tests/main.rs | 1 + crates/planner/tests/measured_cost_file.rs | 262 ++++++++++++++++++ .../tests/measured_cost_file/dash/data.json | 40 +++ .../tests/measured_cost_file/dash/intent.sil | 8 + .../tests/measured_cost_file/dash/tables.json | 10 + .../measured_cost_file/drill_cnt/data.json | 35 +++ .../measured_cost_file/drill_cnt/intent.sil | 6 + .../measured_cost_file/drill_cnt/tables.json | 9 + .../tests/measured_cost_file/rca/data.json | 46 +++ .../tests/measured_cost_file/rca/intent.sil | 8 + .../tests/measured_cost_file/rca/tables.json | 10 + 11 files changed, 435 insertions(+) create mode 100644 crates/planner/tests/measured_cost_file.rs create mode 100644 crates/planner/tests/measured_cost_file/dash/data.json create mode 100644 crates/planner/tests/measured_cost_file/dash/intent.sil create mode 100644 crates/planner/tests/measured_cost_file/dash/tables.json create mode 100644 crates/planner/tests/measured_cost_file/drill_cnt/data.json create mode 100644 crates/planner/tests/measured_cost_file/drill_cnt/intent.sil create mode 100644 crates/planner/tests/measured_cost_file/drill_cnt/tables.json create mode 100644 crates/planner/tests/measured_cost_file/rca/data.json create mode 100644 crates/planner/tests/measured_cost_file/rca/intent.sil create mode 100644 crates/planner/tests/measured_cost_file/rca/tables.json diff --git a/crates/planner/tests/main.rs b/crates/planner/tests/main.rs index 6134a7dd2..d8bf5f1eb 100644 --- a/crates/planner/tests/main.rs +++ b/crates/planner/tests/main.rs @@ -8,6 +8,7 @@ mod columnar_batches; mod deployment_exclusions; mod e2e_plan; mod exact_only_reads; +mod measured_cost_file; mod metricsql_workloads; mod reduce_aggregates; mod runtime_install; diff --git a/crates/planner/tests/measured_cost_file.rs b/crates/planner/tests/measured_cost_file.rs new file mode 100644 index 000000000..b24f482cd --- /dev/null +++ b/crates/planner/tests/measured_cost_file.rs @@ -0,0 +1,262 @@ +//! Planning with a deployment's measured cost file (`calibration/ +//! measured-cost-files/`): a `CostInputs` file holding the deployment's +//! measured time per unit of each operator (`measured_operation_costs`, +//! per row and per series for a scan), its view window cache, where it +//! keeps raw rows and their bytes, and the scale of the formula-priced +//! nodes. The intents are three SIL programs whose runs on one machine +//! were measured (`tests/measured_cost_file//`: each its SIL text, +//! its tables' label columns and its data facts): `drill_cnt` (top-10 +//! hosts by count, then per-user counts over those hosts), `dash` (top-10 +//! services, then their p99 and error counts) and `rca` (services over a +//! p99 bound, their top-5 nodes by p99, those nodes' max cpu). + +use std::collections::BTreeMap; +use std::path::PathBuf; + +use asap_cost::{CostInputs, NodeCostSource}; +use asap_planner::intent::{plan_intents, IntentPlan, IntentPlanningMode, IntentPlanningOptions}; +use asap_planner::{DeploymentCapabilities, PlanningModels, SelectedPlanReport, SqlCatalog}; +use asap_types::ir::operator::OperatorKind; +use asap_types::ir::properties::ExecutionTiming; +use asap_types::ir::schema::{DataType, Field, Schema}; +use asap_types::workload::DataWorkload; + +/// The repository's measured cost files. +fn cost_file_dir() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../calibration/measured-cost-files") +} + +/// The machine the intents were measured on (two 14-core Xeon E5-2683 v3, +/// 56 threads, registered DDR4). +const MEASURED_MACHINE: &str = "x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4"; + +/// A second machine (two 10-core Xeon E5-2660 v2, 40 threads), whose runs +/// of the same plans took 1.22–1.28x as long in every operator class. +const SLOWER_MACHINE: &str = "x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory"; + +/// The measured cost file of `machine`, as JSON and as `CostInputs`. +fn cost_file(machine: &str) -> (serde_json::Value, CostInputs) { + let text = std::fs::read_to_string(cost_file_dir().join(format!("{machine}.json"))) + .unwrap_or_else(|error| panic!("{machine}'s measured cost file: {error}")); + let json: serde_json::Value = serde_json::from_str(&text).unwrap(); + let inputs: CostInputs = serde_json::from_str(&text) + .unwrap_or_else(|error| panic!("{machine}'s file is not CostInputs: {error}")); + (json, inputs) +} + +/// A fixture file of intent `intent`. +fn fixture(intent: &str, name: &str) -> String { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/measured_cost_file") + .join(intent) + .join(name); + std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{path:?}: {error}")) +} + +/// Each table of `intent` as the measured data plane stores it: `ts`, its +/// text label columns, then a `Float64` `value`. +fn catalog(intent: &str) -> SqlCatalog { + let tables: BTreeMap> = + serde_json::from_str(&fixture(intent, "tables.json")).unwrap(); + let mut catalog = SqlCatalog::new(); + for (table, labels) in &tables { + let mut fields = vec![Field::plain("ts", DataType::Timestamp, false)]; + fields.extend( + labels + .iter() + .map(|label| Field::plain(label, DataType::Utf8, false)), + ); + fields.push(Field::plain("value", DataType::Float64, false)); + catalog = catalog.with_table(table, Schema::with_time_index(fields, 0, vec![])); + } + catalog +} + +/// `intent` planned in `mode` with `cost_inputs`, raw data kept. +async fn planned( + intent: &str, + mode: IntentPlanningMode, + cost_inputs: &CostInputs, +) -> (IntentPlan, SelectedPlanReport) { + let data: DataWorkload = serde_json::from_str(&fixture(intent, "data.json")).unwrap(); + let intents = asap_frontend_sil::parse_intents(&fixture(intent, "intent.sil")) + .expect("a well-formed intent"); + let capabilities = DeploymentCapabilities { + raw_data_retained: true, + ..DeploymentCapabilities::default() + }; + let models = PlanningModels::builtin() + .with_deployment_capabilities(&capabilities) + .with_cost_inputs(cost_inputs); + let options = IntentPlanningOptions { + mode, + ..IntentPlanningOptions::default() + }; + plan_intents(&intents, &catalog(intent), &data, models, &options) + .await + .unwrap_or_else(|error| panic!("{intent} plans: {error}")) +} + +const MODES: [IntentPlanningMode; 3] = [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentOnDemandHoles, + IntentPlanningMode::IntentFull, +]; + +/// Whether `measured` is within `ratio` of `predicted`, either way. +fn within(predicted: f64, measured: f64, ratio: f64) -> bool { + predicted <= measured * ratio && measured <= predicted * ratio +} + +/// T1. Each measured cost file is `CostInputs` that validate, and the +/// slower machine's is the measured machine's at 1.25x: every measured time +/// (per unit, per series, per invocation, per state emitted) and the +/// formula-priced nodes' scale (`frozen_calibration_factor`) 1.25 times +/// the measured machine's, everything else equal. +#[test] +fn the_measured_cost_files_validate_and_the_slower_machine_is_one_factor_slower() { + let (measured_json, measured) = cost_file(MEASURED_MACHINE); + let (slower_json, slower) = cost_file(SLOWER_MACHINE); + measured.validate().expect("the measured machine's file validates"); + slower.validate().expect("the slower machine's file validates"); + assert_eq!( + slower.frozen_calibration_factor.unwrap(), + 1.25 * measured.frozen_calibration_factor.unwrap() + ); + let mut scaled = measured_json.clone(); + scaled["frozen_calibration_factor"] = slower_json["frozen_calibration_factor"].clone(); + let table = &mut scaled["measured_operation_costs"]; + for time in ["ns_per_ingested_sample", "ns_per_evaluation"] { + if let Some(ns) = table[time].as_f64() { + table[time] = serde_json::json!(ns * 1.25); + } + } + for entry in table["operators"].as_array_mut().unwrap() { + for time in [ + "ns_per_unit", + "ns_per_series", + "ns_per_invocation", + "ns_per_state_emitted", + ] { + if let Some(ns) = entry[time].as_f64() { + entry[time] = serde_json::json!(ns * 1.25); + } + } + } + let scaled: CostInputs = serde_json::from_value(scaled).unwrap(); + assert_eq!(scaled, slower); +} + +/// T1. With the measured cost file, every node of the three intents' plans +/// in every mode whose operator the file measures is priced from it: scans, +/// time ranges, chains, window merges, merges, finalizes and estimates; the +/// rest (aggregates, summary builds of families it does not measure, +/// projections, sorts, limits, filters, covers) by the formulas. +#[tokio::test(flavor = "multi_thread")] +async fn every_measured_operator_is_priced_from_the_file() { + let (_, inputs) = cost_file(MEASURED_MACHINE); + let measured_kinds = [ + OperatorKind::Scan, + OperatorKind::TimeRange, + OperatorKind::SummaryTumblingWindowChain, + OperatorKind::SummaryMergeWindows, + OperatorKind::SummaryMerge, + OperatorKind::FinalizeExactAccumulator, + OperatorKind::SummaryEstimate, + ]; + for intent in ["drill_cnt", "dash", "rca"] { + for mode in MODES { + let (_, report) = planned(intent, mode, &inputs).await; + for node in &report.predicted_usage.per_node { + if measured_kinds.contains(&node.operator) { + assert_eq!( + node.cost_source, + NodeCostSource::Measured, + "{intent} {mode:?}: node {} ({:?}, {:?})", + node.node_id, + node.operator, + node.timing + ); + } + } + } + } +} + +/// T3. With the measured cost file, the predictions of the queries whose +/// plan does not depend on a binding are within 1.5x of their measured +/// median time per evaluation, in every mode: `drill_cnt` q1 merges and +/// finalizes 10,000 hosts' kept counts (25.2 ms measured), `dash` q1 500 +/// services' kept counts (1.0 ms), `rca` q1 scans 5 min of `requests` +/// (6,000,000 rows of 10,000 series) and takes each service's exact p99 +/// (942 ms). +#[tokio::test(flavor = "multi_thread")] +async fn binding_free_queries_are_predicted_within_one_and_a_half_times_measured() { + let (_, inputs) = cost_file(MEASURED_MACHINE); + for (intent, measured_ms) in [("drill_cnt", 25.2), ("dash", 1.0), ("rca", 942.0)] { + for mode in MODES { + let (_, report) = planned(intent, mode, &inputs).await; + let predicted_ms = report.predicted_usage.per_query[0].query_execution_ms; + assert!( + within(predicted_ms, measured_ms, 1.5), + "{intent} {mode:?} q1: predicted {predicted_ms:.2} ms, measured {measured_ms} ms" + ); + } + } +} + +/// The plan's ingestion-time CPU, in ms per second. +fn ingestion_ms_per_second(report: &SelectedPlanReport) -> f64 { + report + .predicted_usage + .per_node + .iter() + .filter(|node| node.timing == ExecutionTiming::IngestionTime) + .map(|node| node.cpu_core_seconds_per_second * 1_000.0) + .sum() +} + +/// T3. With the measured cost file, full intent planning keeps the shared +/// state of `dash` (its services' p99 and error counts) and `rca` (its +/// nodes' max cpu), which measured cheaper than computing them at query +/// time, and predicts the state's upkeep within 1.5x of its measured +/// ingestion-time CPU (precompute and persist threads): `dash` 9.7 ms/s, +/// `rca` 7.9 ms/s. Query at a time, `dash` keeps only q1's counts, 6.1 +/// ms/s measured, and `drill_cnt` q1's host counts, 6.25 ms/s. +#[tokio::test(flavor = "multi_thread")] +async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() { + let (_, inputs) = cost_file(MEASURED_MACHINE); + for (intent, measured_ms_per_second) in [("dash", 9.7), ("rca", 7.9)] { + let (plan, report) = planned(intent, IntentPlanningMode::IntentFull, &inputs).await; + assert!( + !plan.lightcone_query_indices.is_empty(), + "{intent}: no lightcone kept" + ); + let predicted = ingestion_ms_per_second(&report); + assert!( + within(predicted, measured_ms_per_second, 1.5), + "{intent} full: predicted {predicted:.2} ms/s, measured {measured_ms_per_second}" + ); + } + for (intent, measured_ms_per_second) in [("dash", 6.1), ("drill_cnt", 6.25)] { + let (_, report) = planned(intent, IntentPlanningMode::QueryAtATime, &inputs).await; + let predicted = ingestion_ms_per_second(&report); + assert!( + within(predicted, measured_ms_per_second, 1.5), + "{intent} query at a time: predicted {predicted:.2} ms/s, measured {measured_ms_per_second}" + ); + } +} + +/// T4. Once a binding chosen by an upstream top-k is costed at the rows its +/// heavy values hold (10 of 10,000 Zipf(1) hosts hold 29.3% of `auth`, not +/// 0.1%), `drill_cnt`'s full intent keeps the (host, user) counts and +/// filters them before the time merge: predicted 39.5 per second against +/// 45 for reading the selected rows at query time. +#[tokio::test(flavor = "multi_thread")] +#[ignore = "needs the skew-aware share of a top-k binding (item 6 of the cost calibration, on the IN-list selectivity branch)"] +async fn drill_cnt_keeps_the_lightcone_once_top_k_bindings_hold_their_heavy_rows() { + let (_, inputs) = cost_file(MEASURED_MACHINE); + let (plan, _) = planned("drill_cnt", IntentPlanningMode::IntentFull, &inputs).await; + assert!(!plan.lightcone_query_indices.is_empty()); +} diff --git a/crates/planner/tests/measured_cost_file/dash/data.json b/crates/planner/tests/measured_cost_file/dash/data.json new file mode 100644 index 000000000..f38b340d6 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/dash/data.json @@ -0,0 +1,40 @@ +{ + "arrival": { + "ingesting": { + "rows_per_second": 22000, + "max_out_of_order_ms": 2000 + } + }, + "sources": { + "requests": { + "series_count": 10000, + "sample_interval": 500, + "distinct_values_per_label": { + "service": 500, + "node": 10000 + }, + "rows_held": 6000000, + "column_signs": { + "value": "non_negative" + }, + "column_magnitudes": { + "value": { + "min_abs": 1.0, + "max_abs": 100000.0 + } + } + }, + "errors": { + "series_count": 10000, + "sample_interval": 5000, + "distinct_values_per_label": { + "service": 500, + "node": 10000 + }, + "rows_held": 600000, + "column_signs": { + "value": "non_negative" + } + } + } +} \ No newline at end of file diff --git a/crates/planner/tests/measured_cost_file/dash/intent.sil b/crates/planner/tests/measured_cost_file/dash/intent.sil new file mode 100644 index 000000000..0fedf73c3 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/dash/intent.sil @@ -0,0 +1,8 @@ +INTENT dash EVERY 10s; +q1: ($S, _) := SELECT service, count(*) AS c FROM requests WHERE ts > $now - INTERVAL '5 minutes' GROUP BY service ORDER BY c DESC LIMIT 10 + REQUIRE EXACT, LATENCY <= 500ms; +q2: SELECT service, approx_percentile_cont(value, 0.99) AS p99 FROM requests WHERE service IN $S AND ts > $now - INTERVAL '5 minutes' GROUP BY service + REQUIRE ERROR rel <= 0.05 DELTA 0.05, LATENCY <= 500ms; +q3: SELECT service, count(*) AS errors FROM errors WHERE service IN $S AND ts > $now - INTERVAL '5 minutes' GROUP BY service + REQUIRE EXACT, LATENCY <= 500ms; +GROUP (q1, q2, q3) LATENCY <= 1000ms; diff --git a/crates/planner/tests/measured_cost_file/dash/tables.json b/crates/planner/tests/measured_cost_file/dash/tables.json new file mode 100644 index 000000000..88676954d --- /dev/null +++ b/crates/planner/tests/measured_cost_file/dash/tables.json @@ -0,0 +1,10 @@ +{ + "requests": [ + "service", + "node" + ], + "errors": [ + "service", + "node" + ] +} \ No newline at end of file diff --git a/crates/planner/tests/measured_cost_file/drill_cnt/data.json b/crates/planner/tests/measured_cost_file/drill_cnt/data.json new file mode 100644 index 000000000..747172cd6 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/drill_cnt/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/tests/measured_cost_file/drill_cnt/intent.sil b/crates/planner/tests/measured_cost_file/drill_cnt/intent.sil new file mode 100644 index 000000000..a51cd2020 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/drill_cnt/intent.sil @@ -0,0 +1,6 @@ +INTENT drill_cnt EVERY 10s; +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, LATENCY <= 1000ms; +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, LATENCY <= 1000ms; +GROUP (q1, q2) LATENCY <= 2000ms; diff --git a/crates/planner/tests/measured_cost_file/drill_cnt/tables.json b/crates/planner/tests/measured_cost_file/drill_cnt/tables.json new file mode 100644 index 000000000..3d5eb6844 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/drill_cnt/tables.json @@ -0,0 +1,9 @@ +{ + "flows": [ + "host" + ], + "auth": [ + "host", + "user" + ] +} \ No newline at end of file diff --git a/crates/planner/tests/measured_cost_file/rca/data.json b/crates/planner/tests/measured_cost_file/rca/data.json new file mode 100644 index 000000000..de82643d5 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/rca/data.json @@ -0,0 +1,46 @@ +{ + "arrival": { + "ingesting": { + "rows_per_second": 30000, + "max_out_of_order_ms": 2000 + } + }, + "sources": { + "requests": { + "series_count": 10000, + "sample_interval": 500, + "distinct_values_per_label": { + "service": 500, + "node": 10000 + }, + "rows_held": 6000000, + "column_signs": { + "value": "non_negative" + }, + "column_magnitudes": { + "value": { + "min_abs": 1.0, + "max_abs": 100000.0 + } + } + }, + "node_metrics": { + "series_count": 10000, + "sample_interval": 1000, + "distinct_values_per_label": { + "service": 500, + "node": 10000 + }, + "rows_held": 3000000, + "column_signs": { + "value": "non_negative" + }, + "column_magnitudes": { + "value": { + "min_abs": 1.0, + "max_abs": 1000.0 + } + } + } + } +} \ No newline at end of file diff --git a/crates/planner/tests/measured_cost_file/rca/intent.sil b/crates/planner/tests/measured_cost_file/rca/intent.sil new file mode 100644 index 000000000..f080d9978 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/rca/intent.sil @@ -0,0 +1,8 @@ +INTENT rca EVERY 10s; +q1: ($S, _) := SELECT service, approx_percentile_cont(value, 0.99) AS p99 FROM requests WHERE ts > $now - INTERVAL '5 minutes' GROUP BY service HAVING approx_percentile_cont(value, 0.99) > 250 + REQUIRE ERROR rel <= 0.05 DELTA 0.05, LATENCY <= 1000ms; +q2: ($N, _) := SELECT node, approx_percentile_cont(value, 0.99) AS p99 FROM requests WHERE service IN $S AND ts > $now - INTERVAL '5 minutes' GROUP BY node ORDER BY p99 DESC LIMIT 5 + REQUIRE ERROR rel <= 0.05 DELTA 0.05, LATENCY <= 1000ms; +q3: SELECT node, max(value) AS cpu FROM node_metrics WHERE node IN $N AND ts > $now - INTERVAL '5 minutes' GROUP BY node + REQUIRE EXACT, LATENCY <= 1000ms; +GROUP (q1, q2, q3) LATENCY <= 2000ms; diff --git a/crates/planner/tests/measured_cost_file/rca/tables.json b/crates/planner/tests/measured_cost_file/rca/tables.json new file mode 100644 index 000000000..747fc4404 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/rca/tables.json @@ -0,0 +1,10 @@ +{ + "requests": [ + "service", + "node" + ], + "node_metrics": [ + "service", + "node" + ] +} \ No newline at end of file From 4bc4c47ec52f5627c61bd6024b545477f04d1454 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:32:03 +0000 Subject: [PATCH 03/18] feat(cost): a measured scan entry charges each series the scan visits (ns_per_series) Item 2 of the cost calibration. A deployment whose store keeps raw rows by series pays per series a scan finds and decodes, beside per row: `OperatorCost::ns_per_series` (default 0) is charged per series visited, each series its sources declare and at most one per row read. Validated like every other price; summed over an aggregate's measure entries. Example (T2): 10 min of `auth`, 6,000,000 rows, at 41 ns per row and 8,700 ns per series: 1,116 ms over 100,000 series, 333 ms over 10,000 (246 ms per row alone). The test's 10,000-series data now keeps the source's 10,000 rows per second (sample interval 1 s). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/measured.rs | 5 +++++ crates/cost/src/node/usage/mod.rs | 10 +++++++++ crates/cost/src/node/usage/tests.rs | 33 +++++++++++++++++++++++------ 3 files changed, 41 insertions(+), 7 deletions(-) diff --git a/crates/cost/src/measured.rs b/crates/cost/src/measured.rs index 437336d86..3b77c49da 100644 --- a/crates/cost/src/measured.rs +++ b/crates/cost/src/measured.rs @@ -483,6 +483,7 @@ pub(crate) fn aggregate_lookup( } let entry = priced(entries)?; total.ns_per_unit += entry.ns_per_unit; + total.ns_per_series += entry.ns_per_series; total.ns_per_invocation += entry.ns_per_invocation; total.ns_per_state_emitted += entry.ns_per_state_emitted; total.outside_measured_scale |= entry.outside_measured_scale; @@ -550,6 +551,10 @@ pub(crate) fn validate( } for (index, entry) in table.operators.iter().enumerate() { check("measured_operation_costs.ns_per_unit", entry.ns_per_unit)?; + check( + "measured_operation_costs.ns_per_series", + entry.ns_per_series, + )?; check( "measured_operation_costs.ns_per_invocation", entry.ns_per_invocation, diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 1ee31446c..abc9097ed 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -2371,6 +2371,12 @@ pub(crate) fn node_usage_and_cost_terms<'a>( | ASAPOp::Extension { .. }, ) => input.rows, }; + // The series a scan visits in one computation: each series its sources + // declare, at most one per row read; none for any other node. + let series_visited = match &node.payload { + Payload::NonASAP(NonASAPOp::Scan { .. }) => series.map_or(0, |series| series.min(out.rows)), + _ => 0, + }; let mut detail = detail; // A node with an entry takes its measured time, scanning included; // any other node its formulas' CPU operations times the calibration @@ -2382,6 +2388,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // At ingestion time, the states emitted at window closes too: // the formula's emit term, plus the measured cost per state. let measured_ms = (units as f64 * unit.ns_per_unit + + series_visited as f64 * unit.ns_per_series + unit.ns_per_invocation + states_emitted_per_second * unit.ns_per_state_emitted) * 1e-6 @@ -2391,6 +2398,9 @@ pub(crate) fn node_usage_and_cost_terms<'a>( "; measured {units} x {:.3} ns + {:.3} ns", unit.ns_per_unit, unit.ns_per_invocation ); + if unit.ns_per_series > 0.0 { + detail += &format!(" + {series_visited} series x {:.3} ns", unit.ns_per_series); + } ResourceEstimate::new( measured_ms / speed.ms_per_cpu_op, estimate.peak_memory_bytes(), diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 957b3de71..b2362ecfa 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -3401,7 +3401,10 @@ fn a_scan_charges_its_predicates_per_row_and_compared_value() { [ (CostConstant::ScanOperationsPerRow, 100_000.0), (CostConstant::FilterOperationsPerRow, 100_000.0), - (CostConstant::FilterOperationsPerRowPerComparedValue, 1_000_000.0), + ( + CostConstant::FilterOperationsPerRowPerComparedValue, + 1_000_000.0 + ), ] .into() ); @@ -3434,15 +3437,24 @@ fn a_filter_charges_each_row_and_each_value_it_compares() { }; let terms_of = |pred: ScalarExpr| { let filter = filter_node(pred, auth_schema()); - crate::node_cost_terms(&filter, &[auth_rows(&rows, 100_000)], None, &data, &settings) - .unwrap() - .units_per_constant + crate::node_cost_terms( + &filter, + &[auth_rows(&rows, 100_000)], + None, + &data, + &settings, + ) + .unwrap() + .units_per_constant }; assert_eq!( terms_of(in_list(HOST, "h", 10)), [ (CostConstant::FilterOperationsPerRow, 100_000.0), - (CostConstant::FilterOperationsPerRowPerComparedValue, 1_000_000.0), + ( + CostConstant::FilterOperationsPerRowPerComparedValue, + 1_000_000.0 + ), ] .into() ); @@ -5739,11 +5751,13 @@ fn measured_scan(ns_per_row: f64, ns_per_series: f64) -> CostInputs { } } -/// `auth` declaring `series` series, 10,000 rows per second. +/// `auth` declaring `series` series, each sampled so that the source +/// receives 10,000 rows per second. fn auth_data_with_series(series: u64) -> DataWorkload { let mut data = auth_data(true); for facts in data.sources.values_mut() { facts.series_count = Some(series); + facts.sample_interval = Some(asap_types::workload::DurationMs(series / 10)); } data } @@ -5770,7 +5784,12 @@ fn a_measured_scan_charges_each_series_it_visits() { .work_ms_per_execution }; let with_series = measured_scan(41.0, 8_700.0); - assert_close(work_ms(&with_series, 100_000), 1_116.0, 1e-9, "100,000 series"); + assert_close( + work_ms(&with_series, 100_000), + 1_116.0, + 1e-9, + "100,000 series", + ); assert_close(work_ms(&with_series, 10_000), 333.0, 1e-9, "10,000 series"); let rows_only = measured_scan(41.0, 0.0); assert_close(work_ms(&rows_only, 100_000), 246.0, 1e-9, "per row only"); From 81a422c327e1fc0ed80191f3b20b8bb66e82e70d Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:33:17 +0000 Subject: [PATCH 04/18] feat(cost): name the scan and filter charges and price predicates per compared value Item 3 of the cost calibration. The abstract 1-operation-per-row charges of a scan and a filter become named, measured constants: - `SCAN_OPERATIONS_PER_ROW` (1): the reference executor's in-memory store hands batches on whole, 0.2-1.9 ns per row (batches of 10,000 to 1,000 rows, 1,000 to 100,000 series: no per-series cost there; a deployment's per-series cost comes from its measured file). - `FILTER_OPERATIONS_PER_ROW` (1) and `FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE` (2.4): a filter, and now a scan's predicates too (charged 0 before), per row read and per value each row is compared with. Measured: IN-list of 1 / 10 / 100 values 3.5 / 25.7 / 244 ns per row (2,000,000 rows in batches of 10,000). `compared_values` counts an IN-list's values, one per comparison, null test or subquery membership, summed over AND/OR; a literal compares nothing, so a `TRUE` filter costs what it did. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/analytical.rs | 15 ++++-- crates/cost/src/node/operations_per_unit.rs | 51 +++++++++++++++++++++ crates/cost/src/node/usage/mod.rs | 36 ++++++++++++--- 3 files changed, 91 insertions(+), 11 deletions(-) diff --git a/crates/cost/src/node/analytical.rs b/crates/cost/src/node/analytical.rs index c13cba8ec..195c6b4ce 100644 --- a/crates/cost/src/node/analytical.rs +++ b/crates/cost/src/node/analytical.rs @@ -429,11 +429,16 @@ pub(crate) fn estimate_operator_with_terms( OperatorStatistics::Scan { source_read_bytes, .. }, - ) => ResourceEstimate::new( - left.rows as f64, - per_row_width(left.rows, left.bytes)?, - *source_read_bytes, - ), + ) => { + let terms = NodeCostTerms::of(CostConstant::ScanOperationsPerRow, left.rows as f64); + let estimate = ResourceEstimate::new( + terms.operations(), + per_row_width(left.rows, left.bytes)?, + *source_read_bytes, + ); + named_terms = Some(terms); + estimate + } ( PhysicalOperator::Filter { predicate_operations_per_row, diff --git a/crates/cost/src/node/operations_per_unit.rs b/crates/cost/src/node/operations_per_unit.rs index f89faf704..07130ccfc 100644 --- a/crates/cost/src/node/operations_per_unit.rs +++ b/crates/cost/src/node/operations_per_unit.rs @@ -59,6 +59,7 @@ use asap_types::ir::operator::AggIntent; use asap_types::ir::schema::FieldDataType; +use asap_types::ir::ScalarExpr; use asap_types::summary_type::{ ExactKind, SamplingKind, SamplingParams, SketchParams, StatModelKind, StatModelParams, WaveletKind, WaveletParams, @@ -91,6 +92,56 @@ pub(crate) const FILTER_OPERATIONS_PER_ROW: f64 = 1.0; /// equality's one (see `FILTER_OPERATIONS_PER_ROW`; fitted 2.4). pub(crate) const FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE: f64 = 2.4; +/// The operations one row read costs a filter, or a scan's predicates, +/// evaluating `predicates` (their conjunction): `FILTER_OPERATIONS_PER_ROW` +/// and `FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE` per value each row is +/// compared with ([`compared_values`]). None without a predicate. Example: +/// `host IN (10 values)` costs 1 + 10 x 2.4 = 25 per row. +pub(crate) fn filter_terms_per_row<'e, C: 'e, Col: 'e>( + predicates: impl IntoIterator>, +) -> NodeCostTerms { + let mut predicates = predicates.into_iter().peekable(); + if predicates.peek().is_none() { + return NodeCostTerms::default(); + } + let values: f64 = predicates.map(compared_values).sum(); + let terms = NodeCostTerms::of(CostConstant::FilterOperationsPerRow, 1.0); + match values > 0.0 { + true => terms.plus(CostConstant::FilterOperationsPerRowPerComparedValue, values), + false => terms, + } +} + +/// The values a row is compared with evaluating `predicate`: an IN-list's +/// values, one per comparison, null test or subquery membership, summed +/// over a conjunction or disjunction; a literal, a column or a computed +/// value compares nothing. +fn compared_values(predicate: &ScalarExpr) -> f64 { + match predicate { + ScalarExpr::InList { list, .. } => list.len() as f64, + ScalarExpr::Compare { .. } + | ScalarExpr::IsNull(_) + | ScalarExpr::IsNotNull(_) + | ScalarExpr::InSubquery { .. } + | ScalarExpr::Exists { .. } => 1.0, + ScalarExpr::BoolAnd(items) | ScalarExpr::BoolOr(items) => { + items.iter().map(compared_values).sum() + } + ScalarExpr::Not(inner) => compared_values(inner), + ScalarExpr::Column(_) + | ScalarExpr::Literal(_) + | ScalarExpr::Negative { .. } + | ScalarExpr::Cast { .. } + | ScalarExpr::FunctionCall { .. } + | ScalarExpr::Arithmetic { .. } + | ScalarExpr::Case { .. } + | ScalarExpr::CurrentTimestamp + | ScalarExpr::EvalTimestamp + | ScalarExpr::PromqlScalarFromVector(_) + | ScalarExpr::ScalarSubquery(_) => 0.0, + } +} + /// A row kept by a time range over raw rows, or a state read by a time /// range over a chain's tumbling windows: 9–16 ns per row (median 11) over /// 54 time ranges of 30,000 to 36 M rows at 1 Hz and 10 Hz over 100, 1,000 diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index abc9097ed..2e8e5c8ec 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -24,9 +24,9 @@ use crate::node::analytical::{ }; use crate::node::cost_terms::{CostConstant, NodeCostTerms}; use crate::node::operations_per_unit::{ - chain_emit_terms_per_state, estimate_terms_per_group, hash_aggregate_terms_per_row, - merge_output_terms, merge_terms_per_state, pass_through_merge_terms, state_allocation_terms, - update_terms_per_row, StateLastWrittenBy, + chain_emit_terms_per_state, estimate_terms_per_group, filter_terms_per_row, + hash_aggregate_terms_per_row, merge_output_terms, merge_terms_per_state, + pass_through_merge_terms, state_allocation_terms, update_terms_per_row, StateLastWrittenBy, }; use crate::node::operator_statistics::{ EdgeStatistics, OperatorStatistics, PartitionStatistics, UnaryEdgeStatistics, @@ -1277,7 +1277,9 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }; let (out, estimate, detail) = match &node.payload { Payload::NonASAP(operator) => match operator { - NonASAPOp::Scan { source, .. } => { + NonASAPOp::Scan { + source, predicates, .. + } => { // At ingestion time, one second of arriving rows; at // query time, the arriving rows of the window read above // it, at most the rows the source holds (all of them @@ -1329,6 +1331,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( true => rows.max(1), false => selected_rows, })?; + // Its predicates are evaluated on each row it reads. let estimate = estimate_operator_with_terms( PhysicalOperator::Scan, OperatorStatistics::Scan { @@ -1339,7 +1342,17 @@ pub(crate) fn node_usage_and_cost_terms<'a>( }, source_read_bytes: out.bytes, }, - ); + ) + .map(|(estimate, terms)| { + charged( + terms.plus_terms( + &filter_terms_per_row(predicates.iter().map(|p| &p.0)) + .times(out.rows as f64), + ), + estimate.peak_memory_bytes(), + estimate.scan_bytes(), + ) + }); // Raw data materialized at ingestion time: its consumers // read the rows it retains, not one second of them. let out = match raw_rows_materialized_at_ingestion { @@ -1807,7 +1820,18 @@ pub(crate) fn node_usage_and_cost_terms<'a>( promql: None, }, }, - ); + ) + .map(|(estimate, terms)| { + if let NonASAPOp::Filter { pred, .. } = operator { + charged( + filter_terms_per_row([&pred.0]).times(input.rows as f64), + estimate.peak_memory_bytes(), + estimate.scan_bytes(), + ) + } else { + (estimate, terms) + } + }); // Over states (one per key and window) it keeps its // values' share of them, however many rows each folds; over // rows, its rows' share. From 6199be914062b093ad2b54b88282138457998baf Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:34:52 +0000 Subject: [PATCH 05/18] feat(cost): price the raw rows query-time scans keep where the data plane keeps them Item 4 of the cost calibration. `DataPlaneExecution::raw_data_medium` (default `Disk`) says where the data plane keeps the raw rows its query-time scans read, and `raw_data_bytes_per_row` (default `None`: the decoded width) what one row takes there, as measured. In memory they are charged as memory (average and peak, memory byte cost) instead of disk, in `plan_cost` and in Stage 3 alike: `raw_data_disk_cost_per_second` is renamed `raw_data_cost_per_second` and prices by the medium; Stage 3's peak-memory and disk quantities take the raw part by the medium. T5, revised: the scanning plan of `count_over_time(m[1m])` every minute keeps 60,000 rows, 1,920,000 bytes, on disk by default and in memory for the in-memory deployment (none on disk). At the memory price that scan is no longer the cheapest, so the test costs the default-selected scanning plan for both deployments and checks that Stage 3 then selects a plan keeping no raw data, its objective equal to its plan_cost. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/lib.rs | 8 +-- crates/cost/src/model.rs | 8 +++ crates/cost/src/node/usage/mod.rs | 8 ++- crates/cost/src/plan/cost.rs | 52 +++++++++------ .../tests/stage3_objective.rs | 64 +++++++++++-------- crates/stage3-plan-selection/src/cost.rs | 28 +++++--- 6 files changed, 107 insertions(+), 61 deletions(-) diff --git a/crates/cost/src/lib.rs b/crates/cost/src/lib.rs index bcb6438c4..1a4c60224 100644 --- a/crates/cost/src/lib.rs +++ b/crates/cost/src/lib.rs @@ -21,7 +21,7 @@ //! with the same function and the rules `plan_cost` applies: //! [`plan::execution_demand::executions_per_second`], //! `RefreshWindow::computed_from` (an ingestion-time node's window), [`read_back_ms`], -//! [`raw_data_disk_cost_per_second`] and +//! [`raw_data_cost_per_second`] and //! [`request_overhead_cost_per_second`]. mod measured; mod model; @@ -50,8 +50,8 @@ pub use node::usage::{ }; pub use plan::cost::{ close_together, ingest_decode_cpu_core_seconds_per_second, ingest_threads_building_copies, - partial_copy_merge_ms, plan_cost, raw_data_disk_cost_per_second, refresh_queue, - request_fixed_cost, request_overhead_cost_per_second, requests_per_second, PlanCost, - QueryLatency, RecommendedThreads, RequestFixedCost, RoleThreads, + partial_copy_merge_ms, plan_cost, raw_data_cost_per_second, refresh_queue, request_fixed_cost, + request_overhead_cost_per_second, requests_per_second, PlanCost, QueryLatency, + RecommendedThreads, RequestFixedCost, RoleThreads, }; pub use resources::ResourceUsage; diff --git a/crates/cost/src/model.rs b/crates/cost/src/model.rs index 63cba33f6..1e979a869 100644 --- a/crates/cost/src/model.rs +++ b/crates/cost/src/model.rs @@ -393,6 +393,14 @@ impl DataPlaneExecution { /// Bad input: a thread count of 0, or a utilisation outside (0, 1]. fn validate(&self) -> Result<(), AnalyticalCostError> { + if let Some(bytes) = self.raw_data_bytes_per_row { + if !(bytes.is_finite() && bytes > 0.0) { + return Err(AnalyticalCostError::InvalidCalibration( + "data_plane_execution.raw_data_bytes_per_row", + bytes, + )); + } + } for (name, threads) in [ ( "data_plane_execution.ingest_threads", diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 2e8e5c8ec..baa89fbf2 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -507,7 +507,8 @@ pub struct NodeResourceUsageAndCost<'a> { /// average and peak memory and its cost; 0 for any other node. pub kept_result_bytes: f64, /// A query-time scan's source and the raw bytes it keeps, by their exact - /// rate (fractional rows; linear in its retention). + /// rate (fractional rows; linear in its retention), at the deployment's + /// `raw_data_bytes_per_row` when given. pub raw_scan: Option<(&'a Source, f64)>, /// Its calibration fit. pub fit: CalibrationFit, @@ -2678,6 +2679,11 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(bytes) => bytes, None => out.bytes as f64, }; + // At the deployment's measured bytes per raw row, when given. + let retained = match data_plane_execution.raw_data_bytes_per_row { + Some(bytes_per_row) if width > 0 => retained / width as f64 * bytes_per_row, + Some(_) | None => retained, + }; raw_scan = Some((source, retained)); } } diff --git a/crates/cost/src/plan/cost.rs b/crates/cost/src/plan/cost.rs index 66d3b6d36..e62f776fa 100644 --- a/crates/cost/src/plan/cost.rs +++ b/crates/cost/src/plan/cost.rs @@ -2,7 +2,7 @@ //! ([`node_resource_usage_and_cost`]), then the plan's usage, latency and //! cost ([`plan_cost`]). Stage 3 costs its candidates with the same //! function and rules (`executions_per_second`, `RefreshWindow::computed_from`, -//! `read_back_ms`, [`raw_data_disk_cost_per_second`], +//! `read_back_ms`, [`raw_data_cost_per_second`], //! [`request_overhead_cost_per_second`]), so its objective is the //! `plan_cost` of the plan it selects. @@ -37,7 +37,7 @@ use asap_types::plan::physical_asap_dag::{ PhysicalASAPOperatorPayload as Payload, }; use asap_types::plan::time_window::{read_back_ms, windows_readers_need}; -use asap_types::stages::{anchor_is_evaluation_time, Lifetime}; +use asap_types::stages::{anchor_is_evaluation_time, Lifetime, StorageMedium}; use asap_types::summary_type::SketchParams; use asap_types::workload::{ greatest_common_divisor, AssumedDataFact, DataWorkload, QueryWorkloadEntry, @@ -333,8 +333,8 @@ pub fn plan_cost( // Each node's work in ms on one core: one computation at query time, // one second of arriving rows at ingestion time. let mut work_ms: HashMap = HashMap::new(); - // The raw data query-time scans read, retained on disk: per source, the - // largest scan's (bytes, node). + // The raw data query-time scans read, retained where the data plane + // keeps it: per source, the largest scan's (bytes, node). let mut raw_data: HashMap<&Source, (f64, PhysicalASAPNodeId)> = HashMap::new(); // Each in-memory ingestion-time state's bytes per window (what it keeps // for one window, its output or an exact aggregate's values). @@ -413,14 +413,26 @@ pub fn plan_cost( } for (bytes, id) in raw_data.into_values() { let node = per_node.get_mut(&id).expect("every node is measured"); - node.memory_and_disk.disk_bytes = node - .memory_and_disk - .disk_bytes - .saturating_add(bytes.round() as u64); - node.detail += &format!("; keeps {bytes:.0} bytes of raw data on disk"); + match settings.data_plane_execution.raw_data_medium { + StorageMedium::Disk => { + node.memory_and_disk.disk_bytes = node + .memory_and_disk + .disk_bytes + .saturating_add(bytes.round() as u64); + node.detail += &format!("; keeps {bytes:.0} bytes of raw data on disk"); + } + StorageMedium::Memory => { + node.memory_and_disk.average_memory_bytes += bytes; + node.memory_and_disk.peak_memory_bytes = node + .memory_and_disk + .peak_memory_bytes + .saturating_add(bytes.round() as u64); + node.detail += &format!("; keeps {bytes:.0} bytes of raw data in memory"); + } + } if let (Some(cost), Some(disk_cost)) = ( &mut node.cost_per_second, - raw_data_disk_cost_per_second(bytes, settings), + raw_data_cost_per_second(bytes, settings), ) { *cost += disk_cost; } @@ -927,14 +939,18 @@ pub fn request_overhead_cost_per_second( } } -/// Cost model 1's cost per second of keeping `bytes` of raw data on disk; -/// `None` under cost models 2 and 3. A plan keeps each source once, for its -/// scan that keeps the most ([`plan_cost`]). -pub fn raw_data_disk_cost_per_second(bytes: f64, settings: &CostInputs) -> Option { - settings - .cost_model - .per_node_unit_costs() - .map(|unit_cost| unit_cost.cost_per_disk_byte_second * bytes) +/// Cost model 1's cost per second of keeping `bytes` of raw data where the +/// data plane keeps it (`DataPlaneExecution::raw_data_medium`): at the +/// disk byte cost on disk, at the memory byte cost in memory; `None` under +/// cost models 2 and 3. A plan keeps each source once, for its scan that +/// keeps the most ([`plan_cost`]). +pub fn raw_data_cost_per_second(bytes: f64, settings: &CostInputs) -> Option { + settings.cost_model.per_node_unit_costs().map(|unit_cost| { + match settings.data_plane_execution.raw_data_medium { + StorageMedium::Disk => unit_cost.cost_per_disk_byte_second * bytes, + StorageMedium::Memory => unit_cost.cost_per_memory_byte_second * bytes, + } + }) } /// The window a query-time `Scan` `node` of `dag` reads per execution: the diff --git a/crates/integration-tests/tests/stage3_objective.rs b/crates/integration-tests/tests/stage3_objective.rs index 0d048718f..ccffad31d 100644 --- a/crates/integration-tests/tests/stage3_objective.rs +++ b/crates/integration-tests/tests/stage3_objective.rs @@ -1220,41 +1220,49 @@ fn raw_data_in_memory(raw_data_bytes_per_row: Option) -> CostInputs { settings } -/// The raw-scanning plan of `count_over_time(m[1m])` every minute (raw data -/// kept) and its `plan_cost` usage under `settings`. -fn raw_scanning_plan_usage(settings: &CostInputs) -> (f64, f64, asap_cost::ResourceUsage) { - let w = workload(&[("count_over_time(m[1m])", 60_000, "")]); - let (plan, (objective, plan_cost)) = selected_plan_objective_and_plan_cost(&w, settings, true); - assert!( - plan.nodes.iter().any(|node| { - node.output_state.timing == ExecutionTiming::QueryTime - && matches!(node.payload, PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { .. })) - }), - "the selected plan scans raw data: {plan:#?}" - ); - let entries: Vec<_> = w.query_workload.entries().collect(); - let data = w.data_workload.clone().unwrap(); - let (cost, _) = asap_cost::plan_cost(&plan, &entries, &data, settings).unwrap(); - (objective, plan_cost, cost.usage) +/// Whether `plan` scans raw data at query time. +fn scans_raw_data(plan: &PhysicalASAPDAG) -> bool { + plan.nodes.iter().any(|node| { + node.output_state.timing == ExecutionTiming::QueryTime + && matches!( + node.payload, + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { .. }) + ) + }) } -/// T5. A deployment keeping raw rows in memory at 32 bytes per row: the -/// raw-scanning plan of `count_over_time(m[1m])` every minute (1,000 rows -/// per second of `m`) keeps a minute of rows, 60,000 x 32 = 1,920,000 -/// bytes, as memory, none of it on disk, and Stage 3's objective is its -/// `plan_cost`. On disk (the default) the same plan keeps no raw rows in -/// memory. +/// T5. A deployment keeping raw rows in memory at 32 bytes per row. The +/// plan Stage 3 selects for `count_over_time(m[1m])` every minute (1,000 +/// rows per second of `m`, raw data kept) under the default costs scans a +/// minute of raw rows, 60,000 rows kept on disk; costed for the in-memory +/// deployment it keeps them as memory, 60,000 x 32 = 1,920,000 bytes, and +/// nothing on disk. At the memory price that scan is no longer the +/// cheapest: Stage 3 selects a plan that keeps no raw data, and its +/// objective is that plan's `plan_cost`. #[test] fn raw_data_kept_in_memory_is_charged_as_memory_at_its_bytes_per_row() { - let (_, _, on_disk) = raw_scanning_plan_usage(&CostInputs::default()); - assert!(on_disk.disk_bytes > 0, "{on_disk:?}"); + let w = workload(&[("count_over_time(m[1m])", 60_000, "")]); + let entries: Vec<_> = w.query_workload.entries().collect(); + let data = w.data_workload.clone().unwrap(); + let (scanning, _) = selected_plan_objective_and_plan_cost(&w, &CostInputs::default(), true); + assert!(scans_raw_data(&scanning), "{scanning:#?}"); + let usage = |settings: &CostInputs| { + asap_cost::plan_cost(&scanning, &entries, &data, settings) + .unwrap() + .0 + .usage + }; + let on_disk = usage(&CostInputs::default()); + assert_eq!(on_disk.disk_bytes, 1_920_000, "{on_disk:?}"); let in_memory = raw_data_in_memory(Some(32.0)); - let (objective, plan_cost, usage) = raw_scanning_plan_usage(&in_memory); - assert_equal("raw in memory", (objective, plan_cost)); - assert_eq!(usage.disk_bytes, 0, "{usage:?}"); - let raw_bytes = usage.average_memory_bytes - on_disk.average_memory_bytes; + let kept_in_memory = usage(&in_memory); + assert_eq!(kept_in_memory.disk_bytes, 0, "{kept_in_memory:?}"); + let raw_bytes = kept_in_memory.average_memory_bytes - on_disk.average_memory_bytes; assert!( (raw_bytes - 1_920_000.0).abs() <= 0.02 * 1_920_000.0, "raw rows in memory: {raw_bytes} bytes" ); + let (selected, costs) = selected_plan_objective_and_plan_cost(&w, &in_memory, true); + assert_equal("raw in memory", costs); + assert!(!scans_raw_data(&selected), "{selected:#?}"); } diff --git a/crates/stage3-plan-selection/src/cost.rs b/crates/stage3-plan-selection/src/cost.rs index b1cca2867..eb947416e 100644 --- a/crates/stage3-plan-selection/src/cost.rs +++ b/crates/stage3-plan-selection/src/cost.rs @@ -43,9 +43,10 @@ //! allows. Retention is linear in that amount: $\pi_v$ is what retaining //! one more output (a window, or a second) costs there, and $W^{\mathrm{mat}}_v$ of a //! materialized candidate is its cost less $\pi_v h_v$. A query-time -//! scan's retention is raw data on disk, kept once per source for the -//! selected scan that keeps the most: $r_s \ge \pi_v h_v$ -//! ([`asap_cost::raw_data_disk_cost_per_second`]). A candidate one of whose +//! scan's retention is raw data, on disk or in memory as the data plane +//! keeps it, kept once per source for the selected scan that keeps the +//! most: $r_s \ge \pi_v h_v$ +//! ([`asap_cost::raw_data_cost_per_second`]). A candidate one of whose //! consumers reads it unbounded (a `Scan` read whole, a `TimeShift` //! anchored with `@`) has no $h_v$: it is costed retaining everything. @@ -56,7 +57,7 @@ use asap_cost::plan::execution_demand::{ context_executions_per_second, executions_per_second as rate_of_materialized, }; use asap_cost::{ - node_resource_usage_and_cost, output_interval_ms, raw_data_disk_cost_per_second, AnswerCache, + node_resource_usage_and_cost, output_interval_ms, raw_data_cost_per_second, AnswerCache, CachedViewWindows, CostInputs, NodeResourceUsageAndCost, ProducerOutput, RawRowsShortOfRange, }; use asap_types::ir::operator::Source; @@ -67,7 +68,7 @@ use asap_types::plan::physical_asap_dag::{ }; use asap_types::stages::{ queries_of_context, EvaluationGrid, ExecutionContext, Lifetime, Memo, MemoGroupId, - PhysicalASAPMemoCandidates, PhysicalCandidateId, PhysicalEdgeId, + PhysicalASAPMemoCandidates, PhysicalCandidateId, PhysicalEdgeId, StorageMedium, }; use asap_types::workload::{DataWorkload, QueryWorkloadEntry}; @@ -1251,6 +1252,13 @@ fn quantity_of( }; (asap_cost::ingest_threads_building_copies(cost_inputs, own_cores) - 1) as f64 }; + // A query-time scan's raw data, where the data plane keeps it. + let raw_bytes_in = |medium: StorageMedium| -> f64 { + match usage.raw_scan { + Some((_, bytes)) if cost_inputs.data_plane_execution.raw_data_medium == medium => bytes, + Some(_) | None => 0.0, + } + }; Ok(match quantity { Quantity::CostPerSecond => return cost_per_second(usage, cost_inputs), Quantity::QueryMsPerRun => ( @@ -1279,18 +1287,18 @@ fn quantity_of( Quantity::PeakMemoryBytes => ( usage.cost.memory_and_disk.peak_memory_bytes as f64 + copies() * usage.maintained.unwrap_or(0) as f64, - 0.0, + raw_bytes_in(StorageMedium::Memory), ), Quantity::DiskBytes => ( usage.cost.memory_and_disk.disk_bytes as f64, - usage.raw_scan.map_or(0.0, |(_, bytes)| bytes), + raw_bytes_in(StorageMedium::Disk), ), }) } /// A candidate's cost per second from its usage under cost model 1: its -/// own, and the raw data a query-time scan keeps on disk -/// ([`asap_cost::raw_data_disk_cost_per_second`]). +/// own, and the raw data a query-time scan keeps +/// ([`asap_cost::raw_data_cost_per_second`]). fn cost_per_second( usage: &NodeResourceUsageAndCost<'_>, cost_inputs: &CostInputs, @@ -1300,7 +1308,7 @@ fn cost_per_second( .cost_per_second .ok_or("the selection MILP costs under cost model 1 only")?; let raw_data = match usage.raw_scan { - Some((_, bytes)) => raw_data_disk_cost_per_second(bytes, cost_inputs) + Some((_, bytes)) => raw_data_cost_per_second(bytes, cost_inputs) .ok_or("the selection MILP costs under cost model 1 only")?, None => 0.0, }; From d45b1f353c6a9a44c109034382adf9576b5934f7 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:35:54 +0000 Subject: [PATCH 06/18] feat(cost): a chain's window holds, emits and keeps states only for the groups its rows reach Item 5 of the cost calibration. A tumbling-window chain was charged a state per group in every window, emitted and kept, though a window holds a state only for the groups its rows reach. Now each window holds `expected_distinct_values(rows per window, groups)` of them (rows spread uniformly over the groups): the chain's emitted states, its windows' memory (sealed, open, cached) and a `SummaryMergeWindows`' merged and emitted states and memory scale by that share. Dense chains are unchanged (10,000 rows over 1,000 series reach all but 0.005%). Example (T6): `auth`'s 10 s windows hold 100,000 rows over 100,000 (host, user) groups, 63,212 reached: 6,321.2 states emitted per second, not 10,000, and 61 windows of 63,212 states kept. Rows are assumed uniform over the groups; a declared skew (with item 6) would lower it further (about 25,000 under the measured Zipf data). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/operations_per_unit.rs | 2 +- crates/cost/src/node/usage/mod.rs | 50 ++++++++++++++++----- 2 files changed, 41 insertions(+), 11 deletions(-) diff --git a/crates/cost/src/node/operations_per_unit.rs b/crates/cost/src/node/operations_per_unit.rs index 07130ccfc..51bdd344d 100644 --- a/crates/cost/src/node/operations_per_unit.rs +++ b/crates/cost/src/node/operations_per_unit.rs @@ -453,7 +453,7 @@ fn cache_miss_fraction(entries: f64, entries_in_cache: f64) -> f64 { /// The expected distinct values among `draws` uniform draws from a column /// of `values` values: `values · (1 − e^(−draws / values))`. Example: /// 12,000 rows of 1,000,000 users hold 11,929 distinct users. -fn expected_distinct_values(draws: f64, values: f64) -> f64 { +pub(crate) fn expected_distinct_values(draws: f64, values: f64) -> f64 { -values * (-draws / values).exp_m1() } diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index baa89fbf2..9560af85f 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -24,8 +24,8 @@ use crate::node::analytical::{ }; use crate::node::cost_terms::{CostConstant, NodeCostTerms}; use crate::node::operations_per_unit::{ - chain_emit_terms_per_state, estimate_terms_per_group, filter_terms_per_row, - hash_aggregate_terms_per_row, merge_output_terms, merge_terms_per_state, + chain_emit_terms_per_state, estimate_terms_per_group, expected_distinct_values, + filter_terms_per_row, hash_aggregate_terms_per_row, merge_output_terms, merge_terms_per_state, pass_through_merge_terms, state_allocation_terms, update_terms_per_row, StateLastWrittenBy, }; use crate::node::operator_statistics::{ @@ -686,6 +686,9 @@ pub(crate) fn node_usage_and_cost_terms<'a>( let mut open_output_bytes: Option = None; // The narrower states a `SummaryMergeWindows` merges per execution. let mut narrower_states_merged_per_execution: u64 = 0; + // The share of a chain's or window merge's groups one of its windows + // holds a state for (`groups_reached_share`); 1 for any other node. + let mut window_group_share = 1.0_f64; // The time its raw output rows span, when it reads or narrows raw rows // (else passed on below). let mut read_raw_rows_span_ms: Option = None; @@ -2010,6 +2013,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(rows_per_tumbling_window / group_count.max(1) as f64), )?; built_state_input_rows = Some(input_rows); + window_group_share = groups_reached_share(rows_per_tumbling_window, group_count); open_output_bytes = Some( group_count .checked_mul( @@ -2027,11 +2031,11 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // when its window opens: at ingestion time one second's share // of each group's window (a 10 s window: a tenth of a state per // group); at query time every retained window's. + // Each window emits a state for each group its rows reach. + let window_groups = group_count as f64 * window_group_share; let emitted_states = match ingestion { - true => { - group_count as f64 * ONE_SECOND_MS as f64 / *tumbling_window_width_ms as f64 - } - false => group_count as f64 * retained_output_count as f64, + true => window_groups * ONE_SECOND_MS as f64 / *tumbling_window_width_ms as f64, + false => window_groups * retained_output_count as f64, }; // At query time each row of the scan's lookback is kept in its // window's range, the work a `TimeRange` over the same rows does @@ -2110,8 +2114,22 @@ pub(crate) fn node_usage_and_cost_terms<'a>( if !ingestion { return Err(AnalyticalCostError::UnsupportedCandidate); } - let merged = group_count as f64 * ONE_SECOND_MS as f64 / narrower_width_ms as f64; - let emitted = group_count as f64 * ONE_SECOND_MS as f64 / width_ms as f64; + // The groups a narrower and a wider window reach: the rows of + // `windows_per_window` narrower windows reach more of them. + let narrower_rows = narrower + .output_facts + .state_input_rows + .and_then(|rows| rows.folded_rows_per_state) + .map(|per_state| per_state * group_count as f64); + let narrower_share = + narrower_rows.map_or(1.0, |rows| groups_reached_share(rows, group_count)); + window_group_share = narrower_rows.map_or(1.0, |rows| { + groups_reached_share(rows * windows_per_window as f64, group_count) + }); + let merged = group_count as f64 * narrower_share * ONE_SECOND_MS as f64 + / narrower_width_ms as f64; + let emitted = + group_count as f64 * window_group_share * ONE_SECOND_MS as f64 / width_ms as f64; narrower_states_merged_per_execution = merged.round() as u64; let merged_input_rows = narrower.output_facts.state_input_rows.map(|mut rows| { rows.folded_rows_per_state = rows @@ -2481,11 +2499,13 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // what the node holds: its output, or the values an exact aggregate // keeps per group when that is more. A computation that keeps nothing holds its // working memory while it runs. - let state = out.bytes.max(estimate.peak_memory_bytes()); + // A chain's or window merge's window holds the groups its rows reach. + let reached = |bytes: u64| (bytes as f64 * window_group_share).round() as u64; + let state = reached(out.bytes.max(estimate.peak_memory_bytes())); // The output being built, its states still open: what a query-time // build holds while it runs, and the newest window an ingestion-time // view keeps besides its sealed ones. - let open_state = open_output_bytes.map_or(state, |open| state.max(open)); + let open_state = open_output_bytes.map_or(state, |open| state.max(reached(open))); // One output's bytes in a stored view's files: its rows at the measured // file bytes per state's row, else its decoded bytes (`state`). Only an // output of states has them; raw rows kept at ingestion do not. @@ -3177,6 +3197,16 @@ pub(crate) fn source_rows_in_window( rows * input.source_rows_per_row } +/// The share of `group_count` groups that `rows` rows reach, each row +/// falling in a group uniformly: `expected_distinct_values(rows, groups)` +/// over the groups. A window of a chain holds a state only for these. +/// Example: 100,000 rows over 100,000 groups reach 63.2% of them; 10,000 +/// rows over 1,000, all but 0.005%. +fn groups_reached_share(rows: f64, group_count: u64) -> f64 { + let groups = group_count.max(1) as f64; + (expected_distinct_values(rows.max(0.0), groups) / groups).clamp(0.0, 1.0) +} + /// The times a grouping into `group_count` groups visits a group's state /// while reading `input_rows` rows: once per group per batch of raw rows /// (`raw_batch_width_ms` each) its input arrives in, at most once per row. From bd80459c56142c50ed1ebc25cf012a5d6159943a Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:36:06 +0000 Subject: [PATCH 07/18] feat(calibration): a deployment's measured cost files for two machines Item 1 of the cost calibration: the deployment's measured costs as data, supplied through `CostInputs` (no planner constant changes). `calibration/measured-cost-files/.json` is a CostInputs file: - measured_operation_costs: query-time Scan 41 ns per row + 8,700 ns per series (TimeRange inside it), ingestion-time Scan 150 ns per arriving row, chain updates and window closes, merges (200 ns per exact state, 1,200 per DDSketch state), finalize 300 ns per group, DDSketch estimate, ns_per_ingested_sample 460; - data_plane_execution: the data plane's view window cache (60 s idle, 15-minute files) and raw rows kept in memory at 32 bytes per row; - frozen_calibration_factor 1.0. Fitted on 2026-12-03 from 60-round runs of three SIL intents in three planning modes on one machine (README: each entry's data points). The second machine's file is the same table at 1.25x (measured 1.22-1.28x in every operator class), the formula-priced nodes scaled 1.25x too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- calibration/measured-cost-files/README.md | 38 +++++ ...el-xeon-e5-2660-v2-40t-unknown-memory.json | 135 ++++++++++++++++++ ...l-xeon-e5-2683-v3-56t-registered-ddr4.json | 135 ++++++++++++++++++ 3 files changed, 308 insertions(+) create mode 100644 calibration/measured-cost-files/README.md create mode 100644 calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json create mode 100644 calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json diff --git a/calibration/measured-cost-files/README.md b/calibration/measured-cost-files/README.md new file mode 100644 index 000000000..d2b7bac92 --- /dev/null +++ b/calibration/measured-cost-files/README.md @@ -0,0 +1,38 @@ +# Measured cost files + +Each file is a deployment's measured cost file: a `CostInputs` JSON +(`asap_planner --cost-inputs `, or `PlanningModels::with_cost_inputs`). +It holds what the deployment's data plane measured on one machine. The file +name is the machine key: CPU architecture, CPU model, logical cores and memory +type. Hostnames are never used. + +`x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json` was fitted on 2026-12-03 +from one data plane's runs of three SIL intents (`drill_cnt`, `dash`, `rca`). +There were 60 rounds each, all three planning modes, and two repetitions. Times are +CPU ns of the data plane's threads: + +| entry | value | fitted from | +|---|---|---| +| `Scan` at query time | 41 ns per row read, 8,700 ns per series visited | four filtered raw reads (residuals 0.85-1.15); held out: 1.01, 1.36 | +| `TimeRange` at query time | 0 | inside the scan's per-row time | +| `Scan` at ingestion time | 150 ns per arriving row | chain upkeep of four chains, one and two label columns (85-305 ns per row with the update) | +| chain update (exact) | 55 ns per row | the same fit | +| state emitted at a window close, persist included | 3,900 ns (charged as the formula's emit plus `ns_per_state_emitted`: 2,400 exact, 1,400 DDSketch) | the same fit | +| `SummaryMergeWindows` (exact) | 780 ns per narrower state merged (about 3,900 per state it emits) | the same fit | +| `SummaryMerge` at query time | 200 ns per exact state, 1,200 per DDSketch state, all-in | three merges of 92k-1M states (0.75-1.25) | +| `FinalizeExactAccumulator` | 300 ns per group | the same merges | +| `SummaryEstimate` (DDSketch) | 3,700 ns per group | the executor fit | +| memory per exact state | 48 bytes | the (host, user) chain's resident views | +| raw rows | kept in memory, 32 bytes per row | the raw store's bytes over rows held | +| `ns_per_ingested_sample` | 460 ns (decode 230, append 230) | per-phase CPU counters | + +The view window cache mirrors the data plane's configuration: 60 s idle and +15-minute files. + +`x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json` is the same table for a +second machine. On it, the same plans took 1.22-1.28x as long in every operator +class: raw read, merge, and chain upkeep. So every measured time is 1.25x, and +the formula-priced nodes are scaled 1.25x (`frozen_calibration_factor`). + +A file is refitted by measuring the data plane again on that machine. The +planner reads only the file. diff --git a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json new file mode 100644 index 000000000..475b497a8 --- /dev/null +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json @@ -0,0 +1,135 @@ +{ + "frozen_calibration_factor": 1.25, + "data_plane_execution": { + "view_window_cache": { + "idle_ms": 60000, + "file_span_ms": 900000 + }, + "raw_data_medium": "Memory", + "raw_data_bytes_per_row": 32.0 + }, + "measured_operation_costs": { + "ns_per_ingested_sample": 575.0, + "operators": [ + { + "operator": "Scan", + "phase": "query_time", + "ns_per_unit": 51.25, + "ns_per_series": 10875.0 + }, + { + "operator": "TimeRange", + "phase": "query_time", + "ns_per_unit": 0.0 + }, + { + "operator": "Scan", + "phase": "ingestion_time", + "ns_per_unit": 187.5 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "exact": "Count", + "ns_per_unit": 68.75, + "ns_per_state_emitted": 3000.0, + "memory_bytes_per_state": 48.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "exact": "Max", + "ns_per_unit": 68.75, + "ns_per_state_emitted": 3000.0, + "memory_bytes_per_state": 48.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 145.0, + "ns_per_state_emitted": 1750.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "exact": "Count", + "ns_per_unit": 975.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "exact": "Max", + "ns_per_unit": 975.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 1875.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 250.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 250.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 1500.0 + }, + { + "operator": "FinalizeExactAccumulator", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 375.0 + }, + { + "operator": "FinalizeExactAccumulator", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 375.0 + }, + { + "operator": "SummaryEstimate", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 4625.0 + }, + { + "operator": "SummaryAgg", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 145.0 + } + ] + } +} diff --git a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json new file mode 100644 index 000000000..656efcc90 --- /dev/null +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json @@ -0,0 +1,135 @@ +{ + "frozen_calibration_factor": 1.0, + "data_plane_execution": { + "view_window_cache": { + "idle_ms": 60000, + "file_span_ms": 900000 + }, + "raw_data_medium": "Memory", + "raw_data_bytes_per_row": 32.0 + }, + "measured_operation_costs": { + "ns_per_ingested_sample": 460.0, + "operators": [ + { + "operator": "Scan", + "phase": "query_time", + "ns_per_unit": 41.0, + "ns_per_series": 8700.0 + }, + { + "operator": "TimeRange", + "phase": "query_time", + "ns_per_unit": 0.0 + }, + { + "operator": "Scan", + "phase": "ingestion_time", + "ns_per_unit": 150.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "exact": "Count", + "ns_per_unit": 55.0, + "ns_per_state_emitted": 2400.0, + "memory_bytes_per_state": 48.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "exact": "Max", + "ns_per_unit": 55.0, + "ns_per_state_emitted": 2400.0, + "memory_bytes_per_state": 48.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "ingestion_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 116.0, + "ns_per_state_emitted": 1400.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "exact": "Count", + "ns_per_unit": 780.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "exact": "Max", + "ns_per_unit": 780.0 + }, + { + "operator": "SummaryMergeWindows", + "phase": "ingestion_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 1500.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 200.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 200.0 + }, + { + "operator": "SummaryMerge", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 1200.0 + }, + { + "operator": "FinalizeExactAccumulator", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 300.0 + }, + { + "operator": "FinalizeExactAccumulator", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 300.0 + }, + { + "operator": "SummaryEstimate", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 3700.0 + }, + { + "operator": "SummaryAgg", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 116.0 + } + ] + } +} From 3b302015f76c99fa2acd1aca791738084996ffe0 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:56:46 +0000 Subject: [PATCH 08/18] test: re-pin the anchors items 3 and 5 move Values pinned on today's costs that the cost calibration changes, each explained: - U13 (IN-list anchor): an undeclared IN-list still keeps every row; its filter and scan now cost that plus evaluating it (100,000 x 10 compared values; a scan's 6,000,000 rows x (1 + 10 x 2.4)). - E6 (IN-list anchor): today's drill_cnt costs 177.9132 / 169.2572 / 140.9361 become 192.9132 / 149.6450 / 125.8274: q2's scan evaluates its 10-value IN-list on its 6,000,000 rows (+15.0/s); a chain over `auth` keeps and emits states only for the 63% of groups its windows reach. - lowest_mean_latency pins: distinct-two-forms 36.7112 -> 36.4823 ms (10,000 series at 15 s: a 10 s window reaches 49% of them, fewer states to emit in the refresh), seed-862 709.8367 -> 709.8338, typical dashboard 847.2063 -> 847.0459 ms. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/tests.rs | 32 ++++++++++++++++--- .../planner-cli/tests/inlist_selectivity.rs | 12 ++++--- .../tests/lowest_mean_latency_exactness.rs | 6 ++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index b2362ecfa..6ace04919 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -5569,8 +5569,11 @@ fn more_values_than_the_column_takes_keep_every_row() { } /// 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. +/// on it keeps every row: a filter, a query-time scan and a grouping see +/// what they see without the predicate, and cost that plus evaluating it, +/// 10 compared values per row read +/// (`FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE`; a scan's predicates +/// also `FILTER_OPERATIONS_PER_ROW`). #[test] fn an_undeclared_column_keeps_every_row() { let settings = CostInputs::default(); @@ -5594,7 +5597,16 @@ fn an_undeclared_column_keeps_every_row() { selected.output_facts.statistics, every.output_facts.statistics ); - assert_eq!(selected.cost.cost_per_second, every.cost.cost_per_second); + use crate::node::operations_per_unit::{ + FILTER_OPERATIONS_PER_ROW, FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE, + }; + let cost_per_op = crate::ResourceUnitCost::illustrative().cost_per_cpu_op; + assert_close( + selected.cost.cost_per_second.unwrap() - every.cost.cost_per_second.unwrap(), + 100_000.0 * 10.0 * FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE * cost_per_op, + 1e-6, + "the filter's compared values", + ); let scan = |predicates| { let scan = auth_scan(predicates, ExecutionTiming::QueryTime); let usage = node_resource_usage_and_cost( @@ -5610,10 +5622,20 @@ fn an_undeclared_column_keeps_every_row() { ( usage.output_facts.statistics, usage.output_facts.raw_rows_per_ms, - usage.cost.cost_per_second, + usage.cost.cost_per_second.unwrap(), ) }; - assert_eq!(scan(vec![in_list(HOST, "h", 10)]), scan(vec![])); + let (selected_rows, selected_rate, selected_cost) = scan(vec![in_list(HOST, "h", 10)]); + let (every_rows, every_rate, every_cost) = scan(vec![]); + assert_eq!((selected_rows, selected_rate), (every_rows, every_rate)); + assert_close( + selected_cost - every_cost, + 6_000_000.0 + * (FILTER_OPERATIONS_PER_ROW + 10.0 * FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE) + * cost_per_op, + 1e-6, + "the scan's predicate", + ); } /// U14 (anchor, Q3). Only `In` constraints have a share: `host NOT IN diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 8d0fc17fd..0e85a8796 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -477,7 +477,11 @@ fn a_literal_in_list_shrinks_its_ingestion_time_state() { /// 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. +/// 192.9132, 149.6450 and 125.8274 per second (177.9132, 169.2572 and +/// 140.9361 before the cost calibration: q2's scan now evaluates its +/// 10-value IN-list on each of its 6,000,000 rows, +15.0 per second, and a +/// chain over `auth` keeps and emits states only for the groups its 10 s +/// windows reach, 63% of them). #[test] fn an_undeclared_label_reproduces_todays_costs() { let rounded = |cost: f64| (cost * 1e4).round() / 1e4; @@ -485,17 +489,17 @@ fn an_undeclared_label_reproduces_todays_costs() { &workload(10, Values::Placeholders, false, false), &capabilities(Values::Placeholders, true, &[]), ); - assert_eq!(rounded(mode2.cost_per_second), 177.9132); + assert_eq!(rounded(mode2.cost_per_second), 192.9132); let lightcone = plan( &workload(10, Values::Placeholders, true, false), &capabilities(Values::Placeholders, true, &[]), ); - assert_eq!(rounded(lightcone.cost_per_second), 169.2572); + assert_eq!(rounded(lightcone.cost_per_second), 149.645); let literal = plan( &workload(10, Values::Literals, false, false), &capabilities(Values::Literals, false, &[]), ); - assert_eq!(rounded(literal.cost_per_second), 140.9361); + assert_eq!(rounded(literal.cost_per_second), 125.8274); } /// `sum(rate(m{job="a"}[5m]))` once, `m` 1,000 series every 15 s holding diff --git a/crates/planner-cli/tests/lowest_mean_latency_exactness.rs b/crates/planner-cli/tests/lowest_mean_latency_exactness.rs index 732afe0b4..d49f6d43f 100644 --- a/crates/planner-cli/tests/lowest_mean_latency_exactness.rs +++ b/crates/planner-cli/tests/lowest_mean_latency_exactness.rs @@ -216,7 +216,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { format!("{snapshots}/distinct-two-forms.json"), "raw-retained", false, - 36.7112080558, + 36.4822625029, DISTINCT_VARIABLES, DISTINCT_ROWS, ), @@ -224,7 +224,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { "tools/dag-viewer/workloads/random-mixed-seed-862/workload-01.json".to_string(), "mvp", false, - 709.836719368, + 709.833844188, SEED_VARIABLES, SEED_ROWS, ), @@ -234,7 +234,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { TYPICAL_DASHBOARD.to_string(), "mvp", false, - 847.206346, + 847.045899638, TYPICAL_VARIABLES, TYPICAL_ROWS, ), From cfa34fb53635b4312273a3dc023948474e27dbb6 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 18:56:46 +0000 Subject: [PATCH 09/18] fix(calibration): price a query-time chain from the measured cost files too With the measured scan prices the planner may build a summary chain at query time (dash q2 in query-at-a-time mode); the files measured chains only at ingestion, leaving that node on the formulas. Add query-time chain entries at the same per-row update (exact 55 ns, DDSketch 116 ns; 1.25x on the slower machine), so every node of the measured intents whose operator the files measure is priced from them (T1). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- calibration/measured-cost-files/README.md | 2 +- ...el-xeon-e5-2660-v2-40t-unknown-memory.json | 22 +++++++++++++++++++ ...l-xeon-e5-2683-v3-56t-registered-ddr4.json | 22 +++++++++++++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/calibration/measured-cost-files/README.md b/calibration/measured-cost-files/README.md index d2b7bac92..f6e2e1e3c 100644 --- a/calibration/measured-cost-files/README.md +++ b/calibration/measured-cost-files/README.md @@ -16,7 +16,7 @@ CPU ns of the data plane's threads: | `Scan` at query time | 41 ns per row read, 8,700 ns per series visited | four filtered raw reads (residuals 0.85-1.15); held out: 1.01, 1.36 | | `TimeRange` at query time | 0 | inside the scan's per-row time | | `Scan` at ingestion time | 150 ns per arriving row | chain upkeep of four chains, one and two label columns (85-305 ns per row with the update) | -| chain update (exact) | 55 ns per row | the same fit | +| chain update (exact; DDSketch 116), at ingestion and in a query-time chain | 55 ns per row | the same fit | | state emitted at a window close, persist included | 3,900 ns (charged as the formula's emit plus `ns_per_state_emitted`: 2,400 exact, 1,400 DDSketch) | the same fit | | `SummaryMergeWindows` (exact) | 780 ns per narrower state merged (about 3,900 per state it emits) | the same fit | | `SummaryMerge` at query time | 200 ns per exact state, 1,200 per DDSketch state, all-in | three merges of 92k-1M states (0.75-1.25) | diff --git a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json index 475b497a8..34e61c962 100644 --- a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json @@ -54,6 +54,28 @@ "ns_per_unit": 145.0, "ns_per_state_emitted": 1750.0 }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 68.75 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 68.75 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 145.0 + }, { "operator": "SummaryMergeWindows", "phase": "ingestion_time", diff --git a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json index 656efcc90..d3cb3d431 100644 --- a/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json @@ -54,6 +54,28 @@ "ns_per_unit": 116.0, "ns_per_state_emitted": 1400.0 }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "exact": "Count", + "ns_per_unit": 55.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "exact": "Max", + "ns_per_unit": 55.0 + }, + { + "operator": "SummaryTumblingWindowChain", + "phase": "query_time", + "sketch": { + "DDSketch": { + "alpha": 0.05 + } + }, + "ns_per_unit": 116.0 + }, { "operator": "SummaryMergeWindows", "phase": "ingestion_time", From d861da2335b2ef632a04f3d657c15675e5a92024 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:02:51 +0000 Subject: [PATCH 10/18] style: list every payload in the series-visited match; format the e2e test clippy::wildcard_enum_match_arm (denied in usage/mod.rs) on item 2's match, and rustfmt on the measured cost file test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 2 +- crates/planner/tests/measured_cost_file.rs | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 9560af85f..42620f8f0 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -2418,7 +2418,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // declare, at most one per row read; none for any other node. let series_visited = match &node.payload { Payload::NonASAP(NonASAPOp::Scan { .. }) => series.map_or(0, |series| series.min(out.rows)), - _ => 0, + Payload::NonASAP(_) | Payload::ASAP(_) => 0, }; let mut detail = detail; // A node with an entry takes its measured time, scanning included; diff --git a/crates/planner/tests/measured_cost_file.rs b/crates/planner/tests/measured_cost_file.rs index b24f482cd..47c05c264 100644 --- a/crates/planner/tests/measured_cost_file.rs +++ b/crates/planner/tests/measured_cost_file.rs @@ -117,8 +117,12 @@ fn within(predicted: f64, measured: f64, ratio: f64) -> bool { fn the_measured_cost_files_validate_and_the_slower_machine_is_one_factor_slower() { let (measured_json, measured) = cost_file(MEASURED_MACHINE); let (slower_json, slower) = cost_file(SLOWER_MACHINE); - measured.validate().expect("the measured machine's file validates"); - slower.validate().expect("the slower machine's file validates"); + measured + .validate() + .expect("the measured machine's file validates"); + slower + .validate() + .expect("the slower machine's file validates"); assert_eq!( slower.frozen_calibration_factor.unwrap(), 1.25 * measured.frozen_calibration_factor.unwrap() From d75dc48607a751478b62e93505cbd68a762ea165 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 19:04:59 +0000 Subject: [PATCH 11/18] test(snapshots): regenerate the 10 corpus and 5 sketch plan snapshots whose costs items 3 and 5 move No selected plan changes: every difference is a cost, CPU, memory or detail number of the same DAG. - o11y_bench q02, q05, q06, q12, q18, q19, q21, q22, q23, q25: each scan's label matcher (e.g. `{job="order-service"}`) is now evaluated per row read (1 + 2.4 operations per compared value), e.g. q12's scan 5.9 -> 9.4 us per evaluation, cost 0.5572 -> 0.5607 per second. - sketch plans chains-10m-5m-3m-10s-mvp, distinct-over-time-5pct-raw-retained, random-mixed-seed-862-long-w01-q3-mvp, seed-862-w01-q3-q8-mvp and seed-862-w02-q2-q7-mvp: a chain's window emits and keeps states only for the groups its rows reach, e.g. 667 rows per 10 s window over 10,000 series reach 4,866 of them: 486.6 states emitted per second, not 1,000. Regenerated with UPDATE_SNAPSHOTS=1 (release, --ignored). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- .../corpus_snapshots/o11y_bench/q02.json | 14 ++--- .../corpus_snapshots/o11y_bench/q05.json | 20 +++---- .../corpus_snapshots/o11y_bench/q06.json | 14 ++--- .../corpus_snapshots/o11y_bench/q12.json | 22 +++---- .../corpus_snapshots/o11y_bench/q18.json | 20 +++---- .../corpus_snapshots/o11y_bench/q19.json | 20 +++---- .../corpus_snapshots/o11y_bench/q21.json | 14 ++--- .../corpus_snapshots/o11y_bench/q22.json | 14 ++--- .../corpus_snapshots/o11y_bench/q23.json | 14 ++--- .../corpus_snapshots/o11y_bench/q25.json | 20 +++---- .../chains-10m-5m-3m-10s-mvp.json | 60 +++++++++---------- .../distinct-over-time-5pct-raw-retained.json | 24 ++++---- ...random-mixed-seed-862-long-w01-q3-mvp.json | 40 ++++++------- .../random-mixed-seed-862-w01-q3-q8-mvp.json | 34 +++++------ .../random-mixed-seed-862-w02-q2-q7-mvp.json | 32 +++++----- 15 files changed, 181 insertions(+), 181 deletions(-) diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json index e77307170..bb2382f30 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q02.json @@ -59,15 +59,15 @@ } ], "cost": { - "cost_per_second": 11.671450891, - "cpu_core_seconds_per_second": 0.01113515, + "cost_per_second": 11.674850891, + "cpu_core_seconds_per_second": 0.01113855, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0108, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000108, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000108, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -164,7 +164,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 4290407.1278, - "cpu_ops_per_second": 11128750.0, + "cpu_ops_per_second": 11132150.0, "disk_bytes": 0, "latency_per_query": [ { @@ -181,7 +181,7 @@ "precompute_load": 0.000025, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0001454, + "predicted_busy_thread_seconds_per_second": 0.0001488, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json index eb680dea9..86ee8328a 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q05.json @@ -107,15 +107,15 @@ } ], "cost": { - "cost_per_second": 12.3482115032, - "cpu_core_seconds_per_second": 0.0113086658667, + "cost_per_second": 12.3574115032, + "cpu_core_seconds_per_second": 0.0113178658667, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0132, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000132, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000132, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -265,11 +265,11 @@ "timing": "query_time" }, "6": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -324,7 +324,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 8316365.09248, - "cpu_ops_per_second": 11297465.8667, + "cpu_ops_per_second": 11306665.8667, "disk_bytes": 0, "latency_per_query": [ { @@ -341,7 +341,7 @@ "precompute_load": 0.00005, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0002522, + "predicted_busy_thread_seconds_per_second": 0.0002614, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json index 398295b3c..47c3b5541 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q06.json @@ -60,15 +60,15 @@ } ], "cost": { - "cost_per_second": 14.4073145651, - "cpu_core_seconds_per_second": 0.013871, + "cost_per_second": 14.4107145651, + "cpu_core_seconds_per_second": 0.0138744, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0108, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000108, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000108, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -193,7 +193,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 4290516.52114, - "cpu_ops_per_second": 13864600.0, + "cpu_ops_per_second": 13868000.0, "disk_bytes": 0, "latency_per_query": [ { @@ -210,7 +210,7 @@ "precompute_load": 0.000025, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0001454, + "predicted_busy_thread_seconds_per_second": 0.0001488, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q12.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q12.json index 817939d74..b10dd81c8 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q12.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q12.json @@ -11,19 +11,19 @@ } ], "cost": { - "cost_per_second": 0.557230000102, - "cpu_core_seconds_per_second": 0.00001708, + "cost_per_second": 0.56068666679, + "cpu_core_seconds_per_second": 0.0000205366666667, "per_node": { "0": { - "cost_per_second": 0.546046666702, + "cost_per_second": 0.549503333389, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.89666666667e-6, - "detail": "scan 1000 samples; x 1.0167/s; holds 48 bytes for 0.006 ms; keeps 172848000 bytes of raw data on disk", + "cpu_core_seconds_per_second": 9.35333333333e-6, + "detail": "scan 1000 samples; x 1.0167/s; holds 48 bytes for 0.009 ms; keeps 172848000 bytes of raw data on disk", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, - "query_ms_per_step": 0.0058, + "query_ms_per_step": 0.0092, "refresh_cpu_ms_per_window": 0.0, "refresh_wall_ms_per_window": 0.0, "timing": "query_time" @@ -45,17 +45,17 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 0.00081984, - "cpu_ops_per_second": 12200.0, + "average_memory_bytes": 0.00098576, + "cpu_ops_per_second": 15656.6666667, "disk_bytes": 172848000, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.01666666667, - "latency_ms": 1.0248, + "latency_ms": 1.2322, "precompute_execution_ms": 0.0, "precompute_queueing_ms": 0.0, - "query_execution_ms": 1.0248 + "query_execution_ms": 1.2322 } ], "peak_cpu_cores": 1, @@ -71,7 +71,7 @@ "recommended_threads": 1 }, "query": { - "predicted_busy_thread_seconds_per_second": 0.00001708, + "predicted_busy_thread_seconds_per_second": 0.0000205366666667, "recommended_threads": 1 } }, diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json index f5d712526..a97a36627 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q18.json @@ -302,15 +302,15 @@ } ], "cost": { - "cost_per_second": 23.9418953469, - "cpu_core_seconds_per_second": 0.0143185769167, + "cost_per_second": 23.9510953469, + "cpu_core_seconds_per_second": 0.0143277769167, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0132, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000132, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000132, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -516,11 +516,11 @@ "timing": "query_time" }, "8": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -547,7 +547,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 76986547.442, - "cpu_ops_per_second": 14307376.9167, + "cpu_ops_per_second": 14316576.9167, "disk_bytes": 0, "latency_per_query": [ { @@ -564,7 +564,7 @@ "precompute_load": 0.0000773333333333, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0002522, + "predicted_busy_thread_seconds_per_second": 0.0002614, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json index 5a8323694..49ff48084 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q19.json @@ -302,15 +302,15 @@ } ], "cost": { - "cost_per_second": 16.7598953469, - "cpu_core_seconds_per_second": 0.0143185769167, + "cost_per_second": 16.7690953469, + "cpu_core_seconds_per_second": 0.0143277769167, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0132, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000132, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000132, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -516,11 +516,11 @@ "timing": "query_time" }, "8": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -547,7 +547,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 19530547.442, - "cpu_ops_per_second": 14307376.9167, + "cpu_ops_per_second": 14316576.9167, "disk_bytes": 0, "latency_per_query": [ { @@ -564,7 +564,7 @@ "precompute_load": 0.0000773333333333, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0002522, + "predicted_busy_thread_seconds_per_second": 0.0002614, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json index 10a350bee..e3ec7377d 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q21.json @@ -59,15 +59,15 @@ } ], "cost": { - "cost_per_second": 6.59443659388, - "cpu_core_seconds_per_second": 0.0056336645, + "cost_per_second": 6.59783659388, + "cpu_core_seconds_per_second": 0.0056370645, "per_node": { "0": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -164,7 +164,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 7686176.75107, - "cpu_ops_per_second": 5628864.5, + "cpu_ops_per_second": 5632264.5, "disk_bytes": 0, "latency_per_query": [ { @@ -181,7 +181,7 @@ "precompute_load": 0.000025, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0001068, + "predicted_busy_thread_seconds_per_second": 0.0001102, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json index af944272d..73e8041b4 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q22.json @@ -59,15 +59,15 @@ } ], "cost": { - "cost_per_second": 6.13693659388, - "cpu_core_seconds_per_second": 0.0056336645, + "cost_per_second": 6.14033659388, + "cpu_core_seconds_per_second": 0.0056370645, "per_node": { "0": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -150,7 +150,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 4026176.75107, - "cpu_ops_per_second": 5628864.5, + "cpu_ops_per_second": 5632264.5, "disk_bytes": 0, "latency_per_query": [ { @@ -167,7 +167,7 @@ "precompute_load": 0.000025, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0001068, + "predicted_busy_thread_seconds_per_second": 0.0001102, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json index fa4ef24d6..c042a29be 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q23.json @@ -40,15 +40,15 @@ } ], "cost": { - "cost_per_second": 6.13693659388, - "cpu_core_seconds_per_second": 0.0056336645, + "cost_per_second": 6.14033659388, + "cpu_core_seconds_per_second": 0.0056370645, "per_node": { "0": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -131,7 +131,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 4026176.75107, - "cpu_ops_per_second": 5628864.5, + "cpu_ops_per_second": 5632264.5, "disk_bytes": 0, "latency_per_query": [ { @@ -148,7 +148,7 @@ "precompute_load": 0.000025, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0001068, + "predicted_busy_thread_seconds_per_second": 0.0001102, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json index 77a5fd32b..982f15af5 100644 --- a/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json +++ b/crates/planner-cli/tests/corpus_snapshots/o11y_bench/q25.json @@ -188,15 +188,15 @@ } ], "cost": { - "cost_per_second": 16.7598953469, - "cpu_core_seconds_per_second": 0.0143185769167, + "cost_per_second": 16.7690953469, + "cpu_core_seconds_per_second": 0.0143277769167, "per_node": { "0": { - "cost_per_second": 0.0074, + "cost_per_second": 0.0132, "cost_source": "analytical", - "cpu_core_seconds_per_second": 7.4e-6, + "cpu_core_seconds_per_second": 0.0000132, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 7.4e-6, + "ingest_cpu_core_seconds_per_second": 0.0000132, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -402,11 +402,11 @@ "timing": "query_time" }, "8": { - "cost_per_second": 0.0058, + "cost_per_second": 0.0092, "cost_source": "analytical", - "cpu_core_seconds_per_second": 5.8e-6, + "cpu_core_seconds_per_second": 9.2e-6, "detail": "scan 1000 samples; x 1.0000/s", - "ingest_cpu_core_seconds_per_second": 5.8e-6, + "ingest_cpu_core_seconds_per_second": 9.2e-6, "multiplier": 1, "operator": "Scan", "priced_outside_measured_scale": false, @@ -433,7 +433,7 @@ "source": "analytical-cost-v2 (illustrative statistics)", "usage": { "average_memory_bytes": 19530547.442, - "cpu_ops_per_second": 14307376.9167, + "cpu_ops_per_second": 14316576.9167, "disk_bytes": 0, "latency_per_query": [ { @@ -450,7 +450,7 @@ "precompute_load": 0.0000773333333333, "recommended_configuration": { "ingest": { - "predicted_busy_thread_seconds_per_second": 0.0002522, + "predicted_busy_thread_seconds_per_second": 0.0002614, "recommended_threads": 1 }, "precompute": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json index 18ee2a05b..c0457f15f 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json @@ -130,8 +130,8 @@ } ], "cost": { - "cost_per_second": 4.25529259649e-7, - "cpu_core_seconds_per_second": 0.0339091400893, + "cost_per_second": 3.96542188505e-7, + "cpu_core_seconds_per_second": 0.0324049182077, "per_node": { "0": { "cost_per_second": 3.14989416e-11, @@ -148,45 +148,45 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 1.9509573131e-8, + "cost_per_second": 1.9509573129e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.000262089333333, + "cpu_core_seconds_per_second": 0.000262089333162, "detail": "build KLL in tumbling windows of 300000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 33.3 states emitted; x 1.0000/s; keeps 14400000 bytes", "ingest_cpu_core_seconds_per_second": 0.000178756, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 24.9999999485, + "refresh_wall_ms_per_window": 24.9999999485, "timing": "ingestion_time" }, "10": { - "cost_per_second": 5.34916587385e-8, + "cost_per_second": 2.70600578392e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.002678756, - "detail": "build KLL in tumbling windows of 10000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 1000.0 states emitted; x 1.0000/s; keeps 20320000 bytes", + "cpu_core_seconds_per_second": 0.00139521320242, + "detail": "build KLL in tumbling windows of 10000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 486.6 states emitted; x 1.0000/s; keeps 9887363 bytes", "ingest_cpu_core_seconds_per_second": 0.000178756, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 12.1645720242, + "refresh_wall_ms_per_window": 12.1645720242, "timing": "ingestion_time" }, "11": { - "cost_per_second": 1.33994557364e-8, + "cost_per_second": 1.08439854939e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.000831626666667, - "detail": "merge tumbling windows of 10000 ms into 60000 ms for 10000 groups: 1000.0 states merged, 166.7 states emitted; x 1.0000/s; keeps 3520000 bytes", + "cpu_core_seconds_per_second": 0.000610947582749, + "detail": "merge tumbling windows of 10000 ms into 60000 ms for 10000 groups: 486.6 states merged, 163.6 states emitted; x 1.0000/s; keeps 3455528 bytes", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryMergeWindows", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 49.8976, - "refresh_wall_ms_per_window": 49.8976, + "refresh_cpu_ms_per_window": 36.656854965, + "refresh_wall_ms_per_window": 36.656854965, "timing": "ingestion_time" }, "12": { @@ -360,45 +360,45 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 38476376.2611, - "cpu_ops_per_second": 33907005.6893, + "average_memory_bytes": 27979267.2611, + "cpu_ops_per_second": 32402783.8077, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 357.7276, - "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 74.8976, + "latency_ms": 331.651426938, + "precompute_execution_ms": 24.9999999485, + "precompute_queueing_ms": 48.8214269891, "query_execution_ms": 257.83 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 145.0176, - "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 74.8976, + "latency_ms": 118.941426938, + "precompute_execution_ms": 24.9999999485, + "precompute_queueing_ms": 48.8214269891, "query_execution_ms": 45.12 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.1, - "latency_ms": 391.13793356, - "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 74.8976, + "latency_ms": 365.061760498, + "precompute_execution_ms": 12.1645720242, + "precompute_queueing_ms": 61.6568549134, "query_execution_ms": 291.24033356 } ], "peak_cpu_cores": 4, - "peak_memory_bytes": 69760632, - "precompute_load": 0.00341496, + "peak_memory_bytes": 59263523, + "precompute_load": 0.00191073811833, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.0003603134, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.00341496, + "predicted_busy_thread_seconds_per_second": 0.00191073811833, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json b/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json index 5d7f11300..2cd90ec35 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json @@ -23,8 +23,8 @@ } ], "cost": { - "cost_per_second": 9.50576144852e-9, - "cpu_core_seconds_per_second": 0.000807966666667, + "cost_per_second": 9.50576144658e-9, + "cpu_core_seconds_per_second": 0.000807966666495, "per_node": { "0": { "cost_per_second": 4.30131012023e-10, @@ -41,15 +41,15 @@ "timing": "query_time" }, "1": { - "cost_per_second": 5.43807654299e-9, + "cost_per_second": 5.43807654104e-9, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.0004796, + "cpu_core_seconds_per_second": 0.000479599999828, "detail": "build KMV in tumbling windows of 300000 ms for 10000 groups: 400000 rows x 116.2 ops, 400000 group visits, 10000.0 states emitted; x 0.0033/s; holds 82400000 bytes for 143.880 ms", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, - "query_ms_per_step": 143.88, + "query_ms_per_step": 143.879999948, "refresh_cpu_ms_per_window": 0.0, "refresh_wall_ms_per_window": 0.0, "timing": "query_time" @@ -169,25 +169,25 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 46792.2225787, - "cpu_ops_per_second": 803700.0, + "average_memory_bytes": 46792.2225645, + "cpu_ops_per_second": 803699.999828, "disk_bytes": 12800000, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 196.27, + "latency_ms": 196.269999948, "precompute_execution_ms": 0.0, "precompute_queueing_ms": 0.0, - "query_execution_ms": 196.27 + "query_execution_ms": 196.269999948 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 191.68, + "latency_ms": 191.679999948, "precompute_execution_ms": 0.0, "precompute_queueing_ms": 0.0, - "query_execution_ms": 191.68 + "query_execution_ms": 191.679999948 } ], "peak_cpu_cores": 2, @@ -203,7 +203,7 @@ "recommended_threads": 1 }, "query": { - "predicted_busy_thread_seconds_per_second": 0.000807966666667, + "predicted_busy_thread_seconds_per_second": 0.000807966666495, "recommended_threads": 1 } }, diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json index ce781e4c9..e6cc694d3 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json @@ -82,8 +82,8 @@ } ], "cost": { - "cost_per_second": 6.90158742996e-6, - "cpu_core_seconds_per_second": 0.567225403667, + "cost_per_second": 6.90154946666e-6, + "cpu_core_seconds_per_second": 0.567223950869, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -100,31 +100,31 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 9.06161747829e-7, + "cost_per_second": 9.0612735786e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.03827, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 413720000 bytes", + "cpu_core_seconds_per_second": 0.0382688650018, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 413701196 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 24.9988650018, + "refresh_wall_ms_per_window": 24.9988650018, "timing": "ingestion_time" }, "2": { - "cost_per_second": 1.1789850139e-7, + "cost_per_second": 1.17894928052e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.00741666666667, - "detail": "merge tumbling windows of 1000 ms into 60000 ms for 10000 groups: 10000.0 states merged, 166.7 states emitted; x 1.0000/s; keeps 30000000 bytes", + "cpu_core_seconds_per_second": 0.00741634886716, + "detail": "merge tumbling windows of 1000 ms into 60000 ms for 10000 groups: 9999.5 states merged, 166.7 states emitted; x 1.0000/s; keeps 30000000 bytes", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryMergeWindows", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 445.0, - "refresh_wall_ms_per_window": 445.0, + "refresh_cpu_ms_per_window": 444.980932029, + "refresh_wall_ms_per_window": 444.980932029, "timing": "ingestion_time" }, "3": { @@ -200,29 +200,29 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 455323038.398, - "cpu_ops_per_second": 566745403.667, + "average_memory_bytes": 455304234.398, + "cpu_ops_per_second": 566743950.869, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 990.958737, - "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 445.0, + "latency_ms": 990.938534031, + "precompute_execution_ms": 24.9988650018, + "precompute_queueing_ms": 444.980932029, "query_execution_ms": 520.958737 } ], "peak_cpu_cores": 2, - "peak_memory_bytes": 469760252, - "precompute_load": 0.0324166666667, + "peak_memory_bytes": 469741448, + "precompute_load": 0.0324152138689, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.01385, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.0324166666667, + "predicted_busy_thread_seconds_per_second": 0.0324152138689, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json index 4d372adb2..1d8166f23 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json @@ -142,8 +142,8 @@ } ], "cost": { - "cost_per_second": 9.63895073011e-6, - "cpu_core_seconds_per_second": 0.835978033333, + "cost_per_second": 9.63893014235e-6, + "cpu_core_seconds_per_second": 0.835976898335, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -160,17 +160,17 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 6.02513335601e-7, + "cost_per_second": 6.02492747833e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.03827, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 149720000 bytes", + "cpu_core_seconds_per_second": 0.0382688650018, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 149713196 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 24.9988650018, + "refresh_wall_ms_per_window": 24.9988650018, "timing": "ingestion_time" }, "10": { @@ -358,37 +358,37 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 207978768.904, - "cpu_ops_per_second": 835018033.333, + "average_memory_bytes": 207971964.904, + "cpu_ops_per_second": 835016898.335, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 878.41, - "precompute_execution_ms": 25.0, + "latency_ms": 878.408865002, + "precompute_execution_ms": 24.9988650018, "precompute_queueing_ms": 69.5, "query_execution_ms": 783.91 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.0333333333333, - "latency_ms": 187.291, - "precompute_execution_ms": 15.0, - "precompute_queueing_ms": 79.5, + "latency_ms": 187.289865002, + "precompute_execution_ms": 22.0, + "precompute_queueing_ms": 72.4988650018, "query_execution_ms": 92.791 } ], "peak_cpu_cores": 3, - "peak_memory_bytes": 216440337, - "precompute_load": 0.025975, + "peak_memory_bytes": 216433533, + "precompute_load": 0.0259738650018, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.023, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.025975, + "predicted_busy_thread_seconds_per_second": 0.0259738650018, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json index 1076cee29..1870a54d9 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json @@ -112,8 +112,8 @@ } ], "cost": { - "cost_per_second": 9.90299385708e-6, - "cpu_core_seconds_per_second": 0.8594601426, + "cost_per_second": 9.90297326931e-6, + "cpu_core_seconds_per_second": 0.859459007602, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -130,17 +130,17 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 6.02513335601e-7, + "cost_per_second": 6.02492747833e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.03827, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 149720000 bytes", + "cpu_core_seconds_per_second": 0.0382688650018, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 149713196 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 24.9988650018, + "refresh_wall_ms_per_window": 24.9988650018, "timing": "ingestion_time" }, "10": { @@ -314,37 +314,37 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 207987715.625, - "cpu_ops_per_second": 858500142.6, + "average_memory_bytes": 207980911.625, + "cpu_ops_per_second": 858499007.602, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 880.91, - "precompute_execution_ms": 25.0, + "latency_ms": 880.908865002, + "precompute_execution_ms": 24.9988650018, "precompute_queueing_ms": 72.0, "query_execution_ms": 783.91 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.2, - "latency_ms": 215.000713, + "latency_ms": 214.999578002, "precompute_execution_ms": 15.0, - "precompute_queueing_ms": 82.0, + "precompute_queueing_ms": 81.9988650018, "query_execution_ms": 118.000713 } ], "peak_cpu_cores": 3, - "peak_memory_bytes": 216450338, - "precompute_load": 0.02895, + "peak_memory_bytes": 216443534, + "precompute_load": 0.0289488650018, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.023, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.02895, + "predicted_busy_thread_seconds_per_second": 0.0289488650018, "recommended_threads": 1 }, "query": { From dd23c8c7d0037bce6e66d7c78883fcf6b91b154b Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 20:17:16 +0000 Subject: [PATCH 12/18] fix(cost): restack onto IN-list selectivity: a query-time scan visits only the series its predicates select Item 2 on the IN-list rule: a query-time scan's series visited are the declared series times the share its label predicates keep (kept values over declared values per restricted column), at most one per row read; `a_measured_scan_visits_only_the_series_its_predicates_select` checks 100 of 100,000 series under `host IN (10 of 10,000)`. Tests that now meet the IN-list rule: the scan-predicate terms test reads every arriving row at ingestion time (query time reads the selected series' rows); U5's ingestion scan costs its predicate on every arriving row; Q5-E2's lower bound follows item 5's cheaper chain (78.37/s). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 23 +++++++- crates/cost/src/node/usage/tests.rs | 56 ++++++++++++++----- .../planner-cli/tests/inlist_selectivity.rs | 6 +- 3 files changed, 68 insertions(+), 17 deletions(-) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 42620f8f0..378969318 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -2415,9 +2415,28 @@ pub(crate) fn node_usage_and_cost_terms<'a>( ) => input.rows, }; // The series a scan visits in one computation: each series its sources - // declare, at most one per row read; none for any other node. + // declare, at query time only those its label predicates select (a + // label kept to k of its N values keeps k/N of the series), at most one + // per row read; none for any other node. let series_visited = match &node.payload { - Payload::NonASAP(NonASAPOp::Scan { .. }) => series.map_or(0, |series| series.min(out.rows)), + Payload::NonASAP(NonASAPOp::Scan { .. }) => { + let selected_share: f64 = match (ingestion, kept_by_predicate.as_ref()) { + (false, Some(kept)) => kept + .kept_values_per_column + .iter() + .filter_map(|(&column, &values)| { + declared_distinct_values(Some(column)) + .map(|declared| (values as f64 / declared.max(1) as f64).min(1.0)) + }) + .product(), + (true, _) | (false, None) => 1.0, + }; + series.map_or(0, |series| { + ((series as f64 * selected_share).round() as u64) + .max(1) + .min(out.rows) + }) + } Payload::NonASAP(_) | Payload::ASAP(_) => 0, }; let mut detail = detail; diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 6ace04919..475b795c3 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -3386,31 +3386,33 @@ fn a_scan_charges_each_row_it_reads_by_a_named_constant() { /// A scan's predicates are evaluated on each row it reads, as a filter's: /// `FILTER_OPERATIONS_PER_ROW` per row and /// `FILTER_OPERATIONS_PER_ROW_PER_COMPARED_VALUE` per value each row is -/// compared with (an IN-list's values, an equality's one). 10 s of `auth` -/// (100,000 rows) under `host IN (10 values)`: 100,000 units of -/// `ScanOperationsPerRow` and of `FilterOperationsPerRow`, 1,000,000 of -/// `FilterOperationsPerRowPerComparedValue`. +/// compared with (an IN-list's values, an equality's one). An +/// ingestion-time scan of `auth` under `host IN (10 values)` reads every +/// arriving row, 10,000 a second: 10,000 units of `ScanOperationsPerRow` +/// and of `FilterOperationsPerRow`, 100,000 of +/// `FilterOperationsPerRowPerComparedValue`. (At query time a series store +/// reads only the selected series' rows, and the terms follow those.) #[test] fn a_scan_charges_its_predicates_per_row_and_compared_value() { let settings = CostInputs::default(); let data = auth_data(true); - let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::QueryTime); - let terms = crate::node_cost_terms(&scan, &[], Some(10_000), &data, &settings).unwrap(); + let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::IngestionTime); + let terms = crate::node_cost_terms(&scan, &[], None, &data, &settings).unwrap(); assert_eq!( terms.units_per_constant, [ - (CostConstant::ScanOperationsPerRow, 100_000.0), - (CostConstant::FilterOperationsPerRow, 100_000.0), + (CostConstant::ScanOperationsPerRow, 10_000.0), + (CostConstant::FilterOperationsPerRow, 10_000.0), ( CostConstant::FilterOperationsPerRowPerComparedValue, - 1_000_000.0 + 100_000.0 ), ] .into() ); assert_close( charged_by_terms(&terms), - formula_cpu_per_execution(&scan, &[], Some(10_000), &data, &settings), + formula_cpu_per_execution(&scan, &[], None, &data, &settings), 1e-9, "the formula", ); @@ -5304,8 +5306,9 @@ fn a_query_time_scan_keeps_its_predicates_share() { } /// 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. +/// arriving row (10,000 a second, the CPU of an unfiltered scan plus its +/// predicate on each, 1 + 10 x 2.4 operations) 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(); @@ -5320,7 +5323,12 @@ fn an_ingestion_time_scan_reads_every_arriving_row() { .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); + assert_close( + usage.cpu_ops_per_second, + all.cpu_ops_per_second + 10_000.0 * (1.0 + 10.0 * 2.4), + 1e-9, + "every arriving row and its predicate", + ); } /// U6. A 10 s count-by-user chain at ingestion time over U5's scan counts @@ -5934,3 +5942,25 @@ fn a_dense_chain_emits_a_state_for_every_group() { usage.cost.detail ); } + +/// T2 over a selecting scan: at query time a series store reads only the +/// series its label predicates select. 10 min of `auth` under `host IN (10 +/// of 10,000)` reads 6,000 rows of 100 of its 100,000 series: 6,000 x 41 +/// + 100 x 8,700 ns = 1.116 ms. +#[test] +fn a_measured_scan_visits_only_the_series_its_predicates_select() { + let scan = auth_scan(vec![in_list(HOST, "h", 10)], ExecutionTiming::QueryTime); + let settings = measured_scan(41.0, 8_700.0); + let usage = node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + Some(600_000), + None, + &auth_data_with_series(100_000), + &settings, + ) + .unwrap(); + assert_eq!(usage.output_facts.statistics.rows, 6_000); + assert_close(usage.work_ms_per_execution, 1.116, 1e-9, "100 series"); +} diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 0e85a8796..831f4eb79 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -585,13 +585,15 @@ fn the_compensation_filter_runs_before_the_time_merge() { /// (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 +/// 10 s level, no wider levels to maintain, 89.03/s; 78.37/s once a chain +/// keeps states only for the 63% of groups its windows reach, so the chain +/// costs above 30/s, not 53.8). 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!( - planned.cost_per_second <= 97.0 && planned.cost_per_second > 27.85 + 53.7, + planned.cost_per_second <= 97.0 && planned.cost_per_second > 27.85 + 30.0, "{} (at most ≈97.0/s expected)", planned.cost_per_second ); From 66e8c9928af98f079236d343648d18cb7caff36b Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:51:44 +0000 Subject: [PATCH 13/18] fix(cost): review I1-I4 and item 6: how a window's rows reach groups, readers see them, series only at query time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review of #1555 (important findings): - I1: a window's groups reached now follows how its rows spread (`GroupReach`): periodic series (`sample_interval` declared) reach min(1, rows/groups) - 10,000 series every 15 s in 10 s windows hold 2/3 of them, a window equal to the interval all of them; a key column with a declared Zipf skew (item 6's `zipf_exponent_per_label`) reaches Σ g(1 - e^(-rows p_i/g)) - 100,000 rows over 10,000 Zipf(1) hosts of 10 users reach 28.1% of the (host, user) groups; otherwise rows fall at random (1 - e^(-rows/groups)). - I2: the share is the chain's and window merge's output: its rows and bytes are one window's states (readers, stored files and memory see the same count); `OutputFacts::window_groups` carries every group and the reach so a window merge sizes its wider window. - I3: a measured scan's per-series charge applies only at query time, over the series its predicates select (none at ingestion). - I4: T4 runs: with the measured file and the declared host skew, drill_cnt's full intent keeps the (host, user) counts, below the on-demand plan, and the formulas alone do not keep them. The measured intents' fixtures now declare the generator's skews (hosts Zipf 1.0; services Zipf 0.8). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/lib.rs | 4 +- crates/cost/src/node/usage/kept_share.rs | 2 +- crates/cost/src/node/usage/mod.rs | 167 ++++++++++++++---- crates/cost/src/node/usage/tests.rs | 166 +++++++++++++++-- crates/planner/tests/measured_cost_file.rs | 43 ++++- .../tests/measured_cost_file/dash/data.json | 8 +- .../measured_cost_file/drill_cnt/data.json | 12 +- .../tests/measured_cost_file/rca/data.json | 5 +- 8 files changed, 344 insertions(+), 63 deletions(-) diff --git a/crates/cost/src/lib.rs b/crates/cost/src/lib.rs index 1a4c60224..ee36fc45b 100644 --- a/crates/cost/src/lib.rs +++ b/crates/cost/src/lib.rs @@ -45,8 +45,8 @@ pub use node::cost_terms::{node_cost_terms, CostConstant, NodeCostTerms}; pub use node::operator_statistics::EdgeStatistics; pub use node::usage::{ node_resource_usage_and_cost, output_interval_ms, reads_one_batch_of, summary_type_name, - CachedViewWindows, NodeCost, NodeMemoryAndDisk, NodeResourceUsageAndCost, OutputFacts, - PhaseTimes, ProducerOutput, RawRowsShortOfRange, + CachedViewWindows, GroupReach, NodeCost, NodeMemoryAndDisk, NodeResourceUsageAndCost, + OutputFacts, PhaseTimes, ProducerOutput, RawRowsShortOfRange, WindowGroups, }; pub use plan::cost::{ close_together, ingest_decode_cpu_core_seconds_per_second, ingest_threads_building_copies, diff --git a/crates/cost/src/node/usage/kept_share.rs b/crates/cost/src/node/usage/kept_share.rs index 1974bfc29..f9c85f47c 100644 --- a/crates/cost/src/node/usage/kept_share.rs +++ b/crates/cost/src/node/usage/kept_share.rs @@ -117,7 +117,7 @@ fn share_of_rows_of_values(kept: u64, values: u64, zipf_exponent: Option) - /// 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 { +pub(super) 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)) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 378969318..b66371fbc 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -415,6 +415,35 @@ pub struct OutputFacts<'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>, + /// A chain's or window merge's groups and how a window's rows reach + /// them (its rows are the groups one window holds a state for); `None` + /// for any other node. + pub window_groups: Option, +} + +/// How the rows of one window spread over a chain's groups, which sets +/// how many of them the window holds a state for +/// ([`groups_reached_share`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum GroupReach { + /// Every series is sampled at its declared interval + /// (`sample_interval`): a window of r rows over G groups reaches + /// min(1, r/G) of them. + Periodic, + /// Rows fall on the groups at random, uniformly: 1 − e^(−r/G). + Uniform, + /// A key column's `values` values hold the rows by Zipf(`exponent`) + /// (`zipf_exponent_per_label`), each value's groups uniformly. + Zipf { values: u64, exponent: f64 }, +} + +/// A chain's or window merge's groups ([`OutputFacts::window_groups`]). +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct WindowGroups { + /// Every group it keys states by. + pub groups: u64, + /// How a window's rows reach them. + pub reach: GroupReach, } /// Raw rows fewer than arrive over the range they are read for @@ -686,9 +715,8 @@ pub(crate) fn node_usage_and_cost_terms<'a>( let mut open_output_bytes: Option = None; // The narrower states a `SummaryMergeWindows` merges per execution. let mut narrower_states_merged_per_execution: u64 = 0; - // The share of a chain's or window merge's groups one of its windows - // holds a state for (`groups_reached_share`); 1 for any other node. - let mut window_group_share = 1.0_f64; + // A chain's or window merge's groups and how its windows reach them. + let mut built_window_groups: Option = None; // The time its raw output rows span, when it reads or narrows raw rows // (else passed on below). let mut read_raw_rows_span_ms: Option = None; @@ -2013,9 +2041,38 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(rows_per_tumbling_window / group_count.max(1) as f64), )?; built_state_input_rows = Some(input_rows); - window_group_share = groups_reached_share(rows_per_tumbling_window, group_count); + // A window holds a state for each group its rows reach: under a + // key column with a declared Zipf skew the heavy values' groups + // take most of its rows; periodic series are each sampled every + // interval; otherwise rows fall at random. + let skewed_key = match reduction { + Reduction::Reduce(keys) => keys.keys().iter().find_map(|&column| { + let name = input_schema?.fields.get(column)?.name.as_str(); + let declared = declared_values(name)?; + Some((declared.distinct, declared.zipf_exponent?)) + }), + Reduction::PerEntity => None, + }; + let periodic = !sources.is_empty() + && sources.iter().all(|source| { + data.sources + .get(*source) + .is_some_and(|facts| facts.sample_interval.is_some()) + }); + let reach = match (skewed_key, periodic) { + (Some((values, exponent)), _) => GroupReach::Zipf { values, exponent }, + (None, true) => GroupReach::Periodic, + (None, false) => GroupReach::Uniform, + }; + built_window_groups = Some(WindowGroups { + groups: group_count, + reach, + }); + let window_groups = group_count as f64 + * groups_reached_share(rows_per_tumbling_window, group_count, reach); + let window_states = (window_groups.round() as u64).clamp(1, group_count.max(1)); open_output_bytes = Some( - group_count + window_states .checked_mul( open_state_bytes + state_row_bytes_beside_state( @@ -2032,7 +2089,6 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // of each group's window (a 10 s window: a tenth of a state per // group); at query time every retained window's. // Each window emits a state for each group its rows reach. - let window_groups = group_count as f64 * window_group_share; let emitted_states = match ingestion { true => window_groups * ONE_SECOND_MS as f64 / *tumbling_window_width_ms as f64, false => window_groups * retained_output_count as f64, @@ -2054,9 +2110,10 @@ pub(crate) fn node_usage_and_cost_terms<'a>( } // Each group's state found once per raw batch. let group_visits = visits(group_count); + // One window: a state for each group it reaches. let out = EdgeStatistics { - rows: group_count, - bytes: group_count + rows: window_states, + bytes: window_states .checked_mul( state_bytes + state_row_bytes_beside_state( @@ -2109,27 +2166,40 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .max(1); let width_ms = (*tumbling_window_width_ms).max(1); let windows_per_window = (width_ms / narrower_width_ms).max(1); - let group_count = narrower.output_facts.statistics.rows.max(1); + // Every group, and the narrower windows' states: the groups one + // narrower window reaches. + let window_groups = narrower.output_facts.window_groups; + let group_count = window_groups + .map_or(narrower.output_facts.statistics.rows, |groups| { + groups.groups + }) + .max(1); + let narrower_states = narrower.output_facts.statistics.rows.max(1); // Stage 2 offers it at ingestion time only. if !ingestion { return Err(AnalyticalCostError::UnsupportedCandidate); } - // The groups a narrower and a wider window reach: the rows of - // `windows_per_window` narrower windows reach more of them. + // A wider window reaches the groups the rows of its + // `windows_per_window` narrower windows reach. let narrower_rows = narrower .output_facts .state_input_rows .and_then(|rows| rows.folded_rows_per_state) .map(|per_state| per_state * group_count as f64); - let narrower_share = - narrower_rows.map_or(1.0, |rows| groups_reached_share(rows, group_count)); - window_group_share = narrower_rows.map_or(1.0, |rows| { - groups_reached_share(rows * windows_per_window as f64, group_count) - }); - let merged = group_count as f64 * narrower_share * ONE_SECOND_MS as f64 - / narrower_width_ms as f64; - let emitted = - group_count as f64 * window_group_share * ONE_SECOND_MS as f64 / width_ms as f64; + let wider_states = match (window_groups, narrower_rows) { + (Some(groups), Some(rows)) => ((group_count as f64 + * groups_reached_share( + rows * windows_per_window as f64, + group_count, + groups.reach, + )) + .round() as u64) + .clamp(narrower_states.min(group_count), group_count), + (None, _) | (_, None) => group_count, + }; + built_window_groups = window_groups; + let merged = narrower_states as f64 * ONE_SECOND_MS as f64 / narrower_width_ms as f64; + let emitted = wider_states as f64 * ONE_SECOND_MS as f64 / width_ms as f64; narrower_states_merged_per_execution = merged.round() as u64; let merged_input_rows = narrower.output_facts.state_input_rows.map(|mut rows| { rows.folded_rows_per_state = rows @@ -2163,8 +2233,8 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .times(emitted), ); let out = EdgeStatistics { - rows: group_count, - bytes: group_count + rows: wider_states, + bytes: wider_states .checked_mul( merged_state_bytes + state_row_bytes_beside_state( @@ -2429,9 +2499,10 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .map(|declared| (values as f64 / declared.max(1) as f64).min(1.0)) }) .product(), - (true, _) | (false, None) => 1.0, + (false, None) => 1.0, + (true, _) => 0.0, }; - series.map_or(0, |series| { + series.filter(|_| !ingestion).map_or(0, |series| { ((series as f64 * selected_share).round() as u64) .max(1) .min(out.rows) @@ -2518,13 +2589,11 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // what the node holds: its output, or the values an exact aggregate // keeps per group when that is more. A computation that keeps nothing holds its // working memory while it runs. - // A chain's or window merge's window holds the groups its rows reach. - let reached = |bytes: u64| (bytes as f64 * window_group_share).round() as u64; - let state = reached(out.bytes.max(estimate.peak_memory_bytes())); + let state = out.bytes.max(estimate.peak_memory_bytes()); // The output being built, its states still open: what a query-time // build holds while it runs, and the newest window an ingestion-time // view keeps besides its sealed ones. - let open_state = open_output_bytes.map_or(state, |open| state.max(reached(open))); + let open_state = open_output_bytes.map_or(state, |open| state.max(open)); // One output's bytes in a stored view's files: its rows at the measured // file bytes per state's row, else its decoded bytes (`state`). Only an // output of states has them; raw rows kept at ingestion do not. @@ -2944,6 +3013,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( state_data_span_ms, raw_rows_shifted_back_ms, kept_values_per_column, + window_groups: built_window_groups, }, work_ms_per_execution: node_ms, cpu_ops_per_second: estimate.cpu_ops() * per_second, @@ -3216,14 +3286,41 @@ pub(crate) fn source_rows_in_window( rows * input.source_rows_per_row } -/// The share of `group_count` groups that `rows` rows reach, each row -/// falling in a group uniformly: `expected_distinct_values(rows, groups)` -/// over the groups. A window of a chain holds a state only for these. -/// Example: 100,000 rows over 100,000 groups reach 63.2% of them; 10,000 -/// rows over 1,000, all but 0.005%. -fn groups_reached_share(rows: f64, group_count: u64) -> f64 { +/// The share of `group_count` groups that a window of `rows` rows reaches, +/// by how its rows spread over them ([`GroupReach`]). Examples: 6,667 rows +/// of 10,000 series sampled every 15 s (a 10 s window) reach 66.7% of +/// them periodically; 100,000 rows falling uniformly over 100,000 groups +/// reach 63.2%. +fn groups_reached_share(rows: f64, group_count: u64, reach: GroupReach) -> f64 { let groups = group_count.max(1) as f64; - (expected_distinct_values(rows.max(0.0), groups) / groups).clamp(0.0, 1.0) + let rows = rows.max(0.0); + match reach { + GroupReach::Periodic => (rows / groups).min(1.0), + GroupReach::Uniform => (expected_distinct_values(rows, groups) / groups).clamp(0.0, 1.0), + GroupReach::Zipf { values, exponent } => { + groups_reached_share_under_zipf(rows, group_count, values, exponent) + } + } +} + +fn groups_reached_share_under_zipf(rows: f64, group_count: u64, values: u64, exponent: f64) -> f64 { + let values = values.max(1); + let groups = group_count.max(1) as f64; + let per_value = (groups / values as f64).max(1.0); + let norm = kept_share::generalized_harmonic(values, exponent); + let mut reached = 0.0; + let mut low = 1_u64; + while low <= values { + let high = ((low as f64 * 1.05).ceil() as u64) + .max(low + 1) + .min(values + 1); + let count = (high - low) as f64; + let rank = (low as f64 * (high - 1) as f64).sqrt(); + let share = rank.powf(-exponent) / norm; + reached += count * per_value * -(-(rows.max(0.0) * share / per_value)).exp_m1(); + low = high; + } + (reached / groups).clamp(0.0, 1.0) } /// The times a grouping into `group_count` groups visits a group's state diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 475b795c3..bdb9bddf9 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -70,6 +70,7 @@ fn a_merge_over_a_chain_s_windows_outputs_one_state_per_group() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let windows = node(Payload::NonASAP(NonASAPOp::TimeRange { @@ -188,6 +189,7 @@ fn an_operator_keeping_its_input_window_over_a_chain_or_its_windows_selects_what states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; for &step in path { @@ -256,6 +258,7 @@ fn a_merge_over_a_chain_s_windows_is_costed_by_the_chain_s_family() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -338,6 +341,7 @@ fn a_project_or_filter_over_states_passes_their_family_on() { states_last_merged: true, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; for passing in [ @@ -424,6 +428,7 @@ fn a_merge_over_a_rate_chain_s_windows_is_costed_by_the_rate_accumulator() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -505,6 +510,7 @@ fn raw_rows<'a>( states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, } } @@ -781,6 +787,7 @@ fn a_query_time_chain_pays_the_time_range_over_the_rows_it_reads() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let chain = PhysicalASAPDAGNode { @@ -1049,6 +1056,7 @@ fn a_merge_reading_one_state_per_group_passes_it_through() { distinct_values: None, }), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let merge = PhysicalASAPDAGNode { @@ -1695,6 +1703,7 @@ fn a_kmv_rollup_merge_costs_per_hash_it_inserts() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let rollup = PhysicalASAPDAGNode { @@ -1776,6 +1785,7 @@ fn a_rollup_merges_its_states_when_its_group_estimate_ties_its_input() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let merge_ms = |group_by: Option>| { @@ -1850,6 +1860,7 @@ fn query_time_memory_is_held_only_while_the_node_computes() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let merge = PhysicalASAPDAGNode { @@ -1995,6 +2006,7 @@ fn an_ingestion_time_view_of_raw_rows_keeps_the_rows_its_retention_covers() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let row_schema = Schema::new(vec![ @@ -2071,6 +2083,7 @@ fn a_view_without_retention_is_not_costed() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let shift = PhysicalASAPDAGNode { @@ -2155,6 +2168,7 @@ fn a_view_over_an_ingestion_time_chain_keeps_one_output_per_chain_window() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let usage = node_resource_usage_and_cost( @@ -2232,6 +2246,7 @@ fn ddsketch_build_cost( states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let settings = CostInputs::default(); @@ -2465,6 +2480,7 @@ fn ddsketch_assumed_facts_over_sources( raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let settings = CostInputs::default(); @@ -2666,6 +2682,7 @@ fn kll_merge_cpu_ops_over(k: u32, window_ms: u64, range_s: u64) -> f64 { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let mut chain = node(Payload::ASAP(ASAPOp::SummaryTumblingWindowChain { @@ -2796,6 +2813,7 @@ fn a_finalize_charges_each_group_its_measured_time() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let finalize = node(Payload::ASAP(ASAPOp::FinalizeExactAccumulator { @@ -2856,6 +2874,7 @@ fn a_per_series_aggregate_charges_the_labels_it_carries() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let ms_per_row = |labels: &[&str]| { @@ -2982,6 +3001,7 @@ fn a_merge_over_several_inputs_sizes_its_state_for_all_of_them() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let wider = ProducerOutput { @@ -3090,6 +3110,7 @@ fn kll_estimate_us_per_group(producer: Payload, rows_per_state: u64, state_bytes distinct_values: None, }), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let estimate = node(Payload::ASAP(ASAPOp::SummaryEstimate { @@ -3649,6 +3670,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: Some(rows_per_state), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let windows = PhysicalASAPDAGNode { @@ -3801,6 +3823,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: Some(kmv_rows), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }], None, @@ -3885,6 +3908,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { distinct_values: None, }), kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }], None, @@ -3922,6 +3946,7 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }], None, @@ -4177,6 +4202,7 @@ fn rows_of<'a>(producer: &'a PhysicalASAPDAGNode, rows: u64) -> ProducerOutput<' raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, } } @@ -4415,6 +4441,7 @@ fn counter_sketch_charges_ms(shape: &CounterSketchShape) -> CounterSketchCharges states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let family = FieldDataType::Sketch(algorithm); @@ -4708,6 +4735,7 @@ fn a_ddsketch_build_holds_open_states_and_keeps_sealed_ones() { raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let rows = StateInputRows { @@ -4795,6 +4823,7 @@ fn a_measured_ddsketch_state_size_replaces_the_estimate() { raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let build = PhysicalASAPDAGNode { @@ -5481,6 +5510,7 @@ fn a_merge_by_key_over_a_filtered_state_merges_the_kept_states() { states_last_merged: true, state_input_rows: None, kept_values_per_column: BTreeMap::new(), + window_groups: None, }, }; let compensation = filter_node( @@ -5751,7 +5781,7 @@ fn an_in_list_share_names_the_uniform_rows_per_value_assumption() { } // Cost calibration against a deployment's measurements (proposal -// `dev/cost-calibration.md`, section 5): per-series scan unit (T2), named +// the cost calibration proposal, section 5): per-series scan unit (T2), named // scan and filter constants, active groups per window (T6). /// A deployment's measured cost file with one query-time `Scan` entry: @@ -5860,16 +5890,27 @@ fn auth_count_chain(keys: Vec) -> PhysicalASAPDAGNode { } } +/// `auth` arriving at 10,000 rows per second with no sample interval +/// declared, so its rows fall on the groups at random. +fn auth_data_unsampled() -> DataWorkload { + let mut data = auth_data(true); + for facts in data.sources.values_mut() { + facts.sample_interval = None; + } + data +} + /// T6. A window holds a state only for the groups its rows reach: a 10 s -/// window of `auth` holds 100,000 rows over its 100,000 (host, user) -/// groups, of which 100,000 · (1 − e^−1) = 63,212 appear when rows fall -/// uniformly (`expected_distinct_values`). So the chain emits 6,321.2 -/// states per second, not 10,000, and keeps its 60 sealed windows and the -/// one being built at 63,212 states each, not 100,000. +/// window of `auth` (rows at random, no sample interval) holds 100,000 +/// rows over its 100,000 (host, user) groups, of which 100,000 · (1 − +/// e^−1) = 63,212 appear (`expected_distinct_values`). So the chain's +/// window is 63,212 states (what its readers read), it emits 6,321.2 states +/// per second, not 10,000, and keeps its 60 sealed windows and the one +/// being built. #[test] fn a_chain_emits_and_keeps_states_only_for_the_groups_its_windows_reach() { let settings = CostInputs::default(); - let data = auth_data(true); + let data = auth_data_unsampled(); let scan = auth_scan(vec![], ExecutionTiming::IngestionTime); let scan_usage = node_resource_usage_and_cost(&scan, &[], (1, 1.0), None, None, &data, &settings).unwrap(); @@ -5884,25 +5925,67 @@ fn a_chain_emits_and_keeps_states_only_for_the_groups_its_windows_reach() { &settings, ) .unwrap(); - assert_eq!(usage.output_facts.statistics.rows, 100_000, "the groups"); + assert_eq!( + usage.output_facts.statistics.rows, 63_212, + "the groups reached" + ); + assert_eq!( + usage.output_facts.window_groups.map(|groups| groups.groups), + Some(100_000) + ); assert!( usage.cost.detail.contains("6321.2 states emitted"), "{}", usage.cost.detail ); - let active_share = -(-1.0_f64).exp_m1(); let window_bytes = usage.output_facts.statistics.bytes as f64; assert_close( usage.cost.memory_and_disk.average_memory_bytes, - 61.0 * window_bytes * active_share, + 61.0 * window_bytes, 1e-3, "61 windows of the groups reached", ); } +/// I1. Periodic series: `auth`'s 100,000 series each sampled every 10 s +/// put exactly one row of every series in a 10 s window, so the window +/// holds all 100,000 states (random draws would say 63,212); 10,000 series +/// every 15 s in 10 s windows hold 2/3 of them. +#[test] +fn a_chain_over_periodic_series_reaches_rows_over_groups_of_them() { + let settings = CostInputs::default(); + let emitted = |data: &DataWorkload| { + let scan = auth_scan(vec![], ExecutionTiming::IngestionTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), None, None, data, &settings) + .unwrap(); + let chain = auth_count_chain(vec![HOST, USER]); + node_resource_usage_and_cost( + &chain, + &[produced(&scan, &scan_usage)], + (1, 1.0), + Some(10_000), + None, + data, + &settings, + ) + .unwrap() + .output_facts + .statistics + .rows + }; + assert_eq!(emitted(&auth_data(true)), 100_000); + let mut sparse = auth_data(true); + for facts in sparse.sources.values_mut() { + facts.series_count = Some(100_000); + facts.sample_interval = Some(asap_types::workload::DurationMs(15_000)); + } + assert_eq!(emitted(&sparse), 66_667); +} + /// T6. A dense chain is unchanged: 1,000 series at 1 Hz put 10,000 rows in -/// each 10 s window, so every series appears (1 − e^−10 of them) and -/// the chain emits 100 states per second. +/// each 10 s window, so every series appears (periodic: 10,000 / 1,000, +/// capped at all of them) and the chain emits 100 states per second. #[test] fn a_dense_chain_emits_a_state_for_every_group() { let settings = CostInputs::default(); @@ -5964,3 +6047,62 @@ fn a_measured_scan_visits_only_the_series_its_predicates_select() { assert_eq!(usage.output_facts.statistics.rows, 6_000); assert_close(usage.work_ms_per_execution, 1.116, 1e-9, "100 series"); } + +/// T6 under a declared skew (item 6's `zipf_exponent_per_label`): with +/// `host` declared Zipf(1), a 10 s window of `auth` (100,000 rows over +/// 10,000 hosts of 10 users each) reaches Σ 10·(1 − e^(−100,000·p_i/10)) +/// = 28,134 of its 100,000 (host, user) groups, not the 63,212 uniform +/// rows would: 2,813 states emitted per second. +#[test] +fn a_chain_under_a_declared_skew_reaches_fewer_groups() { + let settings = CostInputs::default(); + let mut data = auth_data_unsampled(); + for facts in data.sources.values_mut() { + facts.zipf_exponent_per_label.insert("host".into(), 1.0); + } + let scan = auth_scan(vec![], ExecutionTiming::IngestionTime); + let scan_usage = + node_resource_usage_and_cost(&scan, &[], (1, 1.0), None, None, &data, &settings).unwrap(); + let chain = auth_count_chain(vec![HOST, USER]); + let usage = node_resource_usage_and_cost( + &chain, + &[produced(&scan, &scan_usage)], + (1, 1.0), + Some(10_000), + None, + &data, + &settings, + ) + .unwrap(); + let emitted: f64 = usage + .cost + .detail + .split(" states emitted") + .next() + .and_then(|head| head.rsplit(", ").next()) + .and_then(|number| number.parse().ok()) + .unwrap_or_else(|| panic!("{}", usage.cost.detail)); + assert_close(emitted, 2_813.4, 0.02, "states emitted per second"); +} + +/// I3. An ingestion-time scan visits no series: its arriving rows come +/// sample by sample, so a phase-less measured entry's `ns_per_series` +/// charges nothing there; 10,000 arriving rows of `auth` at 41 ns are +/// 0.41 ms per second. +#[test] +fn an_ingestion_time_scan_pays_no_per_series_charge() { + let scan = auth_scan(vec![], ExecutionTiming::IngestionTime); + let mut settings = measured_scan(41.0, 8_700.0); + settings.measured_operation_costs.operators[0].phase = None; + let usage = node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + None, + None, + &auth_data(true), + &settings, + ) + .unwrap(); + assert_close(usage.work_ms_per_execution, 0.41, 1e-9, "rows only"); +} diff --git a/crates/planner/tests/measured_cost_file.rs b/crates/planner/tests/measured_cost_file.rs index 47c05c264..57c83e569 100644 --- a/crates/planner/tests/measured_cost_file.rs +++ b/crates/planner/tests/measured_cost_file.rs @@ -252,15 +252,42 @@ async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() } } -/// T4. Once a binding chosen by an upstream top-k is costed at the rows its -/// heavy values hold (10 of 10,000 Zipf(1) hosts hold 29.3% of `auth`, not -/// 0.1%), `drill_cnt`'s full intent keeps the (host, user) counts and -/// filters them before the time merge: predicted 39.5 per second against -/// 45 for reading the selected rows at query time. +/// T4. With the hosts' declared Zipf(1) skew (item 6), q2's IN-list over +/// q1's top-10 hosts keeps the 29.9% of `auth` they hold, not 0.1%. Priced +/// from the measured cost file, full intent planning keeps the (host, user) +/// counts (`lightcone_query_indices` non-empty) and costs less than the +/// on-demand plan of the same file; with the formulas alone it does not. #[tokio::test(flavor = "multi_thread")] -#[ignore = "needs the skew-aware share of a top-k binding (item 6 of the cost calibration, on the IN-list selectivity branch)"] async fn drill_cnt_keeps_the_lightcone_once_top_k_bindings_hold_their_heavy_rows() { let (_, inputs) = cost_file(MEASURED_MACHINE); - let (plan, _) = planned("drill_cnt", IntentPlanningMode::IntentFull, &inputs).await; - assert!(!plan.lightcone_query_indices.is_empty()); + let (full, full_report) = planned("drill_cnt", IntentPlanningMode::IntentFull, &inputs).await; + let (_, on_demand) = planned( + "drill_cnt", + IntentPlanningMode::IntentOnDemandHoles, + &inputs, + ) + .await; + let (formula_full, formula_report) = planned( + "drill_cnt", + IntentPlanningMode::IntentFull, + &CostInputs::default(), + ) + .await; + eprintln!( + "with file: full {:?} (lightcone {:?}), on demand {:?}; formulas: full {:?} (lightcone {:?})", + full_report.cost_per_second, + full.lightcone_query_indices, + on_demand.cost_per_second, + formula_report.cost_per_second, + formula_full.lightcone_query_indices + ); + assert!( + !full.lightcone_query_indices.is_empty(), + "no lightcone kept" + ); + assert!(full_report.cost_per_second.unwrap() < on_demand.cost_per_second.unwrap()); + assert!( + formula_full.lightcone_query_indices.is_empty(), + "the formulas alone keep the lightcone too" + ); } diff --git a/crates/planner/tests/measured_cost_file/dash/data.json b/crates/planner/tests/measured_cost_file/dash/data.json index f38b340d6..3e471d9ad 100644 --- a/crates/planner/tests/measured_cost_file/dash/data.json +++ b/crates/planner/tests/measured_cost_file/dash/data.json @@ -22,6 +22,9 @@ "min_abs": 1.0, "max_abs": 100000.0 } + }, + "zipf_exponent_per_label": { + "service": 0.8 } }, "errors": { @@ -34,7 +37,10 @@ "rows_held": 600000, "column_signs": { "value": "non_negative" + }, + "zipf_exponent_per_label": { + "service": 0.8 } } } -} \ No newline at end of file +} diff --git a/crates/planner/tests/measured_cost_file/drill_cnt/data.json b/crates/planner/tests/measured_cost_file/drill_cnt/data.json index 747172cd6..aae7ddc18 100644 --- a/crates/planner/tests/measured_cost_file/drill_cnt/data.json +++ b/crates/planner/tests/measured_cost_file/drill_cnt/data.json @@ -16,7 +16,10 @@ "column_signs": { "value": "non_negative" }, - "max_distinct_per_evaluation": 100000 + "max_distinct_per_evaluation": 100000, + "zipf_exponent_per_label": { + "host": 1.0 + } }, "auth": { "series_count": 100000, @@ -29,7 +32,10 @@ "column_signs": { "value": "non_negative" }, - "max_distinct_per_evaluation": 100000 + "max_distinct_per_evaluation": 100000, + "zipf_exponent_per_label": { + "host": 1.0 + } } } -} \ No newline at end of file +} diff --git a/crates/planner/tests/measured_cost_file/rca/data.json b/crates/planner/tests/measured_cost_file/rca/data.json index de82643d5..fb97e69b1 100644 --- a/crates/planner/tests/measured_cost_file/rca/data.json +++ b/crates/planner/tests/measured_cost_file/rca/data.json @@ -22,6 +22,9 @@ "min_abs": 1.0, "max_abs": 100000.0 } + }, + "zipf_exponent_per_label": { + "service": 0.8 } }, "node_metrics": { @@ -43,4 +46,4 @@ } } } -} \ No newline at end of file +} From f403938a14de02bf11672230ec36430a04be81a6 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 23:15:41 +0000 Subject: [PATCH 14/18] fix(cost): readers read every group per window (merge prices were fitted on those counts); window share scales memory, stored bytes and emits Revises I2 of the review: scaling the chain's output edge broke Stage 3's per-family folded-rows invariant and the MILP = plan_cost check. The measured SummaryMerge price was fitted against the planner's all-group state counts, so readers keep charging every group; the window's memory, stored file bytes and emitted states hold only the groups its rows reach. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/node/usage/mod.rs | 65 +++++++++++++++-------------- crates/cost/src/node/usage/tests.rs | 37 ++++++++-------- 2 files changed, 52 insertions(+), 50 deletions(-) diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index b66371fbc..32deb64d6 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -416,8 +416,8 @@ pub struct OutputFacts<'a> { /// `auth` leaves `{host: 10}`, which a merge or grouping above keeps. pub kept_values_per_column: BTreeMap<&'a str, u64>, /// A chain's or window merge's groups and how a window's rows reach - /// them (its rows are the groups one window holds a state for); `None` - /// for any other node. + /// them (a window merge sizes its wider window from them); `None` for + /// any other node. pub window_groups: Option, } @@ -717,6 +717,10 @@ pub(crate) fn node_usage_and_cost_terms<'a>( let mut narrower_states_merged_per_execution: u64 = 0; // A chain's or window merge's groups and how its windows reach them. let mut built_window_groups: Option = None; + // The share of its groups one window of a chain or window merge holds a + // state for: what its memory and emitted states count; 1 for any other + // node. + let mut window_group_share = 1.0_f64; // The time its raw output rows span, when it reads or narrows raw rows // (else passed on below). let mut read_raw_rows_span_ms: Option = None; @@ -2068,11 +2072,10 @@ pub(crate) fn node_usage_and_cost_terms<'a>( groups: group_count, reach, }); - let window_groups = group_count as f64 - * groups_reached_share(rows_per_tumbling_window, group_count, reach); - let window_states = (window_groups.round() as u64).clamp(1, group_count.max(1)); + window_group_share = groups_reached_share(rows_per_tumbling_window, group_count, reach); + let window_groups = group_count as f64 * window_group_share; open_output_bytes = Some( - window_states + group_count .checked_mul( open_state_bytes + state_row_bytes_beside_state( @@ -2110,10 +2113,11 @@ pub(crate) fn node_usage_and_cost_terms<'a>( } // Each group's state found once per raw batch. let group_visits = visits(group_count); - // One window: a state for each group it reaches. + // Its readers read every group's state per window: the measured + // merge prices were fitted on those state counts. let out = EdgeStatistics { - rows: window_states, - bytes: window_states + rows: group_count, + bytes: group_count .checked_mul( state_bytes + state_row_bytes_beside_state( @@ -2169,12 +2173,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // Every group, and the narrower windows' states: the groups one // narrower window reaches. let window_groups = narrower.output_facts.window_groups; - let group_count = window_groups - .map_or(narrower.output_facts.statistics.rows, |groups| { - groups.groups - }) - .max(1); - let narrower_states = narrower.output_facts.statistics.rows.max(1); + let group_count = narrower.output_facts.statistics.rows.max(1); // Stage 2 offers it at ingestion time only. if !ingestion { return Err(AnalyticalCostError::UnsupportedCandidate); @@ -2186,20 +2185,20 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .state_input_rows .and_then(|rows| rows.folded_rows_per_state) .map(|per_state| per_state * group_count as f64); - let wider_states = match (window_groups, narrower_rows) { - (Some(groups), Some(rows)) => ((group_count as f64 - * groups_reached_share( - rows * windows_per_window as f64, - group_count, - groups.reach, - )) - .round() as u64) - .clamp(narrower_states.min(group_count), group_count), - (None, _) | (_, None) => group_count, + let share = |rows: f64| { + window_groups.map_or(1.0, |groups| { + groups_reached_share(rows, group_count, groups.reach) + }) }; + let narrower_share = narrower_rows.map_or(1.0, share); + window_group_share = narrower_rows + .map_or(1.0, |rows| share(rows * windows_per_window as f64)) + .max(narrower_share); built_window_groups = window_groups; - let merged = narrower_states as f64 * ONE_SECOND_MS as f64 / narrower_width_ms as f64; - let emitted = wider_states as f64 * ONE_SECOND_MS as f64 / width_ms as f64; + let merged = group_count as f64 * narrower_share * ONE_SECOND_MS as f64 + / narrower_width_ms as f64; + let emitted = + group_count as f64 * window_group_share * ONE_SECOND_MS as f64 / width_ms as f64; narrower_states_merged_per_execution = merged.round() as u64; let merged_input_rows = narrower.output_facts.state_input_rows.map(|mut rows| { rows.folded_rows_per_state = rows @@ -2233,8 +2232,8 @@ pub(crate) fn node_usage_and_cost_terms<'a>( .times(emitted), ); let out = EdgeStatistics { - rows: wider_states, - bytes: wider_states + rows: group_count, + bytes: group_count .checked_mul( merged_state_bytes + state_row_bytes_beside_state( @@ -2589,11 +2588,13 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // what the node holds: its output, or the values an exact aggregate // keeps per group when that is more. A computation that keeps nothing holds its // working memory while it runs. - let state = out.bytes.max(estimate.peak_memory_bytes()); + // A chain's or window merge's window holds the groups its rows reach. + let reached = |bytes: u64| (bytes as f64 * window_group_share).round() as u64; + let state = reached(out.bytes.max(estimate.peak_memory_bytes())); // The output being built, its states still open: what a query-time // build holds while it runs, and the newest window an ingestion-time // view keeps besides its sealed ones. - let open_state = open_output_bytes.map_or(state, |open| state.max(open)); + let open_state = open_output_bytes.map_or(state, |open| state.max(reached(open))); // One output's bytes in a stored view's files: its rows at the measured // file bytes per state's row, else its decoded bytes (`state`). Only an // output of states has them; raw rows kept at ingestion do not. @@ -2601,7 +2602,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(bytes) if outputs_states(&node.output_schema) && !raw_rows_materialized_at_ingestion => { - (out.rows as f64 * bytes).round() as u64 + (out.rows as f64 * window_group_share * bytes).round() as u64 } _ => state, }; diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index bdb9bddf9..c275370e9 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -5903,10 +5903,9 @@ fn auth_data_unsampled() -> DataWorkload { /// T6. A window holds a state only for the groups its rows reach: a 10 s /// window of `auth` (rows at random, no sample interval) holds 100,000 /// rows over its 100,000 (host, user) groups, of which 100,000 · (1 − -/// e^−1) = 63,212 appear (`expected_distinct_values`). So the chain's -/// window is 63,212 states (what its readers read), it emits 6,321.2 states -/// per second, not 10,000, and keeps its 60 sealed windows and the one -/// being built. +/// e^−1) = 63,212 appear (`expected_distinct_values`). So the chain emits +/// 6,321.2 states per second, not 10,000, and keeps its 60 sealed windows +/// and the one being built at 63,212 states each. #[test] fn a_chain_emits_and_keeps_states_only_for_the_groups_its_windows_reach() { let settings = CostInputs::default(); @@ -5925,20 +5924,15 @@ fn a_chain_emits_and_keeps_states_only_for_the_groups_its_windows_reach() { &settings, ) .unwrap(); - assert_eq!( - usage.output_facts.statistics.rows, 63_212, - "the groups reached" - ); - assert_eq!( - usage.output_facts.window_groups.map(|groups| groups.groups), - Some(100_000) - ); + // Its readers read every group's state per window (the measured merge + // prices were fitted on those counts); its memory holds those reached. + assert_eq!(usage.output_facts.statistics.rows, 100_000, "the groups"); assert!( usage.cost.detail.contains("6321.2 states emitted"), "{}", usage.cost.detail ); - let window_bytes = usage.output_facts.statistics.bytes as f64; + let window_bytes = usage.output_facts.statistics.bytes as f64 * -(-1.0_f64).exp_m1(); assert_close( usage.cost.memory_and_disk.average_memory_bytes, 61.0 * window_bytes, @@ -5970,17 +5964,24 @@ fn a_chain_over_periodic_series_reaches_rows_over_groups_of_them() { &settings, ) .unwrap() - .output_facts - .statistics - .rows + .cost + .detail }; - assert_eq!(emitted(&auth_data(true)), 100_000); + assert!( + emitted(&auth_data(true)).contains("10000.0 states emitted"), + "{}", + emitted(&auth_data(true)) + ); let mut sparse = auth_data(true); for facts in sparse.sources.values_mut() { facts.series_count = Some(100_000); facts.sample_interval = Some(asap_types::workload::DurationMs(15_000)); } - assert_eq!(emitted(&sparse), 66_667); + assert!( + emitted(&sparse).contains("6666.7 states emitted"), + "{}", + emitted(&sparse) + ); } /// T6. A dense chain is unchanged: 1,000 series at 1 Hz put 10,000 rows in From bff8c0619a1c0ee408d9ba329dc5bb63f6bb1683 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:59:17 +0000 Subject: [PATCH 15/18] fix(cost): reach from the chain's own key columns; window merges reach too; re-pin anchors after I1 - How a window spreads its rows (`GroupReach`) is read from the node's own output key columns and its sources' facts, not its producer's schema, so a candidate costs the same in Stage 3 and plan_cost. - A window merge's wider window reaches the groups the rows of its narrower windows reach (same reach), its merged and emitted states and memory scaled by it; `OutputFacts::window_groups` is gone (unused). - With periodic series reaching every group again (I1), the anchors move back: E6 192.9132 / 169.4972 / 141.1861 (each IN-list evaluated per row read), distinct-two-forms 36.7112, seed-862 709.8367, typical dashboard 847.2063; Q5-E2 98.22/s, bound 99. - dash/rca fixtures declare no service skew: with it Stage 3's objective and plan_cost differ by 3e-6 relative in dash full intent, also with this branch's reach disabled (reported on the IN-list track). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/cost/src/lib.rs | 4 +- crates/cost/src/node/usage/mod.rs | 88 +++++++------------ crates/cost/src/node/usage/tests.rs | 30 ------- .../planner-cli/tests/inlist_selectivity.rs | 24 ++--- .../tests/lowest_mean_latency_exactness.rs | 6 +- .../tests/measured_cost_file/dash/data.json | 6 -- .../tests/measured_cost_file/rca/data.json | 3 - 7 files changed, 49 insertions(+), 112 deletions(-) diff --git a/crates/cost/src/lib.rs b/crates/cost/src/lib.rs index ee36fc45b..1a4c60224 100644 --- a/crates/cost/src/lib.rs +++ b/crates/cost/src/lib.rs @@ -45,8 +45,8 @@ pub use node::cost_terms::{node_cost_terms, CostConstant, NodeCostTerms}; pub use node::operator_statistics::EdgeStatistics; pub use node::usage::{ node_resource_usage_and_cost, output_interval_ms, reads_one_batch_of, summary_type_name, - CachedViewWindows, GroupReach, NodeCost, NodeMemoryAndDisk, NodeResourceUsageAndCost, - OutputFacts, PhaseTimes, ProducerOutput, RawRowsShortOfRange, WindowGroups, + CachedViewWindows, NodeCost, NodeMemoryAndDisk, NodeResourceUsageAndCost, OutputFacts, + PhaseTimes, ProducerOutput, RawRowsShortOfRange, }; pub use plan::cost::{ close_together, ingest_decode_cpu_core_seconds_per_second, ingest_threads_building_copies, diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 32deb64d6..90dffe8c0 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -415,17 +415,13 @@ pub struct OutputFacts<'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>, - /// A chain's or window merge's groups and how a window's rows reach - /// them (a window merge sizes its wider window from them); `None` for - /// any other node. - pub window_groups: Option, } /// How the rows of one window spread over a chain's groups, which sets /// how many of them the window holds a state for /// ([`groups_reached_share`]). #[derive(Debug, Clone, Copy, PartialEq)] -pub enum GroupReach { +enum GroupReach { /// Every series is sampled at its declared interval /// (`sample_interval`): a window of r rows over G groups reaches /// min(1, r/G) of them. @@ -437,15 +433,6 @@ pub enum GroupReach { Zipf { values: u64, exponent: f64 }, } -/// A chain's or window merge's groups ([`OutputFacts::window_groups`]). -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct WindowGroups { - /// Every group it keys states by. - pub groups: u64, - /// How a window's rows reach them. - pub reach: GroupReach, -} - /// Raw rows fewer than arrive over the range they are read for /// ([`OutputFacts::raw_rows_short_of_range`]). Example: a source /// holding 80 rows, read back 60 s at 8 rows a second: 80 of 480. @@ -715,8 +702,6 @@ pub(crate) fn node_usage_and_cost_terms<'a>( let mut open_output_bytes: Option = None; // The narrower states a `SummaryMergeWindows` merges per execution. let mut narrower_states_merged_per_execution: u64 = 0; - // A chain's or window merge's groups and how its windows reach them. - let mut built_window_groups: Option = None; // The share of its groups one window of a chain or window merge holds a // state for: what its memory and emitted states count; 1 for any other // node. @@ -1038,6 +1023,27 @@ pub(crate) fn node_usage_and_cost_terms<'a>( zipf_exponent, }) }; + // How a window of a chain or window merge spreads its rows over its + // groups: under a key column (named in its output) with a declared + // Zipf skew the heavy values' groups take most of them; periodic series + // are each sampled every interval; otherwise rows fall at random. + let window_reach = || -> GroupReach { + let skewed_key = node.output_schema.fields.iter().find_map(|field| { + let declared = declared_values(field.name.as_str())?; + Some((declared.distinct, declared.zipf_exponent?)) + }); + let periodic = !sources.is_empty() + && sources.iter().all(|source| { + data.sources + .get(*source) + .is_some_and(|facts| facts.sample_interval.is_some()) + }); + match (skewed_key, periodic) { + (Some((values, exponent)), _) => GroupReach::Zipf { values, exponent }, + (None, true) => GroupReach::Periodic, + (None, false) => GroupReach::Uniform, + } + }; // 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. @@ -2045,33 +2051,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(rows_per_tumbling_window / group_count.max(1) as f64), )?; built_state_input_rows = Some(input_rows); - // A window holds a state for each group its rows reach: under a - // key column with a declared Zipf skew the heavy values' groups - // take most of its rows; periodic series are each sampled every - // interval; otherwise rows fall at random. - let skewed_key = match reduction { - Reduction::Reduce(keys) => keys.keys().iter().find_map(|&column| { - let name = input_schema?.fields.get(column)?.name.as_str(); - let declared = declared_values(name)?; - Some((declared.distinct, declared.zipf_exponent?)) - }), - Reduction::PerEntity => None, - }; - let periodic = !sources.is_empty() - && sources.iter().all(|source| { - data.sources - .get(*source) - .is_some_and(|facts| facts.sample_interval.is_some()) - }); - let reach = match (skewed_key, periodic) { - (Some((values, exponent)), _) => GroupReach::Zipf { values, exponent }, - (None, true) => GroupReach::Periodic, - (None, false) => GroupReach::Uniform, - }; - built_window_groups = Some(WindowGroups { - groups: group_count, - reach, - }); + let reach = window_reach(); window_group_share = groups_reached_share(rows_per_tumbling_window, group_count, reach); let window_groups = group_count as f64 * window_group_share; open_output_bytes = Some( @@ -2172,29 +2152,26 @@ pub(crate) fn node_usage_and_cost_terms<'a>( let windows_per_window = (width_ms / narrower_width_ms).max(1); // Every group, and the narrower windows' states: the groups one // narrower window reaches. - let window_groups = narrower.output_facts.window_groups; let group_count = narrower.output_facts.statistics.rows.max(1); // Stage 2 offers it at ingestion time only. if !ingestion { return Err(AnalyticalCostError::UnsupportedCandidate); } - // A wider window reaches the groups the rows of its - // `windows_per_window` narrower windows reach. + // A narrower window reaches the groups its rows reach, a wider + // one those of its `windows_per_window` narrower windows' rows. let narrower_rows = narrower .output_facts .state_input_rows .and_then(|rows| rows.folded_rows_per_state) .map(|per_state| per_state * group_count as f64); - let share = |rows: f64| { - window_groups.map_or(1.0, |groups| { - groups_reached_share(rows, group_count, groups.reach) - }) - }; - let narrower_share = narrower_rows.map_or(1.0, share); + let reach = window_reach(); + let narrower_share = + narrower_rows.map_or(1.0, |rows| groups_reached_share(rows, group_count, reach)); window_group_share = narrower_rows - .map_or(1.0, |rows| share(rows * windows_per_window as f64)) + .map_or(1.0, |rows| { + groups_reached_share(rows * windows_per_window as f64, group_count, reach) + }) .max(narrower_share); - built_window_groups = window_groups; let merged = group_count as f64 * narrower_share * ONE_SECOND_MS as f64 / narrower_width_ms as f64; let emitted = @@ -2602,7 +2579,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( Some(bytes) if outputs_states(&node.output_schema) && !raw_rows_materialized_at_ingestion => { - (out.rows as f64 * window_group_share * bytes).round() as u64 + (out.rows as f64 * bytes).round() as u64 } _ => state, }; @@ -3014,7 +2991,6 @@ pub(crate) fn node_usage_and_cost_terms<'a>( state_data_span_ms, raw_rows_shifted_back_ms, kept_values_per_column, - window_groups: built_window_groups, }, work_ms_per_execution: node_ms, cpu_ops_per_second: estimate.cpu_ops() * per_second, diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index c275370e9..920531255 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -70,7 +70,6 @@ fn a_merge_over_a_chain_s_windows_outputs_one_state_per_group() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let windows = node(Payload::NonASAP(NonASAPOp::TimeRange { @@ -189,7 +188,6 @@ fn an_operator_keeping_its_input_window_over_a_chain_or_its_windows_selects_what states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; for &step in path { @@ -258,7 +256,6 @@ fn a_merge_over_a_chain_s_windows_is_costed_by_the_chain_s_family() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -341,7 +338,6 @@ fn a_project_or_filter_over_states_passes_their_family_on() { states_last_merged: true, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; for passing in [ @@ -428,7 +424,6 @@ fn a_merge_over_a_rate_chain_s_windows_is_costed_by_the_rate_accumulator() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let mut merge = node(Payload::ASAP(ASAPOp::SummaryMerge { @@ -510,7 +505,6 @@ fn raw_rows<'a>( states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, } } @@ -787,7 +781,6 @@ fn a_query_time_chain_pays_the_time_range_over_the_rows_it_reads() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let chain = PhysicalASAPDAGNode { @@ -1056,7 +1049,6 @@ fn a_merge_reading_one_state_per_group_passes_it_through() { distinct_values: None, }), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let merge = PhysicalASAPDAGNode { @@ -1703,7 +1695,6 @@ fn a_kmv_rollup_merge_costs_per_hash_it_inserts() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let rollup = PhysicalASAPDAGNode { @@ -1785,7 +1776,6 @@ fn a_rollup_merges_its_states_when_its_group_estimate_ties_its_input() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let merge_ms = |group_by: Option>| { @@ -1860,7 +1850,6 @@ fn query_time_memory_is_held_only_while_the_node_computes() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let merge = PhysicalASAPDAGNode { @@ -2006,7 +1995,6 @@ fn an_ingestion_time_view_of_raw_rows_keeps_the_rows_its_retention_covers() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let row_schema = Schema::new(vec![ @@ -2083,7 +2071,6 @@ fn a_view_without_retention_is_not_costed() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let shift = PhysicalASAPDAGNode { @@ -2168,7 +2155,6 @@ fn a_view_over_an_ingestion_time_chain_keeps_one_output_per_chain_window() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let usage = node_resource_usage_and_cost( @@ -2246,7 +2232,6 @@ fn ddsketch_build_cost( states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let settings = CostInputs::default(); @@ -2480,7 +2465,6 @@ fn ddsketch_assumed_facts_over_sources( raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let settings = CostInputs::default(); @@ -2682,7 +2666,6 @@ fn kll_merge_cpu_ops_over(k: u32, window_ms: u64, range_s: u64) -> f64 { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let mut chain = node(Payload::ASAP(ASAPOp::SummaryTumblingWindowChain { @@ -2813,7 +2796,6 @@ fn a_finalize_charges_each_group_its_measured_time() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let finalize = node(Payload::ASAP(ASAPOp::FinalizeExactAccumulator { @@ -2874,7 +2856,6 @@ fn a_per_series_aggregate_charges_the_labels_it_carries() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let ms_per_row = |labels: &[&str]| { @@ -3001,7 +2982,6 @@ fn a_merge_over_several_inputs_sizes_its_state_for_all_of_them() { states_last_merged: false, state_input_rows: Some(rows), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let wider = ProducerOutput { @@ -3110,7 +3090,6 @@ fn kll_estimate_us_per_group(producer: Payload, rows_per_state: u64, state_bytes distinct_values: None, }), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let estimate = node(Payload::ASAP(ASAPOp::SummaryEstimate { @@ -3670,7 +3649,6 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: Some(rows_per_state), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let windows = PhysicalASAPDAGNode { @@ -3823,7 +3801,6 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: Some(kmv_rows), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }], None, @@ -3908,7 +3885,6 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { distinct_values: None, }), kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }], None, @@ -3946,7 +3922,6 @@ fn terms_reproduce_the_formula_cpu_of_every_costed_node() { states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }], None, @@ -4202,7 +4177,6 @@ fn rows_of<'a>(producer: &'a PhysicalASAPDAGNode, rows: u64) -> ProducerOutput<' raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, } } @@ -4441,7 +4415,6 @@ fn counter_sketch_charges_ms(shape: &CounterSketchShape) -> CounterSketchCharges states_last_merged: false, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let family = FieldDataType::Sketch(algorithm); @@ -4735,7 +4708,6 @@ fn a_ddsketch_build_holds_open_states_and_keeps_sealed_ones() { raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let rows = StateInputRows { @@ -4823,7 +4795,6 @@ fn a_measured_ddsketch_state_size_replaces_the_estimate() { raw_rows_shifted_back_ms: 0, states_last_merged: false, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let build = PhysicalASAPDAGNode { @@ -5510,7 +5481,6 @@ fn a_merge_by_key_over_a_filtered_state_merges_the_kept_states() { states_last_merged: true, state_input_rows: None, kept_values_per_column: BTreeMap::new(), - window_groups: None, }, }; let compensation = filter_node( diff --git a/crates/planner-cli/tests/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 831f4eb79..32b2d7f4d 100644 --- a/crates/planner-cli/tests/inlist_selectivity.rs +++ b/crates/planner-cli/tests/inlist_selectivity.rs @@ -477,11 +477,11 @@ fn a_literal_in_list_shrinks_its_ingestion_time_state() { /// 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 -/// 192.9132, 149.6450 and 125.8274 per second (177.9132, 169.2572 and -/// 140.9361 before the cost calibration: q2's scan now evaluates its -/// 10-value IN-list on each of its 6,000,000 rows, +15.0 per second, and a -/// chain over `auth` keeps and emits states only for the groups its 10 s -/// windows reach, 63% of them). +/// 192.9132, 169.4972 and 141.1861 per second (177.9132, 169.2572 and +/// 140.9361 before the cost calibration: each scan and filter now +/// evaluates its 10-value IN-list on every row it reads, +15.0, +0.24 and +/// +0.25 per second; `auth`'s periodic series each reach every 10 s window, +/// so its chain keeps every group). #[test] fn an_undeclared_label_reproduces_todays_costs() { let rounded = |cost: f64| (cost * 1e4).round() / 1e4; @@ -494,12 +494,12 @@ fn an_undeclared_label_reproduces_todays_costs() { &workload(10, Values::Placeholders, true, false), &capabilities(Values::Placeholders, true, &[]), ); - assert_eq!(rounded(lightcone.cost_per_second), 149.645); + assert_eq!(rounded(lightcone.cost_per_second), 169.4972); let literal = plan( &workload(10, Values::Literals, false, false), &capabilities(Values::Literals, false, &[]), ); - assert_eq!(rounded(literal.cost_per_second), 125.8274); + assert_eq!(rounded(literal.cost_per_second), 141.1861); } /// `sum(rate(m{job="a"}[5m]))` once, `m` 1,000 series every 15 s holding @@ -583,17 +583,17 @@ fn the_compensation_filter_runs_before_the_time_merge() { /// 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 +/// windows (≈7.4/s): about 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; 78.37/s once a chain -/// keeps states only for the 63% of groups its windows reach, so the chain -/// costs above 30/s, not 53.8). Without Q5 (filter +/// 10 s level, no wider levels to maintain, 89.03/s; 98.22/s with the +/// cost calibration's scan and filter predicates; at least 30/s for the +/// chain). 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!( - planned.cost_per_second <= 97.0 && planned.cost_per_second > 27.85 + 30.0, + planned.cost_per_second <= 99.0 && planned.cost_per_second > 27.85 + 30.0, "{} (at most ≈97.0/s expected)", planned.cost_per_second ); diff --git a/crates/planner-cli/tests/lowest_mean_latency_exactness.rs b/crates/planner-cli/tests/lowest_mean_latency_exactness.rs index d49f6d43f..2fa357f9a 100644 --- a/crates/planner-cli/tests/lowest_mean_latency_exactness.rs +++ b/crates/planner-cli/tests/lowest_mean_latency_exactness.rs @@ -216,7 +216,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { format!("{snapshots}/distinct-two-forms.json"), "raw-retained", false, - 36.4822625029, + 36.711207989, DISTINCT_VARIABLES, DISTINCT_ROWS, ), @@ -224,7 +224,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { "tools/dag-viewer/workloads/random-mixed-seed-862/workload-01.json".to_string(), "mvp", false, - 709.833844188, + 709.836719368, SEED_VARIABLES, SEED_ROWS, ), @@ -234,7 +234,7 @@ fn the_measured_workloads_keep_their_optimum_in_a_bounded_model() { TYPICAL_DASHBOARD.to_string(), "mvp", false, - 847.045899638, + 847.206346, TYPICAL_VARIABLES, TYPICAL_ROWS, ), diff --git a/crates/planner/tests/measured_cost_file/dash/data.json b/crates/planner/tests/measured_cost_file/dash/data.json index 3e471d9ad..d86663763 100644 --- a/crates/planner/tests/measured_cost_file/dash/data.json +++ b/crates/planner/tests/measured_cost_file/dash/data.json @@ -22,9 +22,6 @@ "min_abs": 1.0, "max_abs": 100000.0 } - }, - "zipf_exponent_per_label": { - "service": 0.8 } }, "errors": { @@ -37,9 +34,6 @@ "rows_held": 600000, "column_signs": { "value": "non_negative" - }, - "zipf_exponent_per_label": { - "service": 0.8 } } } diff --git a/crates/planner/tests/measured_cost_file/rca/data.json b/crates/planner/tests/measured_cost_file/rca/data.json index fb97e69b1..a41bf76e2 100644 --- a/crates/planner/tests/measured_cost_file/rca/data.json +++ b/crates/planner/tests/measured_cost_file/rca/data.json @@ -22,9 +22,6 @@ "min_abs": 1.0, "max_abs": 100000.0 } - }, - "zipf_exponent_per_label": { - "service": 0.8 } }, "node_metrics": { From b64df3ff6e02f6ef772491e68c3f70e7f7c6900a Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 4 Dec 2026 03:30:34 +0000 Subject: [PATCH 16/18] test(snapshots): regenerate the sketch plan snapshots after I1 (periodic series reach rows/groups of them) Numbers only, no plan changes. Against the base, only chains-10m-5m-3m-10s still moves on item 5: 10,000 series every 15 s in 10 s windows reach 2/3 of them (6,667 states per window, not every series); the other four return to the base's numbers. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- .../chains-10m-5m-3m-10s-mvp.json | 60 +++++++++---------- .../distinct-over-time-5pct-raw-retained.json | 24 ++++---- ...random-mixed-seed-862-long-w01-q3-mvp.json | 40 ++++++------- .../random-mixed-seed-862-w01-q3-q8-mvp.json | 34 +++++------ .../random-mixed-seed-862-w02-q2-q7-mvp.json | 32 +++++----- 5 files changed, 95 insertions(+), 95 deletions(-) diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json index c0457f15f..01958439b 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/chains-10m-5m-3m-10s-mvp.json @@ -130,8 +130,8 @@ } ], "cost": { - "cost_per_second": 3.96542188505e-7, - "cpu_core_seconds_per_second": 0.0324049182077, + "cost_per_second": 4.06813421429e-7, + "cpu_core_seconds_per_second": 0.032937486756, "per_node": { "0": { "cost_per_second": 3.14989416e-11, @@ -148,45 +148,45 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 1.9509573129e-8, + "cost_per_second": 1.9509573131e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.000262089333162, + "cpu_core_seconds_per_second": 0.000262089333333, "detail": "build KLL in tumbling windows of 300000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 33.3 states emitted; x 1.0000/s; keeps 14400000 bytes", "ingest_cpu_core_seconds_per_second": 0.000178756, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 24.9999999485, - "refresh_wall_ms_per_window": 24.9999999485, + "refresh_cpu_ms_per_window": 25.0, + "refresh_wall_ms_per_window": 25.0, "timing": "ingestion_time" }, "10": { - "cost_per_second": 2.70600578392e-8, + "cost_per_second": 3.63310905982e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.00139521320242, - "detail": "build KLL in tumbling windows of 10000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 486.6 states emitted; x 1.0000/s; keeps 9887363 bytes", + "cpu_core_seconds_per_second": 0.00184542266667, + "detail": "build KLL in tumbling windows of 10000 ms for 10000 groups: 667 rows x 84 ops, 667 group visits, 666.7 states emitted; x 1.0000/s; keeps 13546673 bytes", "ingest_cpu_core_seconds_per_second": 0.000178756, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 12.1645720242, - "refresh_wall_ms_per_window": 12.1645720242, + "refresh_cpu_ms_per_window": 16.6666666667, + "refresh_wall_ms_per_window": 16.6666666667, "timing": "ingestion_time" }, "11": { - "cost_per_second": 1.08439854939e-8, + "cost_per_second": 1.18441856564e-8, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.000610947582749, - "detail": "merge tumbling windows of 10000 ms into 60000 ms for 10000 groups: 486.6 states merged, 163.6 states emitted; x 1.0000/s; keeps 3455528 bytes", + "cpu_core_seconds_per_second": 0.000693306666667, + "detail": "merge tumbling windows of 10000 ms into 60000 ms for 10000 groups: 666.7 states merged, 166.7 states emitted; x 1.0000/s; keeps 3520000 bytes", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryMergeWindows", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 36.656854965, - "refresh_wall_ms_per_window": 36.656854965, + "refresh_cpu_ms_per_window": 41.5984, + "refresh_wall_ms_per_window": 41.5984, "timing": "ingestion_time" }, "12": { @@ -360,45 +360,45 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 27979267.2611, - "cpu_ops_per_second": 32402783.8077, + "average_memory_bytes": 31703049.2611, + "cpu_ops_per_second": 32935352.356, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 331.651426938, - "precompute_execution_ms": 24.9999999485, - "precompute_queueing_ms": 48.8214269891, + "latency_ms": 341.095066667, + "precompute_execution_ms": 25.0, + "precompute_queueing_ms": 58.2650666667, "query_execution_ms": 257.83 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 118.941426938, - "precompute_execution_ms": 24.9999999485, - "precompute_queueing_ms": 48.8214269891, + "latency_ms": 128.385066667, + "precompute_execution_ms": 25.0, + "precompute_queueing_ms": 58.2650666667, "query_execution_ms": 45.12 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.1, - "latency_ms": 365.061760498, - "precompute_execution_ms": 12.1645720242, - "precompute_queueing_ms": 61.6568549134, + "latency_ms": 374.505400227, + "precompute_execution_ms": 16.6666666667, + "precompute_queueing_ms": 66.5984, "query_execution_ms": 291.24033356 } ], "peak_cpu_cores": 4, - "peak_memory_bytes": 59263523, - "precompute_load": 0.00191073811833, + "peak_memory_bytes": 62987305, + "precompute_load": 0.00244330666667, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.0003603134, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.00191073811833, + "predicted_busy_thread_seconds_per_second": 0.00244330666667, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json b/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json index 2cd90ec35..5d7f11300 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/distinct-over-time-5pct-raw-retained.json @@ -23,8 +23,8 @@ } ], "cost": { - "cost_per_second": 9.50576144658e-9, - "cpu_core_seconds_per_second": 0.000807966666495, + "cost_per_second": 9.50576144852e-9, + "cpu_core_seconds_per_second": 0.000807966666667, "per_node": { "0": { "cost_per_second": 4.30131012023e-10, @@ -41,15 +41,15 @@ "timing": "query_time" }, "1": { - "cost_per_second": 5.43807654104e-9, + "cost_per_second": 5.43807654299e-9, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.000479599999828, + "cpu_core_seconds_per_second": 0.0004796, "detail": "build KMV in tumbling windows of 300000 ms for 10000 groups: 400000 rows x 116.2 ops, 400000 group visits, 10000.0 states emitted; x 0.0033/s; holds 82400000 bytes for 143.880 ms", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, - "query_ms_per_step": 143.879999948, + "query_ms_per_step": 143.88, "refresh_cpu_ms_per_window": 0.0, "refresh_wall_ms_per_window": 0.0, "timing": "query_time" @@ -169,25 +169,25 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 46792.2225645, - "cpu_ops_per_second": 803699.999828, + "average_memory_bytes": 46792.2225787, + "cpu_ops_per_second": 803700.0, "disk_bytes": 12800000, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 196.269999948, + "latency_ms": 196.27, "precompute_execution_ms": 0.0, "precompute_queueing_ms": 0.0, - "query_execution_ms": 196.269999948 + "query_execution_ms": 196.27 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 191.679999948, + "latency_ms": 191.68, "precompute_execution_ms": 0.0, "precompute_queueing_ms": 0.0, - "query_execution_ms": 191.679999948 + "query_execution_ms": 191.68 } ], "peak_cpu_cores": 2, @@ -203,7 +203,7 @@ "recommended_threads": 1 }, "query": { - "predicted_busy_thread_seconds_per_second": 0.000807966666495, + "predicted_busy_thread_seconds_per_second": 0.000807966666667, "recommended_threads": 1 } }, diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json index e6cc694d3..ce781e4c9 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-long-w01-q3-mvp.json @@ -82,8 +82,8 @@ } ], "cost": { - "cost_per_second": 6.90154946666e-6, - "cpu_core_seconds_per_second": 0.567223950869, + "cost_per_second": 6.90158742996e-6, + "cpu_core_seconds_per_second": 0.567225403667, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -100,31 +100,31 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 9.0612735786e-7, + "cost_per_second": 9.06161747829e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.0382688650018, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 413701196 bytes", + "cpu_core_seconds_per_second": 0.03827, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 413720000 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 24.9988650018, - "refresh_wall_ms_per_window": 24.9988650018, + "refresh_cpu_ms_per_window": 25.0, + "refresh_wall_ms_per_window": 25.0, "timing": "ingestion_time" }, "2": { - "cost_per_second": 1.17894928052e-7, + "cost_per_second": 1.1789850139e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.00741634886716, - "detail": "merge tumbling windows of 1000 ms into 60000 ms for 10000 groups: 9999.5 states merged, 166.7 states emitted; x 1.0000/s; keeps 30000000 bytes", + "cpu_core_seconds_per_second": 0.00741666666667, + "detail": "merge tumbling windows of 1000 ms into 60000 ms for 10000 groups: 10000.0 states merged, 166.7 states emitted; x 1.0000/s; keeps 30000000 bytes", "ingest_cpu_core_seconds_per_second": 0.0, "multiplier": 1, "operator": "SummaryMergeWindows", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 444.980932029, - "refresh_wall_ms_per_window": 444.980932029, + "refresh_cpu_ms_per_window": 445.0, + "refresh_wall_ms_per_window": 445.0, "timing": "ingestion_time" }, "3": { @@ -200,29 +200,29 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 455304234.398, - "cpu_ops_per_second": 566743950.869, + "average_memory_bytes": 455323038.398, + "cpu_ops_per_second": 566745403.667, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 990.938534031, - "precompute_execution_ms": 24.9988650018, - "precompute_queueing_ms": 444.980932029, + "latency_ms": 990.958737, + "precompute_execution_ms": 25.0, + "precompute_queueing_ms": 445.0, "query_execution_ms": 520.958737 } ], "peak_cpu_cores": 2, - "peak_memory_bytes": 469741448, - "precompute_load": 0.0324152138689, + "peak_memory_bytes": 469760252, + "precompute_load": 0.0324166666667, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.01385, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.0324152138689, + "predicted_busy_thread_seconds_per_second": 0.0324166666667, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json index 1d8166f23..4d372adb2 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w01-q3-q8-mvp.json @@ -142,8 +142,8 @@ } ], "cost": { - "cost_per_second": 9.63893014235e-6, - "cpu_core_seconds_per_second": 0.835976898335, + "cost_per_second": 9.63895073011e-6, + "cpu_core_seconds_per_second": 0.835978033333, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -160,17 +160,17 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 6.02492747833e-7, + "cost_per_second": 6.02513335601e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.0382688650018, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 149713196 bytes", + "cpu_core_seconds_per_second": 0.03827, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 149720000 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 24.9988650018, - "refresh_wall_ms_per_window": 24.9988650018, + "refresh_cpu_ms_per_window": 25.0, + "refresh_wall_ms_per_window": 25.0, "timing": "ingestion_time" }, "10": { @@ -358,37 +358,37 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 207971964.904, - "cpu_ops_per_second": 835016898.335, + "average_memory_bytes": 207978768.904, + "cpu_ops_per_second": 835018033.333, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 878.408865002, - "precompute_execution_ms": 24.9988650018, + "latency_ms": 878.41, + "precompute_execution_ms": 25.0, "precompute_queueing_ms": 69.5, "query_execution_ms": 783.91 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.0333333333333, - "latency_ms": 187.289865002, - "precompute_execution_ms": 22.0, - "precompute_queueing_ms": 72.4988650018, + "latency_ms": 187.291, + "precompute_execution_ms": 15.0, + "precompute_queueing_ms": 79.5, "query_execution_ms": 92.791 } ], "peak_cpu_cores": 3, - "peak_memory_bytes": 216433533, - "precompute_load": 0.0259738650018, + "peak_memory_bytes": 216440337, + "precompute_load": 0.025975, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.023, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.0259738650018, + "predicted_busy_thread_seconds_per_second": 0.025975, "recommended_threads": 1 }, "query": { diff --git a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json index 1870a54d9..1076cee29 100644 --- a/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json +++ b/crates/planner-cli/tests/sketch_plan_snapshots/random-mixed-seed-862-w02-q2-q7-mvp.json @@ -112,8 +112,8 @@ } ], "cost": { - "cost_per_second": 9.90297326931e-6, - "cpu_core_seconds_per_second": 0.859459007602, + "cost_per_second": 9.90299385708e-6, + "cpu_core_seconds_per_second": 0.8594601426, "per_node": { "0": { "cost_per_second": 6.52152e-9, @@ -130,17 +130,17 @@ "timing": "ingestion_time" }, "1": { - "cost_per_second": 6.02492747833e-7, + "cost_per_second": 6.02513335601e-7, "cost_source": "analytical", - "cpu_core_seconds_per_second": 0.0382688650018, - "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 9999.5 states emitted; x 1.0000/s; keeps 149713196 bytes", + "cpu_core_seconds_per_second": 0.03827, + "detail": "build DDSketch in tumbling windows of 1000 ms for 10000 groups: 100000 rows x 117 ops, 1000 group visits, 10000.0 states emitted; x 1.0000/s; keeps 149720000 bytes", "ingest_cpu_core_seconds_per_second": 0.01327, "multiplier": 1, "operator": "SummaryTumblingWindowChain", "priced_outside_measured_scale": false, "query_ms_per_step": 0.0, - "refresh_cpu_ms_per_window": 24.9988650018, - "refresh_wall_ms_per_window": 24.9988650018, + "refresh_cpu_ms_per_window": 25.0, + "refresh_wall_ms_per_window": 25.0, "timing": "ingestion_time" }, "10": { @@ -314,37 +314,37 @@ }, "source": "analytical-cost-v2 (illustrative statistics)", "usage": { - "average_memory_bytes": 207980911.625, - "cpu_ops_per_second": 858499007.602, + "average_memory_bytes": 207987715.625, + "cpu_ops_per_second": 858500142.6, "disk_bytes": 0, "latency_per_query": [ { "allowed_lateness_ms": 0.0, "evaluations_per_second": 1.0, - "latency_ms": 880.908865002, - "precompute_execution_ms": 24.9988650018, + "latency_ms": 880.91, + "precompute_execution_ms": 25.0, "precompute_queueing_ms": 72.0, "query_execution_ms": 783.91 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.2, - "latency_ms": 214.999578002, + "latency_ms": 215.000713, "precompute_execution_ms": 15.0, - "precompute_queueing_ms": 81.9988650018, + "precompute_queueing_ms": 82.0, "query_execution_ms": 118.000713 } ], "peak_cpu_cores": 3, - "peak_memory_bytes": 216443534, - "precompute_load": 0.0289488650018, + "peak_memory_bytes": 216450338, + "precompute_load": 0.02895, "recommended_configuration": { "ingest": { "predicted_busy_thread_seconds_per_second": 0.023, "recommended_threads": 1 }, "precompute": { - "predicted_busy_thread_seconds_per_second": 0.0289488650018, + "predicted_busy_thread_seconds_per_second": 0.02895, "recommended_threads": 1 }, "query": { From d33a9ba624266dfe62800ee029537ae1815dbc95 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 4 Dec 2026 06:01:11 +0000 Subject: [PATCH 17/18] test(planner): assert kept state for the dependents and full < on-demand, not lightcone query indices Under cost model 1 the full intent may be planned once with its dependent queries reading kept state directly, leaving `lightcone_query_indices` empty by design. T3 and T4 now check that the full-intent plan keeps state the on-demand plan does not (more ingestion-time nodes) and costs less than it; T4 also checks that the formulas alone keep no such state. Holds with and without lightcone queries reported. Co-Authored-By: Claude Opus 5.5 --- crates/planner/tests/measured_cost_file.rs | 46 ++++++++++++++++++---- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/crates/planner/tests/measured_cost_file.rs b/crates/planner/tests/measured_cost_file.rs index 57c83e569..632ed97a1 100644 --- a/crates/planner/tests/measured_cost_file.rs +++ b/crates/planner/tests/measured_cost_file.rs @@ -220,6 +220,24 @@ fn ingestion_ms_per_second(report: &SelectedPlanReport) -> f64 { .sum() } +/// The plan's ingestion-time nodes: the state it keeps as rows arrive. +fn ingestion_nodes(report: &SelectedPlanReport) -> usize { + report + .predicted_usage + .per_node + .iter() + .filter(|node| node.timing == ExecutionTiming::IngestionTime) + .count() +} + +/// Whether the full-intent plan keeps state for its dependent queries that +/// the on-demand plan reads at query time: more ingestion-time nodes. This +/// holds whether the planner reports the kept state as lightcone queries or +/// has the dependents read it directly (`lightcone_query_indices` empty). +fn keeps_state_for_dependents(full: &SelectedPlanReport, on_demand: &SelectedPlanReport) -> bool { + ingestion_nodes(full) > ingestion_nodes(on_demand) +} + /// T3. With the measured cost file, full intent planning keeps the shared /// state of `dash` (its services' p99 and error counts) and `rca` (its /// nodes' max cpu), which measured cheaper than computing them at query @@ -231,10 +249,16 @@ fn ingestion_ms_per_second(report: &SelectedPlanReport) -> f64 { async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() { let (_, inputs) = cost_file(MEASURED_MACHINE); for (intent, measured_ms_per_second) in [("dash", 9.7), ("rca", 7.9)] { - let (plan, report) = planned(intent, IntentPlanningMode::IntentFull, &inputs).await; + let (_, report) = planned(intent, IntentPlanningMode::IntentFull, &inputs).await; + let (_, on_demand) = + planned(intent, IntentPlanningMode::IntentOnDemandHoles, &inputs).await; + assert!( + keeps_state_for_dependents(&report, &on_demand), + "{intent}: no state kept for the dependent queries" + ); assert!( - !plan.lightcone_query_indices.is_empty(), - "{intent}: no lightcone kept" + report.cost_per_second.unwrap() < on_demand.cost_per_second.unwrap(), + "{intent}: full intent not cheaper than on demand" ); let predicted = ingestion_ms_per_second(&report); assert!( @@ -255,7 +279,7 @@ async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() /// T4. With the hosts' declared Zipf(1) skew (item 6), q2's IN-list over /// q1's top-10 hosts keeps the 29.9% of `auth` they hold, not 0.1%. Priced /// from the measured cost file, full intent planning keeps the (host, user) -/// counts (`lightcone_query_indices` non-empty) and costs less than the +/// counts (state the on-demand plan does not keep) and costs less than the /// on-demand plan of the same file; with the formulas alone it does not. #[tokio::test(flavor = "multi_thread")] async fn drill_cnt_keeps_the_lightcone_once_top_k_bindings_hold_their_heavy_rows() { @@ -273,6 +297,12 @@ async fn drill_cnt_keeps_the_lightcone_once_top_k_bindings_hold_their_heavy_rows &CostInputs::default(), ) .await; + let (_, formula_on_demand) = planned( + "drill_cnt", + IntentPlanningMode::IntentOnDemandHoles, + &CostInputs::default(), + ) + .await; eprintln!( "with file: full {:?} (lightcone {:?}), on demand {:?}; formulas: full {:?} (lightcone {:?})", full_report.cost_per_second, @@ -282,12 +312,12 @@ async fn drill_cnt_keeps_the_lightcone_once_top_k_bindings_hold_their_heavy_rows formula_full.lightcone_query_indices ); assert!( - !full.lightcone_query_indices.is_empty(), - "no lightcone kept" + keeps_state_for_dependents(&full_report, &on_demand), + "no state kept for q2" ); assert!(full_report.cost_per_second.unwrap() < on_demand.cost_per_second.unwrap()); assert!( - formula_full.lightcone_query_indices.is_empty(), - "the formulas alone keep the lightcone too" + !keeps_state_for_dependents(&formula_report, &formula_on_demand), + "the formulas alone keep q2's state too" ); } From 56de06dec3bd3b8430bc9773cb1f0d8a715d665f Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:34:13 +0000 Subject: [PATCH 18/18] test(planner): compare T3's upkeep with the state the measured runs kept On the eval build, rca's full intent keeps two chains: the measured q3 chain over `node_metrics` (predicted 1.5 + 4.45 + 0.78 = 6.7 ms/s, measured 7.9) and a per-(service, node) DDSketch chain over `requests` for q2 (3.0 + 6.2 + 1.5 = 10.7 ms/s), which no measured run kept. The 17.45 ms/s total compared both with the one chain's 7.9: not a model over-prediction (each node is priced from its measured entries: scan 150 ns/row, DDSketch 116 ns/row, 3.9 us per state emitted). T3 now sums the ingestion-time nodes fed by the measured tables' scans (dash: `requests`, `errors`; rca: `node_metrics`). Co-Authored-By: Claude Opus 5.5 --- crates/planner/tests/measured_cost_file.rs | 79 +++++++++++++++++++--- 1 file changed, 69 insertions(+), 10 deletions(-) diff --git a/crates/planner/tests/measured_cost_file.rs b/crates/planner/tests/measured_cost_file.rs index 632ed97a1..68daa367c 100644 --- a/crates/planner/tests/measured_cost_file.rs +++ b/crates/planner/tests/measured_cost_file.rs @@ -238,18 +238,77 @@ fn keeps_state_for_dependents(full: &SelectedPlanReport, on_demand: &SelectedPla ingestion_nodes(full) > ingestion_nodes(on_demand) } -/// T3. With the measured cost file, full intent planning keeps the shared -/// state of `dash` (its services' p99 and error counts) and `rca` (its -/// nodes' max cpu), which measured cheaper than computing them at query -/// time, and predicts the state's upkeep within 1.5x of its measured -/// ingestion-time CPU (precompute and persist threads): `dash` 9.7 ms/s, -/// `rca` 7.9 ms/s. Query at a time, `dash` keeps only q1's counts, 6.1 -/// ms/s measured, and `drill_cnt` q1's host counts, 6.25 ms/s. +/// The ingestion-time CPU, in ms per second, of the state the plan keeps +/// over `tables`: each ingestion-time node fed, through ingestion-time +/// nodes, by a `Scan` of one of them. +fn ingestion_ms_per_second_over( + plan: &IntentPlan, + report: &SelectedPlanReport, + tables: &[&str], +) -> f64 { + use asap_types::ir::operator::Source; + use asap_types::ir::NonASAPOp; + use asap_types::plan::physical_asap_dag::PhysicalASAPOperatorPayload; + let dag = &plan.plan.dag; + let ingestion = |id| { + report + .predicted_usage + .per_node + .iter() + .find(|node| node.node_id == id) + .filter(|node| node.timing == ExecutionTiming::IngestionTime) + }; + let mut kept: Vec<_> = dag + .nodes + .iter() + .filter(|node| { + matches!( + &node.payload, + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { + source: Source::Table { table_ref }, + .. + }) if tables.contains(&table_ref.as_str()) + ) && ingestion(node.id).is_some() + }) + .map(|node| node.id) + .collect(); + loop { + let more: Vec<_> = dag + .nodes + .iter() + .filter(|node| !kept.contains(&node.id) && ingestion(node.id).is_some()) + .filter(|node| node.producers().iter().any(|p| kept.contains(p))) + .map(|node| node.id) + .collect(); + if more.is_empty() { + break; + } + kept.extend(more); + } + kept.iter() + .filter_map(|&id| ingestion(id)) + .map(|node| node.cpu_core_seconds_per_second * 1_000.0) + .sum() +} + +/// T3. With the measured cost file, full intent planning keeps shared +/// state for `dash` and `rca` and costs less than computing them at query +/// time, and predicts the upkeep of the state the measured runs kept within +/// 1.5x of its measured ingestion-time CPU (precompute and persist threads): +/// `dash`'s chains over `requests` and `errors` 9.7 ms/s, `rca`'s chain over +/// `node_metrics` 7.9 ms/s. (The planner may keep more state than the +/// measured plan did, e.g. `rca`'s per-node p99 over `requests` for q2, +/// whose upkeep no run measured; it is left out of the comparison.) Query +/// at a time, `dash` keeps only q1's counts, 6.1 ms/s measured, and +/// `drill_cnt` q1's host counts, 6.25 ms/s. #[tokio::test(flavor = "multi_thread")] async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() { let (_, inputs) = cost_file(MEASURED_MACHINE); - for (intent, measured_ms_per_second) in [("dash", 9.7), ("rca", 7.9)] { - let (_, report) = planned(intent, IntentPlanningMode::IntentFull, &inputs).await; + for (intent, tables, measured_ms_per_second) in [ + ("dash", &["requests", "errors"][..], 9.7), + ("rca", &["node_metrics"][..], 7.9), + ] { + let (plan, report) = planned(intent, IntentPlanningMode::IntentFull, &inputs).await; let (_, on_demand) = planned(intent, IntentPlanningMode::IntentOnDemandHoles, &inputs).await; assert!( @@ -260,7 +319,7 @@ async fn full_intent_keeps_the_measured_cheaper_state_and_predicts_its_upkeep() report.cost_per_second.unwrap() < on_demand.cost_per_second.unwrap(), "{intent}: full intent not cheaper than on demand" ); - let predicted = ingestion_ms_per_second(&report); + let predicted = ingestion_ms_per_second_over(&plan, &report, tables); assert!( within(predicted, measured_ms_per_second, 1.5), "{intent} full: predicted {predicted:.2} ms/s, measured {measured_ms_per_second}"