diff --git a/crates/devtools/src/lib.rs b/crates/devtools/src/lib.rs index 5b4df3181..d9b5d5dcf 100644 --- a/crates/devtools/src/lib.rs +++ b/crates/devtools/src/lib.rs @@ -45,6 +45,7 @@ pub fn lower_promql_with_sample_interval( }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( asap_frontend_promql::promql_metric_names(query)?, diff --git a/crates/devtools/src/planner_fuzz/mod.rs b/crates/devtools/src/planner_fuzz/mod.rs index 64e3757f1..4917aac3a 100644 --- a/crates/devtools/src/planner_fuzz/mod.rs +++ b/crates/devtools/src/planner_fuzz/mod.rs @@ -166,6 +166,7 @@ impl FuzzWorkload { query_batch: None, repeating_queries: Some(self.queries.iter().map(|q| q.entry.clone()).collect()), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(self.data.clone()), } diff --git a/crates/executor/tests/current_series_heap.rs b/crates/executor/tests/current_series_heap.rs index 7830d02fd..5a6774a1f 100644 --- a/crates/executor/tests/current_series_heap.rs +++ b/crates/executor/tests/current_series_heap.rs @@ -322,6 +322,7 @@ fn population_fixture_compiles_with_dynamic_identity() { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( ["m".to_string()], diff --git a/crates/executor/tests/deployment_computation.rs b/crates/executor/tests/deployment_computation.rs index 174913a22..ce6bffd6a 100644 --- a/crates/executor/tests/deployment_computation.rs +++ b/crates/executor/tests/deployment_computation.rs @@ -39,6 +39,7 @@ fn lower_with(query: &str, accuracy: AccuracyTarget) -> Rc Rc { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( asap_frontend_promql::promql_metric_names(query).unwrap_or_default(), diff --git a/crates/frontend-metricsql/tests/lowering_semantics.rs b/crates/frontend-metricsql/tests/lowering_semantics.rs index eec38fce9..cb20e01da 100644 --- a/crates/frontend-metricsql/tests/lowering_semantics.rs +++ b/crates/frontend-metricsql/tests/lowering_semantics.rs @@ -29,6 +29,7 @@ fn workload(language: QueryLanguage, query: &str) -> PlanningWorkload { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload { arrival: DataArrival::Unknown, diff --git a/crates/frontend-promql/src/lib.rs b/crates/frontend-promql/src/lib.rs index 95fc9511c..9f6d086aa 100644 --- a/crates/frontend-promql/src/lib.rs +++ b/crates/frontend-promql/src/lib.rs @@ -147,6 +147,7 @@ mod tests { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload { arrival: DataArrival::Unknown, diff --git a/crates/frontend-promql/tests/promql_lowering.rs b/crates/frontend-promql/tests/promql_lowering.rs index 0622e9de9..12cce1ab1 100644 --- a/crates/frontend-promql/tests/promql_lowering.rs +++ b/crates/frontend-promql/tests/promql_lowering.rs @@ -1142,6 +1142,7 @@ fn batch_lowers_each_entry_and_reads_per_query_accuracy() { ]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, // Range selectors only: no sample interval is needed. data_workload: None, @@ -1166,6 +1167,7 @@ fn batch_rejects_non_promql_language() { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: None, }; diff --git a/crates/frontend-promql/tests/support.rs b/crates/frontend-promql/tests/support.rs index 299bf4779..8af398e7b 100644 --- a/crates/frontend-promql/tests/support.rs +++ b/crates/frontend-promql/tests/support.rs @@ -26,6 +26,7 @@ pub fn workload(query: &str, accuracy: AccuracyTarget) -> PlanningWorkload { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( asap_frontend_promql::promql_metric_names(query).unwrap_or_default(), diff --git a/crates/integration-tests/src/lib.rs b/crates/integration-tests/src/lib.rs index 98af742ba..69ccfdddd 100644 --- a/crates/integration-tests/src/lib.rs +++ b/crates/integration-tests/src/lib.rs @@ -57,6 +57,7 @@ pub mod fixtures { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( asap_frontend_promql::promql_metric_names(query).unwrap_or_default(), diff --git a/crates/integration-tests/tests/joint_search_equivalence.rs b/crates/integration-tests/tests/joint_search_equivalence.rs index cc5106ea3..cc6834129 100644 --- a/crates/integration-tests/tests/joint_search_equivalence.rs +++ b/crates/integration-tests/tests/joint_search_equivalence.rs @@ -49,6 +49,7 @@ fn workload_of(queries: &[(&str, u32)], accuracy: AccuracyTarget) -> PlanningWor .collect(), ), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload { arrival: DataArrival::Ingesting { @@ -281,6 +282,7 @@ fn example2() -> (PlanningWorkload, asap_frontend_sql::SqlCatalog) { .collect(), ), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, // SQL needs no sample interval; `flows` holds 10,000,000 groups // (one per source IP). diff --git a/crates/integration-tests/tests/pass1_candidates.rs b/crates/integration-tests/tests/pass1_candidates.rs index 3764a38cd..344031e21 100644 --- a/crates/integration-tests/tests/pass1_candidates.rs +++ b/crates/integration-tests/tests/pass1_candidates.rs @@ -66,6 +66,7 @@ fn promql(query: &str) -> QueryRoot { }]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload::sampled_every( asap_frontend_promql::promql_metric_names(query).unwrap_or_default(), @@ -398,6 +399,7 @@ async fn avg_as_sum_and_count( &without_candidates(physical, own), &[single_query_entry(accuracy())], &[], + 0, &declared_data(&exact), &asap_cost::CostInputs::default(), asap_types::deployment_capabilities::FinalResultsCache::NotCached, diff --git a/crates/planner/src/installable/mod.rs b/crates/planner/src/installable/mod.rs index 8b587b04a..1243607b8 100644 --- a/crates/planner/src/installable/mod.rs +++ b/crates/planner/src/installable/mod.rs @@ -290,12 +290,20 @@ impl From for InstallablePlanError { /// installation compiles the selected plan, and one the executor cannot run /// returns `PlanError::Installable` with /// [`InstallablePlanError::MaterializedViewNotExecutable`] or -/// [`InstallablePlanError::QueryRunNotExecutable`]. +/// [`InstallablePlanError::QueryRunNotExecutable`]. The workload's optional +/// queries (`QueryWorkload::optional_query_count`, the last ones) are not +/// answered: the plan, its query texts and its report cover the others. pub async fn plan_installable( input: UserInput<'_>, ) -> Result<(InstallablePlan, SelectedPlanReport), PlanError> { let capabilities = executor_summaries_when_unrestricted(input.models.deployment_capabilities); - let entries: Vec<_> = input.workload.query_workload.entries().collect(); + // The plan answers the queries but the optional ones, which come last. + let query_workload = &input.workload.query_workload; + let answered = query_workload + .entries() + .count() + .saturating_sub(query_workload.optional_query_count); + let entries: Vec<_> = query_workload.entries().take(answered).collect(); let models = input.models.with_deployment_capabilities(&capabilities); let input = UserInput { workload: input.workload, diff --git a/crates/planner/src/intent.rs b/crates/planner/src/intent.rs index f1c4fb4a7..9c53b9026 100644 --- a/crates/planner/src/intent.rs +++ b/crates/planner/src/intent.rs @@ -29,8 +29,8 @@ use serde::{Deserialize, Serialize}; use crate::installable::{executor_summaries_when_unrestricted, installable_with_report}; use crate::{ - e2e_plan, plan_installable, FrontendInput, InstallablePlan, PlanError, PlanningModels, - SelectedPlanReport, SqlCatalog, UserInput, + e2e_plan, plan_installable, CostModel, FrontendInput, InstallablePlan, PlanError, + PlanningModels, SelectedPlanReport, SqlCatalog, UserInput, }; /// The most values one binding is planned with: a larger IN-list is @@ -56,8 +56,10 @@ pub enum IntentPlanningMode { IntentOnDemandHoles, /// The queries planned together, and a state covering every value a /// hole may take (its lightcone) may be kept when cheaper: planned - /// with one lightcone query per IN-list reader and without, the - /// cheaper plan kept. + /// once with one optional lightcone query per IN-list reader, whose + /// states the plan may read but which it does not answer (cost model + /// 1); under cost model 3, planned with the lightcone queries and + /// without, the better plan kept. #[default] IntentFull, } @@ -80,7 +82,8 @@ pub struct IntentPlan { /// The selected plan, as `plan_installable` returns it. pub plan: InstallablePlan, /// Plan queries the planner added (lightcone queries), which a round - /// never issues. + /// never issues: the plan's roots past the intent's queries. Empty + /// under cost model 1, whose plan answers no lightcone query. pub lightcone_query_indices: Vec, /// One per clock of each intent (its queries on one interval), in /// program order, an intent's clocks in the order of their first query. @@ -517,6 +520,7 @@ pub async fn lower_intents( query_batch: None, repeating_queries: Some(entries), group_latency_bounds, + optional_query_count: 0, }, data_workload: Some(data.clone()), }, @@ -730,24 +734,31 @@ pub async fn plan_intents( let planned = plan_joint(&lowered).await?; (lowered, planned) } - // With the lightcone queries and without, the better plan: a - // lightcone query is a root with its own (small) request cost, so - // the plan with them is kept only when their states pay off. + // Under cost model 1, one plan with the lightcone queries optional + // (`QueryWorkload::optional_query_count`): the plan may read their + // states but answers none of them, so it is no dearer than the plan + // without them or with all of them answered. Under cost model 3 + // (no prices), the plans with the lightcone queries and without, + // the better kept. A plan with them that fails falls back to the + // plan without them. IntentPlanningMode::IntentFull => { - let without = lower_intents( - intents, - catalog, - data, - &IntentPlanningOptions { - mode: IntentPlanningMode::IntentOnDemandHoles, - ..options.clone() - }, - ) - .await?; - let planned_without = plan_joint(&without).await?; + let without = without_lightcones(&lowered); if lowered.lightcone_query_indices.is_empty() { - (without, planned_without) + let planned = plan_joint(&without).await?; + (without, planned) + } else if matches!(models.cost_inputs.cost_model, CostModel::UsageOverTime(_)) { + let mut once = lowered.clone(); + once.workload.query_workload.optional_query_count = + lowered.lightcone_query_indices.len(); + match plan_joint(&once).await { + Ok(planned) => (without, planned), + Err(_) => { + let planned = plan_joint(&without).await?; + (without, planned) + } + } } else { + let planned_without = plan_joint(&without).await?; match plan_joint(&lowered).await { Ok(planned_with) if better(&planned_with.1, &planned_without.1, &lowered) => { (lowered, planned_with) @@ -783,6 +794,17 @@ pub async fn plan_intents( )) } +/// `lowered` without its lightcone queries: the workload and rounds +/// `IntentOnDemandHoles` lowers to. +fn without_lightcones(lowered: &LoweredIntents) -> LoweredIntents { + let mut without = lowered.clone(); + if let Some(entries) = without.workload.query_workload.repeating_queries.as_mut() { + entries.truncate(entries.len() - lowered.lightcone_query_indices.len()); + } + without.lightcone_query_indices.clear(); + without +} + /// Whether `with` (the plan with lightcone queries) is better than /// `without`: a lower cost per second, or under cost model 3 (no prices) a /// lower mean latency of the intent's queries (lightcone queries left out). @@ -836,6 +858,7 @@ async fn plan_query_at_a_time( query_batch: None, repeating_queries: Some(vec![entry.clone()]), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(data.clone()), }; diff --git a/crates/planner/src/pass.rs b/crates/planner/src/pass.rs index fd8831075..cbc846e14 100644 --- a/crates/planner/src/pass.rs +++ b/crates/planner/src/pass.rs @@ -123,7 +123,8 @@ pub fn optimize( input: OptimizationInput<'_>, ) -> Result { input.validate()?; - let expected_len = input.workload.len(); + // An optional query (`QueryWorkload::optional_query_count`) has no root. + let expected_len = input.workload.len() - input.workload.query_workload().optional_query_count; let output = pass.optimize(input)?; check_contract(&output, pass.name(), expected_len)?; diff --git a/crates/planner/src/run.rs b/crates/planner/src/run.rs index 74c308601..375aab59b 100644 --- a/crates/planner/src/run.rs +++ b/crates/planner/src/run.rs @@ -171,6 +171,32 @@ pub fn run_planning_until( models: PlanningModels<'_>, settings: PlanSearchSettings, until: RunUntil, +) -> Result { + run_stages( + roots, + entries, + group_latency_bounds, + 0, + data, + models, + settings, + until, + ) +} + +/// [`run_planning_until`] with the last `optional_query_count` queries +/// optional (`QueryWorkload::optional_query_count`): Stage 3 answers only +/// the others. +#[allow(clippy::too_many_arguments)] +fn run_stages( + roots: &[QueryRoot], + entries: &[QueryWorkloadEntry], + group_latency_bounds: &[GroupLatencyBound], + optional_query_count: usize, + data: &DataWorkload, + models: PlanningModels<'_>, + settings: PlanSearchSettings, + until: RunUntil, ) -> Result { let started = Instant::now(); for root in roots { @@ -265,6 +291,7 @@ pub fn run_planning_until( physical, entries, group_latency_bounds, + optional_query_count, data, models.cost_inputs, models.deployment_capabilities.final_results_cache(), @@ -322,16 +349,18 @@ impl OptimizationPass for Stage1ToStage3Pass { .map(|(index, expr)| (*index, QueryRoot::Scalar(expr.clone()))), ); roots.sort_by_key(|(index, _)| *index); - let roots = roots.into_iter().map(|(_, root)| root).collect(); + let roots: Vec = roots.into_iter().map(|(_, root)| root).collect(); let entries: Vec<_> = workload.query_workload().entries().collect(); let data = workload.data_workload().cloned().unwrap_or_default(); - let run = run_planning( - roots, + let run = run_stages( + &roots, &entries, &workload.query_workload().group_latency_bounds, + workload.query_workload().optional_query_count, &data, input.models, PlanSearchSettings::default(), + RunUntil::Stage3, )?; let (plan, selection) = run.selection?; let mut output = PlanOutput::new(plan); diff --git a/crates/planner/tests/e2e_plan.rs b/crates/planner/tests/e2e_plan.rs index 63da6a9c8..f6420fe2d 100644 --- a/crates/planner/tests/e2e_plan.rs +++ b/crates/planner/tests/e2e_plan.rs @@ -66,6 +66,7 @@ fn sql_workload( query_batch: Some(batch_entries), repeating_queries: repeating, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, // `lineitem` at rest, holding a million rows. data_workload: Some(DataWorkload { @@ -321,6 +322,7 @@ async fn each_plan_carries_its_selected_root() { range_evaluation: None, }]), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, // A range selector only: no sample interval is needed; 1,000 rows // arrive per second. @@ -351,6 +353,7 @@ async fn scalar_roots_survive_planning_in_workload_order() { query_batch: Some(queries.iter().map(|q| batch(q)).collect()), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some( DataWorkload::sampled_every( @@ -395,6 +398,7 @@ async fn plans_a_promql_root_series_identity_does_not_cover_over_its_labels() { query_batch: Some(vec![batch(query)]), repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some( DataWorkload::sampled_every( @@ -414,3 +418,39 @@ async fn plans_a_promql_root_series_identity_does_not_cover_over_its_labels() { assert_eq!(output.plan.roots.len(), 1, "{query}"); } } + +/// An optional query (`QueryWorkload::optional_query_count`, the last +/// ones) is planned with the others but not answered: the plan has no root +/// and no query text for it, and its cost is at most the plan of the other +/// queries alone (the optional query's candidates are only more choices). +#[tokio::test] +async fn optional_query_is_planned_but_not_answered() { + let first = batch("SELECT COUNT(DISTINCT l_orderkey) FROM lineitem"); + let optional = batch("SELECT COUNT(DISTINCT l_orderkey), SUM(l_extendedprice) FROM lineitem"); + let catalog = lineitem_catalog(); + let plan = |workload: PlanningWorkload| { + let catalog = catalog.clone(); + async move { + asap_planner::plan_installable(UserInput::new( + &workload, + FrontendInput::Sql { catalog: &catalog }, + PlanningModels::builtin(), + )) + .await + } + }; + let mut with_optional = sql_workload(vec![first.clone(), optional], None); + with_optional.query_workload.optional_query_count = 1; + let (planned, report) = plan(with_optional.clone()).await.expect("plans"); + assert_eq!(planned.dag.roots.len(), 1); + assert_eq!(planned.query_texts, vec![first.query.0.clone()]); + let (_, alone) = plan(sql_workload(vec![first], None)).await.expect("plans"); + let (with, alone) = ( + report.cost_per_second.unwrap(), + alone.cost_per_second.unwrap(), + ); + assert!(with <= alone * (1.0 + 1e-9), "{with} > {alone}"); + + with_optional.query_workload.optional_query_count = 3; + assert!(plan(with_optional).await.is_err()); +} diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index a2369ba88..79eac7b97 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -12,7 +12,7 @@ use asap_planner::intent::{ lower_intents, plan_intents, IntentError, IntentPlan, IntentPlanningMode, IntentPlanningOptions, LoweredIntents, }; -use asap_planner::{PlanningModels, SqlCatalog}; +use asap_planner::{plan_installable, FrontendInput, PlanningModels, SqlCatalog, UserInput}; use asap_types::accuracy::{AccuracyMetric, AccuracyTarget}; use asap_types::ir::properties::selection::{constraint_of, Constraint}; use asap_types::ir::properties::ExecutionTiming; @@ -581,7 +581,8 @@ fn ingestion_states_read(planned: &IntentPlan, query_id: &str) -> Vec, +) -> f64 { + let intents = parse_intents(text).expect("a well-formed intent"); + let (_, without) = plan_intents( + &intents, + catalog, + data, + models, + &IntentPlanningOptions { + mode: IntentPlanningMode::IntentOnDemandHoles, + ..Default::default() + }, + ) + .await + .expect("the intent plans without lightcones"); + let without = without.cost_per_second.expect("cost model 1"); + let lowered = lower_intents(&intents, catalog, data, &IntentPlanningOptions::default()) + .await + .expect("the intent lowers"); + if lowered.lightcone_query_indices.is_empty() { + return without; + } + let mut capabilities = models.deployment_capabilities.clone(); + capabilities + .excluded_candidates + .extend(lowered.hole_exclusions.iter().cloned()); + let with = plan_installable(UserInput::new( + &lowered.workload, + FrontendInput::Sql { catalog }, + models.with_deployment_capabilities(&capabilities), + )) + .await + .ok() + .and_then(|(_, report)| report.cost_per_second); + with.map_or(without, |with| with.min(without)) +} + +/// `IntentFull`'s cost per second, planned as `plan_intents` plans it, and +/// its plan. +async fn intent_full( + text: &str, + catalog: &SqlCatalog, + data: &DataWorkload, + models: PlanningModels<'_>, +) -> (IntentPlan, f64) { + let intents = parse_intents(text).expect("a well-formed intent"); + let (plan, report) = plan_intents( + &intents, + catalog, + data, + models, + &IntentPlanningOptions::default(), + ) + .await + .expect("the intent plans"); + (plan, report.cost_per_second.expect("cost model 1")) +} + +/// Planned once with the lightcone queries left unanswered, `IntentFull` +/// is never dearer than the cheaper of the two plans it used to make +/// (without lightcone queries, and with all of them answered), and the +/// plan answers only the intent's own queries. +#[tokio::test] +async fn intent_full_once_is_no_dearer_than_two_passes() { + let programs = [ + intent_text(&format!( + "{Q1_TOP_5_HOSTS_EXACT} + q2: SELECT host, count(*) AS c FROM auth WHERE host IN $Y AND ts > $now - INTERVAL '10 minutes' GROUP BY host REQUIRE EXACT; + q3: SELECT user, count(*) AS c FROM auth WHERE host IN $Y AND ts > $now - INTERVAL '10 minutes' GROUP BY user REQUIRE EXACT;" + )), + intent_text(&format!("{Q1_TOP_5_HOSTS_EXACT}\n{Q2_COUNT_BY_USER}")), + intent_text(&format!("{Q1_TOP_10_HOSTS}\n{Q2_USERS_OF_Y}")), + CLOCKS.to_string(), + ]; + for (hosts, users, rows_per_second) in [(20, 50, 10_000.0), (300, 1000, 1000.0)] { + let data = data(hosts, users, rows_per_second); + for text in &programs { + let models = PlanningModels::builtin(); + let (once, once_cost) = intent_full(text, &catalog(), &data, models).await; + let two_passes = two_pass_cost(text, &catalog(), &data, models).await; + assert!( + once_cost <= two_passes * (1.0 + 1e-9), + "{text}: once {once_cost} > two passes {two_passes}" + ); + assert!(once.lightcone_query_indices.is_empty(), "{text}"); + let intent_queries: usize = once.intent_rounds.iter().map(|r| r.queries.len()).sum(); + assert_eq!(once.plan.query_texts.len(), intent_queries, "{text}"); + } + } +} + +/// The same check on every intent config under the directory +/// `ASAP_SIL_INTENT_CONFIGS` names whose name ends in `.c1r1`: each holds +/// `intent.sil`, `tables.json` (`{table: [[column, type], ...]}`, `ts` +/// added first) and `data.json`, planned under cost model 1 with raw data +/// retained, query-time results not kept and final results cached. +/// Skipped when the variable is unset. +#[tokio::test] +#[ignore = "needs ASAP_SIL_INTENT_CONFIGS"] +async fn intent_full_once_is_no_dearer_on_intent_configs() { + let Ok(root) = std::env::var("ASAP_SIL_INTENT_CONFIGS") else { + return; + }; + let mut dirs: Vec<_> = std::fs::read_dir(&root) + .expect("a config directory") + .map(|entry| entry.unwrap().path()) + .filter(|path| path.to_string_lossy().ends_with(".c1r1")) + .collect(); + dirs.sort(); + assert!(!dirs.is_empty(), "no *.c1r1 config under {root}"); + let capabilities = asap_planner::DeploymentCapabilities { + supported_summaries: None, + raw_data_retained: true, + query_time_results_retained: false, + final_query_results_cached: true, + ..Default::default() + }; + let cost_inputs = asap_planner::CostInputs::default(); + for dir in dirs { + let read = |name: &str| std::fs::read_to_string(dir.join(name)).unwrap(); + let tables: BTreeMap> = + serde_json::from_str(&read("tables.json")).unwrap(); + let mut catalog = SqlCatalog::new(); + for (table, columns) in &tables { + let mut fields = vec![Field::plain("ts", DataType::Timestamp, false)]; + for (name, data_type) in columns { + let data_type = match data_type.as_str() { + "Utf8" => DataType::Utf8, + "Int64" => DataType::Int64, + "Float64" => DataType::Float64, + other => panic!("column type {other}"), + }; + fields.push(Field::plain(name, data_type, false)); + } + catalog = catalog.with_table(table, Schema::with_time_index(fields, 0, vec![])); + } + let data: DataWorkload = serde_json::from_str(&read("data.json")).unwrap(); + let text = read("intent.sil"); + let models = PlanningModels::builtin() + .with_deployment_capabilities(&capabilities) + .with_cost_inputs(&cost_inputs); + let started = std::time::Instant::now(); + let two_passes = two_pass_cost(&text, &catalog, &data, models).await; + let two_passes_s = started.elapsed().as_secs_f64(); + let started = std::time::Instant::now(); + let (once, once_cost) = intent_full(&text, &catalog, &data, models).await; + let once_s = started.elapsed().as_secs_f64(); + eprintln!( + "{}: two passes {two_passes} ({two_passes_s:.3} s), once {once_cost} ({once_s:.3} s)", + dir.display() + ); + assert!( + once_cost <= two_passes * (1.0 + 1e-9), + "{}: once {once_cost} > two passes {two_passes}", + dir.display() + ); + assert!(once.lightcone_query_indices.is_empty(), "{}", dir.display()); + } +} diff --git a/crates/planner/tests/summary_sharing.rs b/crates/planner/tests/summary_sharing.rs index ce7e77cb3..c1f568b00 100644 --- a/crates/planner/tests/summary_sharing.rs +++ b/crates/planner/tests/summary_sharing.rs @@ -69,6 +69,7 @@ fn promql_workload(queries: &[(&str, f64)]) -> PlanningWorkload { .collect(), ), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload { arrival: DataArrival::Ingesting { @@ -99,6 +100,7 @@ async fn plan_sql(queries: &[&str]) -> PlanOutput { query_batch: None, repeating_queries: Some(queries.iter().map(|query| repeating(query, 0.01)).collect()), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, // `lineitem` at rest, holding a million rows. data_workload: Some(DataWorkload { diff --git a/crates/stage3-plan-selection/src/lib.rs b/crates/stage3-plan-selection/src/lib.rs index 95cb23327..d6ce3a9b8 100644 --- a/crates/stage3-plan-selection/src/lib.rs +++ b/crates/stage3-plan-selection/src/lib.rs @@ -37,6 +37,7 @@ use asap_cost::{ ResourceUnitCost, }; use asap_types::deployment_capabilities::FinalResultsCache; +use asap_types::ir::QueryRoot; use asap_types::plan::physical_asap_dag::PhysicalASAPDAG; use asap_types::stages::{ MemoGroupId, OriginOfCandidateForMemoGroup, PhysicalASAPMemoCandidates, PruneReason, @@ -77,6 +78,18 @@ pub use report::{ /// inputs for its refresh interval beyond their look-back, not for its /// whole span ([`QueryWorkloadEntry::retained_range_span_ms`]). /// +/// The last `optional_query_count` queries are optional: Stage 0 to +/// Stage 2 planned them with the others, so the plan may read their +/// groups' candidates, but the plan does not answer them and has no root +/// for them; its roots, `Selection` and cost are those of the first +/// `entries.len() - optional_query_count` queries. Answering one is never +/// cheaper: every cost term is non-negative and an answer only adds rows +/// ((C), (K), (R), (X)) and terms, so the selection leaves each optional +/// query unanswered rather than choosing. Each must have an operator +/// root; cost model 3's `lowest_mean_latency` takes none. +/// Example: a SIL intent's lightcone query, never issued, whose state its +/// IN-list readers may read. +/// /// Err: invalid or unsupported cost inputs, an infeasible catalog (reported /// as excluded by the deployment when Stage 2 pruned some candidate as /// such), or a solver failure. @@ -84,6 +97,7 @@ pub fn select_plan( physical: &PhysicalASAPMemoCandidates, entries: &[QueryWorkloadEntry], group_latency_bounds: &[GroupLatencyBound], + optional_query_count: usize, data: &DataWorkload, cost_inputs: &CostInputs, final_results_cache: FinalResultsCache, @@ -132,11 +146,35 @@ pub fn select_plan( entries: entries.len(), }); } + // The queries the plan answers: all but the optional ones, which come + // last, each with an operator root. + let answered_query_count = queries.len().saturating_sub(optional_query_count); + if optional_query_count > 0 { + if optional_query_count > queries.len() { + return Err(ErrorSelectingPlan::EntryCount { + candidate: "the optional queries".into(), + roots: queries.len(), + entries: optional_query_count, + }); + } + if cluster_limits.is_some() { + return Err(ErrorSelectingPlan::UnsupportedCostModel( + "optional queries under cost model 3's lowest_mean_latency".into(), + )); + } + if let Some(query) = (answered_query_count..queries.len()) + .find(|&query| !matches!(queries[query].root, QueryRoot::Operator(_))) + { + return Err(ErrorSelectingPlan::OptionalScalarQuery { query }); + } + } + let entries = &entries[..answered_query_count]; let outputs: Vec<(QueryId, MemoGroupId)> = physical .logical_candidates .memo .output_groups() .into_iter() + .filter(|&(query, _)| query < answered_query_count) .map(|(query, group)| (QueryId(query), group)) .collect(); let mut selectable = @@ -321,7 +359,7 @@ pub fn select_plan( ) } }; - let plan = plan_of(physical, &solved, &outputs).map_err(|error| { + let plan = plan_of(physical, &solved, &outputs, answered_query_count).map_err(|error| { ErrorSelectingPlan::Solver(format!("the selected plan is invalid: {error}")) })?; // Selection = `plan_cost`: the MILP's optimum is what `plan_cost` @@ -375,7 +413,7 @@ pub fn select_plan( *known |= cost.is_ok(); } let selection = Selection { - accepted_accuracy_per_query: accepted_accuracy(physical, &plan), + accepted_accuracy_per_query: accepted_accuracy(physical, &plan, answered_query_count), pruned_candidates: costed .iter() .zip(&physical.physical_candidates) diff --git a/crates/stage3-plan-selection/src/milp/accuracy.rs b/crates/stage3-plan-selection/src/milp/accuracy.rs index 120e98c7a..3640849a9 100644 --- a/crates/stage3-plan-selection/src/milp/accuracy.rs +++ b/crates/stage3-plan-selection/src/milp/accuracy.rs @@ -545,13 +545,12 @@ impl AccuracyRules { } let mut composed: Vec> = vec![None; count]; let mut on_walk = vec![false; count]; - let memo = &inputs.physical.logical_candidates.memo; // Per query with a δ, in `answering` order: its bound and the // failure probability it checks, summed over the outputs so far // (`None` once one is unbounded). let mut failure_probability_of_query: Vec<(QueryId, FailureProbabilityBound, Option)> = Vec::new(); - for (&(_, group), &(query, v)) in memo.output_groups().iter().zip(answering) { + for (&(_, group), &(query, v)) in selectable.outputs().iter().zip(answering) { // Compose `v` and every execution below it, producers first. let mut pending: Vec<(usize, bool)> = vec![(v, false)]; while let Some((c, producers_done)) = pending.pop() { @@ -818,9 +817,9 @@ impl<'a> ErrorModel<'a> { shared: &SharedVariables, ) { let rules = self.rules; - let memo = &inputs.physical.logical_candidates.memo; - for (&(query, group), (query_id, executions)) in memo - .output_groups() + for (&(QueryId(query), group), (query_id, executions)) in inputs + .selectable + .outputs() .iter() .zip(inputs.selectable.answering()) { @@ -1151,16 +1150,16 @@ pub(super) fn accuracy_constraints( } } let memo = &inputs.physical.logical_candidates.memo; - let output_groups = memo.output_groups(); + let output_groups = inputs.selectable.outputs(); let mut outputs_per_query = vec![0usize; memo.queries().len()]; - for &(query, _) in &output_groups { + for &(QueryId(query), _) in output_groups { outputs_per_query[query] += 1; } // Per query with a bound and several outputs: the bound and, per // output, what its answering execution gives. let mut several_roots: BTreeMap = BTreeMap::new(); - for (&(query, group), (query_id, executions)) in + for (&(QueryId(query), group), (query_id, executions)) in output_groups.iter().zip(inputs.selectable.answering()) { debug_assert_eq!(query, query_id.0, "answering is in output_groups order"); diff --git a/crates/stage3-plan-selection/src/milp/equivalent_contexts.rs b/crates/stage3-plan-selection/src/milp/equivalent_contexts.rs index b4fb0f1c7..9efb77df1 100644 --- a/crates/stage3-plan-selection/src/milp/equivalent_contexts.rs +++ b/crates/stage3-plan-selection/src/milp/equivalent_contexts.rs @@ -143,11 +143,10 @@ pub(crate) fn copies_in_equivalent_contexts<'a>( own.push(index); } } - let memo = &inputs.physical.logical_candidates.memo; // Per query, each output's answering executions and its root limits. let mut outputs_of: BTreeMap> = BTreeMap::new(); - for (&(query, group), (query_id, answering)) in - memo.output_groups().iter().zip(selectable.answering()) + for (&(QueryId(query), group), (query_id, answering)) in + selectable.outputs().iter().zip(selectable.answering()) { debug_assert_eq!(query, query_id.0, "answering is in output_groups order"); let limits = rules.and_then(|rules| rules.root_limits(*query_id, group)); diff --git a/crates/stage3-plan-selection/src/milp/model/tests.rs b/crates/stage3-plan-selection/src/milp/model/tests.rs index 813047d2f..6483fe96c 100644 --- a/crates/stage3-plan-selection/src/milp/model/tests.rs +++ b/crates/stage3-plan-selection/src/milp/model/tests.rs @@ -327,7 +327,13 @@ fn selects_the_producer_whose_own_and_edge_costs_are_lowest() { assert_eq!(solved.edges[0].edge, edge(&physical, 1, 2)); assert_eq!(solved.outputs[0].candidate, PhysicalCandidateId(2)); - let plan = plan_of(&physical, &solved, &output_groups(&physical)).unwrap(); + let plan = plan_of( + &physical, + &solved, + &output_groups(&physical), + physical.logical_candidates.memo.queries().len(), + ) + .unwrap(); assert_eq!(plan.roots, vec![1]); assert_eq!(plan.edges.len(), 1); assert_eq!((plan.edges[0].producer, plan.edges[0].consumer), (0, 1)); @@ -425,7 +431,13 @@ fn a_result_that_is_not_materialized_runs_once_per_context_that_reads_it() { .map(|execution| execution.context) .collect(); assert_ne!(scan_contexts[0], scan_contexts[1]); - let plan = plan_of(&physical, &solved, &output_groups(&physical)).unwrap(); + let plan = plan_of( + &physical, + &solved, + &output_groups(&physical), + physical.logical_candidates.memo.queries().len(), + ) + .unwrap(); assert_eq!(plan.nodes.len(), 4); assert_eq!(contexts.executions().len(), 6); } @@ -475,7 +487,13 @@ fn a_materialized_chain_runs_once_and_retains_what_its_consumers_read_back() { solved.retention_ms.get(&PhysicalCandidateId(1)), Some(&300_000) ); - let plan = plan_of(&physical, &solved, &output_groups(&physical)).unwrap(); + let plan = plan_of( + &physical, + &solved, + &output_groups(&physical), + physical.logical_candidates.memo.queries().len(), + ) + .unwrap(); let chain_node = plan .nodes .iter() @@ -759,7 +777,13 @@ fn acyclicity_forbids_two_groups_reading_each_other() { selected == vec![0, 1, 4] || selected == vec![0, 2, 3], "{selected:?}" ); - plan_of(&physical, &solved, &output_groups(&physical)).unwrap(); + plan_of( + &physical, + &solved, + &output_groups(&physical), + physical.logical_candidates.memo.queries().len(), + ) + .unwrap(); } /// x08's shape: `max by (job)(count_over_time(m[1m]))`. Path A (scan and diff --git a/crates/stage3-plan-selection/src/plan.rs b/crates/stage3-plan-selection/src/plan.rs index 658a6a408..2344b019a 100644 --- a/crates/stage3-plan-selection/src/plan.rs +++ b/crates/stage3-plan-selection/src/plan.rs @@ -59,7 +59,8 @@ pub(crate) fn candidate_node( } /// The plan of `solved`, whose output `j` answers `outputs[j]` (a query and -/// the group its root, or one operator its scalar root, reads). Nodes are +/// the group its root, or one operator its scalar root, reads), with a root +/// for each of the first `answered_query_count` queries. Nodes are /// numbered producers first. A node whose candidate has $h_v$ retains that /// much (`retention_ms`); one that retains rows a consumer reads unbounded /// has `retention_ms` `None` and keeps every row. @@ -67,6 +68,7 @@ pub(crate) fn plan_of( physical: &PhysicalASAPMemoCandidates, solved: &SolvedSelection, outputs: &[(QueryId, MemoGroupId)], + answered_query_count: usize, ) -> Result { let mut producer_of: HashMap<(Execution, usize), Execution> = HashMap::new(); let mut consumers_of: BTreeMap> = BTreeMap::new(); @@ -132,10 +134,8 @@ pub(crate) fn plan_of( .collect(); let mut roots = Vec::new(); let mut scalar_roots = Vec::new(); - for (query, memo_query) in physical - .logical_candidates - .memo - .queries() + // An optional query (the last ones) is not answered and has no root. + for (query, memo_query) in physical.logical_candidates.memo.queries()[..answered_query_count] .iter() .enumerate() { diff --git a/crates/stage3-plan-selection/src/report.rs b/crates/stage3-plan-selection/src/report.rs index 44dd56b1d..0e736f7ff 100644 --- a/crates/stage3-plan-selection/src/report.rs +++ b/crates/stage3-plan-selection/src/report.rs @@ -275,6 +275,11 @@ pub enum ErrorSelectingPlan { query: usize, failure_probability_bound: Option, }, + /// Bad input: optional query `query` (`select_plan`'s + /// `optional_query_count`) has a scalar root; an optional query needs + /// an operator root, so the plan's other roots keep their positions. + #[error("optional query {query} has a scalar root; optional queries need operator roots")] + OptionalScalarQuery { query: usize }, /// The selection MILP implements cost model 1 and cost model 3's /// `lowest_mean_latency` only. #[error("the selection MILP does not support {0}")] @@ -450,6 +455,7 @@ pub(crate) fn excluded_by_deployment( pub(crate) fn accepted_accuracy( physical: &PhysicalASAPMemoCandidates, plan: &PhysicalASAPDAG, + answered_query_count: usize, ) -> Vec { let memo = &physical.logical_candidates.memo; let mut operator_roots = plan.roots.iter(); @@ -460,7 +466,7 @@ pub(crate) fn accepted_accuracy( .or_default() .push(edge.producer); } - memo.queries() + memo.queries()[..answered_query_count] .iter() .enumerate() .map(|(query, memo_query)| { diff --git a/crates/stage3-plan-selection/src/selectable.rs b/crates/stage3-plan-selection/src/selectable.rs index 9445da815..cf8d7d36f 100644 --- a/crates/stage3-plan-selection/src/selectable.rs +++ b/crates/stage3-plan-selection/src/selectable.rs @@ -149,6 +149,9 @@ pub(crate) struct SelectableExecutions { /// `Memo::output_groups` order, with the executions, by position, that may /// answer it: $z_{q,v}$ exists only for them. answering: Vec<(QueryId, Vec)>, + /// The query output references [`Self::answering`] lists, in its + /// order: `Memo::output_groups` of the queries the plan answers. + outputs: Vec<(QueryId, MemoGroupId)>, /// Per query, by [`QueryId`], the evaluation context it is evaluated /// in: `Evaluation { grid: entry.evaluation_grid() }`, no request /// anchor; `None` for a query with no output reference. Its answering @@ -193,6 +196,7 @@ impl SelectableExecutions { edges_into: Vec::new(), edges_out_of: Vec::new(), answering: Vec::new(), + outputs: outputs.to_vec(), evaluation_context_of_query: vec![None; entries.len()], retained_span_ms_of_query: entries .iter() @@ -488,6 +492,13 @@ impl SelectableExecutions { &self.answering } + /// The query output references the plan answers, in + /// [`Self::answering`] order: each query and the group its operator + /// root, or one operator of its scalar root, reads. + pub(crate) fn outputs(&self) -> &[(QueryId, MemoGroupId)] { + &self.outputs + } + /// Every read of an execution's rows, as (the execution read, by /// position in [`Self::executions`]; its reader; how far back it reads, /// in ms, `None` when unbounded): each selectable edge into its diff --git a/crates/types/src/canonical_form.rs b/crates/types/src/canonical_form.rs new file mode 100644 index 000000000..0ff21345d --- /dev/null +++ b/crates/types/src/canonical_form.rs @@ -0,0 +1,482 @@ +//! A value's canonical form: a compact binary encoding of its serde data +//! model, written straight into a hasher ([`canonical_hash`]) or a reused +//! byte buffer ([`same_canonical_form`]), with no text in between. +//! +//! Memo hash-consing compares expressions by typed equality confirmed by +//! equal canonical forms, and hashes their canonical forms +//! (`stages::logical::memo::hash_consing`). It used to compare and hash +//! their JSON text: the canonical form makes the same decisions without +//! escaping strings or formatting floats. +//! +//! # Equality policy +//! +//! The encoding is injective over values of one type: every serde event +//! (unit, variant index, field name, sequence and map start and end, string +//! length) is written with its own tag, so two values of one type have equal +//! canonical forms iff they serialize to the same event sequence. Floats are +//! written as bit patterns, under a [`FloatBits`] policy: +//! +//! - [`FloatBits::SignedZeros`]: `0.0` and `-0.0` differ, as their JSON +//! texts (`0.0`, `-0.0`) did; every NaN is one bit pattern. Used for +//! hash-consing, always together with typed `==`, which already rejects +//! NaN (`NaN != NaN`), so "typed `==` and equal canonical forms" is +//! exactly "typed `==` and equal JSON": JSON wrote ±∞ and NaN as `null`, +//! and typed `==` tells ±∞ apart and never accepts a NaN. +//! - [`FloatBits::NumericEquality`]: `0.0` and `-0.0` are one value, every +//! NaN one bit pattern: a hash consistent with numeric `==`, for a +//! `Hash` impl next to a derived `PartialEq`. + +use std::cell::RefCell; +use std::hash::Hasher; + +use serde::ser::{self, Serialize}; + +/// How a float is written to the canonical form (module documentation). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FloatBits { + /// `0.0` and `-0.0` differ; every NaN is one value. + SignedZeros, + /// `0.0` and `-0.0` are one value; every NaN is one value. + NumericEquality, +} + +impl FloatBits { + fn f64_bits(self, value: f64) -> u64 { + if value.is_nan() { + f64::NAN.to_bits() + } else if value == 0.0 && self == FloatBits::NumericEquality { + 0 + } else { + value.to_bits() + } + } + + fn f32_bits(self, value: f32) -> u32 { + if value.is_nan() { + f32::NAN.to_bits() + } else if value == 0.0 && self == FloatBits::NumericEquality { + 0 + } else { + value.to_bits() + } + } +} + +/// Where the canonical form goes: a hasher, or a byte buffer. +trait Sink { + fn bytes(&mut self, bytes: &[u8]); +} + +impl Sink for &mut Vec { + fn bytes(&mut self, bytes: &[u8]) { + self.extend_from_slice(bytes); + } +} + +/// A hasher as a [`Sink`]. +struct HasherSink<'h, H: Hasher>(&'h mut H); + +impl Sink for HasherSink<'_, H> { + fn bytes(&mut self, bytes: &[u8]) { + self.0.write(bytes); + } +} + +/// Feeds `value`'s canonical form to `hasher`, floats under `floats`. +/// Values with equal canonical forms feed equal bytes. +pub fn canonical_hash( + value: &T, + floats: FloatBits, + hasher: &mut H, +) { + // A `Serialize` impl that fails feeds the same prefix for equal values. + let _ = value.serialize(&mut CanonicalForm { + sink: HasherSink(hasher), + floats, + }); +} + +thread_local! { + /// Two buffers [`same_canonical_form`] reuses, so comparing allocates + /// only when a value is larger than every earlier one. + static BUFFERS: RefCell<(Vec, Vec)> = const { RefCell::new((Vec::new(), Vec::new())) }; +} + +/// Whether `left` and `right` have one canonical form, floats under +/// `floats` (module documentation); false when either fails to serialize, +/// as unequal JSON was. +pub fn same_canonical_form(left: &T, right: &T, floats: FloatBits) -> bool { + BUFFERS.with(|buffers| { + let Ok(mut buffers) = buffers.try_borrow_mut() else { + // Re-entered from a `Serialize` impl: fresh buffers. + let (mut left_bytes, mut right_bytes) = (Vec::new(), Vec::new()); + return write_canonical_form(left, floats, &mut left_bytes).is_ok() + && write_canonical_form(right, floats, &mut right_bytes).is_ok() + && left_bytes == right_bytes; + }; + let (left_bytes, right_bytes) = &mut *buffers; + left_bytes.clear(); + right_bytes.clear(); + write_canonical_form(left, floats, left_bytes).is_ok() + && write_canonical_form(right, floats, right_bytes).is_ok() + && left_bytes == right_bytes + }) +} + +fn write_canonical_form( + value: &T, + floats: FloatBits, + bytes: &mut Vec, +) -> Result<(), Never> { + value.serialize(&mut CanonicalForm { + sink: bytes, + floats, + }) +} + +/// One tag byte per serde event, so the encoding is self-delimiting. +mod tag { + pub const BOOL: u8 = 1; + pub const I8: u8 = 2; + pub const I16: u8 = 3; + pub const I32: u8 = 4; + pub const I64: u8 = 5; + pub const I128: u8 = 6; + pub const U8: u8 = 7; + pub const U16: u8 = 8; + pub const U32: u8 = 9; + pub const U64: u8 = 10; + pub const U128: u8 = 11; + pub const F32: u8 = 12; + pub const F64: u8 = 13; + pub const CHAR: u8 = 14; + pub const STR: u8 = 15; + pub const BYTES: u8 = 16; + pub const NONE: u8 = 17; + pub const SOME: u8 = 18; + pub const UNIT: u8 = 19; + pub const UNIT_STRUCT: u8 = 20; + pub const UNIT_VARIANT: u8 = 21; + pub const NEWTYPE_STRUCT: u8 = 22; + pub const NEWTYPE_VARIANT: u8 = 23; + pub const SEQ: u8 = 24; + pub const TUPLE: u8 = 25; + pub const TUPLE_STRUCT: u8 = 26; + pub const TUPLE_VARIANT: u8 = 27; + pub const MAP: u8 = 28; + pub const STRUCT: u8 = 29; + pub const STRUCT_VARIANT: u8 = 30; + pub const ELEMENT: u8 = 31; + pub const FIELD: u8 = 32; + pub const SKIPPED_FIELD: u8 = 33; + pub const END: u8 = 34; +} + +/// The serializer writing the canonical form to its sink. +struct CanonicalForm { + sink: S, + floats: FloatBits, +} + +impl CanonicalForm { + fn tag(&mut self, tag: u8) { + self.sink.bytes(&[tag]); + } + + fn length(&mut self, length: usize) { + self.sink.bytes(&(length as u64).to_le_bytes()); + } + + /// A string or byte string: its length, then its bytes. + fn text(&mut self, tag: u8, bytes: &[u8]) { + self.tag(tag); + self.length(bytes.len()); + self.sink.bytes(bytes); + } + + fn variant(&mut self, tag: u8, variant_index: u32) { + self.tag(tag); + self.sink.bytes(&variant_index.to_le_bytes()); + } +} + +/// A value's own `Serialize` impl failed; the canonical form itself never +/// does. +#[derive(Debug)] +struct Never; + +impl std::fmt::Display for Never { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter.write_str("a Serialize impl failed") + } +} + +impl std::error::Error for Never {} + +impl ser::Error for Never { + fn custom(_: T) -> Self { + Never + } +} + +macro_rules! integer { + ($method:ident, $type:ty, $tag:expr) => { + fn $method(self, value: $type) -> Result<(), Never> { + self.tag($tag); + self.sink.bytes(&value.to_le_bytes()); + Ok(()) + } + }; +} + +impl ser::Serializer for &mut CanonicalForm { + type Ok = (); + type Error = Never; + type SerializeSeq = Self; + type SerializeTuple = Self; + type SerializeTupleStruct = Self; + type SerializeTupleVariant = Self; + type SerializeMap = Self; + type SerializeStruct = Self; + type SerializeStructVariant = Self; + + fn serialize_bool(self, value: bool) -> Result<(), Never> { + self.sink.bytes(&[tag::BOOL, u8::from(value)]); + Ok(()) + } + + integer!(serialize_i8, i8, tag::I8); + integer!(serialize_i16, i16, tag::I16); + integer!(serialize_i32, i32, tag::I32); + integer!(serialize_i64, i64, tag::I64); + integer!(serialize_i128, i128, tag::I128); + integer!(serialize_u8, u8, tag::U8); + integer!(serialize_u16, u16, tag::U16); + integer!(serialize_u32, u32, tag::U32); + integer!(serialize_u64, u64, tag::U64); + integer!(serialize_u128, u128, tag::U128); + + fn serialize_f32(self, value: f32) -> Result<(), Never> { + let bits = self.floats.f32_bits(value); + self.tag(tag::F32); + self.sink.bytes(&bits.to_le_bytes()); + Ok(()) + } + + fn serialize_f64(self, value: f64) -> Result<(), Never> { + let bits = self.floats.f64_bits(value); + self.tag(tag::F64); + self.sink.bytes(&bits.to_le_bytes()); + Ok(()) + } + + fn serialize_char(self, value: char) -> Result<(), Never> { + self.tag(tag::CHAR); + self.sink.bytes(&u32::from(value).to_le_bytes()); + Ok(()) + } + + fn serialize_str(self, value: &str) -> Result<(), Never> { + self.text(tag::STR, value.as_bytes()); + Ok(()) + } + + fn serialize_bytes(self, value: &[u8]) -> Result<(), Never> { + self.text(tag::BYTES, value); + Ok(()) + } + + fn serialize_none(self) -> Result<(), Never> { + self.tag(tag::NONE); + Ok(()) + } + + fn serialize_some(self, value: &T) -> Result<(), Never> { + self.tag(tag::SOME); + value.serialize(self) + } + + fn serialize_unit(self) -> Result<(), Never> { + self.tag(tag::UNIT); + Ok(()) + } + + fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Never> { + self.tag(tag::UNIT_STRUCT); + Ok(()) + } + + fn serialize_unit_variant( + self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + ) -> Result<(), Never> { + self.variant(tag::UNIT_VARIANT, variant_index); + Ok(()) + } + + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result<(), Never> { + self.tag(tag::NEWTYPE_STRUCT); + value.serialize(self) + } + + fn serialize_newtype_variant( + self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + value: &T, + ) -> Result<(), Never> { + self.variant(tag::NEWTYPE_VARIANT, variant_index); + value.serialize(self) + } + + fn serialize_seq(self, _len: Option) -> Result { + self.tag(tag::SEQ); + Ok(self) + } + + fn serialize_tuple(self, _len: usize) -> Result { + self.tag(tag::TUPLE); + Ok(self) + } + + fn serialize_tuple_struct(self, _name: &'static str, _len: usize) -> Result { + self.tag(tag::TUPLE_STRUCT); + Ok(self) + } + + fn serialize_tuple_variant( + self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + self.variant(tag::TUPLE_VARIANT, variant_index); + Ok(self) + } + + fn serialize_map(self, _len: Option) -> Result { + self.tag(tag::MAP); + Ok(self) + } + + fn serialize_struct(self, _name: &'static str, _len: usize) -> Result { + self.tag(tag::STRUCT); + Ok(self) + } + + fn serialize_struct_variant( + self, + _name: &'static str, + variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + self.variant(tag::STRUCT_VARIANT, variant_index); + Ok(self) + } +} + +/// Each element after an [`tag::ELEMENT`] tag, the end after +/// [`tag::END`]: sequences, tuples and maps of any length are +/// self-delimiting. +impl CanonicalForm { + fn element(&mut self, value: &T) -> Result<(), Never> { + self.tag(tag::ELEMENT); + value.serialize(self) + } + + fn end(&mut self) -> Result<(), Never> { + self.tag(tag::END); + Ok(()) + } + + /// A struct field: its name (a struct may skip fields, so a position + /// alone does not say which field a value is), then its value. + fn field(&mut self, key: &'static str, value: &T) -> Result<(), Never> { + self.text(tag::FIELD, key.as_bytes()); + value.serialize(self) + } + + fn skipped_field(&mut self, key: &'static str) -> Result<(), Never> { + self.text(tag::SKIPPED_FIELD, key.as_bytes()); + Ok(()) + } +} + +macro_rules! sequence_like { + ($trait:ident, $method:ident) => { + impl ser::$trait for &mut CanonicalForm { + type Ok = (); + type Error = Never; + + fn $method(&mut self, value: &T) -> Result<(), Never> { + self.element(value) + } + + fn end(self) -> Result<(), Never> { + CanonicalForm::end(self) + } + } + }; +} + +sequence_like!(SerializeSeq, serialize_element); +sequence_like!(SerializeTuple, serialize_element); +sequence_like!(SerializeTupleStruct, serialize_field); +sequence_like!(SerializeTupleVariant, serialize_field); + +impl ser::SerializeMap for &mut CanonicalForm { + type Ok = (); + type Error = Never; + + fn serialize_key(&mut self, key: &T) -> Result<(), Never> { + self.element(key) + } + + fn serialize_value(&mut self, value: &T) -> Result<(), Never> { + value.serialize(&mut **self) + } + + fn end(self) -> Result<(), Never> { + CanonicalForm::end(self) + } +} + +macro_rules! struct_like { + ($trait:ident) => { + impl ser::$trait for &mut CanonicalForm { + type Ok = (); + type Error = Never; + + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Never> { + self.field(key, value) + } + + fn skip_field(&mut self, key: &'static str) -> Result<(), Never> { + self.skipped_field(key) + } + + fn end(self) -> Result<(), Never> { + CanonicalForm::end(self) + } + } + }; +} + +struct_like!(SerializeStruct); +struct_like!(SerializeStructVariant); + +#[cfg(test)] +mod tests; diff --git a/crates/types/src/canonical_form/tests.rs b/crates/types/src/canonical_form/tests.rs new file mode 100644 index 000000000..948e62748 --- /dev/null +++ b/crates/types/src/canonical_form/tests.rs @@ -0,0 +1,191 @@ +//! The canonical form decides as JSON text did, on values that typed `==` +//! accepts, and hashes consistently with its equality. + +use std::collections::hash_map::DefaultHasher; +use std::hash::Hasher; + +use serde::Serialize; + +use super::*; + +fn hash(value: &T, floats: FloatBits) -> u64 { + let mut hasher = DefaultHasher::new(); + canonical_hash(value, floats, &mut hasher); + hasher.finish() +} + +/// The decision hash-consing made with JSON: typed `==` confirmed by equal +/// JSON texts. +fn json_decision(left: &T, right: &T) -> bool { + left == right + && match (serde_json::to_string(left), serde_json::to_string(right)) { + (Ok(left), Ok(right)) => left == right, + _ => false, + } +} + +/// The decision it makes now: typed `==` confirmed by equal canonical +/// forms. +fn canonical_decision(left: &T, right: &T) -> bool { + left == right && same_canonical_form(left, right, FloatBits::SignedZeros) +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +enum Shape { + Unit, + Newtype(f64), + Tuple(i64, String), + Struct { + name: String, + #[serde(skip_serializing_if = "Option::is_none")] + limit: Option, + #[serde(skip_serializing_if = "Option::is_none")] + offset: Option, + }, +} + +#[derive(Debug, Clone, PartialEq, Serialize)] +struct Holder { + values: Vec, + shapes: Vec, + keyed: std::collections::BTreeMap, +} + +fn samples() -> Vec { + let floats = [ + 0.0, + -0.0, + 1.0, + 0.1 + 0.2, + 0.3, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + f64::MIN_POSITIVE, + 1e300, + ]; + let mut samples = Vec::new(); + for &a in &floats { + for &b in &floats[..3] { + samples.push(Holder { + values: vec![a, b], + shapes: vec![Shape::Newtype(a), Shape::Unit], + keyed: [("x".to_string(), b)].into_iter().collect(), + }); + } + } + for (name, limit, offset) in [ + ("a", None, None), + ("a", Some(1), None), + ("a", None, Some(1)), + ("a", Some(1), Some(1)), + ("", None, None), + ("\"a\\", None, None), + ] { + samples.push(Holder { + values: vec![], + shapes: vec![ + Shape::Struct { + name: name.to_string(), + limit, + offset, + }, + Shape::Tuple(-1, name.to_string()), + ], + keyed: Default::default(), + }); + } + samples +} + +/// Every pair of samples: the canonical decision is the JSON decision, and +/// values it calls one have one hash. +#[test] +fn decides_as_json_did_on_every_pair() { + let samples = samples(); + for left in &samples { + for right in &samples { + assert_eq!( + canonical_decision(left, right), + json_decision(left, right), + "{left:?} vs {right:?}" + ); + if same_canonical_form(left, right, FloatBits::SignedZeros) { + assert_eq!( + hash(left, FloatBits::SignedZeros), + hash(right, FloatBits::SignedZeros) + ); + } + } + } +} + +/// `0.0` and `-0.0` are two values under `SignedZeros` (as their JSON +/// texts were) and one under `NumericEquality` (as `==` has them). +#[test] +fn signed_zeros_differ_only_under_signed_zeros() { + assert!(!same_canonical_form(&0.0, &-0.0, FloatBits::SignedZeros)); + assert!(same_canonical_form(&0.0, &-0.0, FloatBits::NumericEquality)); + assert_eq!( + hash(&0.0f64, FloatBits::NumericEquality), + hash(&-0.0f64, FloatBits::NumericEquality) + ); + assert!(same_canonical_form( + &0.0f32, + &-0.0f32, + FloatBits::NumericEquality + )); + assert!(!same_canonical_form( + &0.0f32, + &-0.0f32, + FloatBits::SignedZeros + )); +} + +/// Every NaN is one bit pattern, whatever its payload or sign. +#[test] +fn every_nan_is_one_value() { + let other_nan = f64::from_bits(f64::NAN.to_bits() | 1); + assert!(other_nan.is_nan()); + for floats in [FloatBits::SignedZeros, FloatBits::NumericEquality] { + assert!(same_canonical_form(&f64::NAN, &other_nan, floats)); + assert!(same_canonical_form(&f64::NAN, &-f64::NAN, floats)); + assert_eq!(hash(&f64::NAN, floats), hash(&other_nan, floats)); + } +} + +/// A skipped field is not the next field: `{limit: 1}` and `{offset: 1}` +/// differ. +#[test] +fn skipped_fields_keep_fields_apart() { + let limit = Shape::Struct { + name: "a".into(), + limit: Some(1), + offset: None, + }; + let offset = Shape::Struct { + name: "a".into(), + limit: None, + offset: Some(1), + }; + assert!(!same_canonical_form( + &limit, + &offset, + FloatBits::SignedZeros + )); +} + +/// Adjacent strings are delimited: `["ab", "c"]` is not `["a", "bc"]`. +#[test] +fn strings_and_sequences_are_delimited() { + assert!(!same_canonical_form( + &vec!["ab", "c"], + &vec!["a", "bc"], + FloatBits::SignedZeros + )); + assert!(!same_canonical_form( + &vec![vec![1u32], vec![]], + &vec![vec![], vec![1u32]], + FloatBits::SignedZeros + )); +} diff --git a/crates/types/src/lib.rs b/crates/types/src/lib.rs index d3fb45383..ed4416446 100644 --- a/crates/types/src/lib.rs +++ b/crates/types/src/lib.rs @@ -28,6 +28,7 @@ //! //! No execution logic lives in this crate. pub mod accuracy; +pub mod canonical_form; pub mod deployment_capabilities; pub mod ir; pub mod plan; diff --git a/crates/types/src/stages/logical/memo/hash_consing/mod.rs b/crates/types/src/stages/logical/memo/hash_consing/mod.rs index 60d0b925e..b75ff5a96 100644 --- a/crates/types/src/stages/logical/memo/hash_consing/mod.rs +++ b/crates/types/src/stages/logical/memo/hash_consing/mod.rs @@ -1,8 +1,7 @@ //! The one equality that makes two expressions one memo group, and two //! candidates of a group one candidate: typed equality of the operator, its -//! arguments and input groups, confirmed by equal serializations -//! ([`same_value`]; [`same_serialized_expression`] with each side's -//! serialization computed once). [`Memo::find_or_add_group`] looks a group up +//! arguments and input groups, confirmed by equal canonical forms +//! ([`same_value`], [`same_expression`]). [`Memo::find_or_add_group`] looks a group up //! by it, Stage 0 included, and [`Memo::add_candidate`] finds a duplicate by //! it. Parameters θ are not an argument of any operator (they are a //! candidate's `LogicalProperties`), so builds of one family over one input @@ -12,66 +11,60 @@ //! [`Memo::add_candidate`]: super::Memo::add_candidate use std::collections::hash_map::DefaultHasher; -use std::hash::{Hash, Hasher}; +use std::hash::Hasher; use super::MemoGroupId; +use crate::canonical_form::{canonical_hash, same_canonical_form, FloatBits}; use crate::ir::Operator; use crate::stages::CandidateForMemoGroup; -/// The canonical JSON of `expression` (operator, arguments and input -/// groups), serialized once per expression: what [`expression_hash`] hashes -/// and [`same_serialized_expression`] compares. -pub(super) fn serialized_expression(expression: &Operator) -> String { - serde_json::to_string(expression).expect("an expression over memo groups serializes") -} - -/// A hash consistent with [`same_serialized_expression`], used only to -/// narrow the groups compared: SipHash over the expression's -/// [`serialized_expression`]. A non-finite `f64` serializes as `null`, -/// which only widens one bucket; [`same_serialized_expression`] decides. -pub(super) fn expression_hash(serialized: &str) -> u64 { +/// A hash consistent with [`same_expression`], used only to narrow the +/// groups compared: SipHash over the expression's canonical form +/// (`crate::canonical_form`, signed zeros apart, every NaN one value). +pub(super) fn expression_hash(expression: &Operator) -> u64 { let mut hasher = DefaultHasher::new(); - serialized.hash(&mut hasher); + canonical_hash(expression, FloatBits::SignedZeros, &mut hasher); hasher.finish() } -/// Whether `left` and `right` are one expression: typed equality (operator, -/// arguments and input groups) confirmed by equal serializations (each -/// side's [`serialized_expression`], computed once by the caller), as -/// [`same_value`] decides it. -pub(super) fn same_serialized_expression( - (left, left_serialized): (&Operator, &str), - (right, right_serialized): (&Operator, &str), -) -> bool { - left == right && left_serialized == right_serialized +/// Whether `left` and `right` are one expression (operator, arguments and +/// input groups), as [`same_value`] decides it. +pub(super) fn same_expression(left: &Operator, right: &Operator) -> bool { + same_value(left, right) } -/// Typed equality, confirmed by equal serializations: numeric `PartialEq` -/// alone conflates signed zeros, and `SketchParams`' equality omits the -/// recorded error and failure probability. The serialized check is -/// additional evidence, never a replacement for typed equality (JSON maps -/// non-finite floats to `null`). +/// Typed equality, confirmed by equal canonical forms +/// (`crate::canonical_form`, [`FloatBits::SignedZeros`]): numeric +/// `PartialEq` alone conflates signed zeros. The canonical form is +/// additional evidence, never a replacement for typed equality, which +/// rejects every NaN. Together they decide exactly as typed equality +/// confirmed by equal JSON texts did (`crate::canonical_form`'s policy), +/// without writing JSON. pub(super) fn same_value(left: &T, right: &T) -> bool { - left == right - && match (serde_json::to_string(left), serde_json::to_string(right)) { - (Ok(left), Ok(right)) => left == right, - _ => false, - } + left == right && same_canonical_form(left, right, FloatBits::SignedZeros) } /// Whether `left` and `right` are one candidate of a group: the same /// input requirements, so two readouts of one state with different required -/// accuracy are two candidates (compared first: it is cheap and tells -/// readout copies apart), and the same expression and logical properties -/// (parameters), each by [`same_value`] (typed equality first, serialized -/// only when typed-equal). +/// accuracy are two candidates, and the same expression and logical +/// properties (parameters), each by [`same_value`]. Every typed comparison +/// runs before any canonical form is written: candidates of one group +/// mostly share their operator and differ in θ, and typed `==` on θ tells +/// them apart without writing the operator's canonical form. pub(super) fn same_candidate(left: &CandidateForMemoGroup, right: &CandidateForMemoGroup) -> bool { + let (left_parameters, right_parameters) = ( + &left.logical_properties.parameters, + &right.logical_properties.parameters, + ); left.input_requirements == right.input_requirements - && same_value(&left.expression.operator, &right.expression.operator) - && same_value( - &left.logical_properties.parameters, - &right.logical_properties.parameters, + && left.expression.operator == right.expression.operator + && left_parameters == right_parameters + && same_canonical_form( + &left.expression.operator, + &right.expression.operator, + FloatBits::SignedZeros, ) + && same_canonical_form(left_parameters, right_parameters, FloatBits::SignedZeros) } #[cfg(test)] diff --git a/crates/types/src/stages/logical/memo/hash_consing/tests.rs b/crates/types/src/stages/logical/memo/hash_consing/tests.rs index 906f12509..29a64c9a1 100644 --- a/crates/types/src/stages/logical/memo/hash_consing/tests.rs +++ b/crates/types/src/stages/logical/memo/hash_consing/tests.rs @@ -4,13 +4,14 @@ use super::super::tests::kll_k; use super::super::*; +use super::{expression_hash, same_expression, same_value}; use crate::ir::operator::arguments::{GroupKeys, Reduction, Source}; use crate::ir::operator::AggIntent; use crate::ir::scalar::expr_ir::{CompareOpKind, ScalarValue}; use crate::ir::scalar::{ProjectItem, SortKey}; use crate::ir::schema::{DataType, Field, FieldDataType, Schema}; use crate::ir::{ExprSemantics, NonASAPOp, Predicate, ScalarExpr}; -use crate::summary_type::SketchAlgorithm; +use crate::summary_type::{SketchAlgorithm, SketchParams}; use crate::test_support::memo_builders::try_candidate; use crate::test_support::memo_fixtures::{aggregate_with, scan, state}; @@ -383,3 +384,94 @@ fn signed_zero_and_non_finite_literals_are_different_groups() { } assert!(one_group(literal(f64::INFINITY), literal(f64::INFINITY))); } + +/// The decision hash-consing made with JSON text: typed equality +/// confirmed by equal JSON. +fn json_decision(left: &T, right: &T) -> bool { + left == right + && match (serde_json::to_string(left), serde_json::to_string(right)) { + (Ok(left), Ok(right)) => left == right, + _ => false, + } +} + +/// On every pair of expressions over one scan (literals of every float +/// class, quantiles, filters, limits, sorts), [`same_expression`] decides +/// as typed equality confirmed by JSON did, and expressions it calls one +/// have one [`expression_hash`]; so do candidates' θ under [`same_value`]. +#[test] +fn same_expression_decides_as_json_did() { + let mut memo = Memo::new(&DataWorkload::default()); + let scan = memo.find_or_add_group(service_scan()).unwrap(); + let mut expressions = Vec::new(); + for value in [ + 0.0, + -0.0, + 1.0, + 0.1 + 0.2, + 0.3, + f64::INFINITY, + f64::NEG_INFINITY, + f64::NAN, + ] { + expressions.push(Operator::NonASAP(NonASAPOp::Project { + cols: vec![ProjectItem { + alias: Some("v".into()), + expr: ScalarExpr::Literal(ScalarValue::Float64(value)), + }], + child: scan, + })); + let filter = Predicate(ScalarExpr::Compare { + left: Box::new(ScalarExpr::Column(3)), + op: CompareOpKind::Gt, + right: Box::new(ScalarExpr::Literal(ScalarValue::Float64(value))), + semantics: ExprSemantics::Sql, + }); + expressions.push(aggregate_with( + Reduction::by(vec![1]), + vec![( + AggIntent::Quantile { + col: Some(2), + q: 0.5, + }, + Some(filter), + )], + None, + scan, + )); + expressions.push(aggregate_with( + Reduction::by(vec![]), + vec![( + AggIntent::Quantile { + col: Some(2), + q: value, + }, + None, + )], + None, + scan, + )); + } + expressions.push(unordered_limit(scan)); + expressions.push(service_scan()); + let copies = expressions.clone(); + for left in &expressions { + for right in &copies { + let same = same_expression(left, right); + assert_eq!(same, json_decision(left, right), "{left:?} vs {right:?}"); + if same { + assert_eq!(expression_hash(left), expression_hash(right)); + } + } + } + let alphas = [0.01, 0.010000000000000002, 0.0, -0.0]; + for left in alphas { + for right in alphas { + let (left, right) = ( + SketchParams::DDSketch { alpha: left }, + SketchParams::DDSketch { alpha: right }, + ); + assert_eq!(same_value(&left, &right), json_decision(&left, &right)); + } + } +} diff --git a/crates/types/src/stages/logical/memo/mod.rs b/crates/types/src/stages/logical/memo/mod.rs index 95cbb40ef..6525d34e5 100644 --- a/crates/types/src/stages/logical/memo/mod.rs +++ b/crates/types/src/stages/logical/memo/mod.rs @@ -25,9 +25,7 @@ use crate::stages::{ use crate::summary_type::SketchStatistic; use crate::workload::bounds::{declared_max_distinct_per_evaluation, smaller_known, source_name}; use crate::workload::{series_facts, DataArrival, DataWorkload, SourceFacts}; -use hash_consing::{ - expression_hash, same_candidate, same_serialized_expression, serialized_expression, -}; +use hash_consing::{expression_hash, same_candidate, same_expression}; /// The memo, Stage 0's and Stage 1's one type: the memo groups, each with /// its candidates ([`MemoGroup::candidates`]: empty after Stage 0), and each @@ -43,7 +41,7 @@ pub struct Memo { /// The groups [`Self::find_or_add_group`] may return, by /// [`expression_hash`] of their expression: every group whose sharing /// is legal ([`GroupProperties::shareable_when_equal`](crate::stages::GroupProperties::shareable_when_equal)). - groups_by_expression_hash: HashMap>, + groups_by_expression_hash: HashMap>, /// The data workload's facts per source (`DataWorkload::sources`), fixed /// at construction: a `Scan` group's column signs read them. pub(super) source_facts: BTreeMap, @@ -477,7 +475,7 @@ impl Memo { /// Hash-consing: the group whose expression is `expression` (operator, /// arguments and input groups by typed equality, confirmed by equal - /// serializations: `same_serialized_expression`), else a + /// canonical forms: `same_expression`), else a /// new group for it, with the `GroupProperties` `derive_group_properties` /// derives from its input groups, listed as a parent of each input /// group. A group whose copies may return different rows (an unordered @@ -490,19 +488,15 @@ impl Memo { &mut self, expression: Operator, ) -> Result { - let serialized = serialized_expression(&expression); - let hash = expression_hash(&serialized); + let hash = expression_hash(&expression); // Only shareable groups are listed by hash, and an equal expression // is as shareable as the group it equals, which was validated. - if let Some((group, _)) = self + if let Some(group) = self .groups_by_expression_hash .get(&hash) .and_then(|groups| { - groups.iter().find(|(group, known)| { - same_serialized_expression( - (&self.groups[group.0 as usize].expression, known), - (&expression, &serialized), - ) + groups.iter().find(|group| { + same_expression(&self.groups[group.0 as usize].expression, &expression) }) }) { @@ -527,7 +521,7 @@ impl Memo { self.groups_by_expression_hash .entry(hash) .or_default() - .push((id, serialized)); + .push(id); } Ok(id) } diff --git a/crates/types/src/summary_type/parameters.rs b/crates/types/src/summary_type/parameters.rs index d2ec6ada3..ea9b8a553 100644 --- a/crates/types/src/summary_type/parameters.rs +++ b/crates/types/src/summary_type/parameters.rs @@ -187,16 +187,19 @@ pub enum SketchParams { // θ compares and hashes as a value so it can key a stored view // (`ViewStateKey`). Its only float, DDSketch `alpha`, lies in (0, 1) in every // θ the planner builds (`parameters_fit` checks it against the algorithm's -// list), so `==` is an equivalence there; the hash is that of its JSON text, -// which equal values share. The hash allocates a string: fine for a store's -// keys, not for a hot map keyed by θ. +// list), so `==` is an equivalence there; the hash is that of its canonical +// form with floats as `==` has them (`FloatBits::NumericEquality`: signed +// zeros one value), which equal values share. It writes no text and +// allocates nothing. impl Eq for SketchParams {} impl std::hash::Hash for SketchParams { fn hash(&self, state: &mut H) { - serde_json::to_string(self) - .expect("sketch parameters serialize") - .hash(state); + crate::canonical_form::canonical_hash( + self, + crate::canonical_form::FloatBits::NumericEquality, + state, + ); } } diff --git a/crates/types/src/workload/planning.rs b/crates/types/src/workload/planning.rs index 6060cad51..d47c6dddf 100644 --- a/crates/types/src/workload/planning.rs +++ b/crates/types/src/workload/planning.rs @@ -110,6 +110,9 @@ pub enum WorkloadError { /// The workload's query count. queries: usize, }, + /// Bad input: `optional_query_count` is larger than the query count. + #[error("{optional} optional queries, but the workload has {queries} queries")] + TooManyOptionalQueries { optional: usize, queries: usize }, /// Bad input: a source's stream norm bound that is negative or not /// finite. #[error("a stream norm must be finite and non-negative, got {0}")] @@ -200,6 +203,7 @@ mod tests { range_evaluation: None, }]), group_latency_bounds: Vec::new(), + optional_query_count: 0, }, data_workload: Some(DataWorkload { arrival: DataArrival::Ingesting { diff --git a/crates/types/src/workload/query.rs b/crates/types/src/workload/query.rs index 77ebb3664..cd5259e71 100644 --- a/crates/types/src/workload/query.rs +++ b/crates/types/src/workload/query.rs @@ -592,6 +592,19 @@ pub struct QueryWorkload { /// enforces them, as it does `max_latency_ms`. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub group_latency_bounds: Vec, + /// How many of the last queries ([`Self::entries`] order) are + /// optional: planned with the others, so the plan may read the states + /// their computations share with the others', but not answered, so the + /// plan has no root for them and its roots, query texts and cost are + /// those of the other queries. 0 (the default) for none. Example: a SIL + /// intent's lightcone queries, never issued, whose states the queries + /// reading a hole may read for every binding. + #[serde(default, skip_serializing_if = "is_zero")] + pub optional_query_count: usize, +} + +fn is_zero(count: &usize) -> bool { + *count == 0 } /// `Σ_{q ∈ query_indices} L_q ≤ max_latency_ms`: the queries' latencies @@ -629,6 +642,12 @@ impl QueryWorkload { validate_entry(&entry)?; } let queries = self.entries().count(); + if self.optional_query_count > queries { + return Err(WorkloadError::TooManyOptionalQueries { + optional: self.optional_query_count, + queries, + }); + } for (group, bound) in self.group_latency_bounds.iter().enumerate() { let mut indices = bound.query_indices.clone(); indices.sort_unstable(); @@ -935,6 +954,7 @@ mod tests { query_batch: None, repeating_queries: None, group_latency_bounds: Vec::new(), + optional_query_count: 0, } }