From 36dd7f123b7525fa6177ce5a2ed9764d9bf8e7b6 Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:17:57 +0000 Subject: [PATCH 1/3] test(sil): structural free variables: free GROUP BY and free window as choices (failing) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/frontend-sil/tests/sil.rs | 62 +++++++++++++++++++++++++++++ crates/planner/tests/sil_intents.rs | 38 ++++++++++++++++++ 2 files changed, 100 insertions(+) diff --git a/crates/frontend-sil/tests/sil.rs b/crates/frontend-sil/tests/sil.rs index c1ad3a052..602ede31e 100644 --- a/crates/frontend-sil/tests/sil.rs +++ b/crates/frontend-sil/tests/sil.rs @@ -699,6 +699,68 @@ fn a_choice_query_and_a_plain_query_may_not_share_an_id() { ); assert!( matches!(error(&text), SilError::DuplicateQueryId { ref query_id } if query_id == "q1"), +/// A free GROUP BY: one choice written in the select list and in GROUP BY +/// (the same text) is one free variable, taking the same alternative in +/// both places; an alternative in parentheses is substituted without them, +/// so a key list may hold commas. +#[test] +fn a_free_group_by_is_one_choice_written_twice() { + let intent = one(&intent( + "q1: SELECT {region: 0.5, (region, service): 0.3, (service, endpoint): 0.2}, sum(bytes) AS b + FROM flows GROUP BY {region: 0.5, (region, service): 0.3, (service, endpoint): 0.2} + REQUIRE EXACT;", + )); + assert_eq!( + alternatives(&intent), + [ + ( + "q1#0".to_string(), + 0.5, + "SELECT region, sum(bytes) AS b\n FROM flows GROUP BY region".to_string() + ), + ( + "q1#1".to_string(), + 0.3, + "SELECT region, service, sum(bytes) AS b\n FROM flows GROUP BY region, service" + .to_string() + ), + ( + "q1#2".to_string(), + 0.2, + "SELECT service, endpoint, sum(bytes) AS b\n FROM flows GROUP BY service, endpoint" + .to_string() + ), + ] + ); +} + +/// A free window range over a declared set: one alternative per range, +/// combined with a free aggregate (two different choices) as a product. +#[test] +fn a_free_window_combines_with_a_free_aggregate() { + let intent = one(&intent( + "q1: SELECT host, {count: 0.5, approx_distinct: 0.5}(dst) AS v FROM flows + WHERE ts > $now - {INTERVAL '5 minutes': 0.6, INTERVAL '1 hour': 0.3, INTERVAL '6 hours': 0.1} + GROUP BY host REQUIRE EXACT;", + )); + let got = alternatives(&intent); + assert_eq!(got.len(), 6); + assert!(got[0].2.contains("count(dst)") && got[0].2.contains("INTERVAL '5 minutes'")); + assert!(got[5].2.contains("approx_distinct(dst)") && got[5].2.contains("INTERVAL '6 hours'")); + assert!((got[0].1 - 0.3).abs() < 1e-12 && (got[5].1 - 0.05).abs() < 1e-12); +} + +/// The same items with different probabilities are two choices only if +/// their text differs; a free variable written twice with different +/// probabilities is refused rather than combined. +#[test] +fn one_free_variable_written_with_different_probabilities_is_refused() { + let text = intent( + "q1: SELECT {region: 0.5, service: 0.5}, sum(bytes) FROM flows + GROUP BY {region: 0.6, service: 0.4} REQUIRE EXACT;", + ); + assert!( + matches!(error(&text), SilError::InvalidChoice { .. }), "{:?}", parse_intents(&text) ); diff --git a/crates/planner/tests/sil_intents.rs b/crates/planner/tests/sil_intents.rs index 20ae97253..7f548561c 100644 --- a/crates/planner/tests/sil_intents.rs +++ b/crates/planner/tests/sil_intents.rs @@ -1008,3 +1008,41 @@ async fn a_choice_lowers_to_exclusive_alternatives() { assert_eq!(round_query(&lowered, "q3#1").rate, 0.5); assert!(round_query(&lowered, "q1").exclusive_choice.is_none()); } + +/// Structural free variables planned jointly: a free GROUP BY over +/// {host}, {host, user} and a free window over {10 min, 1 h} each lower +/// to exclusive alternatives, and planning them together costs less than +/// planning each alternative alone (the coarser grouping rolls up from the +/// finer one, the windows share a chain). +#[tokio::test] +async fn structural_free_variables_are_cheaper_planned_jointly() { + for queries in [ + "q1: SELECT {host: 0.7, (host, user): 0.3}, sum(bytes) AS b FROM flows + WHERE ts > $now - INTERVAL '1 hour' GROUP BY {host: 0.7, (host, user): 0.3} REQUIRE EXACT;", + "q1: SELECT host, sum(bytes) AS b FROM flows + WHERE ts > $now - {INTERVAL '10 minutes': 0.5, INTERVAL '1 hour': 0.5} GROUP BY host REQUIRE EXACT;", + ] { + let lowered = lowered(queries).await; + assert_eq!(exclusive_group_of(&lowered, "q1#0").as_deref(), Some("q1")); + assert_eq!(exclusive_group_of(&lowered, "q1#1").as_deref(), Some("q1")); + let data = data(20, 50, 10_000.0); + let cost = |mode| { + let data = data.clone(); + async move { + planned_with( + queries, + &data, + &IntentPlanningOptions { + mode, + ..Default::default() + }, + ) + .await + .1 + } + }; + let alone = cost(IntentPlanningMode::QueryAtATime).await; + let joint = cost(IntentPlanningMode::IntentOnDemandHoles).await; + assert!(joint < alone, "{queries}: joint {joint} vs alone {alone}"); + } +} From 07be07df64740186655de869714eb0c77e29029d Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:38:15 +0000 Subject: [PATCH 2/3] feat(sil): structural free variables: one choice written twice is one variable A free GROUP BY is the same weighted choice written in the select list and in GROUP BY: equal choices in one query take one alternative everywhere (the same items with other probabilities are refused), and an alternative in parentheses stands for its contents, so a key list may hold commas. A free window range is a choice over INTERVALs. Both lower to exclusive alternatives; covering is the planner's ordinary sharing (rollup from the finer grouping, one pane chain). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/frontend-sil/src/lib.rs | 8 +++ crates/frontend-sil/src/parse.rs | 87 ++++++++++++++++++++++++++------ 2 files changed, 80 insertions(+), 15 deletions(-) diff --git a/crates/frontend-sil/src/lib.rs b/crates/frontend-sil/src/lib.rs index 74b33ea06..c325835f5 100644 --- a/crates/frontend-sil/src/lib.rs +++ b/crates/frontend-sil/src/lib.rs @@ -35,7 +35,15 @@ //! 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; +//! q6: SELECT {region: 0.5, (region, service): 0.5}, sum(bytes) FROM flows +//! WHERE ts > $now - {INTERVAL '5 minutes': 0.6, INTERVAL '1 hour': 0.4} +//! GROUP BY {region: 0.5, (region, service): 0.5} REQUIRE EXACT; //! ``` +//! +//! Choices are the structural free variables (aggregate, quantile level, +//! window range, grouping keys over a declared set); one written twice +//! with the same text (the grouping keys in SELECT and GROUP BY) is one +//! variable. use std::collections::BTreeMap; diff --git a/crates/frontend-sil/src/parse.rs b/crates/frontend-sil/src/parse.rs index c4bd550a6..824674da4 100644 --- a/crates/frontend-sil/src/parse.rs +++ b/crates/frontend-sil/src/parse.rs @@ -7,6 +7,8 @@ //! sql REQUIRE accuracy [ ',' LATENCY '<=' duration ] //! binder ::= '$' name | '_' //! choice ::= '{' text ':' number (',' text ':' number)* '}' (anywhere in sql) +//! -- a free variable over a declared set; written twice (same +//! -- text) it is one variable; `(a, b)` stands for `a, b` //! accuracy::= EXACT | ERROR (abs | rel | rank) '<=' number [ DELTA number ] //! group ::= GROUP '(' id (',' id)* ')' LATENCY '<=' duration //! duration::= number ('ms' | 's' | 'm' | 'h') @@ -344,7 +346,10 @@ const MAX_ALTERNATIVES_PER_QUERY: usize = 1_000; /// `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 +/// hold `f(a, b)`, and one in parentheses is substituted without them +/// (`(region, service)`). Equal choices are one free variable, taking one +/// alternative everywhere they are written (a free GROUP BY in the select +/// list and in GROUP BY). 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> { @@ -419,7 +424,7 @@ fn alternatives_of(query_id: &str, sql: &str) -> Result "the probability {probability_text} of `{text}` is not in [0, 1]" ))); } - alternatives.push((text.to_string(), probability)); + alternatives.push((without_enclosing_parentheses(text).to_string(), probability)); } let total: f64 = alternatives.iter().map(|(_, p)| p).sum(); if total > 1.0 + 1e-9 { @@ -437,36 +442,88 @@ fn alternatives_of(query_id: &str, sql: &str) -> Result if choices.is_empty() { return Ok(vec![(sql.to_string(), None)]); } - let combinations: usize = choices.iter().map(|(_, a)| a.len()).product(); + // One free variable may be written several times (a free GROUP BY in + // the select list and in GROUP BY): equal choices are one, taking one + // alternative everywhere. The same alternatives with other + // probabilities are refused. + let mut distinct: Vec<&Vec<(String, f64)>> = Vec::new(); + let mut choice_of_occurrence = Vec::with_capacity(choices.len()); + for (_, alternatives) in &choices { + let texts = |a: &Vec<(String, f64)>| a.iter().map(|(t, _)| t.clone()).collect::>(); + let index = match distinct + .iter() + .position(|known| texts(known) == texts(alternatives)) + { + Some(index) if distinct[index] == alternatives => index, + Some(_) => { + return Err(invalid( + "one choice is written twice with different probabilities".into(), + )) + } + None => { + distinct.push(alternatives); + distinct.len() - 1 + } + }; + choice_of_occurrence.push(index); + } + let combinations: usize = distinct.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 + // Every combination (an alternative per distinct choice), the first + // choice varying slowest. + let mut picks: Vec<(Vec, f64)> = vec![(Vec::new(), 1.0)]; + for alternatives in &distinct { + picks = picks .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) + .flat_map(|(pick, probability)| { + alternatives.iter().enumerate().map(move |(index, (_, p))| { + let mut pick = pick.clone(); + pick.push(index); + (pick, probability * p) }) }) .collect(); } - Ok(out + Ok(picks .into_iter() - .map(|(mut text, probability, at)| { + .map(|(pick, probability)| { + let mut text = String::new(); + let mut at = 0; + for ((range, _), &choice) in choices.iter().zip(&choice_of_occurrence) { + text.push_str(&sql[at..range.start]); + text.push_str(&distinct[choice][pick[choice]].0); + at = range.end; + } text.push_str(&sql[at..]); (text, Some(probability)) }) .collect()) } +/// `text` without one pair of parentheses enclosing all of it +/// (`(region, service)` is `region, service`), so an alternative may hold +/// a list; any other text unchanged. +fn without_enclosing_parentheses(text: &str) -> &str { + let Some(inner) = text.strip_prefix('(').and_then(|t| t.strip_suffix(')')) else { + return text; + }; + // The first `(` must close at the end, not earlier (`(a) + (b)`). + let mut depth = 0i32; + for c in inner.chars() { + match c { + '(' => depth += 1, + ')' if depth == 0 => return text, + ')' => depth -= 1, + _ => {} + } + } + inner.trim() +} + fn parse_require(statement: &str, toks: &[Token]) -> Result<(AccuracyTarget, Option), String> { let texts: Vec<&str> = toks.iter().map(|t| t.text(statement)).collect(); let number = |text: &str| { From 66d9653f40340d54fd5af5cadd70786118d4f48c Mon Sep 17 00:00:00 2001 From: zzylol <50204836+zzylol@users.noreply.github.com> Date: Fri, 4 Dec 2026 02:52:36 +0000 Subject: [PATCH 3/3] test(sil): close the duplicate-id test after the rebase onto the review fix Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6boFpwkpMtRc1FnZuYi --- crates/frontend-sil/tests/sil.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/frontend-sil/tests/sil.rs b/crates/frontend-sil/tests/sil.rs index 602ede31e..ce70613f0 100644 --- a/crates/frontend-sil/tests/sil.rs +++ b/crates/frontend-sil/tests/sil.rs @@ -699,6 +699,11 @@ fn a_choice_query_and_a_plain_query_may_not_share_an_id() { ); assert!( matches!(error(&text), SilError::DuplicateQueryId { ref query_id } if query_id == "q1"), + "{:?}", + parse_intents(&text) + ); +} + /// A free GROUP BY: one choice written in the select list and in GROUP BY /// (the same text) is one free variable, taking the same alternative in /// both places; an alternative in parentheses is substituted without them,