diff --git a/calibration/measured-cost-files/README.md b/calibration/measured-cost-files/README.md new file mode 100644 index 000000000..f6e2e1e3c --- /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; 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) | +| `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..34e61c962 --- /dev/null +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2660-v2-40t-unknown-memory.json @@ -0,0 +1,157 @@ +{ + "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": "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", + "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..d3cb3d431 --- /dev/null +++ b/calibration/measured-cost-files/x86_64-intel-xeon-e5-2683-v3-56t-registered-ddr4.json @@ -0,0 +1,157 @@ +{ + "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": "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", + "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 + } + ] + } +} 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/measured.rs b/crates/cost/src/measured.rs index d9256ddde..3b77c49da 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, @@ -538,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/model.rs b/crates/cost/src/model.rs index 4a2597da3..1e979a869 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, } } } @@ -381,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/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/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..51bdd344d 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, @@ -68,6 +69,79 @@ 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; + +/// 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 @@ -379,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/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 1ee31446c..90dffe8c0 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, 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::{ EdgeStatistics, OperatorStatistics, PartitionStatistics, UnaryEdgeStatistics, @@ -417,6 +417,22 @@ pub struct OutputFacts<'a> { pub kept_values_per_column: BTreeMap<&'a str, u64>, } +/// 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)] +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 }, +} + /// 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. @@ -507,7 +523,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, @@ -685,6 +702,10 @@ 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 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; @@ -1002,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. @@ -1277,7 +1319,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 +1373,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 +1384,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 +1862,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. @@ -1985,6 +2051,9 @@ 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); + 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( group_count .checked_mul( @@ -2002,11 +2071,10 @@ 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 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 @@ -2025,6 +2093,8 @@ pub(crate) fn node_usage_and_cost_terms<'a>( } // Each group's state found once per raw batch. let group_visits = visits(group_count); + // Its readers read every group's state per window: the measured + // merge prices were fitted on those state counts. let out = EdgeStatistics { rows: group_count, bytes: group_count @@ -2080,13 +2150,32 @@ 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); + // Every group, and the narrower windows' states: the groups one + // narrower window reaches. let group_count = narrower.output_facts.statistics.rows.max(1); // Stage 2 offers it at ingestion time only. 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; + // 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 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| { + groups_reached_share(rows * windows_per_window as f64, group_count, reach) + }) + .max(narrower_share); + 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 @@ -2371,6 +2460,32 @@ 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 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 { .. }) => { + 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(), + (false, None) => 1.0, + (true, _) => 0.0, + }; + series.filter(|_| !ingestion).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; // A node with an entry takes its measured time, scanning included; // any other node its formulas' CPU operations times the calibration @@ -2382,6 +2497,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 +2507,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(), @@ -2446,11 +2565,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. @@ -2644,6 +2765,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)); } } @@ -3137,6 +3263,43 @@ pub(crate) fn source_rows_in_window( rows * input.source_rows_per_row } +/// 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; + 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 /// 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. diff --git a/crates/cost/src/node/usage/tests.rs b/crates/cost/src/node/usage/tests.rs index 47e8a30e7..920531255 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,91 @@ 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). 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::IngestionTime); + let terms = crate::node_cost_terms(&scan, &[], None, &data, &settings).unwrap(); + assert_eq!( + terms.units_per_constant, + [ + (CostConstant::ScanOperationsPerRow, 10_000.0), + (CostConstant::FilterOperationsPerRow, 10_000.0), + ( + CostConstant::FilterOperationsPerRowPerComparedValue, + 100_000.0 + ), + ] + .into() + ); + assert_close( + charged_by_terms(&terms), + formula_cpu_per_execution(&scan, &[], None, &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 +4070,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 +4208,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 +4266,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 +4827,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 +5220,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 @@ -5209,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(); @@ -5225,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 @@ -5474,8 +5577,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(); @@ -5499,7 +5605,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( @@ -5515,10 +5630,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 @@ -5624,3 +5749,331 @@ 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 +// 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: +/// `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, 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 +} + +/// 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, + })) + } +} + +/// `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` (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 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(); + 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(); + 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(); + // 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 * -(-1.0_f64).exp_m1(); + assert_close( + usage.cost.memory_and_disk.average_memory_bytes, + 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() + .cost + .detail + }; + 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!( + 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 +/// 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(); + 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 + ); +} + +/// 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"); +} + +/// 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/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/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..ccffad31d 100644 --- a/crates/integration-tests/tests/stage3_objective.rs +++ b/crates/integration-tests/tests/stage3_objective.rs @@ -1209,3 +1209,60 @@ 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 +} + +/// 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 +/// 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 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 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/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/inlist_selectivity.rs b/crates/planner-cli/tests/inlist_selectivity.rs index 8d0fc17fd..32b2d7f4d 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, 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; @@ -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), 169.4972); 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), 141.1861); } /// `sum(rate(m{job="a"}[5m]))` once, `m` 1,000 series every 15 s holding @@ -579,15 +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). 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 + 53.7, + 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 732afe0b4..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.7112080558, + 36.711207989, DISTINCT_VARIABLES, DISTINCT_ROWS, ), 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..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": 4.25529259649e-7, - "cpu_core_seconds_per_second": 0.0339091400893, + "cost_per_second": 4.06813421429e-7, + "cpu_core_seconds_per_second": 0.032937486756, "per_node": { "0": { "cost_per_second": 3.14989416e-11, @@ -162,31 +162,31 @@ "timing": "ingestion_time" }, "10": { - "cost_per_second": 5.34916587385e-8, + "cost_per_second": 3.63310905982e-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.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": 25.0, - "refresh_wall_ms_per_window": 25.0, + "refresh_cpu_ms_per_window": 16.6666666667, + "refresh_wall_ms_per_window": 16.6666666667, "timing": "ingestion_time" }, "11": { - "cost_per_second": 1.33994557364e-8, + "cost_per_second": 1.18441856564e-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.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": 49.8976, - "refresh_wall_ms_per_window": 49.8976, + "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": 38476376.2611, - "cpu_ops_per_second": 33907005.6893, + "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": 357.7276, + "latency_ms": 341.095066667, "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 74.8976, + "precompute_queueing_ms": 58.2650666667, "query_execution_ms": 257.83 }, { "allowed_lateness_ms": 0.0, "evaluations_per_second": 0.00333333333333, - "latency_ms": 145.0176, + "latency_ms": 128.385066667, "precompute_execution_ms": 25.0, - "precompute_queueing_ms": 74.8976, + "precompute_queueing_ms": 58.2650666667, "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": 374.505400227, + "precompute_execution_ms": 16.6666666667, + "precompute_queueing_ms": 66.5984, "query_execution_ms": 291.24033356 } ], "peak_cpu_cores": 4, - "peak_memory_bytes": 69760632, - "precompute_load": 0.00341496, + "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.00341496, + "predicted_busy_thread_seconds_per_second": 0.00244330666667, "recommended_threads": 1 }, "query": { 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..68daa367c --- /dev/null +++ b/crates/planner/tests/measured_cost_file.rs @@ -0,0 +1,382 @@ +//! 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() +} + +/// 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) +} + +/// 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, 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!( + keeps_state_for_dependents(&report, &on_demand), + "{intent}: no state kept for the dependent queries" + ); + assert!( + 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_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}" + ); + } + 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. 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 (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() { + let (_, inputs) = cost_file(MEASURED_MACHINE); + 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; + 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, + full.lightcone_query_indices, + on_demand.cost_per_second, + formula_report.cost_per_second, + formula_full.lightcone_query_indices + ); + assert!( + 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!( + !keeps_state_for_dependents(&formula_report, &formula_on_demand), + "the formulas alone keep q2's state too" + ); +} 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..d86663763 --- /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" + } + } + } +} 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..aae7ddc18 --- /dev/null +++ b/crates/planner/tests/measured_cost_file/drill_cnt/data.json @@ -0,0 +1,41 @@ +{ + "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, + "zipf_exponent_per_label": { + "host": 1.0 + } + }, + "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, + "zipf_exponent_per_label": { + "host": 1.0 + } + } + } +} 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..a41bf76e2 --- /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 + } + } + } + } +} 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 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, };