diff --git a/crates/cost/src/model.rs b/crates/cost/src/model.rs index 1e979a869..44439a77f 100644 --- a/crates/cost/src/model.rs +++ b/crates/cost/src/model.rs @@ -6,6 +6,7 @@ use crate::node::analytical::AnalyticalCostError; use crate::MeasuredOperationCosts; use asap_types::stages::StorageMedium; +use std::collections::{BTreeMap, BTreeSet}; /// [`PlanCost::source`](crate::PlanCost::source) when every node is priced from the formulas. pub const COST_SOURCE: &str = "analytical-cost-v2 (illustrative statistics)"; @@ -482,6 +483,13 @@ pub struct CostInputs { /// `asap_planner` tool and tests set them. #[serde(skip)] pub latency_selection_checks: LatencySelectionChecks, + /// Per table, the columns that identify a series in the deployment's + /// store (its series key): a query-time scan selects series only by + /// predicates on these columns, and evaluates any other predicate on + /// every row of the window it reads. A table not listed, and every + /// table when `None` (default), selects series by any label column. + #[serde(skip_serializing_if = "Option::is_none")] + pub series_key_columns: Option>>, } /// How cost model 3's `lowest_mean_latency` solves @@ -582,6 +590,7 @@ impl Default for CostInputs { latency_calibration: LatencyCalibration::NotChecked, latency_selection: LatencySelection::default(), latency_selection_checks: LatencySelectionChecks::default(), + series_key_columns: None, } } } diff --git a/crates/cost/src/node/usage/mod.rs b/crates/cost/src/node/usage/mod.rs index 44e880253..c257e38a0 100644 --- a/crates/cost/src/node/usage/mod.rs +++ b/crates/cost/src/node/usage/mod.rs @@ -876,6 +876,12 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // the restricted columns' values it leaves (`kept_share`); `None` for // any other node. let mut kept_by_predicate: Option> = None; + // For a `Scan`, what its predicates on the series key keep: the series + // (and their rows) a query-time scan selects before reading. Every + // label column is a key unless the deployment declares the source's + // series key (`CostInputs::series_key_columns`); a predicate on another + // column is evaluated on every row read. + let mut selected_by_predicate: Option> = None; let operator = OperatorKind::of(&node.payload); let measured_unit_cost = match &node.payload { Payload::NonASAP(NonASAPOp::Aggregate { measures, .. }) => { @@ -1049,17 +1055,39 @@ pub(crate) fn node_usage_and_cost_terms<'a>( // their values are the input's, IN-lists applied. match &node.payload { Payload::NonASAP(NonASAPOp::Scan { - predicates, schema, .. + source, + predicates, + schema, }) if !predicates.is_empty() => { let conjuncts: Vec<_> = predicates.iter().map(|p| &p.0).collect(); - kept_by_predicate = Some(kept_share::share_of_rows_kept( - &conjuncts, - schema, - &unchanged_columns, - &BTreeMap::new(), - declared_values, - &data.heaviest_value_placeholders, - )); + let share_over = |columns: &BTreeSet<&str>| { + kept_share::share_of_rows_kept( + &conjuncts, + schema, + columns, + &BTreeMap::new(), + declared_values, + &data.heaviest_value_placeholders, + ) + }; + let kept = share_over(&unchanged_columns); + selected_by_predicate = Some( + match settings + .series_key_columns + .as_ref() + .and_then(|keys| keys.get(source_name(source))) + { + Some(key) => share_over( + &unchanged_columns + .iter() + .copied() + .filter(|column| key.contains(*column)) + .collect(), + ), + None => kept.clone(), + }, + ); + kept_by_predicate = Some(kept); } Payload::NonASAP(NonASAPOp::Filter { pred, .. }) => { if let Some(producer) = producers.first() { @@ -1317,6 +1345,9 @@ pub(crate) fn node_usage_and_cost_terms<'a>( ingestion, ) }; + // The rows a `Scan` reads in one computation (its output keeps those + // its predicates keep); `None` for any other node. + let mut scan_rows_read: Option = None; let (out, estimate, detail) = match &node.payload { Payload::NonASAP(operator) => match operator { NonASAPOp::Scan { @@ -1365,31 +1396,36 @@ pub(crate) fn node_usage_and_cost_terms<'a>( })?, }; // At ingestion time it sees every arriving row; at query - // time a series store selects the series its label - // predicates name before reading their rows, so it reads - // only the rows they keep. + // time a series store selects the series its predicates on + // the series key name before reading their rows, so it + // reads only those series' rows, and keeps the rows all its + // predicates keep. let selected_rows = kept_share::rows_kept(rows.max(1), share_kept); - let out = edge(match ingestion { + let read = edge(match ingestion { true => rows.max(1), - false => selected_rows, + false => kept_share::rows_kept( + rows.max(1), + selected_by_predicate.as_ref().map_or(1.0, |s| s.share), + ), })?; + scan_rows_read = Some(read.rows); // Its predicates are evaluated on each row it reads. let estimate = estimate_operator_with_terms( PhysicalOperator::Scan, OperatorStatistics::Scan { edges: UnaryEdgeStatistics { - input: out, - output: out, + input: read, + output: read, promql: None, }, - source_read_bytes: out.bytes, + source_read_bytes: read.bytes, }, ) .map(|(estimate, terms)| { charged( terms.plus_terms( &filter_terms_per_row(predicates.iter().map(|p| &p.0)) - .times(out.rows as f64), + .times(read.rows as f64), ), estimate.peak_memory_bytes(), estimate.scan_bytes(), @@ -2424,9 +2460,13 @@ pub(crate) fn node_usage_and_cost_terms<'a>( + estimate.scan_bytes() as f64 * speed.ms_per_scanned_byte; // What one computation processes, the unit its entry is costed per // ([`OperatorKind`]): the samples a scan reads, the states a merge - // reads, otherwise the rows of its (first) input. + // reads, otherwise the rows of its (first) input. (At ingestion time + // a scan's entry counts the rows it passes on.) let units = match &node.payload { - Payload::NonASAP(NonASAPOp::Scan { .. }) => out.rows, + Payload::NonASAP(NonASAPOp::Scan { .. }) => match ingestion { + true => out.rows, + false => scan_rows_read.unwrap_or(out.rows), + }, Payload::ASAP(ASAPOp::SummaryMerge { .. }) => merged_states(producers)?, // The narrower states it merges in one execution (one second at // ingestion time). @@ -2467,12 +2507,12 @@ 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 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. + // declare, at query time only those its predicates on the series key + // select (a key column 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 { .. }) => { - let selected_share: f64 = match (ingestion, kept_by_predicate.as_ref()) { + let selected_share: f64 = match (ingestion, selected_by_predicate.as_ref()) { (false, Some(kept)) => kept .kept_values_per_column .iter() @@ -2487,7 +2527,7 @@ pub(crate) fn node_usage_and_cost_terms<'a>( series.filter(|_| !ingestion).map_or(0, |series| { ((series as f64 * selected_share).round() as u64) .max(1) - .min(out.rows) + .min(scan_rows_read.unwrap_or(out.rows)) }) } Payload::NonASAP(_) | Payload::ASAP(_) => 0, diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 087286ac7..79bc3d61a 100644 --- a/crates/cost/src/node/usage/tests.rs +++ b/crates/cost/src/node/usage/tests.rs @@ -6079,3 +6079,111 @@ fn an_ingestion_time_scan_pays_no_per_series_charge() { .unwrap(); assert_close(usage.work_ms_per_execution, 0.41, 1e-9, "rows only"); } + +// Series keys (deployment input `series_key_columns`): a query-time scan +// selects series only by predicates on the columns that identify a series +// in the data plane's store. A predicate on any other column is evaluated +// on every row of the window read, as a filter. + +/// `measured_scan` with `auth`'s series identified by `key` alone. +fn measured_scan_keyed(key: &[&str]) -> CostInputs { + CostInputs { + series_key_columns: Some( + [( + "auth".to_string(), + key.iter().map(|c| c.to_string()).collect(), + )] + .into(), + ), + ..measured_scan(41.0, 8_700.0) + } +} + +/// The measured scan of 10 min of `auth` (100,000 series, 6,000,000 rows) +/// under `predicates` with `settings`: (rows out, work ms). +fn keyed_scan(predicates: Vec>, settings: &CostInputs) -> (u64, f64) { + let scan = auth_scan(predicates, ExecutionTiming::QueryTime); + let usage = node_resource_usage_and_cost( + &scan, + &[], + (1, 1.0), + Some(600_000), + None, + &auth_data_with_series(100_000), + settings, + ) + .unwrap(); + ( + usage.output_facts.statistics.rows, + usage.work_ms_per_execution, + ) +} + +/// K1. `auth`'s series keyed by `user`: `host IN (10 of 10,000)` cannot +/// select series, so the scan reads all 6,000,000 rows of its 100,000 +/// series (246 + 870 = 1,116 ms) and keeps the 6,000 rows of the 10 hosts. +#[test] +fn a_predicate_off_the_series_key_reads_every_row_of_the_window() { + let (rows, work_ms) = keyed_scan( + vec![in_list(HOST, "h", 10)], + &measured_scan_keyed(&["user"]), + ); + assert_eq!(rows, 6_000); + assert_close(work_ms, 1_116.0, 1e-9, "every series and row"); +} + +/// K2. Keyed by `host`, the same predicate selects 100 of the 100,000 +/// series and reads their 6,000 rows: 1.116 ms, as without the input. +#[test] +fn a_predicate_on_the_series_key_selects_series() { + let (rows, work_ms) = keyed_scan( + vec![in_list(HOST, "h", 10)], + &measured_scan_keyed(&["host"]), + ); + assert_eq!(rows, 6_000); + assert_close(work_ms, 1.116, 1e-9, "100 series"); +} + +/// K3. Keyed by `user`: `user IN (10 of 100,000)` selects 10 series and +/// reads 600 rows, and `host IN (10)` above it only filters them: 600 rows +/// read, 0.6 kept (at least one), 600 x 41 + 10 x 8,700 ns = 0.1116 ms. +#[test] +fn only_the_key_conjuncts_select_series() { + let settings = measured_scan_keyed(&["user"]); + let (rows, work_ms) = keyed_scan( + vec![in_list(USER, "u", 10), in_list(HOST, "h", 10)], + &settings, + ); + assert_eq!(rows, 1); + assert_close(work_ms, 0.1116, 1e-9, "10 series"); +} + +/// K4. A table the input does not list keeps today's rule (every label +/// column selects series), as does no input at all. +#[test] +fn an_unlisted_table_selects_series_by_every_label() { + let mut settings = measured_scan_keyed(&["user"]); + settings.series_key_columns = + Some([("login_fail".to_string(), ["user".to_string()].into())].into()); + let (rows, work_ms) = keyed_scan(vec![in_list(HOST, "h", 10)], &settings); + assert_eq!(rows, 6_000); + assert_close(work_ms, 1.116, 1e-9, "100 series"); +} + +/// K5. The input is part of a cost inputs file. +#[test] +fn series_key_columns_load_from_a_cost_inputs_file() { + let settings: CostInputs = + serde_json::from_value(serde_json::json!({"series_key_columns": {"login_fail": ["user"]}})) + .unwrap(); + assert_eq!( + settings.series_key_columns, + Some([("login_fail".to_string(), ["user".to_string()].into())].into()) + ); + let round_trip: CostInputs = + serde_json::from_str(&serde_json::to_string(&settings).unwrap()).unwrap(); + assert_eq!(round_trip, settings); + assert!(!serde_json::to_string(&CostInputs::default()) + .unwrap() + .contains("series_key_columns")); +}