Skip to content
43 changes: 31 additions & 12 deletions crates/cost/src/plan/execution_demand/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ pub struct ScheduleGroup {
}

/// One fixed (interval, phase) schedule's queries: each step in ms they
/// use with the longest span in ms at that step, the queries, and the
/// largest fraction of the schedule's times any of them is requested at.
type FixedSchedule = (BTreeMap<u64, u64>, Vec<usize>, f64);
/// use with the longest span in ms at that step, the queries, the largest
/// fraction of the schedule's times any of them outside an exclusive
/// choice is requested at, and per exclusive choice the sum of its
/// alternatives' fractions.
type FixedSchedule = (BTreeMap<u64, u64>, Vec<usize>, f64, BTreeMap<String, f64>);

/// The groups of `queries` evaluated together (each a recurrence with its
/// range evaluation), in the order [`evaluation_rate`] adds them: fixed
Expand All @@ -65,7 +67,9 @@ type FixedSchedule = (BTreeMap<u64, u64>, Vec<usize>, f64);
/// whose instants coincide, e.g. every 20 s and every 30 s meet every 60 s);
/// each estimated rate is its own group.
/// A fixed group is computed at the largest `requested_fraction` of its
/// queries' times (all of them when none gives one).
/// queries' times (all of them when none gives one), the alternatives of
/// one exclusive choice (`exclusive_group`, one of them asked a time)
/// counting as one query at the sum of their fractions, at most 1.
/// One-off, scheduled and unknown queries form one batch group: the most
/// evaluations among them, spread over `non_repeating_query_horizon_seconds`.
pub fn schedule_groups<'r>(
Expand All @@ -88,6 +92,7 @@ pub fn schedule_groups<'r>(
interval,
evaluation_phase,
requested_fraction,
exclusive_group,
}) => {
if interval.0 == 0 {
return Err(AnalyticalCostError::InvalidRecurrence);
Expand All @@ -98,13 +103,19 @@ pub fn schedule_groups<'r>(
.map_or((u64::from(interval.0), 0), |range| {
(range.step_ms, range.span_ms)
});
let (longest_span_ms_by_step_ms, members, fraction) =
let (longest_span_ms_by_step_ms, members, fraction, exclusive_sums) =
by_schedule.entry((interval.0, phase_ms)).or_default();
// A node read by queries requested at different fractions of
// one schedule's times is computed at the largest: the
// others' requests (a dependent query's, below its upstream
// requested every time) fall on times it is computed anyway.
*fraction = fraction.max(requested_fraction.unwrap_or(1.0));
// Exclusive alternatives are asked at different times, so
// their fractions add.
let requested = requested_fraction.unwrap_or(1.0);
match exclusive_group {
Some(group) => *exclusive_sums.entry(group.clone()).or_default() += requested,
None => *fraction = fraction.max(requested),
}
let longest_span_ms = longest_span_ms_by_step_ms.entry(step_ms).or_default();
*longest_span_ms = (*longest_span_ms).max(span_ms);
members.push(query);
Expand Down Expand Up @@ -139,12 +150,20 @@ pub fn schedule_groups<'r>(
let mut groups: Vec<ScheduleGroup> = by_schedule
.into_iter()
.map(
|((interval_ms, _), (longest_span_ms_by_step_ms, queries, fraction))| ScheduleGroup {
queries,
evaluations_per_second: 1_000.0 / f64::from(interval_ms)
* fraction
* distinct_instants_per_request(&longest_span_ms_by_step_ms),
schedule: Schedule::FixedInterval,
|(
(interval_ms, _),
(longest_span_ms_by_step_ms, queries, fraction, exclusive_sums),
)| {
let fraction = exclusive_sums
.values()
.fold(fraction, |largest, &sum| largest.max(sum.min(1.0)));
ScheduleGroup {
queries,
evaluations_per_second: 1_000.0 / f64::from(interval_ms)
* fraction
* distinct_instants_per_request(&longest_span_ms_by_step_ms),
schedule: Schedule::FixedInterval,
}
},
)
.collect();
Expand Down
57 changes: 57 additions & 0 deletions crates/cost/src/plan/execution_demand/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ fn fixed(interval: u32, phase: u64) -> QueryRecurrence {
interval: RepetitionInterval(interval),
evaluation_phase: TimestampMs(phase),
requested_fraction: None,
exclusive_group: None,
})
}

Expand Down Expand Up @@ -568,6 +569,7 @@ fn requested_fraction_scales_the_evaluation_rate() {
interval: RepetitionInterval(10_000),
evaluation_phase: TimestampMs(0),
requested_fraction: Some(0.1),
exclusive_group: None,
});
close(
evaluation_rate([(&sampled, None)], 3600.0).unwrap(),
Expand All @@ -579,3 +581,58 @@ fn requested_fraction_scales_the_evaluation_rate() {
1.0 / 10.0,
);
}

