diff --git a/crates/integration-tests/tests/cm1_latency_bounds.rs b/crates/integration-tests/tests/cm1_latency_bounds.rs new file mode 100644 index 000000000..b27d4f4f5 --- /dev/null +++ b/crates/integration-tests/tests/cm1_latency_bounds.rs @@ -0,0 +1,1075 @@ +//! Latency bounds under cost model 1 (`UsageOverTime`): the plan respects +//! each query's `max_latency_ms`, each group's `GROUP LATENCY` bound and +//! each round's interval, by the deterministic schedule of a round whose +//! queries are all issued at its tick (test plan +//! `cm1-latency-bounds.md`): +//! +//! - per query: its predicted query-time latency `l_q` (the report's +//! `query_execution_ms`, the freshness wait excluded) is within +//! `max_latency_ms`; +//! - per group (Graham's bound): `CP_G + W_G / P_eff <= L_G`, `W_G` the +//! group's query-time work (a node shared by its queries once), `CP_G` +//! the longest dependency chain of `l_q` (a dependent after its +//! binder), `P_eff` the deployment's cores less the plan's ingest and +//! precompute cores; +//! - per round: `W_round / P_eff <= interval`. +//! +//! Expected plans come from a brute-force oracle, not the selection MILP: +//! each combination of the queries' plans (query-time scan or +//! ingestion-time chain, as in `group_latency.rs`) is planned alone with +//! the others excluded, the oracle reads its predicted latencies, work and +//! cost from the report, and keeps the cheapest combination within every +//! bound. Every input is JSON: a field this work adds (`cpu_cores`, +//! `query_dependencies`) is refused when loaded, so those tests fail before +//! the implementation; the per-query tests compile and run today and fail +//! on their assertions, as cost model 1 enforces no bound. + +use std::collections::{BTreeMap, BTreeSet}; + +use asap_planner::{CostInputs, DeploymentCapabilities, PlanningModels}; +use asap_planner_cli::planning_stages::{lower_promql_roots, run_planning_stages_over}; +use serde_json::{json, Value}; + +use crate::lowest_mean_latency_common::{ + cost_inputs, every, max_min_table, over_m, planned, planned_with, usage_over_time, Planned, +}; + +/// Relative tolerance of every bound comparison (the solver's). +const TOLERANCE: f64 = 1e-6; + +// --------------------------------------------------------------------------- +// Inputs +// --------------------------------------------------------------------------- + +/// `max_over_time(m[5m])` (q0) and `min_over_time(m[5m])` (q1) every 10 s. +const MAX: &str = "max_over_time(m[5m])"; +const MIN: &str = "min_over_time(m[5m])"; + +/// The A4 table of `lowest_mean_latency.rs` made dear at ingestion: a scan +/// reads 300,000 samples at `scan_ns` each (100 ns: 30 ms per run); a chain +/// refreshes 1,000 states per 10 s window at `state_ns` each, so it costs +/// more per second than the scan but its query-time read is short; a +/// scanned `min` folds each row `min_ns` slower than `max`. +fn table(scan_ns: f64, state_ns: f64, min_ns: f64) -> Vec { + max_min_table(scan_ns, state_ns, min_ns) +} + +/// Cost model 1 with `table` and `data_plane_execution` (JSON, `{}` for +/// the default). +fn cost_model_1(table: Vec, data_plane_execution: Value) -> Value { + cost_inputs(usage_over_time(), table, json!({}), data_plane_execution) +} + +/// [`cost_model_1`] with the deployment's `cpu_cores` (the input this work +/// adds), or without the field. +fn with_cores(table: Vec, cpu_cores: Option) -> Value { + cost_model_1( + table, + match cpu_cores { + Some(cores) => json!({"cpu_cores": cores}), + None => json!({}), + }, + ) +} + +/// A workload of `entries` over `m` (1,000 series) with `groups` as its +/// group latency bounds, `dependencies` as `(upstream, dependent)` pairs +/// (the field this work adds; omitted when empty) and the last +/// `optional_query_count` entries optional. +fn workload( + entries: Vec, + groups: Value, + dependencies: &[(usize, usize)], + optional_query_count: usize, +) -> Result { + let mut workload = serde_json::to_value(over_m(entries, 1000)).unwrap(); + workload["query_workload"]["group_latency_bounds"] = groups; + if !dependencies.is_empty() { + workload["query_workload"]["query_dependencies"] = Value::Array( + dependencies + .iter() + .map(|&(upstream, dependent)| json!({"upstream": upstream, "dependent": dependent})) + .collect(), + ); + } + if optional_query_count > 0 { + workload["query_workload"]["optional_query_count"] = json!(optional_query_count); + } + serde_json::from_value(workload).map_err(|error| format!("workload does not load: {error}")) +} + +/// One alternative of the exclusive choice `choice` every 10 s, requested +/// at `fraction` of the rounds. +fn alternative(query: &str, choice: &str, fraction: f64, max_latency_ms: Option) -> Value { + let mut entry = every(query, 10_000, max_latency_ms); + entry["demand"]["fixed_interval_at"]["requested_fraction"] = json!(fraction); + entry["demand"]["fixed_interval_at"]["exclusive_group"] = json!(choice); + entry +} + +/// The exclusions forcing each query (`MAX` or `MIN`, by `measures`) onto a +/// chain (`true`) or a query-time scan (`false`), as `group_latency.rs`. +fn forcing(measures: &[&str], on_chain: &[bool]) -> DeploymentCapabilities { + let mut excluded = Vec::new(); + for (&measure, &chain) in measures.iter().zip(on_chain) { + let exact = if measure == "max" { "Max" } else { "Min" }; + if chain { + excluded.push(json!({"aggregate_measure": measure, "timing": "query_time"})); + excluded.push(json!({"summary_family": {"exact": exact}, "timing": "query_time"})); + } else { + excluded.push(json!({"summary_family": {"exact": exact}, "timing": "ingestion_time"})); + } + } + DeploymentCapabilities { + raw_data_retained: true, + excluded_candidates: serde_json::from_value(Value::Array(excluded)).unwrap(), + ..Default::default() + } +} + +/// The measure of a query text (`max` or `min`). +fn measure_of(query: &str) -> &'static str { + if query.starts_with("max") { + "max" + } else { + "min" + } +} + +// --------------------------------------------------------------------------- +// The oracle +// --------------------------------------------------------------------------- + +/// One combination of the queries' plans, planned alone, with what the +/// oracle reads from its report. +#[derive(Debug, Clone)] +struct Combination { + on_chain: Vec, + /// Per query, `l_q`: the report's `query_execution_ms`. + latency_ms: Vec, + cost_per_second: f64, + /// Ingest plus precompute busy thread-seconds per second (the tables + /// have no refresh I/O wait, so they are CPU cores). + background_cores: f64, + /// Per query-time node of the plan: its work per step (ms) and the + /// queries that reach it (instant queries: one step each). + node_work_ms: BTreeMap)>, + /// Per query, its latency less the work of the nodes it reaches: the + /// fixed cost per request. + request_ms: Vec, +} + +impl Combination { + fn of(planned: &Planned, on_chain: Vec, query_count: usize) -> Self { + let dag = serde_json::to_value(&planned.plan.dag).unwrap(); + let query_time: BTreeSet = dag["nodes"] + .as_array() + .unwrap() + .iter() + .filter(|node| node["output_state"]["timing"] == "query_time") + .map(|node| node["id"].as_u64().unwrap()) + .collect(); + let mut inputs: BTreeMap> = BTreeMap::new(); + for edge in dag["edges"].as_array().unwrap() { + inputs + .entry(edge["consumer"].as_u64().unwrap()) + .or_default() + .push(edge["producer"].as_u64().unwrap()); + } + let per_node: BTreeMap = planned.report["predicted_usage"]["per_node"] + .as_array() + .unwrap() + .iter() + .map(|node| { + ( + node["node_id"].as_u64().unwrap(), + node["query_ms_per_step"].as_f64().unwrap_or(0.0), + ) + }) + .collect(); + let mut node_work_ms: BTreeMap)> = BTreeMap::new(); + let mut request_ms = Vec::new(); + let mut latency_ms = Vec::new(); + for q in 0..query_count { + let root = dag["roots"][q].as_u64().unwrap(); + let mut seen = BTreeSet::new(); + let mut stack = vec![root]; + // Query-time nodes only, stopping at ingestion time, as the + // report's latency does. + while let Some(node) = stack.pop() { + if !query_time.contains(&node) || !seen.insert(node) { + continue; + } + stack.extend(inputs.get(&node).into_iter().flatten().copied()); + } + let reached: f64 = seen.iter().map(|node| per_node[node]).sum(); + for &node in &seen { + node_work_ms + .entry(node) + .or_insert((per_node[&node], BTreeSet::new())) + .1 + .insert(q); + } + let latency = planned.query_ms(q, "query_execution_ms"); + latency_ms.push(latency); + request_ms.push((latency - reached).max(0.0)); + } + let configuration = &planned.report["predicted_usage"]["recommended_configuration"]; + let busy = |role: &str| { + configuration[role]["predicted_busy_thread_seconds_per_second"] + .as_f64() + .unwrap_or(0.0) + }; + Combination { + on_chain, + latency_ms, + cost_per_second: planned.report["cost_per_second"].as_f64().unwrap(), + background_cores: busy("ingest") + busy("precompute"), + node_work_ms, + request_ms, + } + } + + /// `W` over `queries` with each query's request weight (1, or an + /// exclusive alternative's fraction): a node at the sum of its readers' + /// weights, at most 1 (a node read by several queries counted once), + /// plus each query's fixed cost per request at its weight. + fn work_ms(&self, queries: &[usize], weight: &[f64]) -> f64 { + let nodes: f64 = self + .node_work_ms + .values() + .map(|(work, readers)| { + let w: f64 = readers + .iter() + .filter(|q| queries.contains(q)) + .map(|&q| weight[q]) + .sum(); + work * w.min(1.0) + }) + .sum(); + nodes + + queries + .iter() + .map(|&q| self.request_ms[q] * weight[q]) + .sum::() + } + + /// `CP` over `queries`: the longest chain of `l_q` along `dependencies` + /// (both ends in `queries`). + fn critical_path_ms(&self, queries: &[usize], dependencies: &[(usize, usize)]) -> f64 { + fn longest( + q: usize, + latency: &[f64], + queries: &[usize], + dependencies: &[(usize, usize)], + ) -> f64 { + latency[q] + + dependencies + .iter() + .filter(|(upstream, dependent)| *upstream == q && queries.contains(dependent)) + .map(|&(_, dependent)| longest(dependent, latency, queries, dependencies)) + .fold(0.0, f64::max) + } + queries + .iter() + .map(|&q| longest(q, &self.latency_ms, queries, dependencies)) + .fold(0.0, f64::max) + } + + /// `P_eff`: `cores` less the background; `None` cores: unbounded. + fn effective_cores(&self, cores: Option) -> Option { + cores.map(|cores| f64::from(cores) - self.background_cores) + } + + /// Graham's bound of a group: `CP + W / P_eff` (`CP` alone without a + /// core count; infinite when `P_eff <= 0`). + fn graham_ms( + &self, + queries: &[usize], + weight: &[f64], + dependencies: &[(usize, usize)], + cores: Option, + ) -> f64 { + let cp = self.critical_path_ms(queries, dependencies); + match self.effective_cores(cores) { + None => cp, + Some(p) if p <= 0.0 => f64::INFINITY, + Some(p) => cp + self.work_ms(queries, weight) / p, + } + } +} + +/// The bounds a workload states, as the oracle checks them. +#[derive(Debug, Clone, Default)] +struct Bounds { + /// Per answered query, its `max_latency_ms`. + max_latency_ms: Vec>, + /// Per group: its queries and `L_G`. + groups: Vec<(Vec, f64)>, + dependencies: Vec<(usize, usize)>, + /// Per answered query, its request weight (1 or its fraction). + weight: Vec, + cpu_cores: Option, + /// The round's interval, ms (one clock). + interval_ms: f64, +} + +impl Bounds { + fn within(value: f64, bound: f64) -> bool { + value <= bound * (1.0 + TOLERANCE) + } + + /// Whether `c` meets every bound. + fn feasible(&self, c: &Combination) -> bool { + let per_query = self + .max_latency_ms + .iter() + .zip(&c.latency_ms) + .all(|(bound, &l)| bound.map_or(true, |bound| Self::within(l, bound))); + let groups = self.groups.iter().all(|(queries, bound)| { + Self::within( + c.graham_ms(queries, &self.weight, &self.dependencies, self.cpu_cores), + *bound, + ) + }); + let all: Vec = (0..self.weight.len()).collect(); + let round = match c.effective_cores(self.cpu_cores) { + None => true, + Some(p) if p <= 0.0 => false, + Some(p) => Self::within(c.work_ms(&all, &self.weight) / p, self.interval_ms), + }; + per_query && groups && round + } + + /// The oracle: the cheapest combination meeting every bound. + fn cheapest<'c>(&self, all: &'c [Combination]) -> Option<&'c Combination> { + all.iter() + .filter(|c| self.feasible(c)) + .min_by(|a, b| a.cost_per_second.total_cmp(&b.cost_per_second)) + } +} + +/// Every combination of `queries`' plans (scan or chain each), each query +/// every 10 s without a bound, planned alone under `cost_inputs` (without +/// the new fields, so this runs today). +async fn combinations(queries: &[&str], cost_inputs: &Value) -> Vec { + let entries: Vec = queries.iter().map(|q| every(q, 10_000, None)).collect(); + combinations_of(entries, queries, cost_inputs).await +} + +/// [`combinations`] of the workload `entries` (their texts `queries`), any +/// bound in them removed. +async fn combinations_of( + mut entries: Vec, + queries: &[&str], + cost_inputs: &Value, +) -> Vec { + for entry in &mut entries { + entry["requirements"]["max_latency_ms"] = Value::Null; + } + let workload = workload(entries, json!([]), &[], 0).unwrap(); + let measures: Vec<&str> = queries.iter().map(|q| measure_of(q)).collect(); + let mut all = Vec::new(); + for mask in 0..(1usize << queries.len()) { + let on_chain: Vec = (0..queries.len()).map(|q| mask & (1 << q) != 0).collect(); + let forced = planned_with(&workload, cost_inputs, &forcing(&measures, &on_chain)) + .await + .unwrap_or_else(|error| panic!("{on_chain:?}: {error}")); + let reads: Vec = (0..queries.len()) + .map(|q| forced.query_reads_a_view(q)) + .collect(); + assert_eq!(reads, on_chain, "the exclusions force the combination"); + all.push(Combination::of(&forced, on_chain, queries.len())); + } + let mut costs: Vec = all.iter().map(|c| c.cost_per_second).collect(); + costs.sort_by(f64::total_cmp); + assert!( + costs + .windows(2) + .all(|pair| pair[1] > pair[0] * (1.0 + 1e-3)), + "instance: combination costs are distinct ({all:?})" + ); + all +} + +/// The queries of `planned` that read a chain. +fn on_chain_of(planned: &Planned, query_count: usize) -> Vec { + (0..query_count) + .map(|q| planned.query_reads_a_view(q)) + .collect() +} + +/// Bounds strictly between the distinct `values` (and one above, one +/// below them all): each one a different set of feasible combinations. +fn sweep(values: &[f64]) -> Vec { + let mut sorted: Vec = values.iter().copied().filter(|v| v.is_finite()).collect(); + sorted.sort_by(f64::total_cmp); + sorted.dedup_by(|a, b| (*a - *b).abs() <= 1e-3 * b.abs().max(1e-9)); + let mut bounds = vec![sorted[0] * 0.5]; + for pair in sorted.windows(2) { + bounds.push((pair[0] + pair[1]) / 2.0); + } + bounds.push(sorted[sorted.len() - 1] * 2.0); + bounds +} + +/// Check one planner result against the oracle: the oracle's combination +/// is selected and meets every bound by its own report, or, when the +/// oracle has none, planning fails naming `cause`. +fn assert_matches_oracle( + label: &str, + selected: Result, + bounds: &Bounds, + all: &[Combination], + cause: &str, +) { + let query_count = bounds.weight.len(); + match bounds.cheapest(all) { + Some(expected) => { + let selected = selected.unwrap_or_else(|error| panic!("{label}: {error}")); + assert_eq!( + on_chain_of(&selected, query_count), + expected.on_chain, + "{label}: oracle {expected:?}" + ); + let own = Combination::of(&selected, expected.on_chain.clone(), query_count); + assert!( + bounds.feasible(&own), + "{label}: the selected plan breaks a bound by its own report: {own:?}" + ); + } + None => { + let error = selected.err().unwrap_or_else(|| { + panic!( + "{label}: the oracle has no plan within the bounds, the planner returned one" + ) + }); + assert!(error.contains(cause), "{label}: {error}"); + } + } +} + +// --------------------------------------------------------------------------- +// The oracle itself (no planner) +// --------------------------------------------------------------------------- + +/// O1. The oracle's arithmetic on a hand-built combination: two queries +/// sharing one node of 30 ms, each with 2 ms of its own and 1 ms per +/// request, 0.5 cores of background. W = 30 + 2 + 2 + 1 + 1 = 36 ms; +/// independent CP = max(33, 33) = 33; with q0 -> q1 CP = 66; on 2 cores +/// P_eff = 1.5, so Graham = 33 + 24 = 57 (independent), 90 (dependent); +/// as alternatives at 0.5 each, W = 30 + 1 + 1 + 0.5 + 0.5 = 33. +#[test] +fn o1_oracle_arithmetic() { + let c = Combination { + on_chain: vec![false, false], + latency_ms: vec![33.0, 33.0], + cost_per_second: 1.0, + background_cores: 0.5, + node_work_ms: BTreeMap::from([ + (0, (30.0, BTreeSet::from([0, 1]))), + (1, (2.0, BTreeSet::from([0]))), + (2, (2.0, BTreeSet::from([1]))), + ]), + request_ms: vec![1.0, 1.0], + }; + let both = [0, 1]; + assert_eq!(c.work_ms(&both, &[1.0, 1.0]), 36.0); + assert_eq!(c.critical_path_ms(&both, &[]), 33.0); + assert_eq!(c.critical_path_ms(&both, &[(0, 1)]), 66.0); + assert_eq!(c.graham_ms(&both, &[1.0, 1.0], &[], Some(2)), 57.0); + assert_eq!(c.graham_ms(&both, &[1.0, 1.0], &[(0, 1)], Some(2)), 90.0); + assert_eq!(c.graham_ms(&both, &[1.0, 1.0], &[], None), 33.0); + assert_eq!(c.work_ms(&both, &[0.5, 0.5]), 33.0); + // No core left after the background: no plan. + assert_eq!(c.graham_ms(&both, &[1.0, 1.0], &[], Some(0)), f64::INFINITY); + let bounds = Bounds { + max_latency_ms: vec![None, None], + groups: vec![(both.to_vec(), 57.0)], + weight: vec![1.0, 1.0], + cpu_cores: Some(2), + interval_ms: 10_000.0, + ..Bounds::default() + }; + assert!(bounds.feasible(&c)); + let tighter = Bounds { + groups: vec![(both.to_vec(), 56.0)], + ..bounds.clone() + }; + assert!(!tighter.feasible(&c)); + let short_round = Bounds { + groups: vec![], + interval_ms: 23.0, + ..bounds + }; + // W / P_eff = 36 / 1.5 = 24 > 23. + assert!(!short_round.feasible(&c)); +} + +// --------------------------------------------------------------------------- +// Per query +// --------------------------------------------------------------------------- + +/// The per-query instance: q0 alone, scanned (about 30 ms of query time, +/// the cheaper plan) or on a chain (dearer, under 1 ms of query time). +async fn single_max() -> (Value, Vec) { + let settings = cost_model_1(table(100.0, 1_000_000.0, 0.0), json!({})); + let all = combinations(&[MAX], &settings).await; + (settings, all) +} + +/// L1. Cost model 1 keeps each query's query-time latency within its +/// `max_latency_ms`: for a bound above both plans, between them and below +/// both, the plan is the oracle's cheapest within the bound, and planning +/// fails naming `LatencyBoundExceeded` when no plan is. +#[tokio::test] +async fn l1_cost_model_1_respects_max_latency_ms() { + let (settings, all) = single_max().await; + let scan = &all[0]; + let chain = &all[1]; + assert!( + scan.cost_per_second < chain.cost_per_second && scan.latency_ms[0] > chain.latency_ms[0], + "instance: the cheaper scan is slower ({all:?})" + ); + for bound in sweep(&[scan.latency_ms[0], chain.latency_ms[0]]) { + let workload = workload(vec![every(MAX, 10_000, Some(bound))], json!([]), &[], 0).unwrap(); + let bounds = Bounds { + max_latency_ms: vec![Some(bound)], + weight: vec![1.0], + interval_ms: 10_000.0, + ..Bounds::default() + }; + assert_matches_oracle( + &format!("max_latency_ms {bound}"), + planned(&workload, &settings, true).await, + &bounds, + &all, + "LatencyBoundExceeded", + ); + } +} + +/// L2. A bound no plan meets is an error naming the query's latency bound, +/// not a plan over it. +#[tokio::test] +async fn l2_no_plan_within_the_bound_is_an_error() { + let (settings, all) = single_max().await; + let least = all + .iter() + .map(|c| c.latency_ms[0]) + .fold(f64::INFINITY, f64::min); + let workload = workload( + vec![every(MAX, 10_000, Some(least * 0.5))], + json!([]), + &[], + 0, + ) + .unwrap(); + let error = planned(&workload, &settings, true) + .await + .err() + .expect("no plan within half the least latency"); + assert!(error.contains("LatencyBoundExceeded"), "{error}"); +} + +/// L3. A bound every plan meets changes nothing: the plan and its cost are +/// those without the bound (no over-constraint, e.g. by counting the +/// freshness wait). +#[tokio::test] +async fn l3_a_loose_bound_changes_nothing() { + let (settings, all) = single_max().await; + let most = all.iter().map(|c| c.latency_ms[0]).fold(0.0, f64::max); + let free = planned( + &workload(vec![every(MAX, 10_000, None)], json!([]), &[], 0).unwrap(), + &settings, + true, + ) + .await + .unwrap(); + let loose = planned( + &workload( + vec![every(MAX, 10_000, Some(most * 2.0))], + json!([]), + &[], + 0, + ) + .unwrap(), + &settings, + true, + ) + .await + .unwrap(); + assert_eq!(free.plan.dag, loose.plan.dag); + assert_eq!( + free.report["cost_per_second"], + loose.report["cost_per_second"] + ); +} + +/// L4. The bound is on query-time latency only: the chain's freshness wait +/// (its 1 s refresh, in the report's `latency_ms`) is over the bound but +/// its `query_execution_ms` is within it, so the chain is selected rather +/// than no plan. +#[tokio::test] +async fn l4_the_freshness_wait_is_not_bounded() { + let (settings, all) = single_max().await; + let chain = &all[1]; + let scan = &all[0]; + let bound = (chain.latency_ms[0] + scan.latency_ms[0]) / 2.0; + let workload = workload(vec![every(MAX, 10_000, Some(bound))], json!([]), &[], 0).unwrap(); + let selected = planned(&workload, &settings, true) + .await + .unwrap_or_else(|error| panic!("{error}")); + assert!( + selected.query_ms(0, "latency_ms") > bound, + "instance: the chain's whole latency (freshness included) is over the bound" + ); + assert!(selected.query_reads_a_view(0), "the chain"); + assert!(selected.query_ms(0, "query_execution_ms") <= bound * (1.0 + TOLERANCE)); +} + +/// L5. As under cost model 3 (A18), an execution whose least query-time +/// latency is over every reader's bound is left out before the MILP and +/// counted in the selection's `executions_pruned_by_latency_bound`. +#[tokio::test] +async fn l5_executions_over_every_readers_bound_are_pruned() { + let (settings, all) = single_max().await; + let bound = (all[0].latency_ms[0] + all[1].latency_ms[0]) / 2.0; + let workload = workload(vec![every(MAX, 10_000, Some(bound))], json!([]), &[], 0).unwrap(); + let settings: CostInputs = serde_json::from_value(settings).unwrap(); + let capabilities = DeploymentCapabilities { + raw_data_retained: true, + ..Default::default() + }; + let models = PlanningModels::builtin() + .with_cost_inputs(&settings) + .with_deployment_capabilities(&capabilities); + let entries: Vec<_> = workload.query_workload.entries().collect(); + let data = workload.data_workload.clone().unwrap(); + let run = run_planning_stages_over( + lower_promql_roots(&workload).unwrap(), + &entries, + &data, + models, + ) + .unwrap(); + let (_, selection) = run.run.selection.as_ref().expect("a plan is selected"); + assert!( + selection.executions_pruned_by_latency_bound > 0, + "the scan's executions are left out" + ); +} + +/// L6. An optional query (a lightcone, never issued) needs no latency +/// bound: its own bound, tighter than any plan, does not make planning +/// fail, and the plan is the one without that bound. +#[tokio::test] +async fn l6_an_optional_query_has_no_latency_bound() { + let settings = cost_model_1(table(100.0, 1_000_000.0, 0.0), json!({})); + let with_bound = |bound| { + workload( + vec![every(MAX, 10_000, None), every(MIN, 10_000, bound)], + json!([]), + &[], + 1, + ) + .unwrap() + }; + let free = planned(&with_bound(None), &settings, true).await.unwrap(); + let bounded = planned(&with_bound(Some(1e-6)), &settings, true) + .await + .unwrap_or_else(|error| panic!("the optional query's bound is not enforced: {error}")); + assert_eq!(free.plan.dag, bounded.plan.dag); +} + +/// L7. An exclusive alternative's bound holds whenever it is requested, +/// whatever its fraction: q0 and q1 are the alternatives of one choice at +/// 0.5 each, q0 bounded between its chain and scan latencies, so q0 reads +/// its chain. +#[tokio::test] +async fn l7_an_alternatives_bound_ignores_its_fraction() { + let settings = cost_model_1(table(100.0, 1_000_000.0, 3_333.0), json!({})); + let alternatives = |bound| { + vec![ + alternative(MAX, "c", 0.5, bound), + alternative(MIN, "c", 0.5, None), + ] + }; + let all = combinations_of(alternatives(None), &[MAX, MIN], &settings).await; + let scanned = all.iter().find(|c| !c.on_chain[0]).unwrap().latency_ms[0]; + let chained = all.iter().find(|c| c.on_chain[0]).unwrap().latency_ms[0]; + assert!(chained < scanned, "instance ({all:?})"); + let bound = (scanned + chained) / 2.0; + let workload = workload(alternatives(Some(bound)), json!([]), &[], 0).unwrap(); + let selected = planned(&workload, &settings, true) + .await + .unwrap_or_else(|error| panic!("{error}")); + assert!(selected.query_reads_a_view(0), "q0 on its chain"); + assert!(selected.query_ms(0, "query_execution_ms") <= bound * (1.0 + TOLERANCE)); +} + +// --------------------------------------------------------------------------- +// Per group (Graham's bound) +// --------------------------------------------------------------------------- + +/// The group instance: q0 (`max`) and q1 (`min`), each scanned or chained; +/// both scanned share one scan; chains refresh at `state_ns` per state. +async fn max_and_min(state_ns: f64, min_ns: f64) -> (Vec, Vec) { + let table = table(100.0, state_ns, min_ns); + let all = combinations(&[MAX, MIN], &cost_model_1(table.clone(), json!({}))).await; + (table, all) +} + +/// Plan q0 and q1 under one group bound `bound_ms` with `dependencies` +/// and `cpu_cores`, against the oracle. +async fn check_group( + label: &str, + table: &[Value], + all: &[Combination], + bound_ms: f64, + dependencies: &[(usize, usize)], + cpu_cores: Option, +) { + let selected = match workload( + vec![every(MAX, 10_000, None), every(MIN, 10_000, None)], + json!([{"query_indices": [0, 1], "max_latency_ms": bound_ms}]), + dependencies, + 0, + ) { + Ok(workload) => planned(&workload, &with_cores(table.to_vec(), cpu_cores), true).await, + Err(error) => Err(error), + }; + let bounds = Bounds { + max_latency_ms: vec![None, None], + groups: vec![(vec![0, 1], bound_ms)], + dependencies: dependencies.to_vec(), + weight: vec![1.0, 1.0], + cpu_cores, + interval_ms: 10_000.0, + }; + assert_matches_oracle( + &format!("{label}: group bound {bound_ms} ms"), + selected, + &bounds, + all, + "LatencyBoundExceeded", + ); +} + +/// G1. Independent queries on 2 cores: for bounds between every +/// combination's Graham value, the plan is the oracle's. +#[tokio::test] +async fn g1_group_bound_matches_the_oracle() { + let (table, all) = max_and_min(1_000_000.0, 3_333.0).await; + let values: Vec = all + .iter() + .map(|c| c.graham_ms(&[0, 1], &[1.0, 1.0], &[], Some(2))) + .collect(); + let unconstrained = Bounds { + max_latency_ms: vec![None, None], + weight: vec![1.0, 1.0], + interval_ms: 10_000.0, + ..Bounds::default() + } + .cheapest(&all) + .unwrap() + .clone(); + let least = values.iter().copied().fold(f64::INFINITY, f64::min); + assert!( + unconstrained.graham_ms(&[0, 1], &[1.0, 1.0], &[], Some(2)) > least * (1.0 + 1e-3), + "instance: the bound must bind ({all:?})" + ); + for bound in sweep(&values) { + check_group("independent", &table, &all, bound, &[], Some(2)).await; + } +} + +/// G2. A dependency lengthens the critical path: with q0 -> q1, CP is +/// l0 + l1, so some bound that admits a plan of independent queries +/// admits a dearer one or none; the plan is the oracle's for each bound. +#[tokio::test] +async fn g2_a_dependent_runs_after_its_binder() { + let (table, all) = max_and_min(1_000_000.0, 3_333.0).await; + let dependencies = [(0, 1)]; + let independent: Vec = all + .iter() + .map(|c| c.graham_ms(&[0, 1], &[1.0, 1.0], &[], Some(2))) + .collect(); + let dependent: Vec = all + .iter() + .map(|c| c.graham_ms(&[0, 1], &[1.0, 1.0], &dependencies, Some(2))) + .collect(); + let mut values = independent.clone(); + values.extend(&dependent); + let bounds = sweep(&values); + let differs = bounds.iter().any(|&bound| { + let oracle = |deps: &[(usize, usize)]| { + Bounds { + max_latency_ms: vec![None, None], + groups: vec![(vec![0, 1], bound)], + dependencies: deps.to_vec(), + weight: vec![1.0, 1.0], + cpu_cores: Some(2), + interval_ms: 10_000.0, + } + .cheapest(&all) + .map(|c| c.on_chain.clone()) + }; + oracle(&[]) != oracle(&dependencies) + }); + assert!( + differs, + "instance: the dependency must change the oracle ({all:?})" + ); + for bound in bounds { + check_group("q0 -> q1", &table, &all, bound, &dependencies, Some(2)).await; + } +} + +/// G3. A node the group's queries share counts once in W_G: both scanned, +/// q0 and q1 read one scan; on 1 core, a bound between Graham's value with +/// the scan once and with it twice admits the shared plan, the cheapest. +#[tokio::test] +async fn g3_a_shared_node_counts_once_in_the_groups_work() { + let (table, all) = max_and_min(1_000_000.0, 3_333.0).await; + let scans = &all[0]; + assert_eq!(scans.on_chain, [false, false]); + let shared = scans + .node_work_ms + .values() + .filter(|(_, readers)| readers.len() == 2) + .map(|(work, _)| work) + .sum::(); + assert!(shared > 1.0, "instance: the scans share a node ({scans:?})"); + let once = scans.graham_ms(&[0, 1], &[1.0, 1.0], &[], Some(1)); + let twice = once + shared; + let bound = (once + twice) / 2.0; + let cheapest = all + .iter() + .min_by(|a, b| a.cost_per_second.total_cmp(&b.cost_per_second)) + .unwrap(); + assert_eq!( + cheapest.on_chain, + [false, false], + "instance: the scans are cheapest" + ); + check_group("shared scan", &table, &all, bound, &[], Some(1)).await; +} + +/// G4. The background takes cores from the queries: a chain's ingest and +/// precompute busy cores lower P_eff, so with the same bound the oracle's +/// plan changes with the deployment's cores; the plan follows it. +#[tokio::test] +async fn g4_background_cores_reduce_the_parallelism() { + let (table, all) = max_and_min(5_000_000.0, 3_333.0).await; + assert!( + all.iter().any(|c| c.background_cores > 0.3), + "instance: a chain plan keeps cores busy ({all:?})" + ); + let mut values = Vec::new(); + for cores in [1, 2, 4] { + values.extend( + all.iter() + .map(|c| c.graham_ms(&[0, 1], &[1.0, 1.0], &[], Some(cores))), + ); + } + // Ignoring the background must change the oracle for some bound and + // core count, or the test does not test it. + let without_background: Vec = all + .iter() + .cloned() + .map(|mut c| { + c.background_cores = 0.0; + c + }) + .collect(); + let bounds = sweep(&values); + let matters = bounds.iter().any(|&bound| { + [1, 2, 4].iter().any(|&cores| { + let b = Bounds { + max_latency_ms: vec![None, None], + groups: vec![(vec![0, 1], bound)], + weight: vec![1.0, 1.0], + cpu_cores: Some(cores), + interval_ms: 10_000.0, + ..Bounds::default() + }; + b.cheapest(&all).map(|c| c.on_chain.clone()) + != b.cheapest(&without_background).map(|c| c.on_chain.clone()) + }) + }); + assert!(matters, "instance: the background must matter ({all:?})"); + for cores in [1, 2, 4] { + for &bound in &bounds { + check_group( + &format!("{cores} cores"), + &table, + &all, + bound, + &[], + Some(cores), + ) + .await; + } + } +} + +/// G5. Without the deployment's core count, a group bound still holds its +/// critical path (`CP_G <= L_G`, true on any number of cores): bounds +/// between the combinations' CP select the oracle's plan. +#[tokio::test] +async fn g5_without_a_core_count_the_critical_path_is_bounded() { + let (table, all) = max_and_min(1_000_000.0, 3_333.0).await; + let values: Vec = all + .iter() + .map(|c| c.critical_path_ms(&[0, 1], &[])) + .collect(); + for bound in sweep(&values) { + check_group("no cores", &table, &all, bound, &[], None).await; + } +} + +/// G6. Exclusive alternatives in a group: at most one is requested per +/// round, so each counts in W_G at its fraction (a node they share at the +/// sum, at most 1) and CP takes the longest alternative; the plan is the +/// oracle's for bounds between the combinations' values. +#[tokio::test] +async fn g6_alternatives_count_in_the_groups_work_at_their_fractions() { + let table = table(100.0, 1_000_000.0, 3_333.0); + let alternatives = vec![ + alternative(MAX, "c", 0.5, None), + alternative(MIN, "c", 0.5, None), + ]; + let all = combinations_of( + alternatives.clone(), + &[MAX, MIN], + &cost_model_1(table.clone(), json!({})), + ) + .await; + let weight = [0.5, 0.5]; + let values: Vec = all + .iter() + .map(|c| c.graham_ms(&[0, 1], &weight, &[], Some(1))) + .collect(); + for bound in sweep(&values) { + let selected = match workload( + alternatives.clone(), + json!([{"query_indices": [0, 1], "max_latency_ms": bound}]), + &[], + 0, + ) { + Ok(workload) => planned(&workload, &with_cores(table.clone(), Some(1)), true).await, + Err(error) => Err(error), + }; + let bounds = Bounds { + max_latency_ms: vec![None, None], + groups: vec![(vec![0, 1], bound)], + weight: weight.to_vec(), + cpu_cores: Some(1), + interval_ms: 10_000.0, + ..Bounds::default() + }; + assert_matches_oracle( + &format!("alternatives: group bound {bound} ms"), + selected, + &bounds, + &all, + "LatencyBoundExceeded", + ); + } +} + +// --------------------------------------------------------------------------- +// Per round +// --------------------------------------------------------------------------- + +/// R1. Every round fits its interval: `W_round / P_eff <= interval`. With +/// scans of about 12 s of work per 10 s round, the plan for each core +/// count is the oracle's, and planning fails naming +/// `LatencyOverRepeatInterval` when no plan fits. +#[tokio::test] +async fn r1_every_round_fits_its_interval() { + let table = table(40_000.0, 20_000_000.0, 3_333.0); + let all = combinations(&[MAX, MIN], &cost_model_1(table.clone(), json!({}))).await; + let core_counts = [1, 2, 3, 4, 8]; + let unconstrained = all + .iter() + .min_by(|a, b| a.cost_per_second.total_cmp(&b.cost_per_second)) + .unwrap(); + let bounds_for = |cores| Bounds { + max_latency_ms: vec![None, None], + weight: vec![1.0, 1.0], + cpu_cores: Some(cores), + interval_ms: 10_000.0, + ..Bounds::default() + }; + assert!( + core_counts.iter().any(|&cores| bounds_for(cores) + .cheapest(&all) + .map(|c| c.on_chain.clone()) + != Some(unconstrained.on_chain.clone())), + "instance: the round bound must bind for some core count ({all:?})" + ); + let workload = workload( + vec![every(MAX, 10_000, None), every(MIN, 10_000, None)], + json!([]), + &[], + 0, + ) + .unwrap(); + for cores in core_counts { + assert_matches_oracle( + &format!("{cores} cores"), + planned(&workload, &with_cores(table.clone(), Some(cores)), true).await, + &bounds_for(cores), + &all, + "LatencyOverRepeatInterval", + ); + } +} + +// --------------------------------------------------------------------------- +// Regressions +// --------------------------------------------------------------------------- + +/// X1. Without latency bounds and without the core count, cost model 1's +/// plan is the oracle's cheapest combination (the bounds' rows add +/// nothing when there are none). +#[tokio::test] +async fn x1_without_bounds_the_plan_is_the_cheapest() { + let (table, all) = max_and_min(1_000_000.0, 3_333.0).await; + let workload = workload( + vec![every(MAX, 10_000, None), every(MIN, 10_000, None)], + json!([]), + &[], + 0, + ) + .unwrap(); + let selected = planned(&workload, &cost_model_1(table, json!({})), true) + .await + .unwrap(); + let cheapest = all + .iter() + .min_by(|a, b| a.cost_per_second.total_cmp(&b.cost_per_second)) + .unwrap(); + assert_eq!(on_chain_of(&selected, 2), cheapest.on_chain); +} + +/// X2. A dependency that names a query the workload does not have, or a +/// query depending on itself, is refused when the workload is validated. +#[tokio::test] +async fn x2_bad_dependencies_are_refused() { + for dependencies in [vec![(0, 2)], vec![(1, 1)], vec![(0, 1), (1, 0)]] { + let workload = workload( + vec![every(MAX, 10_000, None), every(MIN, 10_000, None)], + json!([]), + &dependencies, + 0, + ) + .expect("the field loads"); + assert!( + workload.validate().is_err(), + "{dependencies:?} must be refused" + ); + } +} diff --git a/crates/integration-tests/tests/main.rs b/crates/integration-tests/tests/main.rs index c94de7d2b..fdd90da0e 100644 --- a/crates/integration-tests/tests/main.rs +++ b/crates/integration-tests/tests/main.rs @@ -9,6 +9,7 @@ mod accuracy_at_query_roots; mod aggregate; mod binary_op; mod calibration_terms; +mod cm1_latency_bounds; mod crate_graph; mod default_cost_plan_ranking; mod deployment_exclusions; diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index bdde13a47..d4dd48ad4 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -455,6 +455,22 @@ async fn group_latency_lowers_to_query_indices() { ); } +/// Each dependent runs after its binder: the lowering lists the +/// dependency as entry indices (`QueryWorkload::query_dependencies`, which +/// Stage 3 reads for a group's critical path). +#[tokio::test] +async fn dependencies_lower_to_query_indices() { + let lowered = lowered(&format!("{Q1_TOP_10_HOSTS}\n{Q2_USERS_OF_Y}")).await; + let workload = serde_json::to_value(&lowered.workload.query_workload).unwrap(); + assert_eq!( + workload["query_dependencies"], + serde_json::json!([{ + "upstream": query_index(&lowered, "q1"), + "dependent": query_index(&lowered, "q2"), + }]) + ); +} + /// The reader of the probe on main: `count(*)` by user over `host IN $Y` /// folds the IN-list into an ingestion-time Scan without the guard. const Q2_COUNT_BY_USER: &str = "q2: SELECT user, count(*) AS c FROM auth