diff --git a/crates/cost/src/plan/execution_demand/mod.rs b/crates/cost/src/plan/execution_demand/mod.rs index ec61caa4e..71a07b1fe 100644 --- a/crates/cost/src/plan/execution_demand/mod.rs +++ b/crates/cost/src/plan/execution_demand/mod.rs @@ -47,9 +47,11 @@ pub struct ScheduleGroup { } /// One fixed (interval, phase) schedule's queries: each step in ms they -/// use with the longest span in ms at that step, the queries, and the -/// largest fraction of the schedule's times any of them is requested at. -type FixedSchedule = (BTreeMap, Vec, f64); +/// use with the longest span in ms at that step, the queries, the largest +/// fraction of the schedule's times any of them outside an exclusive +/// choice is requested at, and per exclusive choice the sum of its +/// alternatives' fractions. +type FixedSchedule = (BTreeMap, Vec, f64, BTreeMap); /// The groups of `queries` evaluated together (each a recurrence with its /// range evaluation), in the order [`evaluation_rate`] adds them: fixed @@ -65,7 +67,9 @@ type FixedSchedule = (BTreeMap, Vec, f64); /// whose instants coincide, e.g. every 20 s and every 30 s meet every 60 s); /// each estimated rate is its own group. /// A fixed group is computed at the largest `requested_fraction` of its -/// queries' times (all of them when none gives one). +/// queries' times (all of them when none gives one), the alternatives of +/// one exclusive choice (`exclusive_group`, one of them asked a time) +/// counting as one query at the sum of their fractions, at most 1. /// One-off, scheduled and unknown queries form one batch group: the most /// evaluations among them, spread over `non_repeating_query_horizon_seconds`. pub fn schedule_groups<'r>( @@ -88,6 +92,7 @@ pub fn schedule_groups<'r>( interval, evaluation_phase, requested_fraction, + exclusive_group, }) => { if interval.0 == 0 { return Err(AnalyticalCostError::InvalidRecurrence); @@ -98,13 +103,19 @@ pub fn schedule_groups<'r>( .map_or((u64::from(interval.0), 0), |range| { (range.step_ms, range.span_ms) }); - let (longest_span_ms_by_step_ms, members, fraction) = + let (longest_span_ms_by_step_ms, members, fraction, exclusive_sums) = by_schedule.entry((interval.0, phase_ms)).or_default(); // A node read by queries requested at different fractions of // one schedule's times is computed at the largest: the // others' requests (a dependent query's, below its upstream // requested every time) fall on times it is computed anyway. - *fraction = fraction.max(requested_fraction.unwrap_or(1.0)); + // Exclusive alternatives are asked at different times, so + // their fractions add. + let requested = requested_fraction.unwrap_or(1.0); + match exclusive_group { + Some(group) => *exclusive_sums.entry(group.clone()).or_default() += requested, + None => *fraction = fraction.max(requested), + } let longest_span_ms = longest_span_ms_by_step_ms.entry(step_ms).or_default(); *longest_span_ms = (*longest_span_ms).max(span_ms); members.push(query); @@ -139,12 +150,20 @@ pub fn schedule_groups<'r>( let mut groups: Vec = by_schedule .into_iter() .map( - |((interval_ms, _), (longest_span_ms_by_step_ms, queries, fraction))| ScheduleGroup { - queries, - evaluations_per_second: 1_000.0 / f64::from(interval_ms) - * fraction - * distinct_instants_per_request(&longest_span_ms_by_step_ms), - schedule: Schedule::FixedInterval, + |( + (interval_ms, _), + (longest_span_ms_by_step_ms, queries, fraction, exclusive_sums), + )| { + let fraction = exclusive_sums + .values() + .fold(fraction, |largest, &sum| largest.max(sum.min(1.0))); + ScheduleGroup { + queries, + evaluations_per_second: 1_000.0 / f64::from(interval_ms) + * fraction + * distinct_instants_per_request(&longest_span_ms_by_step_ms), + schedule: Schedule::FixedInterval, + } }, ) .collect(); diff --git a/crates/cost/src/plan/execution_demand/tests.rs b/crates/cost/src/plan/execution_demand/tests.rs index 34cf5dcd2..b1edd6c40 100644 --- a/crates/cost/src/plan/execution_demand/tests.rs +++ b/crates/cost/src/plan/execution_demand/tests.rs @@ -7,6 +7,7 @@ fn fixed(interval: u32, phase: u64) -> QueryRecurrence { interval: RepetitionInterval(interval), evaluation_phase: TimestampMs(phase), requested_fraction: None, + exclusive_group: None, }) } @@ -568,6 +569,7 @@ fn requested_fraction_scales_the_evaluation_rate() { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: Some(0.1), + exclusive_group: None, }); close( evaluation_rate([(&sampled, None)], 3600.0).unwrap(), @@ -579,3 +581,58 @@ fn requested_fraction_scales_the_evaluation_rate() { 1.0 / 10.0, ); } + +/// A fixed interval requested at `fraction` of its times, one alternative +/// of the exclusive choice `group` when given. +fn alternative(fraction: f64, group: Option<&str>) -> QueryRecurrence { + QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt { + interval: RepetitionInterval(10_000), + evaluation_phase: TimestampMs(0), + requested_fraction: Some(fraction), + exclusive_group: group.map(str::to_string), + }) +} + +/// Exclusive alternatives (one of them asked per round, each with its +/// fraction) add: a node both read is computed at 0.3 + 0.7 of the +/// rounds, not at the larger 0.7. Without the marker the readers are +/// nested (a dependent below its upstream) and the larger stays. +#[test] +fn exclusive_alternatives_add_their_fractions() { + let (a, b) = (alternative(0.3, Some("q1")), alternative(0.7, Some("q1"))); + close( + evaluation_rate([(&a, None), (&b, None)], 3600.0).unwrap(), + 1.0 / 10.0, + ); + let (a, b) = (alternative(0.3, None), alternative(0.7, None)); + close( + evaluation_rate([(&a, None), (&b, None)], 3600.0).unwrap(), + 0.7 / 10.0, + ); +} + +/// One choice's sum is one reader among the others on its schedule: the +/// largest of the sum (0.2 + 0.3) and an independent reader (0.4), or of +/// two choices' sums; a sum above 1 is capped at every round. +#[test] +fn an_exclusive_choice_is_one_reader_at_its_summed_fraction() { + let (a, b, other) = ( + alternative(0.2, Some("q1")), + alternative(0.3, Some("q1")), + alternative(0.4, None), + ); + close( + evaluation_rate([(&a, None), (&b, None), (&other, None)], 3600.0).unwrap(), + 0.5 / 10.0, + ); + let (c, d) = (alternative(0.25, Some("q2")), alternative(0.5, Some("q2"))); + close( + evaluation_rate([(&a, None), (&b, None), (&c, None), (&d, None)], 3600.0).unwrap(), + 0.75 / 10.0, + ); + let (e, f) = (alternative(0.6, Some("q3")), alternative(0.7, Some("q3"))); + close( + evaluation_rate([(&e, None), (&f, None)], 3600.0).unwrap(), + 1.0 / 10.0, + ); +} diff --git a/crates/devtools/tests/planner_fuzz.rs b/crates/devtools/tests/planner_fuzz.rs index 6037f5f9d..eaef6327d 100644 --- a/crates/devtools/tests/planner_fuzz.rs +++ b/crates/devtools/tests/planner_fuzz.rs @@ -391,6 +391,7 @@ fn summed_over_a_chain(labels: &[&str]) -> FuzzWorkload { interval: RepetitionInterval(60_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }; generated_workload(Language::Promql, vec![query], 1_000, 1_000) } diff --git a/crates/executor/tests/main.rs b/crates/executor/tests/main.rs index 957963c5a..b76066315 100644 --- a/crates/executor/tests/main.rs +++ b/crates/executor/tests/main.rs @@ -26,6 +26,7 @@ mod raw_scan; mod sql_relational_operators; mod state_column_updater; mod stored_tumbling_window_memory_limit; +mod streamed_copies; mod summary_projection; mod text_extremum_memory; mod thread_safety; diff --git a/crates/executor/tests/streamed_copies.rs b/crates/executor/tests/streamed_copies.rs new file mode 100644 index 000000000..e033aae17 --- /dev/null +++ b/crates/executor/tests/streamed_copies.rs @@ -0,0 +1,154 @@ +//! A plan that streams one copy of a query-time result per reader (two +//! exclusive alternatives over one hour of raw rows, each with its own +//! `TimeRange` instead of one held for both) runs: each copy reads the raw +//! data on its own, and each query's answer equals its answer planned +//! alone. + +use std::{collections::BTreeMap, sync::Arc}; + +use asap_executor::sources::InMemoryDataStore; +use asap_executor::{ + physical_planner::{compile, promql_rows}, + runtime::{Limits, RunContext, Scope}, + values::Batch, +}; +use asap_planner::{e2e_plan, FrontendInput, PlanningModels, UserInput}; +use futures::{executor::block_on, StreamExt}; +use planner_types::ir::operator::Source; +use planner_types::ir::NonASAPOp; +use planner_types::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPOperatorPayload}; +use planner_types::stages::Lifetime; +use planner_types::workload::PlanningWorkload; + +/// `queries` (each its text, requested fraction and exclusive choice) +/// every 60 s over the gauge `m`. +fn workload(queries: &[(&str, f64, Option<&str>)]) -> PlanningWorkload { + let entries: Vec = queries + .iter() + .map(|(query, fraction, group)| { + let mut demand = serde_json::json!({"interval": 60_000, "evaluation_phase": 0, + "requested_fraction": fraction}); + if let Some(group) = group { + demand["exclusive_group"] = serde_json::json!(group); + } + serde_json::json!({ + "query": query, + "demand": {"fixed_interval_at": demand}, + "requirements": {"max_latency_ms": null}, + "predictability": {"predictable": {"known_at": null}}, + }) + }) + .collect(); + serde_json::from_value(serde_json::json!({ + "query_workload": {"language": "promql", "repeating_queries": entries}, + "data_workload": { + "arrival": {"ingesting": {"rows_per_second": 1000.0}}, + "sources": {"m": {"series_count": 1000, "metric_type": "gauge", "sample_interval": 1000}}, + }, + })) + .unwrap() +} + +fn plan(workload: &PlanningWorkload) -> PhysicalASAPDAG { + block_on(e2e_plan(UserInput::new( + workload, + FrontendInput::Promql, + PlanningModels::builtin(), + ))) + .expect("the workload plans") + .plan +} + +/// `(instance, ts, value)` samples of `m`. +const SAMPLES: &[(&str, i64, f64)] = &[ + ("a", 3_000_000, 4.), + ("a", 3_100_000, 4.), + ("a", 3_200_000, 1.), + ("b", 3_300_000, 7.), + ("b", 3_400_000, 2.), + ("b", 3_500_000, 2.), +]; +const END_MS: i64 = 3_600_000; + +/// Each root's `(series, value)` rows in one query-time run of `dag` over +/// [`SAMPLES`], every raw data slot bound to them. +fn run_every_root(dag: &PhysicalASAPDAG) -> Vec> { + let roots: Vec = dag.roots.iter().map(|&root| root as u64).collect(); + let program = compile(dag, &[], &roots).unwrap(); + let mut store = InMemoryDataStore::default(); + let mut bound: Vec = Vec::new(); + for node in &dag.nodes { + let PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { source, .. }) = &node.payload + else { + continue; + }; + if bound.contains(source) { + continue; + } + bound.push(source.clone()); + let schema = Arc::new(node.output_schema.clone()); + let rows = SAMPLES + .iter() + .map(|(instance, at, value)| { + let labels = BTreeMap::from([ + ("__name__".to_string(), "m".to_string()), + ("instance".to_string(), instance.to_string()), + ]); + promql_rows::series_row(&schema, &labels, *at, *value).unwrap() + }) + .collect(); + let batch = Batch::try_new(schema.clone(), rows).unwrap(); + store = store + .with_raw_data(source.clone(), schema, vec![batch]) + .unwrap(); + } + let physical_dag = program.instantiate(Arc::new(store)).unwrap(); + let context = RunContext::new( + Scope::Query { + evaluation_time_ms: END_MS, + }, + Limits::default(), + ) + .unwrap(); + block_on(async { + let mut answers = Vec::new(); + for mut stream in physical_dag.execute(program.roots(), context).unwrap() { + let mut rows = BTreeMap::new(); + while let Some(batch) = stream.next().await { + for row in batch.unwrap().to_rows() { + let (value, key) = row.split_last().unwrap(); + rows.insert(format!("{key:?}"), format!("{value:?}")); + } + } + answers.push(rows); + } + answers + }) +} + +#[test] +fn streamed_copies_per_reader_run_and_answer_as_planned_alone() { + let queries = ["entropy_over_time(m[1h])", "l2_over_time(m[1h])"]; + let joint = plan(&workload(&[ + (queries[0], 0.4, Some("q")), + (queries[1], 0.6, Some("q")), + ])); + let time_ranges: Vec = joint + .nodes + .iter() + .filter(|node| { + matches!( + node.payload, + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::TimeRange { .. }) + ) + }) + .map(|node| node.lifetime) + .collect(); + assert_eq!(time_ranges, [Lifetime::None, Lifetime::None], "{joint:#?}"); + let answers = run_every_root(&joint); + for (index, query) in queries.iter().enumerate() { + let alone = run_every_root(&plan(&workload(&[(query, 1.0, None)]))); + assert!(!answers[index].is_empty(), "{query}"); + assert_eq!(answers[index], alone[0], "{query}"); + } +} diff --git a/crates/frontend-sil/src/lib.rs b/crates/frontend-sil/src/lib.rs index 668b3f326..74b33ea06 100644 --- a/crates/frontend-sil/src/lib.rs +++ b/crates/frontend-sil/src/lib.rs @@ -25,6 +25,17 @@ //! WHERE ts > $now - INTERVAL '1 hour' GROUP BY host REQUIRE EXACT; //! GROUP (q1, q2) LATENCY <= 150ms; //! ``` +//! +//! A weighted choice `{alternative: p, …}` in a query's text (an +//! uncertain operator or constant, its distribution mined from history) +//! makes the query one alternative query per alternative +//! ([`ExclusiveChoice`]), at most one asked per round: +//! +//! ```text +//! q4: SELECT host, {count: 0.4, approx_distinct: 0.6}(dst) FROM flows GROUP BY host +//! REQUIRE ERROR rel <= 0.05 DELTA 0.01; +//! q5: SELECT approx_percentile_cont(bytes, {0.5: 0.3, 0.99: 0.7}) FROM flows REQUIRE EXACT; +//! ``` use std::collections::BTreeMap; @@ -78,6 +89,29 @@ pub struct IntentQuery { /// `KEYS ~n`: the result rows per round the user declares, used only /// when the planner cannot bound them. pub declared_result_rows: Option, + /// The choice this query is one alternative of, when its text holds + /// a weighted choice (`{count: 0.4, approx_distinct: 0.6}(dst)`); + /// `None` for a query without one. + pub exclusive_choice: Option, +} + +/// Which alternative of a weighted choice a query is. A query written with +/// choices (`q1: SELECT {count: 0.4, approx_distinct: 0.6}(dst) …`) is +/// one query per combination of their alternatives (`q1#0`, `q1#1`), the +/// choices replaced by the alternatives' text: in each round at most one +/// of them is asked, each with its probability. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExclusiveChoice { + /// The id of the query as written (`q1`): the choice's name. + pub choice_query_id: String, + /// Its position among the choice's alternatives asked with a positive + /// probability (its id is `{choice_query_id}#{alternative_index}`). + pub alternative_index: usize, + /// The chance it is the alternative asked in a round, in (0, 1]: the + /// product of its alternatives' probabilities; the choice's add to at + /// most 1. + pub probability: f64, } /// One hole of a query's text. @@ -155,6 +189,10 @@ pub enum SilError { /// Two queries with one id. #[error("query id {query_id} is used twice")] DuplicateQueryId { query_id: String }, + /// A weighted choice whose probabilities are outside [0, 1], add to + /// more than 1 or are all 0, or one in a query that binds variables. + #[error("query {query_id}: {message}")] + InvalidChoice { query_id: String, message: String }, } /// Parse and check a SIL program: one or more intents. diff --git a/crates/frontend-sil/src/parse.rs b/crates/frontend-sil/src/parse.rs index d6b45ce78..c4bd550a6 100644 --- a/crates/frontend-sil/src/parse.rs +++ b/crates/frontend-sil/src/parse.rs @@ -6,6 +6,7 @@ //! [ WITH RATE number ] [ KEYS '~' integer ] //! sql REQUIRE accuracy [ ',' LATENCY '<=' duration ] //! binder ::= '$' name | '_' +//! choice ::= '{' text ':' number (',' text ':' number)* '}' (anywhere in sql) //! accuracy::= EXACT | ERROR (abs | rel | rank) '<=' number [ DELTA number ] //! group ::= GROUP '(' id (',' id)* ')' LATENCY '<=' duration //! duration::= number ('ms' | 's' | 'm' | 'h') @@ -13,14 +14,17 @@ //! //! Then the checks of [`check_intent`]: one binder per variable, every //! hole bound, no cycle (the queries are put in round order), each query -//! on one clock, triggers and groups valid. +//! on one clock, triggers and groups valid. A query with choices is first +//! made one query per combination of alternatives ([`alternatives_of`]). use std::collections::{BTreeMap, BTreeSet}; use asap_types::accuracy::{AccuracyMetric, AccuracyTarget}; use crate::lex::{statement_ends, tokens, Token, TokenKind, COMPARISONS}; -use crate::{Hole, HolePosition, Intent, IntentGroupLatencyBound, IntentQuery, SilError}; +use crate::{ + ExclusiveChoice, Hole, HolePosition, Intent, IntentGroupLatencyBound, IntentQuery, SilError, +}; /// The built-in evaluation time. pub(crate) const NOW: &str = "now"; @@ -81,17 +85,23 @@ pub(crate) fn parse_program(text: &str) -> Result, SilError> { } else { intent .queries - .push(parse_query(statement, &toks).map_err(|error| match error { + .extend(parse_query(statement, &toks).map_err(|error| match error { QueryError::Syntax(at, message) => syntax(at, &message), QueryError::Sil(error) => error, })?); } } + // Ids as written: a query with a choice once, whatever its alternatives. let mut seen = BTreeSet::new(); for query in intents.iter().flat_map(|intent| &intent.queries) { - if !seen.insert(query.query_id.clone()) { + let written_id = match &query.exclusive_choice { + Some(choice) if choice.alternative_index > 0 => continue, + Some(choice) => &choice.choice_query_id, + None => &query.query_id, + }; + if !seen.insert(written_id.clone()) { return Err(SilError::DuplicateQueryId { - query_id: query.query_id.clone(), + query_id: written_id.clone(), }); } } @@ -167,7 +177,9 @@ enum QueryError { Sil(SilError), } -fn parse_query(statement: &str, toks: &[Token]) -> Result { +/// The query of one statement, or one per combination of the alternatives +/// of its choices ([`alternatives_of`]). +fn parse_query(statement: &str, toks: &[Token]) -> Result, QueryError> { let syntax = |at: usize, message: &str| QueryError::Syntax(at, message.to_string()); let Some(id) = toks.first().filter(|t| t.kind == TokenKind::Word) else { return Err(syntax(0, "expected `id:`")); @@ -266,29 +278,193 @@ fn parse_query(statement: &str, toks: &[Token]) -> Result QueryError::Syntax(sql_start + at, message), + error => error, + })?; + if alternatives[0].1.is_some() && !output_variables.is_empty() { + return Err(QueryError::Sil(SilError::InvalidChoice { query_id, - message: "WITH RATE is the chance a dependent query is triggered; \ - a query reading no variable runs every round of its interval" + message: "a query with a choice binds no variable: its readers would not \ + know which alternative's result they read" .into(), })); } - Ok(IntentQuery { - query_id, - round_interval_ms, - output_variables, - sql_template, - holes, - accuracy, - max_latency_ms, - trigger_rate, - declared_result_rows, - }) + let mut queries = Vec::with_capacity(alternatives.len()); + for (index, (sql_template, probability)) in alternatives.into_iter().enumerate() { + let holes = holes_of(&query_id, &sql_template).map_err(QueryError::Sil)?; + if rate_given && holes.is_empty() { + return Err(QueryError::Sil(SilError::InvalidTrigger { + query_id, + message: "WITH RATE is the chance a dependent query is triggered; \ + a query reading no variable runs every round of its interval" + .into(), + })); + } + let exclusive_choice = probability.map(|probability| ExclusiveChoice { + choice_query_id: query_id.clone(), + alternative_index: index, + probability, + }); + queries.push(IntentQuery { + query_id: match &exclusive_choice { + Some(_) => format!("{query_id}#{index}"), + None => query_id.clone(), + }, + round_interval_ms, + output_variables: output_variables.clone(), + sql_template, + holes, + accuracy: accuracy.clone(), + max_latency_ms, + trigger_rate, + declared_result_rows, + exclusive_choice, + }); + } + Ok(queries) +} + +/// One weighted choice of a query's text: its byte range (`{` to `}`) and +/// each alternative asked with a positive probability, its text and +/// probability. +type Choice = (std::ops::Range, Vec<(String, f64)>); + +/// The most alternatives the choices of one query make, combined. +const MAX_ALTERNATIVES_PER_QUERY: usize = 1_000; + +/// `sql` with each combination of its choices' alternatives asked with a +/// positive probability (`{count: 0.4, approx_distinct: 0.6}(dst)`, the +/// first choice varying slowest), each choice replaced by the +/// alternative's text, with the combination's probability (the product); +/// `sql` itself with `None` when it has no choice. An alternative is the +/// text before an entry's last top-level `:`, its probability the number +/// after it; entries are split at top-level commas, so an alternative may +/// hold `f(a, b)`. Refused: an unclosed, nested or empty choice, a +/// probability that is not a number in [0, 1], a choice whose +/// probabilities add to more than 1, or no alternative asked. +fn alternatives_of(query_id: &str, sql: &str) -> Result)>, QueryError> { + let toks = tokens(sql); + let syntax = |at: usize| { + QueryError::Syntax( + at, + "expected a choice {alternative: probability, …}".to_string(), + ) + }; + let invalid = |message: String| { + QueryError::Sil(SilError::InvalidChoice { + query_id: query_id.to_string(), + message, + }) + }; + // Each choice's byte range and alternatives. + let mut choices: Vec = Vec::new(); + let mut i = 0; + while i < toks.len() { + if toks[i].is(sql, "}") { + return Err(syntax(toks[i].range.start)); + } + if !toks[i].is(sql, "{") { + i += 1; + continue; + } + let open = i; + let close = (open + 1..toks.len()) + .find(|&j| toks[j].is(sql, "}") || toks[j].is(sql, "{")) + .filter(|&j| toks[j].is(sql, "}")) + .ok_or_else(|| syntax(toks[open].range.start))?; + // Entries split at commas outside parentheses and brackets. + let mut entries: Vec<&[Token]> = Vec::new(); + let (mut depth, mut start) = (0i32, open + 1); + for j in open + 1..=close { + let token = &toks[j]; + if token.is(sql, "(") || token.is(sql, "[") { + depth += 1; + } else if token.is(sql, ")") || token.is(sql, "]") { + depth -= 1; + } else if j == close || (depth == 0 && token.is(sql, ",")) { + entries.push(&toks[start..j]); + start = j + 1; + } + } + let mut alternatives = Vec::with_capacity(entries.len()); + for entry in entries { + let mut depth = 0i32; + let mut colon = None; + for (j, token) in entry.iter().enumerate() { + if token.is(sql, "(") || token.is(sql, "[") { + depth += 1; + } else if token.is(sql, ")") || token.is(sql, "]") { + depth -= 1; + } else if depth == 0 && token.kind == TokenKind::Punctuation && token.is(sql, ":") { + colon = Some(j); + } + } + let at = entry + .first() + .map_or(toks[open].range.start, |t| t.range.start); + let colon = colon + .filter(|&j| j > 0 && j + 1 < entry.len()) + .ok_or_else(|| syntax(at))?; + let text = &sql[entry[0].range.start..entry[colon - 1].range.end]; + let probability_text = + sql[entry[colon].range.end..entry[entry.len() - 1].range.end].trim(); + let probability: f64 = probability_text.parse().map_err(|_| syntax(at))?; + if !(0.0..=1.0).contains(&probability) { + return Err(invalid(format!( + "the probability {probability_text} of `{text}` is not in [0, 1]" + ))); + } + alternatives.push((text.to_string(), probability)); + } + let total: f64 = alternatives.iter().map(|(_, p)| p).sum(); + if total > 1.0 + 1e-9 { + return Err(invalid(format!( + "the probabilities of a choice add to {total}, more than 1" + ))); + } + alternatives.retain(|(_, p)| *p > 0.0); + if alternatives.is_empty() { + return Err(invalid("no alternative of a choice is ever asked".into())); + } + choices.push((toks[open].range.start..toks[close].range.end, alternatives)); + i = close + 1; + } + if choices.is_empty() { + return Ok(vec![(sql.to_string(), None)]); + } + let combinations: usize = choices.iter().map(|(_, a)| a.len()).product(); + if combinations > MAX_ALTERNATIVES_PER_QUERY { + return Err(invalid(format!( + "its choices make {combinations} alternatives, more than {MAX_ALTERNATIVES_PER_QUERY}" + ))); + } + // Every combination, the first choice varying slowest. + let mut out = vec![(String::new(), 1.0, 0usize)]; + for (range, alternatives) in &choices { + out = out + .into_iter() + .flat_map(|(text, probability, at)| { + alternatives.iter().map(move |(alternative, p)| { + let mut text = text.clone(); + text.push_str(&sql[at..range.start]); + text.push_str(alternative); + (text, probability * p, range.end) + }) + }) + .collect(); + } + Ok(out + .into_iter() + .map(|(mut text, probability, at)| { + text.push_str(&sql[at..]); + (text, Some(probability)) + }) + .collect()) } fn parse_require(statement: &str, toks: &[Token]) -> Result<(AccuracyTarget, Option), String> { @@ -450,8 +626,19 @@ fn check_intent(intent: &mut Intent) -> Result<(), SilError> { .iter() .find(|id| !position.contains_key(id.as_str())) { + let has_a_choice = intent.queries.iter().any(|q| { + q.exclusive_choice + .as_ref() + .is_some_and(|choice| &choice.choice_query_id == unknown) + }); return Err(SilError::InvalidGroup { - message: format!("{unknown} is no query of intent {}", intent.name), + message: match has_a_choice { + true => format!( + "{unknown} has a choice, of which one alternative runs a round; \ + a group over it is not supported" + ), + false => format!("{unknown} is no query of intent {}", intent.name), + }, }); } let intervals: BTreeSet = group diff --git a/crates/frontend-sil/tests/sil.rs b/crates/frontend-sil/tests/sil.rs index 295c4213f..c1ad3a052 100644 --- a/crates/frontend-sil/tests/sil.rs +++ b/crates/frontend-sil/tests/sil.rs @@ -505,3 +505,201 @@ fn rejects_when() { other => panic!("{other:?}"), } } + +/// The alternatives' (query id, probability, SQL) of `intent`'s queries. +fn alternatives(intent: &Intent) -> Vec<(String, f64, String)> { + intent + .queries + .iter() + .map(|q| { + let choice = q.exclusive_choice.as_ref().expect("an alternative"); + assert_eq!( + q.query_id, + format!("{}#{}", choice.choice_query_id, choice.alternative_index) + ); + ( + q.query_id.clone(), + choice.probability, + q.sql_template.clone(), + ) + }) + .collect() +} + +/// An aggregate choice `{count: 0.4, approx_distinct: 0.6}(dst)` is two +/// alternative queries `q1#0` and `q1#1`, the choice replaced by each +/// alternative, each with its probability and the query's requirements. +#[test] +fn an_aggregate_choice_lowers_to_one_query_per_alternative() { + let intent = one(&intent( + "q1: SELECT host, {count: 0.4, approx_distinct: 0.6}(dst) AS v FROM flows GROUP BY host + REQUIRE ERROR rel <= 0.05 DELTA 0.01, LATENCY <= 50ms;", + )); + assert_eq!( + alternatives(&intent), + [ + ( + "q1#0".to_string(), + 0.4, + "SELECT host, count(dst) AS v FROM flows GROUP BY host".to_string() + ), + ( + "q1#1".to_string(), + 0.6, + "SELECT host, approx_distinct(dst) AS v FROM flows GROUP BY host".to_string() + ), + ] + ); + for query in &intent.queries { + assert_eq!( + query.exclusive_choice.as_ref().unwrap().choice_query_id, + "q1" + ); + assert_eq!(query.max_latency_ms, Some(50.0)); + assert_eq!( + query.accuracy, + AccuracyTarget::max_error(0.05) + .failure_probability(0.01) + .accuracy_metric(AccuracyMetric::Relative) + ); + } +} + +/// A choice in a constant position (`{0.5: 0.3, 0.99: 0.7}`), an +/// alternative with commas inside parentheses, and a second choice in one +/// query: every combination, its probability the product. +#[test] +fn constant_choices_combine_and_alternatives_may_hold_commas() { + let intent = one(&intent( + "q1: SELECT host, approx_percentile_cont(bytes, {0.5: 0.3, 0.99: 0.7}) AS v FROM flows + WHERE ts > $now - {INTERVAL '1 minute': 0.5, INTERVAL '1 hour': 0.5} GROUP BY host + REQUIRE EXACT; + q2: SELECT {count(DISTINCT dst): 0.25, approx_percentile_cont(bytes, 0.9): 0.75} FROM flows + REQUIRE EXACT;", + )); + let got = alternatives(&intent); + assert_eq!(got.len(), 6); + let q1: Vec<_> = got + .iter() + .filter(|(id, ..)| id.starts_with("q1#")) + .collect(); + let probabilities: Vec = q1.iter().map(|(_, p, _)| *p).collect(); + assert_eq!(probabilities, [0.15, 0.15, 0.35, 0.35]); + assert!( + q1[0].2.contains("approx_percentile_cont(bytes, 0.5)"), + "{}", + q1[0].2 + ); + assert!( + q1[0].2.contains("$now - INTERVAL '1 minute'"), + "{}", + q1[0].2 + ); + assert!(q1[1].2.contains("$now - INTERVAL '1 hour'"), "{}", q1[1].2); + assert!( + q1[2].2.contains("approx_percentile_cont(bytes, 0.99)"), + "{}", + q1[2].2 + ); + let q2: Vec<_> = got + .iter() + .filter(|(id, ..)| id.starts_with("q2#")) + .collect(); + assert_eq!(q2[0].2, "SELECT count(DISTINCT dst) FROM flows"); + assert_eq!( + q2[1].2, + "SELECT approx_percentile_cont(bytes, 0.9) FROM flows" + ); +} + +/// An alternative with probability 0 is never asked and not planned; a +/// choice with one alternative left is still marked. +#[test] +fn an_alternative_never_asked_is_dropped() { + let intent = one(&intent( + "q1: SELECT {count: 0, sum: 1}(bytes) FROM flows REQUIRE EXACT;", + )); + assert_eq!( + alternatives(&intent), + [( + "q1#0".to_string(), + 1.0, + "SELECT sum(bytes) FROM flows".to_string() + )] + ); +} + +/// A dependent query may carry a choice: each alternative reads the +/// variable and keeps the query's trigger rate. +#[test] +fn a_dependent_query_may_carry_a_choice() { + let intent = one(&intent( + "q1: ($Y, _) := SELECT host, count(*) AS c FROM flows GROUP BY host ORDER BY c DESC LIMIT 5 REQUIRE EXACT; + q2: WITH RATE 0.5 SELECT {count: 0.5, sum: 0.5}(bytes) FROM auth WHERE host IN $Y REQUIRE EXACT;", + )); + let dependents: Vec<_> = intent + .queries + .iter() + .filter(|q| q.query_id.starts_with("q2#")) + .collect(); + assert_eq!(dependents.len(), 2); + for query in dependents { + assert_eq!(query.trigger_rate, 0.5); + assert_eq!(query.input_variables(), ["Y"]); + assert_eq!(query.holes.len(), 1); + } +} + +/// Refused: probabilities adding to more than 1, a probability that is +/// not a number in [0, 1], no alternative asked, a choice in a query that +/// binds variables (which alternative's result would bind them), and a +/// group over a query with a choice (only one alternative runs a round). +#[test] +fn ill_formed_choices_are_refused() { + for text in [ + "q1: SELECT {count: 0.6, sum: 0.6}(bytes) FROM flows REQUIRE EXACT;", + "q1: SELECT {count: 1.5}(bytes) FROM flows REQUIRE EXACT;", + "q1: SELECT {count: -0.5, sum: 0.5}(bytes) FROM flows REQUIRE EXACT;", + "q1: SELECT {count: 0}(bytes) FROM flows REQUIRE EXACT;", + "q1: ($Y) := SELECT {max: 0.5, min: 0.5}(host) AS h FROM flows REQUIRE EXACT;", + ] { + assert!( + matches!(error(&intent(text)), SilError::InvalidChoice { .. }), + "{text}: {:?}", + parse_intents(&intent(text)) + ); + } + for text in [ + "q1: SELECT {count 0.5, sum: 0.5}(bytes) FROM flows REQUIRE EXACT;", + "q1: SELECT {count: 0.5, sum: 0.5(bytes) FROM flows REQUIRE EXACT;", + ] { + assert!( + matches!(error(&intent(text)), SilError::Syntax { .. }), + "{text}: {:?}", + parse_intents(&intent(text)) + ); + } + assert!(matches!( + error(&intent( + "q1: SELECT {count: 0.5, sum: 0.5}(bytes) FROM flows REQUIRE EXACT; + q2: SELECT count(*) FROM auth REQUIRE EXACT; + GROUP (q1, q2) LATENCY <= 10ms;" + )), + SilError::InvalidGroup { .. } + )); +} + +/// A query with a choice keeps its written id: another query with that id +/// is refused, as for queries without choices. +#[test] +fn a_choice_query_and_a_plain_query_may_not_share_an_id() { + let text = intent( + "q1: SELECT count(*) FROM flows REQUIRE EXACT; + q1: SELECT {count: 0.5, sum: 0.5}(bytes) FROM flows REQUIRE EXACT;", + ); + assert!( + matches!(error(&text), SilError::DuplicateQueryId { ref query_id } if query_id == "q1"), + "{:?}", + parse_intents(&text) + ); +} diff --git a/crates/integration-tests/tests/joint_search_equivalence.rs b/crates/integration-tests/tests/joint_search_equivalence.rs index cc5106ea3..b2e8ed4e0 100644 --- a/crates/integration-tests/tests/joint_search_equivalence.rs +++ b/crates/integration-tests/tests/joint_search_equivalence.rs @@ -38,6 +38,7 @@ fn workload_of(queries: &[(&str, u32)], accuracy: AccuracyTarget) -> PlanningWor interval: RepetitionInterval(interval), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: QueryRequirements { accuracy: accuracy.clone(), @@ -270,6 +271,7 @@ fn example2() -> (PlanningWorkload, asap_frontend_sql::SqlCatalog) { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: QueryRequirements { accuracy: AccuracyTarget::max_error(epsilon).failure_probability(delta), diff --git a/crates/integration-tests/tests/production_rollup_workloads.rs b/crates/integration-tests/tests/production_rollup_workloads.rs index 5bd7c9205..6f4a83bd4 100644 --- a/crates/integration-tests/tests/production_rollup_workloads.rs +++ b/crates/integration-tests/tests/production_rollup_workloads.rs @@ -44,6 +44,7 @@ fn entry(accuracy: &AccuracyTarget, interval_ms: u32) -> QueryWorkloadEntry { interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }), range_evaluation: None, } diff --git a/crates/integration-tests/tests/stage3_objective.rs b/crates/integration-tests/tests/stage3_objective.rs index d9d272573..1d6b7f68a 100644 --- a/crates/integration-tests/tests/stage3_objective.rs +++ b/crates/integration-tests/tests/stage3_objective.rs @@ -1209,3 +1209,99 @@ fn the_objective_is_the_plan_cost_on_a_group_left_join_of_two_hour_increases() { objective_and_plan_cost(&w, &CostInputs::default(), true), ); } + +/// `query` every 60 s requested at `fraction` of the rounds, one +/// alternative of the exclusive choice `group` when given. +fn alternative(query: &str, fraction: f64, group: Option<&str>) -> serde_json::Value { + let mut entry = requested(query, 60_000, None); + entry["demand"]["fixed_interval_at"]["requested_fraction"] = serde_json::json!(fraction); + if let Some(group) = group { + entry["demand"]["fixed_interval_at"]["exclusive_group"] = serde_json::json!(group); + } + entry +} + +/// The plan's `TimeRange` nodes, each with its lifetime and how many of +/// the plan's queries read it. +fn time_ranges_with_lifetime_and_readers(plan: &PhysicalASAPDAG) -> Vec<(Lifetime, usize)> { + plan.nodes + .iter() + .filter(|node| { + matches!( + node.payload, + PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::TimeRange { .. }) + ) + }) + .map(|node| { + let readers = plan + .roots + .iter() + .filter(|&&root| { + let mut pending = vec![root]; + let mut seen = vec![root]; + while let Some(id) = pending.pop() { + if id == node.id { + return true; + } + for edge in plan.edges.iter().filter(|edge| edge.consumer == id) { + if !seen.contains(&edge.producer) { + seen.push(edge.producer); + pending.push(edge.producer); + } + } + } + false + }) + .count(); + (node.lifetime, readers) + }) + .collect() +} + +/// Two exclusive alternatives (exact entropy at 0.4 of the rounds, exact +/// L2 at 0.6, one asked per round) over one hour of raw `m`: a shared +/// `TimeRange` held for both runs every round anyway (0.4 + 0.6) and holds +/// an hour of rows, so the plan streams one `TimeRange` per alternative, +/// each read once and held by none; Stage 3's objective is `plan_cost` of +/// that plan. +#[test] +fn exclusive_alternatives_stream_one_time_range_each() { + let w = over_m(vec![ + alternative("entropy_over_time(m[1h])", 0.4, Some("q")), + alternative("l2_over_time(m[1h])", 0.6, Some("q")), + ]); + let (plan, objective_and_plan_cost) = + selected_plan_objective_and_plan_cost(&w, &CostInputs::default(), true); + assert_equal("exclusive alternatives", objective_and_plan_cost); + assert_eq!( + time_ranges_with_lifetime_and_readers(&plan), + [(Lifetime::None, 1), (Lifetime::None, 1)], + "{plan:#?}" + ); +} + +/// Two queries every round over one hour of raw `m`, not alternatives of +/// a choice: no streamed copy per query is offered (the plan is the one +/// selected before copies existed), the objective is `plan_cost` of the +/// plan, and a streamed `TimeRange` is read by one query. +#[test] +fn the_objective_is_the_plan_cost_with_a_streamed_copy_per_reader() { + for rows_per_second in [1_000.0, 100_000.0] { + let mut w = over_m(vec![ + alternative("entropy_over_time(m[1h])", 1.0, None), + alternative("l2_over_time(m[1h])", 1.0, None), + ]); + if let Some(data) = w.data_workload.as_mut() { + data.arrival = serde_json::from_value( + serde_json::json!({"ingesting": {"rows_per_second": rows_per_second}}), + ) + .unwrap(); + } + let (plan, objective_and_plan_cost) = + selected_plan_objective_and_plan_cost(&w, &CostInputs::default(), true); + assert_equal("streamed or held", objective_and_plan_cost); + for (lifetime, readers) in time_ranges_with_lifetime_and_readers(&plan) { + assert!(lifetime != Lifetime::None || readers == 1, "{plan:#?}"); + } + } +} diff --git a/crates/planner/src/intent.rs b/crates/planner/src/intent.rs index f1c4fb4a7..dd37888f0 100644 --- a/crates/planner/src/intent.rs +++ b/crates/planner/src/intent.rs @@ -6,8 +6,8 @@ use std::collections::BTreeMap; use asap_frontend_sil::{ - sql_without_order_by_and_limit, HolePosition, Intent, IntentGroupLatencyBound, IntentQuery, - SilError, + sql_without_order_by_and_limit, ExclusiveChoice, HolePosition, Intent, IntentGroupLatencyBound, + IntentQuery, SilError, }; use asap_frontend_sql::lower_sql; use asap_stage0_memo::memo_of_queries; @@ -126,6 +126,15 @@ pub struct IntentRoundQuery { pub skip_if_empty: bool, pub accuracy: AccuracyTarget, pub max_latency_ms: Option, + /// The weighted choice it is one alternative of (`q1#0` of `q1`'s + /// `{count: 0.4, approx_distinct: 0.6}`), with the chance it is the + /// one asked in a round; `None` for a query without a choice. A round + /// issues at most one alternative of a choice (the one the user asks). + /// The plan was costed with this query requested at that chance (times + /// its trigger rate and its upstreams' fraction), its choice's + /// alternatives exclusive (`RepeatedDemand::FixedIntervalAt::exclusive_group`). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub exclusive_choice: Option, } /// A variable a query reads and where it comes from. @@ -261,15 +270,23 @@ pub async fn lower_intents( data: &DataWorkload, options: &IntentPlanningOptions, ) -> Result { + // A query with a choice is overridden by its written id (`q3` for + // `q3#0`, `q3#1`). + let written_id = |query: &IntentQuery| -> String { + query.exclusive_choice.as_ref().map_or_else( + || query.query_id.clone(), + |choice| choice.choice_query_id.clone(), + ) + }; for (query_id, rate) in &options.trigger_rate_overrides { let known = intents .iter() .flat_map(|intent| &intent.queries) - .any(|query| &query.query_id == query_id); + .any(|query| &written_id(query) == query_id); let dependent = intents .iter() .flat_map(|intent| &intent.queries) - .any(|query| &query.query_id == query_id && !query.holes.is_empty()); + .any(|query| &written_id(query) == query_id && !query.holes.is_empty()); if !known || !dependent || !(*rate > 0.0 && *rate <= 1.0) { return Err(IntentError::InvalidRateOverride(format!( "{query_id}: {rate} (a query of the intent reading a variable, a rate in (0, 1])" @@ -295,12 +312,18 @@ pub async fn lower_intents( .collect(); let own_rate = options .trigger_rate_overrides - .get(&query_id) + .get(&written_id(query)) .copied() .unwrap_or(query.trigger_rate); // Dependents of one upstream fire together, so the smallest - // upstream fraction bounds a query's (decision D7). + // upstream fraction bounds a query's (decision D7); an + // alternative of a choice is asked at its probability of that. + let choice_probability = query + .exclusive_choice + .as_ref() + .map_or(1.0, |choice| choice.probability); let requested_fraction = own_rate + * choice_probability * upstream .iter() .map(|binder| binder.requested_fraction) @@ -432,6 +455,10 @@ pub async fn lower_intents( sql, interval_ms, (requested_fraction < 1.0).then_some(requested_fraction), + query + .exclusive_choice + .as_ref() + .map(|choice| choice.choice_query_id.clone()), QueryRequirements { accuracy: query.accuracy.clone(), max_latency_ms: query.max_latency_ms, @@ -454,6 +481,7 @@ pub async fn lower_intents( rate: own_rate, accuracy: query.accuracy.clone(), max_latency_ms: query.max_latency_ms, + exclusive_choice: query.exclusive_choice.clone(), }); } for bound in &intent.group_latency_bounds { @@ -612,11 +640,13 @@ fn binder_column( } /// A query every `interval_ms` at phase 0, known in advance, requested at -/// `requested_fraction` of those times (`None`: all). +/// `requested_fraction` of those times (`None`: all), one alternative of +/// the exclusive choice `exclusive_group` when given. fn repeating_entry( sql: String, interval_ms: u32, requested_fraction: Option, + exclusive_group: Option, requirements: QueryRequirements, ) -> RepeatingEntry { RepeatingEntry { @@ -625,6 +655,7 @@ fn repeating_entry( interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(0), requested_fraction, + exclusive_group, }, requirements, predictability: Predictability::Predictable { known_at: None }, @@ -648,6 +679,7 @@ async fn lightcone_entry( sql, interval_ms, None, + None, QueryRequirements { accuracy: query.accuracy.clone(), max_latency_ms: None, diff --git a/crates/planner/tests/e2e_plan.rs b/crates/planner/tests/e2e_plan.rs index 63da6a9c8..a5bc5fbe1 100644 --- a/crates/planner/tests/e2e_plan.rs +++ b/crates/planner/tests/e2e_plan.rs @@ -189,6 +189,7 @@ async fn lowers_repeating_sql_entries_too() { interval: RepetitionInterval(60_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: approximate_for("approx_percentile_cont"), predictability: Predictability::Unknown, @@ -315,6 +316,7 @@ async fn each_plan_carries_its_selected_root() { interval: RepetitionInterval(60_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: approximate(), predictability: Predictability::Unknown, diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index a2369ba88..20ae97253 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -303,6 +303,7 @@ fn schedule_of(lowered: &LoweredIntents, query_id: &str) -> (u32, Option) { interval: RepetitionInterval(ms), evaluation_phase, requested_fraction, + .. }) => { assert_eq!(evaluation_phase.0, 0); (*ms, *requested_fraction) @@ -960,3 +961,50 @@ async fn binder_of_an_unnamed_expression_is_refused() { "{result:?}" ); } + +/// The exclusive choice of `query_id`'s lowered entry. +fn exclusive_group_of(lowered: &LoweredIntents, query_id: &str) -> Option { + let entries: Vec<_> = lowered.workload.query_workload.entries().collect(); + match &entries[query_index(lowered, query_id)].recurrence { + QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt { + exclusive_group, .. + }) => exclusive_group.clone(), + other => panic!("{other:?}"), + } +} + +/// A choice lowers to one entry per alternative, requested at its +/// probability times the query's own fraction (here a dependent at rate +/// 0.5) and marked with the choice, and to one round query per +/// alternative saying which choice it is one alternative of. +#[tokio::test] +async fn a_choice_lowers_to_exclusive_alternatives() { + let lowered = lowered( + "q1: ($Y, _) := SELECT host, count(*) AS c FROM flows GROUP BY host ORDER BY c DESC LIMIT 5 REQUIRE EXACT; + q2: SELECT host, {count: 0.25, approx_distinct: 0.75}(dst) AS v FROM flows GROUP BY host REQUIRE EXACT; + q3: WITH RATE 0.5 SELECT {count: 0.5, sum: 0.5}(bytes) FROM auth WHERE host IN $Y REQUIRE EXACT;", + ) + .await; + assert_eq!(exclusive_group_of(&lowered, "q1"), None); + for (query_id, choice, fraction) in [ + ("q2#0", "q2", 0.25), + ("q2#1", "q2", 0.75), + ("q3#0", "q3", 0.25), + ("q3#1", "q3", 0.25), + ] { + assert_eq!( + exclusive_group_of(&lowered, query_id).as_deref(), + Some(choice) + ); + assert!( + close(schedule_of(&lowered, query_id).1, Some(fraction)), + "{query_id}" + ); + let round = round_query(&lowered, query_id); + let alternative = round.exclusive_choice.as_ref().expect("an alternative"); + assert_eq!(alternative.choice_query_id, choice); + } + assert!(text_of(&lowered, "q2#1").contains("approx_distinct(dst)")); + assert_eq!(round_query(&lowered, "q3#1").rate, 0.5); + assert!(round_query(&lowered, "q1").exclusive_choice.is_none()); +} diff --git a/crates/planner/tests/summary_sharing.rs b/crates/planner/tests/summary_sharing.rs index ce7e77cb3..9550a4bcf 100644 --- a/crates/planner/tests/summary_sharing.rs +++ b/crates/planner/tests/summary_sharing.rs @@ -50,6 +50,7 @@ fn repeating(query: &str, epsilon: f64) -> RepeatingEntry { interval: RepetitionInterval(600_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: requirements(query, epsilon), predictability: Predictability::Unknown, diff --git a/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs b/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs index 3c9275622..6f145d71a 100644 --- a/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs +++ b/crates/stage1-pass2-reuse-candidates/src/test_fixtures.rs @@ -58,6 +58,7 @@ pub fn entry(interval_ms: u32) -> QueryWorkloadEntry { interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }), range_evaluation: None, } diff --git a/crates/stage3-plan-selection/src/cost.rs b/crates/stage3-plan-selection/src/cost.rs index c98cd907e..6713b6d55 100644 --- a/crates/stage3-plan-selection/src/cost.rs +++ b/crates/stage3-plan-selection/src/cost.rs @@ -952,6 +952,10 @@ pub(crate) fn execution_quantities( /// ([`asap_cost::plan::execution_demand::executions_per_second`]); in the /// ingestion pipeline, once per second of arriving rows. /// +/// In a context streaming for one query alone +/// (`SelectableExecutions::streamed_for_query`), as often as that query +/// runs. +/// /// Example: queries every 10 s, 10 s and 30 s reaching a scan: 1/10 per /// second in the 10 s context, 1/30 in the 30 s one. pub(crate) fn executions_per_second( @@ -978,25 +982,35 @@ pub(crate) fn executions_per_second( .collect() }; let rate = match selectable.context(execution.context) { - ExecutionContext::Evaluation { grid } => match selectable.request_anchor(execution.context) - { - Some((at, queries)) => context_executions_per_second( - Some(at), - entries_of(queries.iter().map(|query| query.0).collect()), - answer_cache, - non_repeating_query_horizon_seconds, - ), - None => context_executions_per_second( - None, - entries_of(queries_of_context( - grid.period_ms, - selectable.readers_of(group_of(execution.candidate), |anchor| anchor.is_none()), - entries, - )), + ExecutionContext::Evaluation { grid } => { + // The queries the execution runs for: a copy context's one + // query, a request context's queries, or those on the grid + // whose walk reaches its group. + let (at, queries) = match ( + selectable.streamed_for_query(execution.context), + selectable.request_anchor(execution.context), + ) { + (Some(query), _) => (None, vec![query.0]), + (None, Some((at, queries))) => { + (Some(at), queries.iter().map(|query| query.0).collect()) + } + (None, None) => ( + None, + queries_of_context( + grid.period_ms, + selectable + .readers_of(group_of(execution.candidate), |anchor| anchor.is_none()), + entries, + ), + ), + }; + context_executions_per_second( + at, + entries_of(queries), answer_cache, non_repeating_query_horizon_seconds, - ), - }, + ) + } ExecutionContext::Materialized(m) => { let properties = physical.physical_candidates[m.0].physical_properties; rate_of_materialized( diff --git a/crates/stage3-plan-selection/src/cost/tests.rs b/crates/stage3-plan-selection/src/cost/tests.rs index 15f554e0b..c8981260c 100644 --- a/crates/stage3-plan-selection/src/cost/tests.rs +++ b/crates/stage3-plan-selection/src/cost/tests.rs @@ -166,6 +166,7 @@ fn no_execution_reading_a_producer_costs_less_than_nothing() { interval: RepetitionInterval(DAY_MS as u32), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }), range_evaluation: None, }; diff --git a/crates/stage3-plan-selection/src/milp/model/tests.rs b/crates/stage3-plan-selection/src/milp/model/tests.rs index 813047d2f..a545bf883 100644 --- a/crates/stage3-plan-selection/src/milp/model/tests.rs +++ b/crates/stage3-plan-selection/src/milp/model/tests.rs @@ -162,11 +162,29 @@ fn every(interval_ms: u32) -> QueryWorkloadEntry { interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }), range_evaluation: None, } } +/// `count` queries on a 10 s grid, the alternatives of one exclusive +/// choice, each asked in `1 / count` of the rounds. +fn alternatives_every_10s(count: usize) -> Vec { + (0..count) + .map(|_| { + let mut entry = every(10_000); + entry.recurrence = QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt { + interval: RepetitionInterval(10_000), + evaluation_phase: TimestampMs(0), + requested_fraction: Some(1.0 / count as f64), + exclusive_group: Some("choice".into()), + }); + entry + }) + .collect() +} + /// What the MILP is built over for `physical` and `entries`, with every /// execution of candidate `v` costing `w[v]`, every edge from `u` to `c` /// `edge_costs[(u, c)]` (0 when missing) and candidate `v` retaining at @@ -388,6 +406,128 @@ fn a_query_time_result_that_is_not_materialized_has_one_consumer_per_context() { assert_eq!(solved.unwrap_err(), SelectionMilpError::Infeasible); } +/// The scan of `a_query_time_result_that_is_not_materialized_has_one_consumer_per_context` +/// read by two alternatives of one exclusive choice: each may read its own +/// streamed copy of the scan's `None` candidate (cost 1 each, in its copy +/// context), so the optimum streams twice (2) rather than read the +/// `OneEvaluation` candidate (cost 10), holds it when that costs 1.5, and +/// without it still has a plan. +#[test] +fn alternatives_may_each_read_a_streamed_copy_of_a_shared_result() { + let mut memo = empty_memo(); + let m = scan(&mut memo); + let last_5m = range(&mut memo, 300, m); + let last_1m = range(&mut memo, 60, m); + query(&mut memo, last_5m, None); + query(&mut memo, last_1m, None); + let physical = physical( + memo, + &[ + (own_candidate(m), NONE), + (own_candidate(last_5m), NONE), + (own_candidate(last_1m), NONE), + (own_candidate(m), ONE_EVALUATION), + ], + ); + let entries = alternatives_every_10s(2); + let (solved, _) = solve(&physical, &entries, &[1.0, 1.0, 1.0, 10.0], &[], &[]); + assert_eq!(candidates(&solved.unwrap()), vec![0, 0, 1, 2]); + let (solved, _) = solve(&physical, &entries, &[1.0, 1.0, 1.0, 1.5], &[], &[]); + assert_eq!(candidates(&solved.unwrap()), vec![1, 2, 3]); + let without_one_evaluation = PhysicalASAPMemoCandidates::new( + physical.logical_candidates.clone(), + physical.physical_candidates[..3].to_vec(), + physical + .edges() + .map(|(_, edge)| edge) + .filter(|edge| edge.producer_candidate_id.0 < 3) + .collect(), + vec![], + ); + let (solved, _) = solve( + &without_one_evaluation, + &entries, + &[1.0, 1.0, 1.0], + &[], + &[], + ); + assert_eq!(candidates(&solved.unwrap()), vec![0, 0, 1, 2]); +} + +/// An alternative and a query outside its choice reading one scan: no +/// streamed copy is offered (not every reader is an alternative of one +/// choice), so the scan is shared as before: its `OneEvaluation` +/// candidate read by both (cost 10) is the only plan. +#[test] +fn a_result_also_read_outside_the_choice_gets_no_streamed_copy() { + let mut memo = empty_memo(); + let m = scan(&mut memo); + let last_5m = range(&mut memo, 300, m); + let last_1m = range(&mut memo, 60, m); + query(&mut memo, last_5m, None); + query(&mut memo, last_1m, None); + let physical = physical( + memo, + &[ + (own_candidate(m), NONE), + (own_candidate(last_5m), NONE), + (own_candidate(last_1m), NONE), + (own_candidate(m), ONE_EVALUATION), + ], + ); + let mut entries = alternatives_every_10s(2); + entries[1] = every(10_000); + let (solved, _) = solve(&physical, &entries, &[1.0, 1.0, 1.0, 10.0], &[], &[]); + assert_eq!(candidates(&solved.unwrap()), vec![1, 2, 3]); +} + +/// Without exclusive alternatives no streamed copy is offered: `m[5m]` and +/// `m[10m]` every 10 s and the same two every 20 s, the scan offered +/// `None` and `OneEvaluation`, have exactly the executions they had +/// before copies existed (one per candidate and context), and the 20 s +/// context still shares the 10 s one's variables. +#[test] +fn without_alternatives_no_copy_is_offered_and_equivalent_contexts_stay_shared() { + let mut memo = empty_memo(); + let m = scan(&mut memo); + let last_5m = range(&mut memo, 300, m); + let last_10m = range(&mut memo, 600, m); + for _ in 0..2 { + query(&mut memo, last_5m, None); + query(&mut memo, last_10m, None); + } + let physical = physical( + memo, + &[ + (own_candidate(m), NONE), + (own_candidate(m), ONE_EVALUATION), + (own_candidate(last_5m), NONE), + (own_candidate(last_10m), NONE), + ], + ); + let entries = vec![every(10_000), every(10_000), every(20_000), every(20_000)]; + let (selectable, costs) = + selection_inputs(&physical, &entries, &[1.0, 2.0, 1.0, 1.0], &[], &[]); + // Two contexts, each running all four candidates once. + assert_eq!(selectable.executions().len(), 8); + let inputs = SelectionInputs { + physical: &physical, + entries: &entries, + selectable: &selectable, + costs: &costs, + kept_query_time_results: None, + answer_cache: None, + }; + let shared = copies_in_equivalent_contexts(&inputs, &[true; 8], None); + let copies = shared + .original_of_execution + .iter() + .enumerate() + .filter(|(index, original)| index != *original) + .count(); + assert_eq!(copies, 4); +} + /// The same two queries every 10 s and every 15 s: two contexts, each /// running the scan that is not materialized once for its own query /// (cost 1 each), cheaper than one `OneEvaluation` run (cost 10), which diff --git a/crates/stage3-plan-selection/src/selectable.rs b/crates/stage3-plan-selection/src/selectable.rs index 9445da815..91d95614b 100644 --- a/crates/stage3-plan-selection/src/selectable.rs +++ b/crates/stage3-plan-selection/src/selectable.rs @@ -28,6 +28,20 @@ //! - An input of a consumer in $\kappa$ reads a producer, over an admissible //! edge, only where the producer delivers on $\kappa$ //! (`PhysicalASAPMemoCandidates::delivers_on`). +//! - A query-time result that is not materialized (`None`) is read once +//! per run, so in a root evaluation context it has one reader. Where +//! several queries of the context read its group, a consumer read by one +//! query $q$ alone (or $q$'s output), when every reader of the group is +//! an alternative of one exclusive choice +//! (`RepeatedDemand::FixedIntervalAt::exclusive_group`), may instead read +//! a copy of it streamed for $q$ alone, in a context of its own, $\kappa_q$ (same +//! grid, run as often as $q$ is requested): one streamed copy per reader +//! instead of one result held for all. In $\kappa_q$ a `None` input is +//! $q$'s copy too; any other input is the one of $\kappa$. +//! Example: entropy and L2 over one hour of raw rows, two alternatives +//! asked 0.4 and 0.6 of the rounds: each reads its own streamed +//! `TimeRange` (0.4 and 0.6 of the rounds) instead of one `TimeRange` +//! held in memory every round. use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; @@ -43,7 +57,9 @@ use asap_types::stages::{ query_reads, EvaluationGrid, ExecutionContext, ExecutionContextId, MemoGroupId, PhysicalASAPMemoCandidates, PhysicalCandidateId, PhysicalEdgeId, }; -use asap_types::workload::{greatest_common_divisor, QueryWorkloadEntry}; +use asap_types::workload::{ + greatest_common_divisor, QueryRecurrence, QueryWorkloadEntry, RepeatedDemand, +}; /// A query, by index in the workload. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -128,8 +144,13 @@ pub(crate) struct SelectableExecutions { /// evaluation grid that reach it), ascending; `None` for any other /// context. request_anchor_of_context: Vec, - /// The id of each context with its request anchor. - context_ids: HashMap<(ExecutionContext, RequestAnchor), ExecutionContextId>, + /// Per context, by [`ExecutionContextId`]: the query a copy context + /// $\kappa_q$ streams its `None` results for, alone; `None` for any + /// other context. + streamed_for_query_of_context: Vec>, + /// The id of each context with its request anchor and the query it + /// streams for. + context_ids: HashMap<(ExecutionContext, RequestAnchor, Option), ExecutionContextId>, /// Per memo group, each (query, anchor) whose walk over the memo reaches /// it ([`query_reads`]): the anchor of the `TimeShift` above it it is /// read per request below, `None` in the query's evaluation context. @@ -187,6 +208,7 @@ impl SelectableExecutions { reads_of_group: reads_of_groups(physical, entries, outputs), contexts: Vec::new(), request_anchor_of_context: Vec::new(), + streamed_for_query_of_context: Vec::new(), context_ids: HashMap::new(), executions: Vec::new(), edges: Vec::new(), @@ -220,31 +242,50 @@ impl SelectableExecutions { { continue; } - if let Some(execution) = - selectable.execution_reading(physical, context, PhysicalCandidateId(v), false) - { - executions.push(execution); - if reached.insert(execution) { - pending.push(execution); + let v = PhysicalCandidateId(v); + let copy = selectable.streamed_copy_context(physical, entries, context, query, v); + for context in std::iter::once(context).chain(copy) { + if let Some(execution) = + selectable.execution_reading(physical, context, v, false) + { + executions.push(execution); + if reached.insert(execution) { + pending.push(execution); + } } } } answering.push((query, executions)); } let mut edges = BTreeSet::new(); + // Copies are offered only to alternatives of an exclusive choice: + // a workload without one keeps its executions (and the MILP's + // symmetry reduction over equivalent contexts) unchanged. + let any_alternative = + (0..entries.len()).any(|query| exclusive_group_of(entries, QueryId(query)).is_some()); while let Some(consumer) = pending.pop() { let c = consumer.candidate; let context = selectable.input_context(physical, entries, consumer); + // The one query reading the consumer, when its inputs may be + // copies streamed for that query alone. + let only_reader = (any_alternative && context == consumer.context) + .then(|| selectable.only_reader(physical, entries, consumer)) + .flatten(); for input in 0..physical.input_count(c) { for &edge in physical.admissible_edges_into(c, input) { let u = physical.edge(edge).producer_candidate_id; let off_the_grid = physical.operator(c).reads_input_off_the_grid(input); - if let Some(producer) = - selectable.execution_reading(physical, context, u, off_the_grid) - { - edges.insert((consumer, edge, producer)); - if reached.insert(producer) { - pending.push(producer); + let copy = only_reader.filter(|_| !off_the_grid).and_then(|query| { + selectable.streamed_copy_context(physical, entries, context, query, u) + }); + for context in std::iter::once(context).chain(copy) { + if let Some(producer) = + selectable.execution_reading(physical, context, u, off_the_grid) + { + edges.insert((consumer, edge, producer)); + if reached.insert(producer) { + pending.push(producer); + } } } } @@ -289,18 +330,103 @@ impl SelectableExecutions { &mut self, context: ExecutionContext, request_anchor: RequestAnchor, + ) -> ExecutionContextId { + self.context_id_streamed_for(context, request_anchor, None) + } + + /// [`Self::context_id`] of the context streaming for `streamed_for` + /// alone ([`Self::streamed_for_query_of_context`]) when given. + fn context_id_streamed_for( + &mut self, + context: ExecutionContext, + request_anchor: RequestAnchor, + streamed_for: Option, ) -> ExecutionContextId { let id = ExecutionContextId(self.contexts.len()); *self .context_ids - .entry((context, request_anchor.clone())) + .entry((context, request_anchor.clone(), streamed_for)) .or_insert_with(|| { self.contexts.push(context); self.request_anchor_of_context.push(request_anchor); + self.streamed_for_query_of_context.push(streamed_for); id }) } + /// The queries of root evaluation context `context` whose walk + /// reaches `group` there. + fn readers_in_context( + &self, + entries: &[QueryWorkloadEntry], + context: ExecutionContextId, + group: MemoGroupId, + ) -> Vec { + let ExecutionContext::Evaluation { grid } = self.contexts[context.0] else { + return Vec::new(); + }; + queries_of_context( + grid.period_ms, + self.readers_of(group, |anchor| anchor.is_none()), + entries, + ) + } + + /// The one query reading `consumer`, an execution in a root evaluation + /// context, there; `None` when it has several or none. + fn only_reader( + &self, + physical: &PhysicalASAPMemoCandidates, + entries: &[QueryWorkloadEntry], + consumer: Execution, + ) -> Option { + if !self.is_root_evaluation_context(consumer.context) { + return None; + } + let group = physical.physical_candidates[consumer.candidate.0] + .logical_candidate_id + .group; + match self.readers_in_context(entries, consumer.context, group)[..] { + [query] => Some(QueryId(query)), + _ => None, + } + } + + /// $\kappa_q$, the context streaming for `query` alone in root + /// evaluation context `context`, when `u` is a query-time result that + /// is not materialized (one reader per context) whose group several + /// queries read there, all alternatives of `query`'s exclusive choice + /// ([`exclusive_group_of`]): `query`'s own streamed copy of `u` runs + /// in it. + fn streamed_copy_context( + &mut self, + physical: &PhysicalASAPMemoCandidates, + entries: &[QueryWorkloadEntry], + context: ExecutionContextId, + query: QueryId, + u: PhysicalCandidateId, + ) -> Option { + let candidate = &physical.physical_candidates[u.0]; + let choice = exclusive_group_of(entries, query)?; + if !candidate.physical_properties.has_one_reader_per_context() + || !self.is_root_evaluation_context(context) + { + return None; + } + // Only where every reader is an alternative of `query`'s choice: + // any other reader keeps the hold-or-share choice of before. + let readers = + self.readers_in_context(entries, context, candidate.logical_candidate_id.group); + if readers.len() < 2 + || readers + .iter() + .any(|&reader| exclusive_group_of(entries, QueryId(reader)) != Some(choice)) + { + return None; + } + Some(self.context_id_streamed_for(self.contexts[context.0], None, Some(query))) + } + /// The execution of producer `u` a consumer whose inputs run in /// `context` reads, when `u` delivers on it (an input read off the grid /// on purpose, `read_off_the_grid`, only when stored at ingestion @@ -335,6 +461,12 @@ impl SelectableExecutions { self.context_id(ExecutionContext::Materialized(u), None) } else if properties.timing() == ExecutionTiming::IngestionTime { self.context_id(ExecutionContext::EVERY_ARRIVING_ROW, None) + } else if self.streamed_for_query_of_context[context.0].is_some() + && !properties.has_one_reader_per_context() + { + // In a copy context only `None` results are the query's own + // copies; a held one is the root evaluation context's. + self.context_id(self.contexts[context.0], None) } else { context }; @@ -447,6 +579,13 @@ impl SelectableExecutions { pub(crate) fn is_root_evaluation_context(&self, id: ExecutionContextId) -> bool { matches!(self.contexts[id.0], ExecutionContext::Evaluation { .. }) && self.request_anchor_of_context[id.0].is_none() + && self.streamed_for_query_of_context[id.0].is_none() + } + + /// For a context $\kappa_q$ that streams `None` results for one query + /// alone, that query; `None` for any other context. + pub(crate) fn streamed_for_query(&self, id: ExecutionContextId) -> Option { + self.streamed_for_query_of_context[id.0] } /// The context with id `id`. @@ -567,3 +706,18 @@ fn reads_of_groups( entries, ) } + +/// The exclusive choice query `query` is one alternative of +/// (`RepeatedDemand::FixedIntervalAt::exclusive_group`), if any: asked in +/// some rounds only, never with its choice's other alternatives, so a +/// result only they share is better streamed once per alternative than +/// held. +fn exclusive_group_of(entries: &[QueryWorkloadEntry], query: QueryId) -> Option<&str> { + match entries.get(query.0).map(|entry| &entry.recurrence) { + Some(QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt { + exclusive_group: Some(group), + .. + })) => Some(group.as_str()), + _ => None, + } +} diff --git a/crates/types/src/workload/planning.rs b/crates/types/src/workload/planning.rs index 6060cad51..2d4a5250c 100644 --- a/crates/types/src/workload/planning.rs +++ b/crates/types/src/workload/planning.rs @@ -95,6 +95,14 @@ pub enum WorkloadError { /// Bad input: a fixed interval's `requested_fraction` outside (0, 1]. #[error("requested fraction must be in (0, 1], got {0}")] InvalidRequestedFraction(f64), + /// Bad input: the alternatives of exclusive choice `exclusive_group` + /// are on different intervals or phases, or their requested fractions + /// (an omitted one being 1) add to more than 1. + #[error("exclusive choice {exclusive_group}: {reason}")] + InvalidExclusiveGroup { + exclusive_group: String, + reason: String, + }, /// Bad input: a query's `max_latency_ms` that is negative or not /// finite. #[error("response latency must be finite and non-negative, got {0} ms")] @@ -191,6 +199,7 @@ mod tests { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: QueryRequirements { accuracy: AccuracyTarget::max_error(0.01).failure_probability(0.001), diff --git a/crates/types/src/workload/query.rs b/crates/types/src/workload/query.rs index 77ebb3664..eeb0aadbd 100644 --- a/crates/types/src/workload/query.rs +++ b/crates/types/src/workload/query.rs @@ -1,5 +1,7 @@ //! The query workload: each query, its requirements and its recurrence. +use std::collections::BTreeMap; + use crate::accuracy::AccuracyTarget; use crate::deployment_capabilities::FinalResultsCache; use crate::ir::operator::AtModifier; @@ -160,6 +162,7 @@ pub struct DemandEstimate { /// interval: RepetitionInterval(10_000), /// evaluation_phase: TimestampMs(0), /// requested_fraction: None, +/// exclusive_group: None, /// }; /// let scheduled = RepeatedDemand::Scheduled(vec![ /// TimestampMs(100_000), @@ -183,6 +186,16 @@ pub enum RepeatedDemand { /// fraction; the evaluation times (the grid) are unchanged. #[serde(default, skip_serializing_if = "Option::is_none")] requested_fraction: Option, + /// The name of the exclusive choice this query is one alternative + /// of; `None`: none. At each evaluation time at most one query of + /// a choice is requested (an uncertain operator mined from + /// history: `count` or `distinct` or `quantile(0.99)`), each with + /// probability its `requested_fraction`, so a node several of them + /// read is computed at the sum of their fractions (at most 1), + /// not the largest. The queries of one choice share their interval + /// and phase, and their fractions add to at most 1. + #[serde(default, skip_serializing_if = "Option::is_none")] + exclusive_group: Option, }, Scheduled(Vec), EstimatedRate(DemandEstimate), @@ -206,6 +219,7 @@ pub enum RepeatedDemand { /// interval: RepetitionInterval(60_000), /// evaluation_phase: TimestampMs(0), /// requested_fraction: None, +/// exclusive_group: None, /// }, /// ); /// ``` @@ -388,6 +402,7 @@ pub struct BatchEntry { /// interval: RepetitionInterval(10_000), /// evaluation_phase: TimestampMs(0), /// requested_fraction: None, +/// exclusive_group: None, /// }, /// requirements: QueryRequirements::default(), /// predictability: Predictability::Predictable { known_at: None }, @@ -429,6 +444,7 @@ pub struct RepeatingEntry { /// interval: RepetitionInterval(10_000), /// evaluation_phase: TimestampMs(0), /// requested_fraction: None, +/// exclusive_group: None, /// }, /// ), /// range_evaluation: None, @@ -625,8 +641,39 @@ impl QueryWorkload { } pub(crate) fn validate(&self) -> Result<(), WorkloadError> { + // Per exclusive choice, its alternatives' (interval, phase) and + // the sum of their fractions. + let mut exclusive_groups: BTreeMap = BTreeMap::new(); for entry in self.entries() { validate_entry(&entry)?; + if let QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt { + interval, + evaluation_phase, + requested_fraction, + exclusive_group: Some(group), + }) = &entry.recurrence + { + let schedule = (interval.0, evaluation_phase.0 % u64::from(interval.0)); + let (first_schedule, sum) = exclusive_groups + .entry(group.clone()) + .or_insert((schedule, 0.0)); + let invalid = |reason: String| WorkloadError::InvalidExclusiveGroup { + exclusive_group: group.clone(), + reason, + }; + if *first_schedule != schedule { + return Err(invalid(format!( + "alternatives every {} ms at phase {} ms and every {} ms at phase {} ms", + first_schedule.0, first_schedule.1, schedule.0, schedule.1 + ))); + } + *sum += requested_fraction.unwrap_or(1.0); + if *sum > 1.0 + 1e-9 { + return Err(invalid(format!( + "the alternatives' requested fractions add to {sum}, more than 1" + ))); + } + } } let queries = self.entries().count(); for (group, bound) in self.group_latency_bounds.iter().enumerate() { @@ -708,7 +755,8 @@ mod tests { repeated(RepeatedDemand::FixedIntervalAt { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), - requested_fraction: None + requested_fraction: None, + exclusive_group: None, }) .fixed_interval_ms(), Some(10_000) @@ -717,7 +765,8 @@ mod tests { repeated(RepeatedDemand::FixedIntervalAt { interval: RepetitionInterval(60_000), evaluation_phase: TimestampMs(5_000), - requested_fraction: None + requested_fraction: None, + exclusive_group: None, }) .fixed_interval_ms(), Some(60_000) @@ -726,7 +775,8 @@ mod tests { repeated(RepeatedDemand::FixedIntervalAt { interval: RepetitionInterval(0), evaluation_phase: TimestampMs(0), - requested_fraction: None + requested_fraction: None, + exclusive_group: None, }) .fixed_interval_ms(), None @@ -795,6 +845,7 @@ mod tests { interval: RepetitionInterval(0), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: QueryRequirements::default(), predictability: Predictability::Predictable { known_at: None }, @@ -850,6 +901,7 @@ mod tests { interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(phase_ms), requested_fraction: None, + exclusive_group: None, }) }; // Refreshes every 30 s at phase 0 and steps every 60 s: evaluations @@ -955,6 +1007,7 @@ mod tests { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }, requirements: QueryRequirements::default(), predictability: Predictability::Predictable { known_at: None }, @@ -1065,6 +1118,7 @@ mod tests { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: Some(0.1), + exclusive_group: None, }); assert_eq!(sampled.fixed_interval_ms(), Some(10_000)); assert_eq!(sampled.evaluation_grid_ms(None), Some(10_000)); @@ -1072,6 +1126,7 @@ mod tests { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }; assert_eq!( serde_json::to_value(&every).unwrap(), @@ -1087,6 +1142,72 @@ mod tests { )); } + /// An exclusive choice's marker reads and writes in a fixed interval's + /// JSON, left out when `None`. + #[test] + fn exclusive_group_reads_and_writes_in_the_json() { + let json = serde_json::json!({"fixed_interval_at": { + "interval": 10_000, "evaluation_phase": 0, + "requested_fraction": 0.3, "exclusive_group": "q1"}}); + let read: RepeatedDemand = serde_json::from_value(json.clone()).unwrap(); + assert!(matches!( + &read, + RepeatedDemand::FixedIntervalAt { exclusive_group: Some(group), .. } if group == "q1" + )); + assert_eq!(serde_json::to_value(&read).unwrap(), json); + } + + /// The alternatives of one exclusive choice: refused when their + /// fractions add to more than 1 (an omitted fraction is 1) or when + /// they are on different intervals or phases; accepted otherwise. + #[test] + fn an_exclusive_choice_is_refused_above_one_or_across_schedules() { + let alternative = |interval: u32, phase: u64, fraction: Option| RepeatingEntry { + query: Query("alternative".into()), + demand: RepeatedDemand::FixedIntervalAt { + interval: RepetitionInterval(interval), + evaluation_phase: TimestampMs(phase), + requested_fraction: fraction, + exclusive_group: Some("q1".into()), + }, + requirements: QueryRequirements::default(), + predictability: Predictability::Unknown, + range_evaluation: None, + }; + let validate = |entries: Vec| { + let mut workload = base_workload(); + workload.repeating_queries = Some(entries); + workload.validate() + }; + assert_eq!( + validate(vec![ + alternative(10_000, 0, Some(0.4)), + alternative(10_000, 0, Some(0.6)), + ]), + Ok(()) + ); + for refused in [ + vec![ + alternative(10_000, 0, Some(0.6)), + alternative(10_000, 0, Some(0.6)), + ], + vec![ + alternative(10_000, 0, None), + alternative(10_000, 0, Some(0.1)), + ], + vec![ + alternative(10_000, 0, Some(0.4)), + alternative(60_000, 0, Some(0.6)), + ], + vec![ + alternative(10_000, 0, Some(0.4)), + alternative(10_000, 5_000, Some(0.6)), + ], + ] { + assert!(validate(refused.clone()).is_err(), "{refused:?}"); + } + } + /// K3: a requested fraction outside (0, 1] is refused. #[test] fn requested_fraction_out_of_range_is_refused() { @@ -1098,6 +1219,7 @@ mod tests { interval: RepetitionInterval(10_000), evaluation_phase: TimestampMs(0), requested_fraction: Some(fraction), + exclusive_group: None, }, requirements: QueryRequirements::default(), predictability: Predictability::Unknown, @@ -1135,6 +1257,7 @@ mod tests { interval: RepetitionInterval(interval_ms), evaluation_phase: TimestampMs(0), requested_fraction: None, + exclusive_group: None, }) }; let dashboard = entry(every(15_000), Some(hour_at_15s));