/// A fixed interval requested at `fraction` of its times, one alternative
/// of the exclusive choice `group` when given.
fn alternative(fraction: f64, group: Option<&str>) -> QueryRecurrence {
QueryRecurrence::Repeated(RepeatedDemand::FixedIntervalAt {
interval: RepetitionInterval(10_000),
evaluation_phase: TimestampMs(0),
requested_fraction: Some(fraction),
exclusive_group: group.map(str::to_string),
})
}

/// Exclusive alternatives (one of them asked per round, each with its
/// fraction) add: a node both read is computed at 0.3 + 0.7 of the
/// rounds, not at the larger 0.7. Without the marker the readers are
/// nested (a dependent below its upstream) and the larger stays.
#[test]
fn exclusive_alternatives_add_their_fractions() {
let (a, b) = (alternative(0.3, Some("q1")), alternative(0.7, Some("q1")));
close(
evaluation_rate([(&a, None), (&b, None)], 3600.0).unwrap(),
1.0 / 10.0,
);
let (a, b) = (alternative(0.3, None), alternative(0.7, None));
close(
evaluation_rate([(&a, None), (&b, None)], 3600.0).unwrap(),
0.7 / 10.0,
);
}

/// One choice's sum is one reader among the others on its schedule: the
/// largest of the sum (0.2 + 0.3) and an independent reader (0.4), or of
/// two choices' sums; a sum above 1 is capped at every round.
#[test]
fn an_exclusive_choice_is_one_reader_at_its_summed_fraction() {
let (a, b, other) = (
alternative(0.2, Some("q1")),
alternative(0.3, Some("q1")),
alternative(0.4, None),
);
close(
evaluation_rate([(&a, None), (&b, None), (&other, None)], 3600.0).unwrap(),
0.5 / 10.0,
);
let (c, d) = (alternative(0.25, Some("q2")), alternative(0.5, Some("q2")));
close(
evaluation_rate([(&a, None), (&b, None), (&c, None), (&d, None)], 3600.0).unwrap(),
0.75 / 10.0,
);
let (e, f) = (alternative(0.6, Some("q3")), alternative(0.7, Some("q3")));
close(
evaluation_rate([(&e, None), (&f, None)], 3600.0).unwrap(),
1.0 / 10.0,
);
}
1 change: 1 addition & 0 deletions crates/devtools/tests/planner_fuzz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,6 +391,7 @@ fn summed_over_a_chain(labels: &[&str]) -> FuzzWorkload {
interval: RepetitionInterval(60_000),
evaluation_phase: TimestampMs(0),
requested_fraction: None,
exclusive_group: None,
};
generated_workload(Language::Promql, vec![query], 1_000, 1_000)
}
Expand Down
1 change: 1 addition & 0 deletions crates/executor/tests/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ mod raw_scan;
mod sql_relational_operators;
mod state_column_updater;
mod stored_tumbling_window_memory_limit;
mod streamed_copies;
mod summary_projection;
mod text_extremum_memory;
mod thread_safety;
Expand Down
154 changes: 154 additions & 0 deletions crates/executor/tests/streamed_copies.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
//! A plan that streams one copy of a query-time result per reader (two
//! exclusive alternatives over one hour of raw rows, each with its own
//! `TimeRange` instead of one held for both) runs: each copy reads the raw
//! data on its own, and each query's answer equals its answer planned
//! alone.

