Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/frontend-sil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
87 changes: 72 additions & 15 deletions crates/frontend-sil/src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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<Vec<(String, Option<f64>)>, QueryError> {
Expand Down Expand Up @@ -419,7 +424,7 @@ fn alternatives_of(query_id: &str, sql: &str) -> Result<Vec<(String, Option<f64>
"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 {
Expand All @@ -437,36 +442,88 @@ fn alternatives_of(query_id: &str, sql: &str) -> Result<Vec<(String, Option<f64>
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::<Vec<_>>();
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<usize>, 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<f64>), String> {
let texts: Vec<&str> = toks.iter().map(|t| t.text(statement)).collect();
let number = |text: &str| {
Expand Down
67 changes: 67 additions & 0 deletions crates/frontend-sil/tests/sil.rs
Original file line number Diff line number Diff line change
Expand Up @@ -703,3 +703,70 @@ fn a_choice_query_and_a_plain_query_may_not_share_an_id() {
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,
/// 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)
);
}
38 changes: 38 additions & 0 deletions crates/planner/tests/sil_intents.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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}");
}
}