use std::{collections::BTreeMap, sync::Arc};

use asap_executor::sources::InMemoryDataStore;
use asap_executor::{
physical_planner::{compile, promql_rows},
runtime::{Limits, RunContext, Scope},
values::Batch,
};
use asap_planner::{e2e_plan, FrontendInput, PlanningModels, UserInput};
use futures::{executor::block_on, StreamExt};
use planner_types::ir::operator::Source;
use planner_types::ir::NonASAPOp;
use planner_types::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPOperatorPayload};
use planner_types::stages::Lifetime;
use planner_types::workload::PlanningWorkload;

/// `queries` (each its text, requested fraction and exclusive choice)
/// every 60 s over the gauge `m`.
fn workload(queries: &[(&str, f64, Option<&str>)]) -> PlanningWorkload {
let entries: Vec<serde_json::Value> = queries
.iter()
.map(|(query, fraction, group)| {
let mut demand = serde_json::json!({"interval": 60_000, "evaluation_phase": 0,
"requested_fraction": fraction});
if let Some(group) = group {
demand["exclusive_group"] = serde_json::json!(group);
}
serde_json::json!({
"query": query,
"demand": {"fixed_interval_at": demand},
"requirements": {"max_latency_ms": null},
"predictability": {"predictable": {"known_at": null}},
})
})
.collect();
serde_json::from_value(serde_json::json!({
"query_workload": {"language": "promql", "repeating_queries": entries},
"data_workload": {
"arrival": {"ingesting": {"rows_per_second": 1000.0}},
"sources": {"m": {"series_count": 1000, "metric_type": "gauge", "sample_interval": 1000}},
},
}))
.unwrap()
}

fn plan(workload: &PlanningWorkload) -> PhysicalASAPDAG {
block_on(e2e_plan(UserInput::new(
workload,
FrontendInput::Promql,
PlanningModels::builtin(),
)))
.expect("the workload plans")
.plan
}

/// `(instance, ts, value)` samples of `m`.
const SAMPLES: &[(&str, i64, f64)] = &[
("a", 3_000_000, 4.),
("a", 3_100_000, 4.),
("a", 3_200_000, 1.),
("b", 3_300_000, 7.),
("b", 3_400_000, 2.),
("b", 3_500_000, 2.),
];
const END_MS: i64 = 3_600_000;

/// Each root's `(series, value)` rows in one query-time run of `dag` over
/// [`SAMPLES`], every raw data slot bound to them.
fn run_every_root(dag: &PhysicalASAPDAG) -> Vec<BTreeMap<String, String>> {
let roots: Vec<u64> = dag.roots.iter().map(|&root| root as u64).collect();
let program = compile(dag, &[], &roots).unwrap();
let mut store = InMemoryDataStore::default();
let mut bound: Vec<Source> = Vec::new();
for node in &dag.nodes {
let PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::Scan { source, .. }) = &node.payload
else {
continue;
};
if bound.contains(source) {
continue;
}
bound.push(source.clone());
let schema = Arc::new(node.output_schema.clone());
let rows = SAMPLES
.iter()
.map(|(instance, at, value)| {
let labels = BTreeMap::from([
("__name__".to_string(), "m".to_string()),
("instance".to_string(), instance.to_string()),
]);
promql_rows::series_row(&schema, &labels, *at, *value).unwrap()
})
.collect();
let batch = Batch::try_new(schema.clone(), rows).unwrap();
store = store
.with_raw_data(source.clone(), schema, vec![batch])
.unwrap();
}
let physical_dag = program.instantiate(Arc::new(store)).unwrap();
let context = RunContext::new(
Scope::Query {
evaluation_time_ms: END_MS,
},
Limits::default(),
)
.unwrap();
block_on(async {
let mut answers = Vec::new();
for mut stream in physical_dag.execute(program.roots(), context).unwrap() {
let mut rows = BTreeMap::new();
while let Some(batch) = stream.next().await {
for row in batch.unwrap().to_rows() {
let (value, key) = row.split_last().unwrap();
rows.insert(format!("{key:?}"), format!("{value:?}"));
}
}
answers.push(rows);
}
answers
})
}

#[test]
fn streamed_copies_per_reader_run_and_answer_as_planned_alone() {
let queries = ["entropy_over_time(m[1h])", "l2_over_time(m[1h])"];
let joint = plan(&workload(&[
(queries[0], 0.4, Some("q")),
(queries[1], 0.6, Some("q")),
]));
let time_ranges: Vec<Lifetime> = joint
.nodes
.iter()
.filter(|node| {
matches!(
node.payload,
PhysicalASAPOperatorPayload::NonASAP(NonASAPOp::TimeRange { .. })
)
})
.map(|node| node.lifetime)
.collect();
assert_eq!(time_ranges, [Lifetime::None, Lifetime::None], "{joint:#?}");
let answers = run_every_root(&joint);
for (index, query) in queries.iter().enumerate() {
let alone = run_every_root(&plan(&workload(&[(query, 1.0, None)])));
assert!(!answers[index].is_empty(), "{query}");
assert_eq!(answers[index], alone[0], "{query}");
}
}
38 changes: 38 additions & 0 deletions crates/frontend-sil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,17 @@
//! WHERE ts > $now - INTERVAL '1 hour' GROUP BY host REQUIRE EXACT;
//! GROUP (q1, q2) LATENCY <= 150ms;
//! ```
//!
//! A weighted choice `{alternative: p, …}` in a query's text (an
//! uncertain operator or constant, its distribution mined from history)
//! makes the query one alternative query per alternative
//! ([`ExclusiveChoice`]), at most one asked per round:
//!
//! ```text
//! q4: SELECT host, {count: 0.4, approx_distinct: 0.6}(dst) FROM flows GROUP BY host
//! REQUIRE ERROR rel <= 0.05 DELTA 0.01;
//! q5: SELECT approx_percentile_cont(bytes, {0.5: 0.3, 0.99: 0.7}) FROM flows REQUIRE EXACT;
//! ```

use std::collections::BTreeMap;

Expand Down Expand Up @@ -78,6 +89,29 @@ pub struct IntentQuery {
/// `KEYS ~n`: the result rows per round the user declares, used only
/// when the planner cannot bound them.
pub declared_result_rows: Option<u64>,
/// The choice this query is one alternative of, when its text holds
/// a weighted choice (`{count: 0.4, approx_distinct: 0.6}(dst)`);
/// `None` for a query without one.
pub exclusive_choice: Option<ExclusiveChoice>,
}

/// Which alternative of a weighted choice a query is. A query written with
/// choices (`q1: SELECT {count: 0.4, approx_distinct: 0.6}(dst) …`) is
/// one query per combination of their alternatives (`q1#0`, `q1#1`), the
/// choices replaced by the alternatives' text: in each round at most one
/// of them is asked, each with its probability.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ExclusiveChoice {
/// The id of the query as written (`q1`): the choice's name.
pub choice_query_id: String,
/// Its position among the choice's alternatives asked with a positive
/// probability (its id is `{choice_query_id}#{alternative_index}`).
pub alternative_index: usize,
/// The chance it is the alternative asked in a round, in (0, 1]: the
/// product of its alternatives' probabilities; the choice's add to at
/// most 1.
pub probability: f64,
}

/// One hole of a query's text.
Expand Down Expand Up @@ -155,6 +189,10 @@ pub enum SilError {
/// Two queries with one id.
#[error("query id {query_id} is used twice")]
DuplicateQueryId { query_id: String },
/// A weighted choice whose probabilities are outside [0, 1], add to
/// more than 1 or are all 0, or one in a query that binds variables.
#[error("query {query_id}: {message}")]
InvalidChoice { query_id: String, message: String },
}

/// Parse and check a SIL program: one or more intents.
Expand Down
Loading