From 43f78e22324843e95cc9eddb9571ed4729d2216d Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:25:17 +0000 Subject: [PATCH 01/20] test(data_plane): intent round loop interface and failing tests The intent round loop's schedule, record and binding-step types, with the bodies left as todo!, and the tests of the spec: empty binding skip, chain of three, fan-out, diamond, duplicate values, upstream error and timeout, round overrun, group latency, accuracy against the issued binding, schedule validation, parameter-slot mode, and one round over a real installed plan. Every test fails at the todo!. Co-Authored-By: Claude Opus 5.5 --- data_plane/Cargo.toml | 2 + data_plane/src/intent.rs | 747 ++++++++++++++++++++++++++++++ data_plane/src/lib.rs | 1 + data_plane/tests/intent_rounds.rs | 200 ++++++++ 4 files changed, 950 insertions(+) create mode 100644 data_plane/src/intent.rs create mode 100644 data_plane/tests/intent_rounds.rs diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index e08a01bfe..032897ee1 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -36,6 +36,8 @@ futures = "0.3" form_urlencoded = "1" [dev-dependencies] +# Paused time for the intent loop's latency and overrun tests. +tokio = { workspace = true, features = ["test-util"] } control_plane.workspace = true tower = { version = "0.5", features = ["util"] } http-body-util = "0.1" diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs new file mode 100644 index 000000000..715b56b86 --- /dev/null +++ b/data_plane/src/intent.rs @@ -0,0 +1,747 @@ +//! Intent round loop: runs a planned intent's queries round by round. +//! +//! An intent is a set of planned queries with dependencies: a downstream +//! query reads a variable (`$Y`) bound to the values of one output column of +//! an upstream query's answer. At each round's evaluation time `T` the loop +//! runs the queries in topological order, binds each upstream answer's +//! column values into the downstream queries that read them, skips a query +//! whose binding is empty, and records each query's latency, each latency +//! group's latency, the bindings issued and the answers. +//! +//! The schedule type here mirrors the planner's `intent_rounds` output +//! (the SIL planner <-> data plane contract); it is the one place to adapt +//! when the planner's final JSON schema lands. No planning happens here: each +//! query is answered by the installed plan, as an HTTP query is. +//! +//! How a bound value reaches the plan is the binding step +//! ([`BindMode`]): today the downstream query is planned grouped by the +//! bound column and its answer is filtered by the binding +//! ([`BindMode::FilterGroupedResult`]); filling a parameter slot of the plan +//! per round ([`BindMode::ParameterSlot`]) waits for the planner to emit +//! such slots. + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use tokio::time::Instant; + +use crate::query::{ResultSample, Unanswered}; +use crate::result_cache::Answer; + +/// The output column naming an answer row's value rather than a label. +pub const VALUE_COLUMN: &str = "__value__"; + +/// One planned intent's rounds: the queries run every `round_interval_ms`. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntentSchedule { + /// Time between two rounds' evaluation times. + pub round_interval_ms: u64, + /// The intent's queries, in any order (the loop orders them). + pub queries: Vec, + /// Latency targets over sets of queries of one round (`GROUP (q1, q2) <= L`). + #[serde(default)] + pub group_latency_ms: Vec, +} + +/// One query of an intent. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct IntentQuery { + /// The query's name in the intent (`q1`). + pub query_id: String, + /// The installed plan's query text that answers it (the contract's + /// `plan_root`, resolved to its query text). + pub query: String, + /// The variables it reads and the upstream answers that bind them. + #[serde(default)] + pub depends_on: Vec, + /// Where each variable it reads is applied. + #[serde(default)] + pub bind_slots: Vec, + /// Fraction of rounds it runs in; only 1 (every round) is supported. + #[serde(default = "every_round")] + pub rate: f64, + /// Skip the query in a round where one of its bindings is empty + /// (default true, as the contract requires). + #[serde(default = "skip_if_empty")] + pub skip_if_empty: bool, +} + +fn every_round() -> f64 { + 1.0 +} + +fn skip_if_empty() -> bool { + true +} + +/// A variable bound to one output column of an upstream query's answer. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Dependency { + /// The variable's name (`Y` for `$Y`). + pub variable: String, + /// The query whose answer binds it. + pub upstream_query_id: String, + /// The upstream answer's column whose values bind it: a label name, or + /// [`VALUE_COLUMN`] for the value. (The contract's `output_position`, + /// resolved to the column it names.) + pub output_column: String, +} + +/// Where a variable's values are applied to the downstream query. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct BindSlot { + /// The variable applied. + pub variable: String, + /// The downstream answer's label the binding filters on + /// ([`BindMode::FilterGroupedResult`]): `host` for `host IN $Y`. + pub column: String, +} + +/// A latency target over queries of one round. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GroupLatency { + pub query_ids: Vec, + /// From the first of them starting to the last of them ending. + pub max_ms: u64, +} + +/// How a binding reaches the downstream query: the binding step. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)] +#[serde(rename_all = "snake_case")] +pub enum BindMode { + /// Run the downstream query as planned (grouped by each bound column) + /// and keep the answer rows whose bound columns hold a bound value. + /// Needs no planner or executor change. + FilterGroupedResult, + /// Fill the plan's parameter slot (an `IN` list on a query-time filter + /// node) with the bound values each round. Follow-up: waits for the + /// planner to emit parameter slots and the executor to accept values. + ParameterSlot, +} + +/// What the loop runs a planned query with. +pub trait QueryRunner: Sync { + /// The installed plan's answer to `query` at `time_ms`. + fn answer( + &self, + query: &str, + time_ms: i64, + ) -> impl Future> + Send; +} + +/// A variable's values in one round, deduplicated and sorted. +pub type Bindings = BTreeMap>; + +/// An intent ready to run: its schedule checked and its queries ordered. +#[derive(Debug, Clone)] +pub struct IntentLoop { + schedule: IntentSchedule, + /// Indices into `schedule.queries`, every upstream before its consumers. + order: Vec, + mode: BindMode, + query_timeout: Duration, +} + +/// What happened to one query in one round. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum QueryStatus { + Answered, + /// A binding it reads was empty: not run. + SkippedEmptyBinding, + /// An upstream query failed or was skipped: not run. + SkippedUpstream, + /// Its run failed or timed out (`error` says which). + Failed, +} + +/// One answer row. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AnswerRow { + pub labels: BTreeMap, + pub value: f64, +} + +/// One query in one round. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct QueryRecord { + pub query_id: String, + pub status: QueryStatus, + /// From starting its run to having its (filtered) answer; `None` when + /// it did not run. + pub latency_ms: Option, + /// The bindings issued to it (empty ones included). + pub bindings: Bindings, + pub answer: Vec, + pub error: Option, +} + +/// One latency group in one round. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct GroupRecord { + pub query_ids: Vec, + pub max_ms: u64, + /// From the first member starting to the last member ending, over the + /// members that ran; `None` when none ran. + pub latency_ms: Option, + /// Whether every member ran. + pub complete: bool, + /// Every member ran and `latency_ms <= max_ms`. + pub met: bool, +} + +/// Whether a round ran. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RoundStatus { + Ran, + /// Its start passed while an earlier round still ran: not run. + Missed, +} + +/// One round: its queries and groups. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct RoundRecord { + pub round: u64, + pub evaluation_ms: i64, + pub status: RoundStatus, + /// How long after its scheduled start it started. + pub start_lag_ms: f64, + pub duration_ms: f64, + /// It ended after the next round's scheduled start. + pub overrun: bool, + pub queries: Vec, + pub groups: Vec, +} + +impl IntentLoop { + /// Checks `schedule` and orders its queries. Refused (bad input): an + /// unknown upstream or group member, a variable bound by more than one + /// dependency or read without one, a dependency cycle, or a rate other + /// than 1. + pub fn new( + schedule: IntentSchedule, + mode: BindMode, + query_timeout: Duration, + ) -> anyhow::Result { + let _ = (schedule, mode, query_timeout); + todo!("intent round loop: validate and order") + } + + /// The query ids in the order a round runs them. + pub fn order(&self) -> Vec<&str> { + self.order + .iter() + .map(|&i| self.schedule.queries[i].query_id.as_str()) + .collect() + } + + /// Runs round `round` at evaluation time `time_ms`. + pub async fn run_round( + &self, + runner: &R, + round: u64, + time_ms: i64, + ) -> RoundRecord { + let _ = (runner, round, time_ms, self.mode, self.query_timeout); + todo!("intent round loop: one round") + } + + /// Runs `rounds` rounds: round r evaluates at `first_evaluation_ms + r + /// * interval` and starts at `start + r * interval`. Rounds never + /// overlap: a round whose start passes while an earlier one runs is + /// recorded as missed, not run. `emit` gets each round as it ends. + pub async fn run_rounds( + &self, + runner: &R, + first_evaluation_ms: i64, + rounds: u64, + start: Instant, + emit: impl FnMut(RoundRecord), + ) { + let _ = (runner, first_evaluation_ms, rounds, start, emit); + todo!("intent round loop: rounds") + } +} + +impl QueryRunner for crate::engine::EngineHandle { + /// The result cache's answer, else a query run, as an HTTP instant + /// query is answered. + async fn answer(&self, query: &str, time_ms: i64) -> Result { + let _ = (query, time_ms); + todo!("intent round loop: engine runner") + } +} + +/// The distinct values of `column` in `answer`. +pub fn binding_values(answer: &[ResultSample], column: &str) -> BTreeSet { + let _ = (answer, column); + todo!("intent round loop: binding values") +} + +/// The rows of `answer` whose label `slot.column` holds one of +/// `bindings[slot.variable]`, for every slot. The harness filters the exact +/// reference with it too: a dependent query's accuracy is defined for the +/// binding actually issued. +pub fn filter_by_bindings( + answer: &[ResultSample], + slots: &[BindSlot], + bindings: &Bindings, +) -> Vec { + let _ = (answer, slots, bindings); + todo!("intent round loop: filter") +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + /// A fake installed plan: each query text's answer, latency and error. + #[derive(Default)] + struct FakeRunner { + answers: BTreeMap>, + delays: BTreeMap, + errors: BTreeMap, + /// Query texts in the order they were run. + calls: Mutex>, + } + + impl FakeRunner { + fn with(mut self, query: &str, rows: &[(&[(&str, &str)], f64)]) -> Self { + self.answers.insert(query.into(), rows_of(rows)); + self + } + fn delay(mut self, query: &str, ms: u64) -> Self { + self.delays.insert(query.into(), Duration::from_millis(ms)); + self + } + fn error(mut self, query: &str, error: &str) -> Self { + self.errors.insert(query.into(), error.into()); + self + } + fn calls(&self) -> Vec { + self.calls.lock().unwrap().clone() + } + } + + impl QueryRunner for FakeRunner { + async fn answer(&self, query: &str, _time_ms: i64) -> Result { + self.calls.lock().unwrap().push(query.to_string()); + if let Some(delay) = self.delays.get(query) { + tokio::time::sleep(*delay).await; + } + if let Some(error) = self.errors.get(query) { + return Err(Unanswered::Execution(error.clone())); + } + Ok(Arc::new( + self.answers.get(query).cloned().unwrap_or_default(), + )) + } + } + + fn rows_of(rows: &[(&[(&str, &str)], f64)]) -> Vec { + rows.iter() + .map(|(labels, value)| ResultSample { + labels: Arc::new( + labels + .iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect(), + ), + value: *value, + }) + .collect() + } + + /// A query whose text is its id, reading `deps` (variable, upstream, + /// output column) through slots filtering on (variable, column). + fn query(id: &str, deps: &[(&str, &str, &str)], slots: &[(&str, &str)]) -> IntentQuery { + IntentQuery { + query_id: id.into(), + query: id.into(), + depends_on: deps + .iter() + .map(|(variable, upstream, column)| Dependency { + variable: (*variable).into(), + upstream_query_id: (*upstream).into(), + output_column: (*column).into(), + }) + .collect(), + bind_slots: slots + .iter() + .map(|(variable, column)| BindSlot { + variable: (*variable).into(), + column: (*column).into(), + }) + .collect(), + rate: 1.0, + skip_if_empty: true, + } + } + + fn schedule(queries: Vec) -> IntentSchedule { + IntentSchedule { + round_interval_ms: 1_000, + queries, + group_latency_ms: vec![], + } + } + + fn intent(queries: Vec) -> IntentLoop { + IntentLoop::new( + schedule(queries), + BindMode::FilterGroupedResult, + Duration::from_secs(10), + ) + .unwrap() + } + + fn record<'a>(round: &'a RoundRecord, id: &str) -> &'a QueryRecord { + round.queries.iter().find(|q| q.query_id == id).unwrap() + } + + fn values(values: &[&str]) -> BTreeSet { + values.iter().map(|v| v.to_string()).collect() + } + + fn label_values(record: &QueryRecord, label: &str) -> Vec { + record + .answer + .iter() + .map(|row| row.labels[label].clone()) + .collect() + } + + /// q1 -> q2 over `host`: the shape most tests use. + fn host_pair() -> Vec { + vec![ + query("q1", &[], &[]), + query("q2", &[("Y", "q1", "host")], &[("Y", "host")]), + ] + } + + /// A downstream query whose binding is empty is skipped, not run, and + /// the empty binding is recorded. + #[tokio::test] + async fn empty_binding_skips_the_downstream_query() { + let runner = FakeRunner::default() + .with("q1", &[]) + .with("q2", &[(&[("host", "a")], 1.0)]); + let round = intent(host_pair()).run_round(&runner, 0, 1_000).await; + let q2 = record(&round, "q2"); + assert_eq!(q2.status, QueryStatus::SkippedEmptyBinding); + assert_eq!(q2.latency_ms, None); + assert_eq!(q2.bindings["Y"], values(&[])); + assert_eq!(runner.calls(), vec!["q1"]); + } + + /// q1 -> q2 -> q3: each runs after its upstream, filtered by the values + /// its upstream's (filtered) answer holds. + #[tokio::test] + async fn chain_of_three_binds_each_hop() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 9.0), (&[("host", "b")], 8.0)]) + .with( + "q2", + &[ + (&[("host", "a"), ("user", "u1")], 1.0), + (&[("host", "b"), ("user", "u2")], 1.0), + (&[("host", "c"), ("user", "u3")], 1.0), + ], + ) + .with( + "q3", + &[ + (&[("user", "u1")], 5.0), + (&[("user", "u2")], 6.0), + (&[("user", "u3")], 7.0), + ], + ); + let queries = vec![ + query("q3", &[("Z", "q2", "user")], &[("Z", "user")]), + query("q1", &[], &[]), + query("q2", &[("Y", "q1", "host")], &[("Y", "host")]), + ]; + let intent = intent(queries); + assert_eq!(intent.order(), vec!["q1", "q2", "q3"]); + let round = intent.run_round(&runner, 0, 1_000).await; + assert_eq!(runner.calls(), vec!["q1", "q2", "q3"]); + assert_eq!(record(&round, "q2").bindings["Y"], values(&["a", "b"])); + assert_eq!(label_values(record(&round, "q2"), "user"), ["u1", "u2"]); + assert_eq!(record(&round, "q3").bindings["Z"], values(&["u1", "u2"])); + assert_eq!(label_values(record(&round, "q3"), "user"), ["u1", "u2"]); + assert!(round + .queries + .iter() + .all(|q| q.status == QueryStatus::Answered)); + } + + /// One upstream feeding two downstream queries runs once; both get its + /// binding. + #[tokio::test] + async fn fan_out_runs_the_upstream_once() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .with("q2", &[(&[("host", "a")], 1.0), (&[("host", "b")], 2.0)]) + .with("q3", &[(&[("host", "a")], 3.0), (&[("host", "b")], 4.0)]); + let queries = vec![ + query("q1", &[], &[]), + query("q2", &[("Y", "q1", "host")], &[("Y", "host")]), + query("q3", &[("Y", "q1", "host")], &[("Y", "host")]), + ]; + let round = intent(queries).run_round(&runner, 0, 1_000).await; + assert_eq!(runner.calls(), vec!["q1", "q2", "q3"]); + assert_eq!(label_values(record(&round, "q2"), "host"), ["a"]); + assert_eq!(label_values(record(&round, "q3"), "host"), ["a"]); + } + + /// Diamond q1 -> (q2, q3) -> q4: q4 runs last and keeps only rows + /// matching both bindings. + #[tokio::test] + async fn diamond_applies_every_binding() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0), (&[("host", "b")], 1.0)]) + .with( + "q2", + &[ + (&[("host", "a"), ("user", "u1")], 1.0), + (&[("host", "x"), ("user", "u9")], 1.0), + ], + ) + .with("q3", &[(&[("host", "b"), ("region", "r1")], 1.0)]) + .with( + "q4", + &[ + (&[("user", "u1"), ("region", "r1")], 1.0), + (&[("user", "u1"), ("region", "r2")], 2.0), + (&[("user", "u2"), ("region", "r1")], 3.0), + ], + ); + let queries = vec![ + query( + "q4", + &[("U", "q2", "user"), ("R", "q3", "region")], + &[("U", "user"), ("R", "region")], + ), + query("q3", &[("Y3", "q1", "host")], &[("Y3", "host")]), + query("q2", &[("Y2", "q1", "host")], &[("Y2", "host")]), + query("q1", &[], &[]), + ]; + let intent = intent(queries); + assert_eq!(intent.order().first(), Some(&"q1")); + assert_eq!(intent.order().last(), Some(&"q4")); + let round = intent.run_round(&runner, 0, 1_000).await; + let q4 = record(&round, "q4"); + assert_eq!(q4.bindings["U"], values(&["u1"])); + assert_eq!(q4.bindings["R"], values(&["r1"])); + assert_eq!(q4.answer.len(), 1); + assert_eq!(q4.answer[0].value, 1.0); + } + + /// Repeated upstream values bind once and duplicate no downstream row. + #[tokio::test] + async fn duplicate_values_bind_once() { + let runner = FakeRunner::default() + .with( + "q1", + &[ + (&[("host", "a"), ("dst", "d1")], 1.0), + (&[("host", "a"), ("dst", "d2")], 2.0), + ], + ) + .with("q2", &[(&[("host", "a")], 7.0), (&[("host", "b")], 8.0)]); + let round = intent(host_pair()).run_round(&runner, 0, 1_000).await; + let q2 = record(&round, "q2"); + assert_eq!(q2.bindings["Y"], values(&["a"])); + assert_eq!(q2.answer.len(), 1); + } + + /// An upstream that fails is recorded with its error; its downstream + /// query is skipped, not run. + #[tokio::test] + async fn upstream_error_skips_downstream() { + let runner = FakeRunner::default() + .error("q1", "pane missing") + .with("q2", &[(&[("host", "a")], 1.0)]); + let round = intent(host_pair()).run_round(&runner, 0, 1_000).await; + let q1 = record(&round, "q1"); + assert_eq!(q1.status, QueryStatus::Failed); + assert!(q1.error.as_deref().unwrap().contains("pane missing")); + assert_eq!(record(&round, "q2").status, QueryStatus::SkippedUpstream); + assert_eq!(runner.calls(), vec!["q1"]); + } + + /// An upstream slower than the query timeout fails as timed out; its + /// downstream query is skipped. + #[tokio::test(start_paused = true)] + async fn upstream_timeout_skips_downstream() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .delay("q1", 5_000); + let intent = IntentLoop::new( + schedule(host_pair()), + BindMode::FilterGroupedResult, + Duration::from_secs(1), + ) + .unwrap(); + let round = intent.run_round(&runner, 0, 1_000).await; + let q1 = record(&round, "q1"); + assert_eq!(q1.status, QueryStatus::Failed); + assert!(q1.error.as_deref().unwrap().contains("timed out")); + assert_eq!(record(&round, "q2").status, QueryStatus::SkippedUpstream); + } + + /// A round longer than the interval is marked overrun; the rounds whose + /// start passed meanwhile are recorded as missed, and the next round + /// runs at its own start and evaluation time. + #[tokio::test(start_paused = true)] + async fn overrun_misses_the_passed_rounds() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .delay("q1", 2_500); + let intent = intent(vec![query("q1", &[], &[])]); + let mut rounds = Vec::new(); + let start = Instant::now(); + intent + .run_rounds(&runner, 10_000, 4, start, |r| rounds.push(r)) + .await; + let status: Vec<_> = rounds.iter().map(|r| (r.round, r.status)).collect(); + assert_eq!( + status, + vec![ + (0, RoundStatus::Ran), + (1, RoundStatus::Missed), + (2, RoundStatus::Missed), + (3, RoundStatus::Ran), + ] + ); + assert!(rounds[0].overrun); + assert_eq!(rounds[3].evaluation_ms, 13_000); + assert_eq!(rounds[3].start_lag_ms, 0.0); + assert_eq!(runner.calls().len(), 2); + } + + /// Group latency spans the first member's start to the last member's + /// end; each query's latency is its own run. + #[tokio::test(start_paused = true)] + async fn group_latency_spans_its_members() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .delay("q1", 300) + .with("q2", &[(&[("host", "a")], 1.0)]) + .delay("q2", 200); + let mut schedule = schedule(host_pair()); + schedule.group_latency_ms = vec![GroupLatency { + query_ids: vec!["q1".into(), "q2".into()], + max_ms: 400, + }]; + let intent = IntentLoop::new( + schedule, + BindMode::FilterGroupedResult, + Duration::from_secs(10), + ) + .unwrap(); + let round = intent.run_round(&runner, 0, 1_000).await; + assert_eq!(record(&round, "q1").latency_ms, Some(300.0)); + assert_eq!(record(&round, "q2").latency_ms, Some(200.0)); + let group = &round.groups[0]; + assert_eq!(group.latency_ms, Some(500.0)); + assert!(group.complete); + assert!(!group.met); + } + + /// The dependent query answers for the binding the approximate upstream + /// issued ({a, c}), not the exact top hosts ({a, b}): it equals the + /// exact grouped answer filtered by the issued binding. + #[tokio::test] + async fn dependent_answer_follows_the_issued_binding() { + let grouped = [ + (&[("host", "a")][..], 10.0), + (&[("host", "b")][..], 20.0), + (&[("host", "c")][..], 30.0), + ]; + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 9.0), (&[("host", "c")], 8.0)]) + .with("q2", &grouped); + let intent = intent(host_pair()); + let round = intent.run_round(&runner, 0, 1_000).await; + let q2 = record(&round, "q2"); + assert_eq!(q2.bindings["Y"], values(&["a", "c"])); + let slots = &host_pair()[1].bind_slots; + let reference = filter_by_bindings(&rows_of(&grouped), slots, &q2.bindings); + let reference: Vec = reference + .iter() + .map(|s| AnswerRow { + labels: (*s.labels).clone(), + value: s.value, + }) + .collect(); + assert_eq!(q2.answer, reference); + assert_eq!(label_values(q2, "host"), ["a", "c"]); + } + + /// Bad schedules are refused with the reason. + #[test] + fn invalid_schedules_are_refused() { + let refused = |queries: Vec, reason: &str| { + let error = IntentLoop::new( + schedule(queries), + BindMode::FilterGroupedResult, + Duration::from_secs(1), + ) + .unwrap_err() + .to_string(); + assert!(error.contains(reason), "{error:?} lacks {reason:?}"); + }; + refused( + vec![ + query("q1", &[("X", "q2", "host")], &[("X", "host")]), + query("q2", &[("Y", "q1", "host")], &[("Y", "host")]), + ], + "cycle", + ); + refused( + vec![query("q2", &[("Y", "q9", "host")], &[("Y", "host")])], + "unknown upstream", + ); + refused( + vec![ + query("q1", &[], &[]), + query("q0", &[], &[]), + query("q2", &[("Y", "q1", "host")], &[("Y", "host")]), + query("q3", &[("Y", "q0", "host")], &[("Y", "host")]), + ], + "bound by more than one", + ); + refused( + vec![query("q1", &[], &[]), query("q2", &[], &[("Y", "host")])], + "no dependency binds", + ); + let mut sampled = host_pair(); + sampled[1].rate = 0.5; + refused(sampled, "rate"); + } + + /// Parameter-slot binding is a marked follow-up: the query fails with + /// the reason instead of running unbound. + #[tokio::test] + async fn parameter_slot_mode_is_not_supported_yet() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0)]) + .with("q2", &[(&[("host", "a")], 1.0)]); + let intent = IntentLoop::new( + schedule(host_pair()), + BindMode::ParameterSlot, + Duration::from_secs(1), + ) + .unwrap(); + let round = intent.run_round(&runner, 0, 1_000).await; + let q2 = record(&round, "q2"); + assert_eq!(q2.status, QueryStatus::Failed); + assert!(q2.error.as_deref().unwrap().contains("parameter slot")); + assert_eq!(runner.calls(), vec!["q1"]); + } +} diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 5d7167674..89090a93d 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -16,6 +16,7 @@ pub mod engine; pub mod ingestion; +pub mod intent; pub mod memory_budget; pub mod metrics; pub mod persist; diff --git a/data_plane/tests/intent_rounds.rs b/data_plane/tests/intent_rounds.rs new file mode 100644 index 000000000..d2c1b9b7a --- /dev/null +++ b/data_plane/tests/intent_rounds.rs @@ -0,0 +1,200 @@ +//! The intent round loop over a real installed plan: an upstream query's +//! answer binds a downstream query planned grouped by the bound label, and +//! the downstream answer is the engine's grouped answer filtered by the +//! values the upstream issued. + +mod common; + +use std::collections::BTreeMap; +use std::sync::Arc; +use std::time::Duration; + +use asap_planner::PlanningWorkload; +use control_plane::plan_workload; +use data_plane::engine::EngineOptions; +use data_plane::intent::{ + BindMode, BindSlot, Dependency, IntentLoop, IntentQuery, IntentSchedule, QueryRunner, + QueryStatus, +}; +use data_plane::remote_write::{Label, Sample, TimeSeries}; +use data_plane::{router, DataPlane}; + +/// The evaluation time of the round. +const EVALUATION_MS: i64 = 3_600_000; + +/// The upstream: the region with the largest 100 s sum. +const UPSTREAM: &str = "topk(1, sum by (region) (sum_over_time(data[100s])))"; +/// The downstream, planned grouped by the bound label `region`. +const DOWNSTREAM: &str = "sum by (region, service) (sum_over_time(data[100s]))"; + +/// `queries` every 10 s, exact, over six series of `data`, planned jointly. +fn workload(queries: &[&str]) -> PlanningWorkload { + let entries: Vec = queries + .iter() + .map(|query| { + format!( + r#"{{"query": {query:?}, "demand": {{"fixed_interval_at": {{"interval": 10000, "evaluation_phase": 0}}}}, + "requirements": {{}}, + "predictability": {{"predictable": {{"known_at": null}}}}}}"# + ) + }) + .collect(); + serde_json::from_str(&format!( + r#"{{"query_workload": {{"language": "promql", "repeating_queries": [{}]}}, + "data_workload": {{"arrival": {{"ingesting": {{"rows_per_second": 0.6}}}}, + "sources": {{"data": {{"series_count": 6, "sample_interval": 10000, + "metric_type": "gauge", "column_signs": {{"value": "non_negative"}}}}}}}}}}"#, + entries.join(",") + )) + .unwrap() +} + +/// Six series (region east/west x service api/web/db), one sample every +/// 10 s over the two minutes before `EVALUATION_MS`; west's are larger. +fn series() -> Vec { + let mut all = Vec::new(); + for (s, (region, service)) in [ + ("east", "api"), + ("east", "web"), + ("east", "db"), + ("west", "api"), + ("west", "web"), + ("west", "db"), + ] + .into_iter() + .enumerate() + { + let labels = [ + ("__name__", "data"), + ("region", region), + ("service", service), + ] + .iter() + .map(|(name, value)| Label { + name: name.to_string(), + value: value.to_string(), + }) + .collect(); + let samples = (0..12) + .map(|step| Sample { + timestamp: EVALUATION_MS - 120_000 + 5_000 + step * 10_000, + value: (s as f64 + 1.0) * 10.0 + step as f64, + }) + .collect(); + all.push(TimeSeries { labels, samples }); + } + all +} + +/// One round over the installed plan: the downstream query is answered +/// for the region the upstream picked (west) only, and equals the engine's +/// grouped answer filtered by that binding. +#[tokio::test] +async fn round_over_installed_plan_filters_by_upstream_answer() { + let mut inputs = common::inputs(false); + inputs.ignore_accuracy_guarantees = true; + let plan = plan_workload(&workload(&[UPSTREAM, DOWNSTREAM]), &inputs) + .unwrap_or_else(|e| panic!("{e}")) + .0; + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan).unwrap(), + "http://127.0.0.1:1".into(), + EngineOptions { + no_forward: true, + ..EngineOptions::default() + }, + ) + .unwrap(), + ); + let app = router(state.clone()); + // One request per sample time, in time order, as a paced feeder sends. + let mut by_time: BTreeMap> = BTreeMap::new(); + for series in series() { + for sample in &series.samples { + by_time + .entry(sample.timestamp) + .or_default() + .push(TimeSeries { + labels: series.labels.clone(), + samples: vec![sample.clone()], + }); + } + } + for timeseries in by_time.into_values() { + common::remote_write(&app, timeseries).await; + } + for _ in 0..1000 { + if state.engine.queued_samples() == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + common::barrier(&app, EVALUATION_MS).await; + + let schedule = IntentSchedule { + round_interval_ms: 10_000, + queries: vec![ + IntentQuery { + query_id: "q1".into(), + query: UPSTREAM.into(), + depends_on: vec![], + bind_slots: vec![], + rate: 1.0, + skip_if_empty: true, + }, + IntentQuery { + query_id: "q2".into(), + query: DOWNSTREAM.into(), + depends_on: vec![Dependency { + variable: "R".into(), + upstream_query_id: "q1".into(), + output_column: "region".into(), + }], + bind_slots: vec![BindSlot { + variable: "R".into(), + column: "region".into(), + }], + rate: 1.0, + skip_if_empty: true, + }, + ], + group_latency_ms: vec![], + }; + let intent = IntentLoop::new( + schedule, + BindMode::FilterGroupedResult, + Duration::from_secs(30), + ) + .unwrap(); + let round = intent.run_round(&state.engine, 0, EVALUATION_MS).await; + let q1 = &round.queries[0]; + let q2 = &round.queries[1]; + assert_eq!(q1.status, QueryStatus::Answered, "{q1:?}"); + assert_eq!(q2.status, QueryStatus::Answered, "{q2:?}"); + assert_eq!( + q2.bindings["R"].iter().collect::>(), + ["west"], + "{q1:?}" + ); + let grouped = state + .engine + .answer(DOWNSTREAM, EVALUATION_MS) + .await + .unwrap(); + assert_eq!(grouped.len(), 6, "{grouped:?}"); + let mut expected: Vec<(String, f64)> = grouped + .iter() + .filter(|s| s.labels["region"] == "west") + .map(|s| (s.labels["service"].clone(), s.value)) + .collect(); + expected.sort_by(|a, b| a.0.cmp(&b.0)); + let mut answered: Vec<(String, f64)> = q2 + .answer + .iter() + .map(|row| (row.labels["service"].clone(), row.value)) + .collect(); + answered.sort_by(|a, b| a.0.cmp(&b.0)); + assert_eq!(answered, expected); + assert!(q1.latency_ms.is_some() && q2.latency_ms.is_some()); +} From 149b5aff72cc09db8718bebeac5de08bee00a382 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:25:47 +0000 Subject: [PATCH 02/20] feat(data_plane): check an intent schedule and order its queries IntentLoop::new refuses an unknown upstream or latency-group member, a variable bound by two different upstream outputs, a variable read with no dependency (or bound with no slot), a rate other than 1, and a dependency cycle; it orders the queries topologically, keeping the schedule's order among ready queries. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 91 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 89 insertions(+), 2 deletions(-) diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 715b56b86..51abaa5e3 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -226,8 +226,95 @@ impl IntentLoop { mode: BindMode, query_timeout: Duration, ) -> anyhow::Result { - let _ = (schedule, mode, query_timeout); - todo!("intent round loop: validate and order") + let queries = &schedule.queries; + let index_of = |id: &str| queries.iter().position(|q| q.query_id == id); + // Each variable's one binding: (upstream, output column). + let mut bound_by: BTreeMap<&str, (&str, &str)> = BTreeMap::new(); + for query in queries { + if query.rate != 1.0 { + anyhow::bail!( + "query {}: rate {} is not supported (only 1: every round)", + query.query_id, + query.rate + ); + } + for dependency in &query.depends_on { + if index_of(&dependency.upstream_query_id).is_none() { + anyhow::bail!( + "query {}: unknown upstream query {}", + query.query_id, + dependency.upstream_query_id + ); + } + let binding = ( + dependency.upstream_query_id.as_str(), + dependency.output_column.as_str(), + ); + if let Some(&other) = bound_by.get(dependency.variable.as_str()) { + if other != binding { + anyhow::bail!( + "variable ${} is bound by more than one query output: {other:?} and {binding:?}", + dependency.variable + ); + } + } + bound_by.insert(&dependency.variable, binding); + } + for slot in &query.bind_slots { + if !query.depends_on.iter().any(|d| d.variable == slot.variable) { + anyhow::bail!( + "query {}: no dependency binds the variable ${} it reads", + query.query_id, + slot.variable + ); + } + } + for dependency in &query.depends_on { + if !query + .bind_slots + .iter() + .any(|s| s.variable == dependency.variable) + { + anyhow::bail!( + "query {}: the variable ${} has no bind slot", + query.query_id, + dependency.variable + ); + } + } + } + for group in &schedule.group_latency_ms { + if let Some(id) = group.query_ids.iter().find(|id| index_of(id).is_none()) { + anyhow::bail!("latency group: unknown query {id}"); + } + } + // Kahn's algorithm; among ready queries, the schedule's order. + let mut order = Vec::with_capacity(queries.len()); + let mut placed = vec![false; queries.len()]; + while order.len() < queries.len() { + let ready = (0..queries.len()).find(|&i| { + !placed[i] + && queries[i] + .depends_on + .iter() + .all(|d| placed[index_of(&d.upstream_query_id).expect("checked above")]) + }); + let Some(ready) = ready else { + let rest: Vec<&str> = (0..queries.len()) + .filter(|&i| !placed[i]) + .map(|i| queries[i].query_id.as_str()) + .collect(); + anyhow::bail!("the dependencies of {rest:?} form a cycle"); + }; + placed[ready] = true; + order.push(ready); + } + Ok(Self { + schedule, + order, + mode, + query_timeout, + }) } /// The query ids in the order a round runs them. From 5ef7d7b00eb1458c7ed767ab506d1651e103d7d1 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:26:52 +0000 Subject: [PATCH 03/20] feat(data_plane): run one intent round with the grouped-result binding run_round runs the queries in order: each variable's binding is the distinct values of its upstream answer's output column; a query is skipped when an upstream failed or was skipped, or when a binding is empty. The binding step (bind_and_run) filters the downstream query's grouped answer by the bound values (BindMode::FilterGroupedResult); BindMode::ParameterSlot fails with the reason until the plan has parameter slots. Each run is bounded by the query timeout; the round records each query's latency, bindings and answer, and each latency group's span. The engine answers like an HTTP instant query. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 181 +++++++++++++++++++++++++++++++++++++-- 1 file changed, 173 insertions(+), 8 deletions(-) diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 51abaa5e3..e80cac6e4 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -332,8 +332,118 @@ impl IntentLoop { round: u64, time_ms: i64, ) -> RoundRecord { - let _ = (runner, round, time_ms, self.mode, self.query_timeout); - todo!("intent round loop: one round") + let round_start = Instant::now(); + let queries = &self.schedule.queries; + // Per query: its answer when it was answered, and when it ran. + let mut answers: Vec>> = vec![None; queries.len()]; + let mut spans: Vec> = vec![None; queries.len()]; + let mut records: Vec> = vec![None; queries.len()]; + for &i in &self.order { + let query = &queries[i]; + let mut record = QueryRecord { + query_id: query.query_id.clone(), + status: QueryStatus::Answered, + latency_ms: None, + bindings: Bindings::new(), + answer: vec![], + error: None, + }; + let mut upstream_missing = false; + for dependency in &query.depends_on { + let upstream = queries + .iter() + .position(|q| q.query_id == dependency.upstream_query_id) + .expect("checked in new"); + match &answers[upstream] { + Some(answer) => { + record.bindings.insert( + dependency.variable.clone(), + binding_values(answer, &dependency.output_column), + ); + } + None => upstream_missing = true, + } + } + if upstream_missing { + record.status = QueryStatus::SkippedUpstream; + } else if query.skip_if_empty && record.bindings.values().any(BTreeSet::is_empty) { + record.status = QueryStatus::SkippedEmptyBinding; + } else { + let started = Instant::now(); + let result = tokio::time::timeout( + self.query_timeout, + bind_and_run(self.mode, runner, query, &record.bindings, time_ms), + ) + .await; + let ended = Instant::now(); + spans[i] = Some((started, ended)); + record.latency_ms = Some(millis(ended - started)); + match result { + Ok(Ok(answer)) => { + record.answer = answer + .iter() + .map(|sample| AnswerRow { + labels: (*sample.labels).clone(), + value: sample.value, + }) + .collect(); + answers[i] = Some(answer); + } + Ok(Err(error)) => { + record.status = QueryStatus::Failed; + record.error = Some(error); + } + Err(_) => { + record.status = QueryStatus::Failed; + record.error = Some(format!( + "timed out after {} ms", + self.query_timeout.as_millis() + )); + } + } + } + records[i] = Some(record); + } + let groups = self + .schedule + .group_latency_ms + .iter() + .map(|group| { + let members: Vec> = group + .query_ids + .iter() + .map(|id| { + let i = queries.iter().position(|q| &q.query_id == id); + spans[i.expect("checked in new")] + }) + .collect(); + let ran: Vec<(Instant, Instant)> = members.iter().flatten().copied().collect(); + let latency_ms = ran + .iter() + .map(|(start, _)| *start) + .min() + .zip(ran.iter().map(|(_, end)| *end).max()) + .map(|(first, last)| millis(last - first)); + let complete = ran.len() == members.len(); + GroupRecord { + query_ids: group.query_ids.clone(), + max_ms: group.max_ms, + latency_ms, + complete, + met: complete && latency_ms.is_some_and(|l| l <= group.max_ms as f64), + } + }) + .collect(); + RoundRecord { + round, + evaluation_ms: time_ms, + status: RoundStatus::Ran, + start_lag_ms: 0.0, + duration_ms: millis(round_start.elapsed()), + overrun: false, + queries: records.into_iter().flatten().collect(), + groups, + } } /// Runs `rounds` rounds: round r evaluates at `first_evaluation_ms + r @@ -353,19 +463,59 @@ impl IntentLoop { } } +/// The binding step: `query`'s answer at `time_ms` for `bindings`, in +/// `mode`. A query that reads no variable runs as planned in either mode. +async fn bind_and_run( + mode: BindMode, + runner: &R, + query: &IntentQuery, + bindings: &Bindings, + time_ms: i64, +) -> Result, String> { + if query.bind_slots.is_empty() { + let answer = runner.answer(&query.query, time_ms).await; + return answer.map(|a| a.to_vec()).map_err(|e| e.to_string()); + } + match mode { + BindMode::FilterGroupedResult => { + let grouped = runner + .answer(&query.query, time_ms) + .await + .map_err(|e| e.to_string())?; + Ok(filter_by_bindings(&grouped, &query.bind_slots, bindings)) + } + // Follow-up: needs the planner's per-round parameter slots and an + // executor entry point that takes their values. + BindMode::ParameterSlot => Err( + "binding by parameter slot is not supported yet: the plan has no parameter slots to fill" + .into(), + ), + } +} + impl QueryRunner for crate::engine::EngineHandle { /// The result cache's answer, else a query run, as an HTTP instant /// query is answered. async fn answer(&self, query: &str, time_ms: i64) -> Result { - let _ = (query, time_ms); - todo!("intent round loop: engine runner") + match self.cached(query, time_ms) { + Some(answer) => Ok(answer), + None => self.evaluate(query.to_string(), time_ms).await, + } } } /// The distinct values of `column` in `answer`. pub fn binding_values(answer: &[ResultSample], column: &str) -> BTreeSet { - let _ = (answer, column); - todo!("intent round loop: binding values") + answer + .iter() + .filter_map(|sample| { + if column == VALUE_COLUMN { + Some(sample.value.to_string()) + } else { + sample.labels.get(column).cloned() + } + }) + .collect() } /// The rows of `answer` whose label `slot.column` holds one of @@ -377,8 +527,23 @@ pub fn filter_by_bindings( slots: &[BindSlot], bindings: &Bindings, ) -> Vec { - let _ = (answer, slots, bindings); - todo!("intent round loop: filter") + answer + .iter() + .filter(|sample| { + slots.iter().all(|slot| { + let values = bindings.get(&slot.variable); + sample + .labels + .get(&slot.column) + .is_some_and(|value| values.is_some_and(|v| v.contains(value))) + }) + }) + .cloned() + .collect() +} + +fn millis(duration: Duration) -> f64 { + duration.as_secs_f64() * 1000.0 } #[cfg(test)] From 81cf577912786f57b1ea5903b79e480586bc827b Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:27:30 +0000 Subject: [PATCH 04/20] feat(data_plane): run intent rounds on the interval grid run_rounds starts round r at start + r x interval and evaluates it at first_evaluation_ms + r x interval. Rounds never overlap: a round ending after the next round's start is marked overrun, and the rounds whose start passed meanwhile are recorded as missed, not run. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index e80cac6e4..f622cdbd7 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -456,10 +456,37 @@ impl IntentLoop { first_evaluation_ms: i64, rounds: u64, start: Instant, - emit: impl FnMut(RoundRecord), + mut emit: impl FnMut(RoundRecord), ) { - let _ = (runner, first_evaluation_ms, rounds, start, emit); - todo!("intent round loop: rounds") + let interval_ms = self.schedule.round_interval_ms; + let scheduled = |round: u64| start + Duration::from_millis(interval_ms * round); + let mut round = 0; + while round < rounds { + tokio::time::sleep_until(scheduled(round)).await; + let start_lag_ms = millis(Instant::now() - scheduled(round)); + let evaluation_ms = first_evaluation_ms + (round * interval_ms) as i64; + let mut record = self.run_round(runner, round, evaluation_ms).await; + record.start_lag_ms = start_lag_ms; + let ended = Instant::now(); + record.overrun = ended > scheduled(round + 1); + emit(record); + // The next round whose start is still ahead (or now). + let mut next = round + 1; + while next < rounds && scheduled(next) < ended { + emit(RoundRecord { + round: next, + evaluation_ms: first_evaluation_ms + (next * interval_ms) as i64, + status: RoundStatus::Missed, + start_lag_ms: 0.0, + duration_ms: 0.0, + overrun: false, + queries: vec![], + groups: vec![], + }); + next += 1; + } + round = next; + } } } From ae9fa9fbe0f66f8b0d4ada7af2fb71490d7a9ca1 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:32:06 +0000 Subject: [PATCH 05/20] feat(data_plane): --intent runs an intent's rounds beside the server With --intent and --intent-first-evaluation-ms, the data plane runs the intent round loop against its own engine while it ingests Remote Write as usual: round r starts --intent-delay-ms after its evaluation time and is written to --intent-out as one JSON line (per query status, latency, bindings and answer; per group its span). Co-Authored-By: Claude Opus 5.5 --- data_plane/src/main.rs | 59 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index f330e1ecf..a05a83a8b 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -21,6 +21,7 @@ static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:8\0"; use data_plane::engine::{EngineOptions, PrecomputeMode}; use data_plane::ingestion::IngestionOptions; +use data_plane::intent::{BindMode, IntentLoop}; use data_plane::persist::ViewRead; use data_plane::{router, DataPlane, DEFAULT_FORWARD_TIMEOUT}; @@ -170,6 +171,32 @@ struct Args { /// `pread`. #[arg(long, value_enum, default_value_t = ViewRead::Mmap)] view_read: ViewRead, + /// An intent's planned rounds (`data_plane::intent::IntentSchedule` + /// JSON) to run against the installed plan, beside serving as usual. + #[arg(long, requires = "intent_first_evaluation_ms")] + intent: Option, + /// Where each intent round is written, one JSON line per round: per + /// query its status, latency, bindings and answer; per latency group + /// its span. + #[arg(long, default_value = "intent_rounds.jsonl")] + intent_out: PathBuf, + /// The first round's evaluation time (ms since the epoch); round r + /// evaluates at this + r x the round interval. + #[arg(long)] + intent_first_evaluation_ms: Option, + /// How many rounds to run. + #[arg(long, default_value_t = 10)] + intent_rounds: u64, + /// How long after its evaluation time (wall clock) a round starts, so + /// its windows are closed by then (the harness' query delay). + #[arg(long, default_value_t = 6000)] + intent_delay_ms: u64, + /// The longest one intent query may run before it fails as timed out. + #[arg(long, default_value_t = 30_000)] + intent_query_timeout_ms: u64, + /// How bound values reach a downstream query. + #[arg(long, value_enum, default_value_t = BindMode::FilterGroupedResult)] + intent_bind_mode: BindMode, } #[tokio::main] @@ -235,6 +262,38 @@ async fn main() -> anyhow::Result<()> { None => state, }; tracing::info!(queries = state.queries.len(), "installed plan"); + if let Some(path) = &args.intent { + let schedule = serde_json::from_str(&std::fs::read_to_string(path)?)?; + let intent = IntentLoop::new( + schedule, + args.intent_bind_mode, + Duration::from_millis(args.intent_query_timeout_ms), + )?; + let first_evaluation_ms = args + .intent_first_evaluation_ms + .expect("clap requires it with --intent"); + // Round 0 starts `intent_delay_ms` after its evaluation time. + let wait_ms = first_evaluation_ms + args.intent_delay_ms as i64 + - data_plane::ingestion::wall_clock_ms(); + let start = tokio::time::Instant::now() + Duration::from_millis(wait_ms.max(0) as u64); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args.intent_out)?); + let (state, rounds) = (state.clone(), args.intent_rounds); + tokio::spawn(async move { + intent + .run_rounds(&state.engine, first_evaluation_ms, rounds, start, |round| { + use std::io::Write; + let written = serde_json::to_writer(&mut out, &round) + .map_err(std::io::Error::from) + .and_then(|()| writeln!(out)) + .and_then(|()| out.flush()); + if let Err(error) = written { + tracing::error!(%error, "writing an intent round"); + } + }) + .await; + tracing::info!(rounds, "intent rounds done"); + }); + } let listener = tokio::net::TcpListener::bind(&args.listen).await?; tracing::info!(address = %listener.local_addr()?, "listening"); axum::serve(listener, router(state)).await?; From 4bb1906ebb43f38e212415d53f6aa86743c1dcaa Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:32:06 +0000 Subject: [PATCH 06/20] docs(bench): run an intent workload end to end with the round loop Co-Authored-By: Claude Opus 5.5 --- bench/demo/harness/README.md | 44 ++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/bench/demo/harness/README.md b/bench/demo/harness/README.md index cc8af0c4e..91ce541ff 100644 --- a/bench/demo/harness/README.md +++ b/bench/demo/harness/README.md @@ -235,3 +235,47 @@ dashboards. `live/ingest_exporter.py` (port 19724) exports, per engine: The asap-demo row "Ingestion while querying" shows these. The live setup gives each engine 12 cores (ASAP 24-35, VictoriaMetrics 36-47). The feeders, the query load, the proxies and the browser use 48-55. + +# Intent workloads (round loop) + +An intent is a set of planned queries where a downstream query reads the +values of an upstream query's output column (`host IN $Y`). The data plane +runs it round by round (`data_plane::intent`): queries in dependency order, +each binding the distinct values its upstream answered, a query skipped when +a binding is empty or an upstream failed, and every round written as one +JSON line. + +Inputs: the installed plan (`plan.json`, every intent query planned, a +downstream query grouped by each label it is filtered on), the intent's +schedule (`intent.json`, below), and the data feed by Remote Write as for +any other arm (paced feeder, `stream_start_ms` S). + +```json +{"round_interval_ms": 10000, + "queries": [ + {"query_id": "q1", "query": "topk(1, sum by (region) (sum_over_time(data[100s])))"}, + {"query_id": "q2", "query": "sum by (region, service) (sum_over_time(data[100s]))", + "depends_on": [{"variable": "R", "upstream_query_id": "q1", "output_column": "region"}], + "bind_slots": [{"variable": "R", "column": "region"}]}], + "group_latency_ms": [{"query_ids": ["q1", "q2"], "max_ms": 15}]} +``` + +```sh +data_plane --plan plan.json --no-forward --stream-start-ms $S \ + --intent intent.json --intent-out rounds.jsonl \ + --intent-first-evaluation-ms $((S + LONGEST_LOOKBACK_MS)) --intent-rounds 30 \ + --intent-delay-ms 6000 +``` + +Output (`rounds.jsonl`, one line per round): `round`, `evaluation_ms`, +`status` (`ran` or `missed`: its start passed while the previous round still +ran), `start_lag_ms`, `duration_ms`, `overrun`; per query `status` +(`answered`, `skipped_empty_binding`, `skipped_upstream`, `failed`), +`latency_ms`, `bindings` (the values issued), `answer`, `error`; per latency +group `latency_ms` (first member's start to last member's end), `complete`, +`met`. A dependent query's accuracy is judged against the exact grouped +answer filtered by the binding it was issued +(`data_plane::intent::filter_by_bindings`), not by the exact upstream's. + +The schedule format mirrors the planner's `intent_rounds` contract; the +planner's final output is adapted in `data_plane::intent` when it lands. From 00355520fadc8dbf5468732141bd42b81493f2ee Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:34:45 +0000 Subject: [PATCH 07/20] test(data_plane): intent rounds from the planner's final intent schema The planner's intent output (IntentPlan, the SIL contract's final schema v1) types the round loop reads, with the adapter to the loop's schedule left as todo!; the end-to-end round now starts from that JSON. Group latency follows the contract: from the round's start to the last member's end (group_latency_runs_from_the_round_start fails: the loop still measures from the first member's start). Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 123 +++++++++++++++++++++++++----- data_plane/tests/intent_rounds.rs | 89 ++++++++++++--------- 2 files changed, 159 insertions(+), 53 deletions(-) diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index f622cdbd7..d3832bb57 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -103,8 +103,8 @@ pub struct BindSlot { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GroupLatency { pub query_ids: Vec, - /// From the first of them starting to the last of them ending. - pub max_ms: u64, + /// From the round's start to the last of them ending. + pub max_latency_ms: f64, } /// How a binding reaches the downstream query: the binding step. @@ -182,13 +182,13 @@ pub struct QueryRecord { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct GroupRecord { pub query_ids: Vec, - pub max_ms: u64, - /// From the first member starting to the last member ending, over the - /// members that ran; `None` when none ran. + pub max_latency_ms: f64, + /// From the round's start to the last member that ran ending; `None` + /// when none ran. pub latency_ms: Option, /// Whether every member ran. pub complete: bool, - /// Every member ran and `latency_ms <= max_ms`. + /// Every member ran and `latency_ms <= max_latency_ms`. pub met: bool, } @@ -216,6 +216,70 @@ pub struct RoundRecord { pub groups: Vec, } +/// The planner's output for planned intents (the SIL contract's final +/// schema, v1): the fields the round loop reads; the others are ignored. +#[derive(Debug, Clone, Deserialize)] +pub struct IntentPlan { + /// The plan to install (`--plan`); every intent query is one of its + /// queries. + pub plan: asap_planner::InstallablePlan, + pub intent_rounds: Vec, +} + +/// One planned intent's rounds, as the planner writes them. +#[derive(Debug, Clone, Deserialize)] +pub struct PlannedIntent { + pub intent_name: String, + pub round_interval_ms: u64, + /// In round order (topological). + pub queries: Vec, + #[serde(default)] + pub group_latency_ms: Vec, +} + +/// One planned intent query, as the planner writes it. +#[derive(Debug, Clone, Deserialize)] +pub struct PlannedIntentQuery { + pub query_id: String, + /// Its query in the plan: `plan.query_texts[query_index]`, root + /// `plan.dag.roots[query_index]`. + pub query_index: usize, + #[serde(default)] + pub depends_on: Vec, + /// One per hole occurrence; the placeholders and nodes they name are + /// for [`BindMode::ParameterSlot`]. + #[serde(default)] + pub bind_slots: Vec, + pub rate: f64, + pub skip_if_empty: bool, +} + +/// A variable bound to the upstream result's column at `output_position`. +#[derive(Debug, Clone, Deserialize)] +pub struct PlannedDependency { + pub variable: String, + pub upstream_query_id: String, + pub output_position: usize, +} + +/// A hole of the planned query that `variable` fills. +#[derive(Debug, Clone, Deserialize)] +pub struct PlannedBindSlot { + pub variable: String, +} + +impl IntentSchedule { + /// The rounds of the intent `intent_name` of `intent_plan`: each query's + /// text from the plan, and each `output_position` resolved to the + /// column of the upstream root's output schema (its value column: + /// [`VALUE_COLUMN`]). [`BindMode::FilterGroupedResult`] filters on the + /// bound upstream column's name. + pub fn from_intent_plan(intent_plan: &IntentPlan, intent_name: &str) -> anyhow::Result { + let _ = (intent_plan, intent_name); + todo!("intent round loop: planner schema adapter") + } +} + impl IntentLoop { /// Checks `schedule` and orders its queries. Refused (bad input): an /// unknown upstream or group member, a variable bound by more than one @@ -427,10 +491,10 @@ impl IntentLoop { let complete = ran.len() == members.len(); GroupRecord { query_ids: group.query_ids.clone(), - max_ms: group.max_ms, + max_latency_ms: group.max_latency_ms, latency_ms, complete, - met: complete && latency_ms.is_some_and(|l| l <= group.max_ms as f64), + met: complete && latency_ms.is_some_and(|l| l <= group.max_latency_ms), } }) .collect(); @@ -903,20 +967,32 @@ mod tests { assert_eq!(runner.calls().len(), 2); } - /// Group latency spans the first member's start to the last member's - /// end; each query's latency is its own run. + /// Group latency runs from the round's start to the last member's end + /// (the contract's L_G, measured from the round time): a group of q2 + /// alone also counts q1, which ran before it. Each query's latency is + /// its own run. #[tokio::test(start_paused = true)] - async fn group_latency_spans_its_members() { + async fn group_latency_runs_from_the_round_start() { let runner = FakeRunner::default() .with("q1", &[(&[("host", "a")], 1.0)]) .delay("q1", 300) .with("q2", &[(&[("host", "a")], 1.0)]) .delay("q2", 200); let mut schedule = schedule(host_pair()); - schedule.group_latency_ms = vec![GroupLatency { - query_ids: vec!["q1".into(), "q2".into()], - max_ms: 400, - }]; + schedule.group_latency_ms = vec![ + GroupLatency { + query_ids: vec!["q1".into(), "q2".into()], + max_latency_ms: 400.0, + }, + GroupLatency { + query_ids: vec!["q1".into()], + max_latency_ms: 400.0, + }, + GroupLatency { + query_ids: vec!["q2".into()], + max_latency_ms: 600.0, + }, + ]; let intent = IntentLoop::new( schedule, BindMode::FilterGroupedResult, @@ -926,10 +1002,19 @@ mod tests { let round = intent.run_round(&runner, 0, 1_000).await; assert_eq!(record(&round, "q1").latency_ms, Some(300.0)); assert_eq!(record(&round, "q2").latency_ms, Some(200.0)); - let group = &round.groups[0]; - assert_eq!(group.latency_ms, Some(500.0)); - assert!(group.complete); - assert!(!group.met); + let latency: Vec<_> = round + .groups + .iter() + .map(|g| (g.latency_ms, g.complete, g.met)) + .collect(); + assert_eq!( + latency, + vec![ + (Some(500.0), true, false), + (Some(300.0), true, true), + (Some(500.0), true, true), + ] + ); } /// The dependent query answers for the binding the approximate upstream diff --git a/data_plane/tests/intent_rounds.rs b/data_plane/tests/intent_rounds.rs index d2c1b9b7a..c2bbc6422 100644 --- a/data_plane/tests/intent_rounds.rs +++ b/data_plane/tests/intent_rounds.rs @@ -1,7 +1,7 @@ -//! The intent round loop over a real installed plan: an upstream query's -//! answer binds a downstream query planned grouped by the bound label, and -//! the downstream answer is the engine's grouped answer filtered by the -//! values the upstream issued. +//! The intent round loop over a real installed plan, from the planner's +//! intent output: an upstream query's answer binds a downstream query +//! planned grouped by the bound label, and the downstream answer is the +//! engine's grouped answer filtered by the values the upstream issued. mod common; @@ -13,8 +13,7 @@ use asap_planner::PlanningWorkload; use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::intent::{ - BindMode, BindSlot, Dependency, IntentLoop, IntentQuery, IntentSchedule, QueryRunner, - QueryStatus, + BindMode, IntentLoop, IntentPlan, IntentSchedule, QueryRunner, QueryStatus, VALUE_COLUMN, }; use data_plane::remote_write::{Label, Sample, TimeSeries}; use data_plane::{router, DataPlane}; @@ -132,35 +131,47 @@ async fn round_over_installed_plan_filters_by_upstream_answer() { } common::barrier(&app, EVALUATION_MS).await; - let schedule = IntentSchedule { - round_interval_ms: 10_000, - queries: vec![ - IntentQuery { - query_id: "q1".into(), - query: UPSTREAM.into(), - depends_on: vec![], - bind_slots: vec![], - rate: 1.0, - skip_if_empty: true, - }, - IntentQuery { - query_id: "q2".into(), - query: DOWNSTREAM.into(), - depends_on: vec![Dependency { - variable: "R".into(), - upstream_query_id: "q1".into(), - output_column: "region".into(), - }], - bind_slots: vec![BindSlot { - variable: "R".into(), - column: "region".into(), - }], - rate: 1.0, - skip_if_empty: true, - }, - ], - group_latency_ms: vec![], + // The planner's intent output (SIL contract, final schema v1) over + // this plan: q2 reads $R, bound to q1's `region` column (position 1 of + // `topk`'s output: the value, then `region`). + let index = |text: &str| { + plan.query_texts + .iter() + .position(|q| q.trim() == text) + .unwrap() }; + let intent_plan: IntentPlan = serde_json::from_value(serde_json::json!({ + "planning_mode": "intent_full", + "plan": plan, + "lightcone_query_indices": [], + "intent_rounds": [{ + "intent_name": "triage", + "round_interval_ms": 10_000, + "round_phase_ms": 0, + "queries": [ + {"query_id": "q1", "query_index": index(UPSTREAM), + "plan_root": plan.dag.roots[index(UPSTREAM)], + "output_variables": [null, "R"], "depends_on": [], "bind_slots": [], + "rate": 1.0, "planned_rate": 1.0, "when_condition": null, + "skip_if_empty": false, "accuracy": null, "max_latency_ms": null}, + {"query_id": "q2", "query_index": index(DOWNSTREAM), + "plan_root": plan.dag.roots[index(DOWNSTREAM)], + "output_variables": [null, null, null], + "depends_on": [{"variable": "R", "upstream_query_id": "q1", "output_position": 1}], + "bind_slots": [{"variable": "R", "position": "in_list", "planned_value_count": 1, + "placeholder_values": [{"Utf8": "__sil_R_0"}], "plan_node_ids": []}], + "rate": 1.0, "planned_rate": 1.0, "when_condition": null, + "skip_if_empty": true, "accuracy": null, "max_latency_ms": null} + ], + "group_latency_ms": [{"query_ids": ["q1", "q2"], "max_latency_ms": 60_000.0}] + }] + })) + .unwrap(); + let schedule = IntentSchedule::from_intent_plan(&intent_plan, "triage").unwrap(); + assert_eq!(schedule.queries[0].query, UPSTREAM); + assert_eq!(schedule.queries[1].depends_on[0].output_column, "region"); + assert_eq!(schedule.queries[1].bind_slots[0].column, "region"); + assert!(IntentSchedule::from_intent_plan(&intent_plan, "other").is_err()); let intent = IntentLoop::new( schedule, BindMode::FilterGroupedResult, @@ -197,4 +208,14 @@ async fn round_over_installed_plan_filters_by_upstream_answer() { answered.sort_by(|a, b| a.0.cmp(&b.0)); assert_eq!(answered, expected); assert!(q1.latency_ms.is_some() && q2.latency_ms.is_some()); + assert!(round.groups[0].complete && round.groups[0].met); + + // Position 0 of `topk`'s output is its value column. + let mut by_value = intent_plan.clone(); + by_value.intent_rounds[0].queries[1].depends_on[0].output_position = 0; + let schedule = IntentSchedule::from_intent_plan(&by_value, "triage").unwrap(); + assert_eq!( + schedule.queries[1].depends_on[0].output_column, + VALUE_COLUMN + ); } From db76eee837193cff049daf06d37a359131f55802 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:35:58 +0000 Subject: [PATCH 08/20] feat(data_plane): intent rounds from the planner's intent output IntentSchedule::from_intent_plan reads one intent of the planner's IntentPlan: each query's text is plan.query_texts[query_index], and each dependency's output_position is resolved through the upstream root's output schema to a label name, or __value__ for the value column. Group latency is now measured from the round's start to the last member's end, as the contract defines L_G. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 132 ++++++++++++++++++++++++++++++++++----- data_plane/src/query.rs | 2 +- 2 files changed, 119 insertions(+), 15 deletions(-) diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index d3832bb57..96b7d077a 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -275,8 +275,84 @@ impl IntentSchedule { /// [`VALUE_COLUMN`]). [`BindMode::FilterGroupedResult`] filters on the /// bound upstream column's name. pub fn from_intent_plan(intent_plan: &IntentPlan, intent_name: &str) -> anyhow::Result { - let _ = (intent_plan, intent_name); - todo!("intent round loop: planner schema adapter") + let intent = intent_plan + .intent_rounds + .iter() + .find(|intent| intent.intent_name == intent_name) + .ok_or_else(|| anyhow::anyhow!("the plan has no intent {intent_name:?}"))?; + let plan = &intent_plan.plan; + let query_text = |index: usize| { + plan.query_texts + .get(index) + .map(|text| text.trim().to_string()) + .ok_or_else(|| anyhow::anyhow!("query index {index} is not in the plan")) + }; + let queries = intent + .queries + .iter() + .map(|query| { + let depends_on = query + .depends_on + .iter() + .map(|dependency| { + let upstream = intent + .queries + .iter() + .find(|q| q.query_id == dependency.upstream_query_id) + .ok_or_else(|| { + anyhow::anyhow!( + "query {}: unknown upstream query {}", + query.query_id, + dependency.upstream_query_id + ) + })?; + Ok(Dependency { + variable: dependency.variable.clone(), + upstream_query_id: dependency.upstream_query_id.clone(), + output_column: output_column( + plan, + upstream.query_index, + dependency.output_position, + )?, + }) + }) + .collect::>>()?; + let bind_slots = query + .bind_slots + .iter() + .map(|slot| { + let column = depends_on + .iter() + .find(|d| d.variable == slot.variable) + .map(|d| d.output_column.clone()) + .ok_or_else(|| { + anyhow::anyhow!( + "query {}: no dependency binds the variable ${}", + query.query_id, + slot.variable + ) + })?; + Ok(BindSlot { + variable: slot.variable.clone(), + column, + }) + }) + .collect::>>()?; + Ok(IntentQuery { + query_id: query.query_id.clone(), + query: query_text(query.query_index)?, + depends_on, + bind_slots, + rate: query.rate, + skip_if_empty: query.skip_if_empty, + }) + }) + .collect::>>()?; + Ok(Self { + round_interval_ms: intent.round_interval_ms, + queries, + group_latency_ms: intent.group_latency_ms.clone(), + }) } } @@ -398,9 +474,10 @@ impl IntentLoop { ) -> RoundRecord { let round_start = Instant::now(); let queries = &self.schedule.queries; - // Per query: its answer when it was answered, and when it ran. + // Per query: its answer when it was answered, and when its run + // ended (group latency runs from the round's start to it). let mut answers: Vec>> = vec![None; queries.len()]; - let mut spans: Vec> = vec![None; queries.len()]; + let mut ends: Vec> = vec![None; queries.len()]; let mut records: Vec> = vec![None; queries.len()]; for &i in &self.order { let query = &queries[i]; @@ -440,7 +517,7 @@ impl IntentLoop { ) .await; let ended = Instant::now(); - spans[i] = Some((started, ended)); + ends[i] = Some(ended); record.latency_ms = Some(millis(ended - started)); match result { Ok(Ok(answer)) => { @@ -473,21 +550,16 @@ impl IntentLoop { .group_latency_ms .iter() .map(|group| { - let members: Vec> = group + let members: Vec> = group .query_ids .iter() .map(|id| { let i = queries.iter().position(|q| &q.query_id == id); - spans[i.expect("checked in new")] + ends[i.expect("checked in new")] }) .collect(); - let ran: Vec<(Instant, Instant)> = members.iter().flatten().copied().collect(); - let latency_ms = ran - .iter() - .map(|(start, _)| *start) - .min() - .zip(ran.iter().map(|(_, end)| *end).max()) - .map(|(first, last)| millis(last - first)); + let ran: Vec = members.iter().flatten().copied().collect(); + let latency_ms = ran.iter().max().map(|&last| millis(last - round_start)); let complete = ran.len() == members.len(); GroupRecord { query_ids: group.query_ids.clone(), @@ -595,6 +667,38 @@ impl QueryRunner for crate::engine::EngineHandle { } } +/// The name of the column at `position` of query `query_index`'s root +/// output: a label, or [`VALUE_COLUMN`] for the value column the answer +/// rows carry. +fn output_column( + plan: &asap_planner::InstallablePlan, + query_index: usize, + position: usize, +) -> anyhow::Result { + let root = *plan + .dag + .roots + .get(query_index) + .ok_or_else(|| anyhow::anyhow!("query index {query_index} has no root in the plan"))?; + let schema = &plan + .dag + .nodes + .iter() + .find(|node| node.id == root) + .ok_or_else(|| anyhow::anyhow!("the plan has no node {root}"))? + .output_schema; + let field = schema.fields.get(position).ok_or_else(|| { + anyhow::anyhow!( + "query index {query_index}: no output column at position {position} (it has {})", + schema.fields.len() + ) + })?; + if crate::query::value_column(schema).ok() == Some(position) { + return Ok(VALUE_COLUMN.to_string()); + } + Ok(field.name.clone()) +} + /// The distinct values of `column` in `answer`. pub fn binding_values(answer: &[ResultSample], column: &str) -> BTreeSet { answer diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index 744c1dfd1..0c7ee5a16 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -503,7 +503,7 @@ fn slots_read( /// The column holding a result row's value: the one `Float64` column, or, /// with none, the one `Int64` column (a `count` answers in integers, e.g. /// `count by (region) (... > 1000)`). -fn value_column(schema: &Schema) -> Result { +pub(crate) fn value_column(schema: &Schema) -> Result { use asap_executor::planner::ir::schema::{DataType, FieldDataType}; let columns = |dtype: DataType| -> Vec { schema From 1229bf5b6721caa143729cd1804ecc2c7f023d0b Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 07:37:06 +0000 Subject: [PATCH 09/20] feat(data_plane): --intent reads the planner's intent output --intent now takes the planner's IntentPlan with --intent-name; the harness doc installs its plan and runs the named intent. Co-Authored-By: Claude Opus 5.5 --- bench/demo/harness/README.md | 32 +++++++++++--------------------- data_plane/src/intent.rs | 23 ++++++++++++----------- data_plane/src/main.rs | 19 ++++++++++++++----- 3 files changed, 37 insertions(+), 37 deletions(-) diff --git a/bench/demo/harness/README.md b/bench/demo/harness/README.md index 91ce541ff..dfe54364f 100644 --- a/bench/demo/harness/README.md +++ b/bench/demo/harness/README.md @@ -245,24 +245,16 @@ each binding the distinct values its upstream answered, a query skipped when a binding is empty or an upstream failed, and every round written as one JSON line. -Inputs: the installed plan (`plan.json`, every intent query planned, a -downstream query grouped by each label it is filtered on), the intent's -schedule (`intent.json`, below), and the data feed by Remote Write as for -any other arm (paced feeder, `stream_start_ms` S). - -```json -{"round_interval_ms": 10000, - "queries": [ - {"query_id": "q1", "query": "topk(1, sum by (region) (sum_over_time(data[100s])))"}, - {"query_id": "q2", "query": "sum by (region, service) (sum_over_time(data[100s]))", - "depends_on": [{"variable": "R", "upstream_query_id": "q1", "output_column": "region"}], - "bind_slots": [{"variable": "R", "column": "region"}]}], - "group_latency_ms": [{"query_ids": ["q1", "q2"], "max_ms": 15}]} -``` +Inputs: the planner's intent output (`intent_plan.json`, its `IntentPlan`: +the `plan` to install and the `intent_rounds`), and the data feed by Remote +Write as for any other arm (paced feeder, `stream_start_ms` S). Today's +binding filters the downstream query's answer by the bound values, so the +downstream query must be planned grouped by the label it is filtered on. ```sh +jq .plan intent_plan.json > plan.json data_plane --plan plan.json --no-forward --stream-start-ms $S \ - --intent intent.json --intent-out rounds.jsonl \ + --intent intent_plan.json --intent-name triage --intent-out rounds.jsonl \ --intent-first-evaluation-ms $((S + LONGEST_LOOKBACK_MS)) --intent-rounds 30 \ --intent-delay-ms 6000 ``` @@ -272,10 +264,8 @@ Output (`rounds.jsonl`, one line per round): `round`, `evaluation_ms`, ran), `start_lag_ms`, `duration_ms`, `overrun`; per query `status` (`answered`, `skipped_empty_binding`, `skipped_upstream`, `failed`), `latency_ms`, `bindings` (the values issued), `answer`, `error`; per latency -group `latency_ms` (first member's start to last member's end), `complete`, -`met`. A dependent query's accuracy is judged against the exact grouped -answer filtered by the binding it was issued +group `latency_ms` (round start to the last member's end, the queries run one +after another in round order), `complete`, `met`. A dependent query's +accuracy is judged against the exact grouped answer filtered by the binding +it was issued (`data_plane::intent::filter_by_bindings`), not by the exact upstream's. - -The schedule format mirrors the planner's `intent_rounds` contract; the -planner's final output is adapted in `data_plane::intent` when it lands. diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 96b7d077a..2e664c650 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -8,17 +8,17 @@ //! whose binding is empty, and records each query's latency, each latency //! group's latency, the bindings issued and the answers. //! -//! The schedule type here mirrors the planner's `intent_rounds` output -//! (the SIL planner <-> data plane contract); it is the one place to adapt -//! when the planner's final JSON schema lands. No planning happens here: each +//! The planner's intent output ([`IntentPlan`], the SIL contract's final +//! schema v1) is read into the loop's [`IntentSchedule`] +//! ([`IntentSchedule::from_intent_plan`]). No planning happens here: each //! query is answered by the installed plan, as an HTTP query is. //! //! How a bound value reaches the plan is the binding step -//! ([`BindMode`]): today the downstream query is planned grouped by the -//! bound column and its answer is filtered by the binding -//! ([`BindMode::FilterGroupedResult`]); filling a parameter slot of the plan -//! per round ([`BindMode::ParameterSlot`]) waits for the planner to emit -//! such slots. +//! ([`BindMode`]): today the downstream query's answer, grouped by the +//! bound column, is filtered by the binding +//! ([`BindMode::FilterGroupedResult`]); substituting the bound values for +//! the plan's placeholders each round ([`BindMode::ParameterSlot`]) is the +//! follow-up. use std::collections::{BTreeMap, BTreeSet}; use std::future::Future; @@ -115,9 +115,10 @@ pub enum BindMode { /// and keep the answer rows whose bound columns hold a bound value. /// Needs no planner or executor change. FilterGroupedResult, - /// Fill the plan's parameter slot (an `IN` list on a query-time filter - /// node) with the bound values each round. Follow-up: waits for the - /// planner to emit parameter slots and the executor to accept values. + /// Substitute the bound values for the slot's placeholders in a copy of + /// the plan (`col IN (placeholders)` in the slot's query-time nodes) and + /// compile and run the query's root each round. Follow-up: the engine + /// compiles each run once, at install time. ParameterSlot, } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index a05a83a8b..ca31c0b10 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -21,7 +21,7 @@ static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:8\0"; use data_plane::engine::{EngineOptions, PrecomputeMode}; use data_plane::ingestion::IngestionOptions; -use data_plane::intent::{BindMode, IntentLoop}; +use data_plane::intent::{BindMode, IntentLoop, IntentPlan, IntentSchedule}; use data_plane::persist::ViewRead; use data_plane::{router, DataPlane, DEFAULT_FORWARD_TIMEOUT}; @@ -171,10 +171,14 @@ struct Args { /// `pread`. #[arg(long, value_enum, default_value_t = ViewRead::Mmap)] view_read: ViewRead, - /// An intent's planned rounds (`data_plane::intent::IntentSchedule` - /// JSON) to run against the installed plan, beside serving as usual. - #[arg(long, requires = "intent_first_evaluation_ms")] + /// The planner's intent output (`IntentPlan` JSON): its intent + /// `--intent-name` is run round by round against the installed plan, + /// beside serving as usual. `--plan` must install its `plan`. + #[arg(long, requires_all = ["intent_first_evaluation_ms", "intent_name"])] intent: Option, + /// Which of the output's intents to run. + #[arg(long)] + intent_name: Option, /// Where each intent round is written, one JSON line per round: per /// query its status, latency, bindings and answer; per latency group /// its span. @@ -263,7 +267,12 @@ async fn main() -> anyhow::Result<()> { }; tracing::info!(queries = state.queries.len(), "installed plan"); if let Some(path) = &args.intent { - let schedule = serde_json::from_str(&std::fs::read_to_string(path)?)?; + let intent_plan: IntentPlan = serde_json::from_str(&std::fs::read_to_string(path)?)?; + let name = args + .intent_name + .as_deref() + .expect("clap requires it with --intent"); + let schedule = IntentSchedule::from_intent_plan(&intent_plan, name)?; let intent = IntentLoop::new( schedule, args.intent_bind_mode, From 0283e5ab24f3f6829d72e29f923f45e37e1af23d Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:39:06 +0000 Subject: [PATCH 10/20] chore(deps): pin ASAPPlanner to the SIL intent planner head (draft) ASAPPlanner#1553's head (3ef265d) plans SIL intents; its sketch library pin (c5f7866) now holds the merge-in-place DDSketch the backend patched in, so the patch goes. The executor's state view API was renamed: StateColumn::from_mapped -> from_views, family_has_mapped_form -> family_has_view_layout, and per-state view bytes now come from a state column (segment::column_views). SketchAlgorithm variants take the Planner's names (KLL, CountMinSketch, ...). Adds asap-frontend-sil as a dev-dependency for the intent end-to-end test. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 48 +++++++++++++-------- Cargo.toml | 15 ++----- data_plane/Cargo.toml | 2 + data_plane/examples/view_read_bench.rs | 2 +- data_plane/src/persist.rs | 36 +++++++++++----- data_plane/src/segment.rs | 58 +++++++++++++++++--------- data_plane/src/state_codec.rs | 2 +- 7 files changed, 103 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0fe141a86..5ce9ebe9e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -333,7 +333,7 @@ dependencies = [ [[package]] name = "asap-accuracy" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", "asap_sketchlib", @@ -344,7 +344,7 @@ dependencies = [ [[package]] name = "asap-cost" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", "asap_sketchlib", @@ -356,7 +356,7 @@ dependencies = [ [[package]] name = "asap-executor" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "ahash", "arrow", @@ -374,7 +374,7 @@ dependencies = [ [[package]] name = "asap-frontend-common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", "serde", @@ -384,7 +384,7 @@ dependencies = [ [[package]] name = "asap-frontend-metricsql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-frontend-common", "asap-types", @@ -395,17 +395,27 @@ dependencies = [ [[package]] name = "asap-frontend-promql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-frontend-common", "asap-types", "promql-parser", ] +[[package]] +name = "asap-frontend-sil" +version = "0.1.0" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" +dependencies = [ + "asap-types", + "serde", + "thiserror 2.0.20", +] + [[package]] name = "asap-frontend-sql" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-frontend-common", "asap-sql-function-catalog", @@ -417,13 +427,14 @@ dependencies = [ [[package]] name = "asap-planner" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-accuracy", "asap-cost", "asap-executor", "asap-frontend-metricsql", "asap-frontend-promql", + "asap-frontend-sil", "asap-frontend-sql", "asap-stage0-memo", "asap-stage1-pass1-per-computation-candidates", @@ -439,12 +450,12 @@ dependencies = [ [[package]] name = "asap-sql-function-catalog" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" [[package]] name = "asap-stage0-memo" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", ] @@ -452,7 +463,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass1-per-computation-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", "thiserror 2.0.20", @@ -461,7 +472,7 @@ dependencies = [ [[package]] name = "asap-stage1-pass2-reuse-candidates" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-accuracy", "asap-types", @@ -471,7 +482,7 @@ dependencies = [ [[package]] name = "asap-stage2-physical-optimization" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-types", ] @@ -479,7 +490,7 @@ dependencies = [ [[package]] name = "asap-stage3-plan-selection" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap-accuracy", "asap-cost", @@ -494,7 +505,7 @@ dependencies = [ [[package]] name = "asap-types" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "asap_sketchlib", "serde", @@ -505,7 +516,7 @@ dependencies = [ [[package]] name = "asap_sketchlib" version = "0.4.0" -source = "git+https://www.github.com/ProjectASAP/asap_sketchlib?rev=355093f48f2649df1b86f2d390c2faa145a5f0a0#355093f48f2649df1b86f2d390c2faa145a5f0a0" +source = "git+https://github.com/ProjectASAP/asap_sketchlib?rev=c5f786637766461532d5ee310436cae8bb61d152#c5f786637766461532d5ee310436cae8bb61d152" dependencies = [ "rand 0.9.5", "rmp-serde", @@ -954,6 +965,7 @@ dependencies = [ "ahash", "anyhow", "asap-executor", + "asap-frontend-sil", "asap-planner", "asap_sketchlib", "axum", @@ -2477,7 +2489,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "metricsql_common" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "chrono", ] @@ -2485,7 +2497,7 @@ dependencies = [ [[package]] name = "metricsql_parser" version = "0.1.0" -source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=1d527bca445b6372f0eb72aafd725d04a3a77dfb#1d527bca445b6372f0eb72aafd725d04a3a77dfb" +source = "git+https://github.com/ProjectASAP/ASAPPlanner?rev=3ef265d20e74679bcb8cb3d2bed8de6c59fb690f#3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" dependencies = [ "ahash", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 801171e39..aa7010d59 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,12 +10,12 @@ version = "0.1.0" # The backend depends on two Planner crates, at one immutable revision: # `asap-planner` to plan and `asap-executor` to execute. Planner IR types # are reached through `asap_executor::planner`. -asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } -asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "1d527bca445b6372f0eb72aafd725d04a3a77dfb" } +asap-planner = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" } +asap-executor = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" } # The sketch library the Planner's executor pins, for the byte encodings of # the sketch states the data plane persists; keep it at the Planner's rev -# (here overridden below for the executor too). -asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = "389530ce23b121520f0218a4471e376db2c35945" } +# (draft: ASAPPlanner#1553 head, for SIL intents). +asap_sketchlib = { git = "https://github.com/ProjectASAP/asap_sketchlib", rev = "c5f786637766461532d5ee310436cae8bb61d152" } serde = { version = "1.0", features = ["derive"] } # `float_roundtrip`: a plan file reloads to the plan it was written from @@ -30,10 +30,3 @@ tokio = { version = "1.0", features = ["full"] } axum = "0.7" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } control_plane = { path = "control_plane" } - -# asap_sketchlib#271's head, ahead of the Planner's pin (389530c): DDSketch -# view merges in place, with width-specialized loops (a 1 h quantile over -# cold windows 3x faster). Drop when the Planner's pin moves past it. The -# `www.` URL is a distinct source, so it may patch the one the Planner names. -[patch."https://github.com/ProjectASAP/asap_sketchlib"] -asap_sketchlib = { git = "https://www.github.com/ProjectASAP/asap_sketchlib", rev = "355093f48f2649df1b86f2d390c2faa145a5f0a0" } diff --git a/data_plane/Cargo.toml b/data_plane/Cargo.toml index 032897ee1..edb6161ed 100644 --- a/data_plane/Cargo.toml +++ b/data_plane/Cargo.toml @@ -36,6 +36,8 @@ futures = "0.3" form_urlencoded = "1" [dev-dependencies] +# Parses SIL intents for the intent round loop's end-to-end test. +asap-frontend-sil = { git = "https://github.com/ProjectASAP/ASAPPlanner", rev = "3ef265d20e74679bcb8cb3d2bed8de6c59fb690f" } # Paused time for the intent loop's latency and overrun tests. tokio = { workspace = true, features = ["test-util"] } control_plane.workspace = true diff --git a/data_plane/examples/view_read_bench.rs b/data_plane/examples/view_read_bench.rs index bdea03ee0..c969c0ca5 100644 --- a/data_plane/examples/view_read_bench.rs +++ b/data_plane/examples/view_read_bench.rs @@ -35,7 +35,7 @@ fn main() { let _ = std::fs::remove_dir_all(&dir); let family = match family_name { - "kll" => FieldDataType::Sketch(SketchAlgorithm::Kll), + "kll" => FieldDataType::Sketch(SketchAlgorithm::KLL), "ddsketch" => FieldDataType::Sketch(SketchAlgorithm::DDSketch), "counter" => FieldDataType::ExactAggregate(ExactKind::Counter, ExactParams::Counter), other => panic!("unknown family {other}: kll, ddsketch or counter"), diff --git a/data_plane/src/persist.rs b/data_plane/src/persist.rs index aa4f286d2..3b996548c 100644 --- a/data_plane/src/persist.rs +++ b/data_plane/src/persist.rs @@ -1116,7 +1116,17 @@ mod tests { DataType, Field, FieldDataType, Schema, PROMQL_SERIES_IDENTITY, }; use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm}; - use asap_executor::values::state_view_bytes; + + /// One state's view bytes, as the segment writer stores them. + fn state_view_bytes(family: &FieldDataType, state: &Arc) -> Vec { + let row = vec![vec![Value::Summary { + family: family.clone(), + state: state.clone(), + }]]; + crate::segment::column_views(family, &row, 0) + .unwrap() + .remove(0) + } /// A fresh directory for one test's segments. fn segment_dir(test: &str) -> PathBuf { @@ -1131,11 +1141,11 @@ mod tests { use SketchAlgorithm as A; Some(FieldDataType::Sketch(match kernel { SketchKernel::DDSketch => A::DDSketch, - SketchKernel::Kll => A::Kll, - SketchKernel::CountMin => A::Cms, - SketchKernel::Kmv => A::Kmv, - SketchKernel::Hll(_) => A::Hll, - SketchKernel::WeightedFrequency(FrequencyKind::CmsHeap) => A::CmsWithHeap, + SketchKernel::Kll => A::KLL, + SketchKernel::CountMin => A::CountMinSketch, + SketchKernel::Kmv => A::KMV, + SketchKernel::Hll(_) => A::HLL, + SketchKernel::WeightedFrequency(FrequencyKind::CmsHeap) => A::CountMinSketchWithHeap, SketchKernel::WeightedFrequency(FrequencyKind::CountSketchHeap) => { A::CountSketchWithHeap } @@ -1315,7 +1325,11 @@ mod tests { .collect(); out.push(( "HydraCms".into(), - window_batch(10, FieldDataType::Sketch(SketchAlgorithm::HydraCms), groups), + window_batch( + 10, + FieldDataType::Sketch(SketchAlgorithm::HydraCountMinSketch), + groups, + ), )); out } @@ -1364,7 +1378,9 @@ mod tests { .to_rows() .iter() .map(|row| match &row[4] { - Value::Summary { state, .. } => state_view_bytes(state.as_ref()).unwrap().len(), + Value::Summary { state, .. } => { + state_view_bytes(&batch.schema().fields[4].dtype, state).len() + } _ => unreachable!(), }) .sum(); @@ -1472,14 +1488,14 @@ mod tests { let dir = segment_dir("cold-read"); let (_, a, b) = states().remove(1); let (a, b): (Arc, Arc) = (Arc::from(a), Arc::from(b)); - let kll = FieldDataType::Sketch(SketchAlgorithm::Kll); + let kll = FieldDataType::Sketch(SketchAlgorithm::KLL); let states: Vec> = (0..1000) .map(|i| if i % 2 == 0 { a.clone() } else { b.clone() }) .collect(); let held = 4 * (states.len() + 1) + states .iter() - .map(|s| state_view_bytes(s.as_ref()).unwrap().len().div_ceil(8) * 8) + .map(|s| state_view_bytes(&kll, s).len().div_ceil(8) * 8) .sum::(); let (first, second) = ( window_batch(10, kll.clone(), states.clone()), diff --git a/data_plane/src/segment.rs b/data_plane/src/segment.rs index 44682f5d8..d9755ce66 100644 --- a/data_plane/src/segment.rs +++ b/data_plane/src/segment.rs @@ -37,9 +37,7 @@ use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::planner::summary_type::{ExactKind, SketchAlgorithm}; use asap_executor::summary_kernels::HydraCms; -use asap_executor::values::{ - family_has_mapped_form, state_view_bytes, Batch, BatchColumn, SchemaRef, Value, -}; +use asap_executor::values::{family_has_view_layout, Batch, BatchColumn, SchemaRef, Value}; use asap_executor::Error; use serde::{Deserialize, Serialize}; @@ -906,20 +904,14 @@ pub(crate) fn encode_fragment( // each state's mapped layout (`None` when a state has none, e.g. a // keyed exact state, or the column has no compact form). let mut compact = compact_kind(&field.dtype).and_then(|kind| { - let views = rows - .iter() - .map(|row| match &row[column] { - Value::Summary { state, .. } => state_view_bytes(state.as_ref()), - _ => None, - }) - .collect::>>()?; + let views = column_views(&field.dtype, rows, column)?; Some((kind, encode_states(kind, views.iter())?)) }); // Otherwise the column in the mapped layout, when it has one. let mut mapped = match &field.dtype { FieldDataType::Plain(_) => None, _ if compact.is_some() => None, - family if family_has_mapped_form(family) => mapped_states(rows, column), + family if family_has_view_layout(family) => mapped_states(&field.dtype, rows, column), _ => None, }; let (kind, mut flags, data): (u32, u32, Vec) = match &field.dtype { @@ -1105,21 +1097,49 @@ impl IdentityLabels { /// Column `column` of `rows` in the executor's mapped state layout: the /// `u32` offsets (`rows + 1`) and the states back to back, each padded to 8 /// bytes; `None` when a state has no mapped form. -fn mapped_states(rows: &[Vec], column: usize) -> Option<(Vec, Vec)> { +fn mapped_states( + family: &FieldDataType, + rows: &[Vec], + column: usize, +) -> Option<(Vec, Vec)> { let mut offsets = Vec::with_capacity((rows.len() + 1) * 4); let mut states = Vec::new(); offsets.extend_from_slice(&0u32.to_le_bytes()); - for row in rows { - let Value::Summary { state, .. } = &row[column] else { - return None; - }; - states.extend(state_view_bytes(state.as_ref())?); + for view in column_views(family, rows, column)? { + states.extend(view); states.resize(padded(states.len()), 0); offsets.extend_from_slice(&u32::try_from(states.len()).ok()?.to_le_bytes()); } Some((offsets, states)) } +/// Each state of column `column` of `rows`, of `family`, in the executor's +/// view layout ([`asap_executor::values::StateColumn::view_bytes`]); `None` +/// when a value is not a state or a state has no view layout. +pub(crate) fn column_views( + family: &FieldDataType, + rows: &[Vec], + column: usize, +) -> Option>> { + if rows + .iter() + .any(|row| !matches!(row[column], Value::Summary { .. })) + { + return None; + } + let field = asap_executor::planner::ir::schema::Field { + name: "state".into(), + dtype: family.clone(), + nullable: true, + }; + let values = rows.iter().map(|row| vec![row[column].clone()]).collect(); + let (_, states) = one_column(&field, values).ok()?; + let states = states?; + (0..states.len()) + .map(|index| states.view_bytes(index).map(|view| view.into_owned())) + .collect() +} + /// A little-endian `u64` at `at` of `bytes`. fn word(bytes: &[u8], at: usize) -> Result { Ok(u64::from_le_bytes( @@ -1369,7 +1389,7 @@ fn decode_fragment( decode_states(compact, &bytes[data.0..data.0 + data.1], rows) .ok_or_else(damaged)?; state_bytes += states.len() * 8 + offsets.len() * 4; - let column = asap_executor::values::StateColumn::from_mapped( + let column = asap_executor::values::StateColumn::from_views( field.dtype.clone(), Buffer::from(states), ScalarBuffer::from(offsets), @@ -1387,7 +1407,7 @@ fn decode_fragment( state_bytes += data.1 + valid.1; let offsets = ScalarBuffer::::new(buffer(bytes, data.0, data.1)?, 0, rows + 1); let states = buffer(bytes, valid.0, valid.1)?; - let column = asap_executor::values::StateColumn::from_mapped( + let column = asap_executor::values::StateColumn::from_views( field.dtype.clone(), states, offsets, diff --git a/data_plane/src/state_codec.rs b/data_plane/src/state_codec.rs index c84dc241d..1f8396781 100644 --- a/data_plane/src/state_codec.rs +++ b/data_plane/src/state_codec.rs @@ -2,7 +2,7 @@ //! (docs/design/tiered-view-storage.md, "On-disk format"). //! //! A state column is written in the executor's mapped layout -//! ([`asap_executor::values::state_view_bytes`]): fixed-width fields and +//! ([`asap_executor::values::StateColumn::view_bytes`]): fixed-width fields and //! 8-byte-aligned arrays. That layout is large for the small //! states of narrow panes: a DDSketch of ten samples is an 88-byte header //! plus a dense run of 1-byte bucket counts, most of them empty. This module From ea5b809a0b529adfeb5e1fa87a6450919b62cbec Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:39:06 +0000 Subject: [PATCH 11/20] test(data_plane): parameter-slot binding, keyed results, SIL intents in three modes Failing tests for binding an intent query's holes in the plan: - placeholders: IN-lists and the rollup form `col = p0 OR ..` take the bound values; a comparison takes exactly one; values convert to the placeholder's type; a placeholder left in an unknown form is an error. - QueryTimeResults keeps a node's result under each binding apart. - The loop hands the runner each slot's placeholders and values (BindMode::ParameterSlot); a slot without placeholders fails. - intent_sil_modes: a SQL intent planned by the Planner as query-at-a-time, intent with on-demand holes and full intent, run two rounds each, answers exact; q2 bound to other hosts at one time. The unit tests fail at todo!; the end-to-end test fails because the data plane does not store SQL tables yet. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/intent.rs | 133 ++++++++++-- data_plane/src/lib.rs | 1 + data_plane/src/placeholders.rs | 216 +++++++++++++++++++ data_plane/src/store.rs | 63 ++++++ data_plane/tests/intent_sil_modes.rs | 311 +++++++++++++++++++++++++++ 5 files changed, 709 insertions(+), 15 deletions(-) create mode 100644 data_plane/src/placeholders.rs create mode 100644 data_plane/tests/intent_sil_modes.rs diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 2e664c650..bd0eb1ad5 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -27,6 +27,9 @@ use std::time::Duration; use serde::{Deserialize, Serialize}; use tokio::time::Instant; +use asap_executor::planner::ir::scalar::expr_ir::ScalarValue; + +use crate::placeholders::{SlotBinding, SlotPosition}; use crate::query::{ResultSample, Unanswered}; use crate::result_cache::Answer; @@ -97,6 +100,17 @@ pub struct BindSlot { /// The downstream answer's label the binding filters on /// ([`BindMode::FilterGroupedResult`]): `host` for `host IN $Y`. pub column: String, + /// Where the hole sits ([`BindMode::ParameterSlot`]). + #[serde(default = "in_list")] + pub position: SlotPosition, + /// The literals the planner put in the plan for this hole, which + /// [`BindMode::ParameterSlot`] replaces with the bound values. + #[serde(default)] + pub placeholder_values: Vec, +} + +fn in_list() -> SlotPosition { + SlotPosition::InList } /// A latency target over queries of one round. @@ -115,10 +129,11 @@ pub enum BindMode { /// and keep the answer rows whose bound columns hold a bound value. /// Needs no planner or executor change. FilterGroupedResult, - /// Substitute the bound values for the slot's placeholders in a copy of + /// Replace the slot's placeholders with the bound values in a copy of /// the plan (`col IN (placeholders)` in the slot's query-time nodes) and - /// compile and run the query's root each round. Follow-up: the engine - /// compiles each run once, at install time. + /// compile and run the query's root each round + /// ([`crate::placeholders`]). The default for the planner's intent + /// plans. ParameterSlot, } @@ -130,6 +145,15 @@ pub trait QueryRunner: Sync { query: &str, time_ms: i64, ) -> impl Future> + Send; + + /// The answer to `query` at `time_ms` with its holes bound: each slot's + /// placeholders replaced by its values ([`BindMode::ParameterSlot`]). + fn answer_bound( + &self, + query: &str, + time_ms: i64, + slots: &[SlotBinding], + ) -> impl Future> + Send; } /// A variable's values in one round, deduplicated and sorted. @@ -224,6 +248,9 @@ pub struct IntentPlan { /// The plan to install (`--plan`); every intent query is one of its /// queries. pub plan: asap_planner::InstallablePlan, + /// Plan queries the planner added (lightcone queries): never issued. + #[serde(default)] + pub lightcone_query_indices: Vec, pub intent_rounds: Vec, } @@ -267,6 +294,9 @@ pub struct PlannedDependency { #[derive(Debug, Clone, Deserialize)] pub struct PlannedBindSlot { pub variable: String, + pub position: SlotPosition, + /// The literals that stand for the hole in the plan. + pub placeholder_values: Vec, } impl IntentSchedule { @@ -336,6 +366,8 @@ impl IntentSchedule { Ok(BindSlot { variable: slot.variable.clone(), column, + position: slot.position, + placeholder_values: slot.placeholder_values.clone(), }) }) .collect::>>()?; @@ -648,12 +680,9 @@ async fn bind_and_run( .map_err(|e| e.to_string())?; Ok(filter_by_bindings(&grouped, &query.bind_slots, bindings)) } - // Follow-up: needs the planner's per-round parameter slots and an - // executor entry point that takes their values. - BindMode::ParameterSlot => Err( - "binding by parameter slot is not supported yet: the plan has no parameter slots to fill" - .into(), - ), + BindMode::ParameterSlot => { + todo!("parameter slots: bind and run") + } } } @@ -666,6 +695,18 @@ impl QueryRunner for crate::engine::EngineHandle { None => self.evaluate(query.to_string(), time_ms).await, } } + + /// A query run of `query` over a copy of the plan with its holes bound; + /// never from or into the result cache. + async fn answer_bound( + &self, + query: &str, + time_ms: i64, + slots: &[SlotBinding], + ) -> Result { + let _ = (query, time_ms, slots); + todo!("parameter slots: engine") + } } /// The name of the column at `position` of query `query_index`'s root @@ -753,8 +794,11 @@ mod tests { answers: BTreeMap>, delays: BTreeMap, errors: BTreeMap, - /// Query texts in the order they were run. + /// Query texts in the order they were run (` (bound)` when run + /// with bound holes). calls: Mutex>, + /// The slots of every bound run. + bound: Mutex>, } impl FakeRunner { @@ -773,6 +817,9 @@ mod tests { fn calls(&self) -> Vec { self.calls.lock().unwrap().clone() } + fn bound_slots(&self) -> Vec { + self.bound.lock().unwrap().clone() + } } impl QueryRunner for FakeRunner { @@ -788,6 +835,21 @@ mod tests { self.answers.get(query).cloned().unwrap_or_default(), )) } + + /// The fake plan's answer as if its holes were bound (the test + /// sets the bound plan's answer). + async fn answer_bound( + &self, + query: &str, + _time_ms: i64, + slots: &[SlotBinding], + ) -> Result { + self.calls.lock().unwrap().push(format!("{query} (bound)")); + self.bound.lock().unwrap().extend(slots.iter().cloned()); + Ok(Arc::new( + self.answers.get(query).cloned().unwrap_or_default(), + )) + } } fn rows_of(rows: &[(&[(&str, &str)], f64)]) -> Vec { @@ -823,6 +885,8 @@ mod tests { .map(|(variable, column)| BindSlot { variable: (*variable).into(), column: (*column).into(), + position: SlotPosition::InList, + placeholder_values: vec![placeholder(variable)], }) .collect(), rate: 1.0, @@ -830,6 +894,11 @@ mod tests { } } + /// The placeholder the fake plan holds for `variable`. + fn placeholder(variable: &str) -> ScalarValue { + ScalarValue::Utf8(format!("__sil_{variable}_0")) + } + fn schedule(queries: Vec) -> IntentSchedule { IntentSchedule { round_interval_ms: 1_000, @@ -1194,15 +1263,46 @@ mod tests { refused(sampled, "rate"); } - /// Parameter-slot binding is a marked follow-up: the query fails with - /// the reason instead of running unbound. + /// Parameter-slot binding hands the runner each slot's placeholders + /// and the values bound to them, and answers what the bound plan + /// answers (no filter on the loop's side). + #[tokio::test] + async fn parameter_slot_mode_binds_the_plan() { + let runner = FakeRunner::default() + .with("q1", &[(&[("host", "a")], 1.0), (&[("host", "b")], 2.0)]) + .with("q2", &[(&[("user", "u1")], 5.0)]); + let intent = IntentLoop::new( + schedule(host_pair()), + BindMode::ParameterSlot, + Duration::from_secs(1), + ) + .unwrap(); + let round = intent.run_round(&runner, 0, 1_000).await; + let q2 = record(&round, "q2"); + assert_eq!(q2.status, QueryStatus::Answered, "{q2:?}"); + assert_eq!(label_values(q2, "user"), ["u1"]); + assert_eq!(runner.calls(), vec!["q1", "q2 (bound)"]); + assert_eq!( + runner.bound_slots(), + vec![SlotBinding { + position: SlotPosition::InList, + placeholders: vec![placeholder("Y")], + values: values(&["a", "b"]), + }] + ); + } + + /// A slot without placeholders cannot be bound in the plan: the query + /// fails with the reason rather than running with its holes unfilled. #[tokio::test] - async fn parameter_slot_mode_is_not_supported_yet() { + async fn parameter_slot_without_placeholders_fails() { let runner = FakeRunner::default() .with("q1", &[(&[("host", "a")], 1.0)]) .with("q2", &[(&[("host", "a")], 1.0)]); + let mut queries = host_pair(); + queries[1].bind_slots[0].placeholder_values.clear(); let intent = IntentLoop::new( - schedule(host_pair()), + schedule(queries), BindMode::ParameterSlot, Duration::from_secs(1), ) @@ -1210,7 +1310,10 @@ mod tests { let round = intent.run_round(&runner, 0, 1_000).await; let q2 = record(&round, "q2"); assert_eq!(q2.status, QueryStatus::Failed); - assert!(q2.error.as_deref().unwrap().contains("parameter slot")); + assert!( + q2.error.as_deref().unwrap().contains("no placeholders"), + "{q2:?}" + ); assert_eq!(runner.calls(), vec!["q1"]); } } diff --git a/data_plane/src/lib.rs b/data_plane/src/lib.rs index 89090a93d..c0eee1f02 100644 --- a/data_plane/src/lib.rs +++ b/data_plane/src/lib.rs @@ -20,6 +20,7 @@ pub mod intent; pub mod memory_budget; pub mod metrics; pub mod persist; +pub mod placeholders; pub mod prometheus; pub mod push; pub mod query; diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs new file mode 100644 index 000000000..0325a65d1 --- /dev/null +++ b/data_plane/src/placeholders.rs @@ -0,0 +1,216 @@ +//! Binds an intent query's holes: replaces the placeholder literals the +//! planner put in its plan with the values bound this round, in a copy of +//! the plan's DAG (the SIL contract's binding procedure, step 2). +//! +//! A hole in an IN-list is planned as `col IN (p_0, .., p_n-1)`, or, after +//! the planner's rollup compensation, `col = p_0 OR .. OR col = p_n-1`; +//! either becomes `col IN (v_1, .., v_m)` with the bound values (`m` may +//! differ from `n`). A hole in a comparison holds one placeholder, replaced +//! by the one bound value. The rewrite works on the DAG's serialized form, +//! so it reaches every expression of a node (Scan predicates, Filter and +//! Join predicates, a summary build's filter, selection properties) +//! without naming each operator; a placeholder left in a form it does not +//! know is an error rather than a silently empty answer. + +use std::collections::BTreeSet; + +use asap_executor::planner::ir::scalar::expr_ir::ScalarValue; +use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; +use serde::{Deserialize, Serialize}; +use serde_json::Value as Json; + +/// Where a hole sits in its query. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum SlotPosition { + /// `col IN $Y`: any number of values. + InList, + /// `col > $T`: exactly one value. + Comparison, +} + +/// One hole of a query and the values bound to it this round. +#[derive(Debug, Clone, PartialEq)] +pub struct SlotBinding { + pub position: SlotPosition, + /// The literals the planner put in the plan for this hole. + pub placeholders: Vec, + /// The bound values, as the upstream answer's text; each is converted + /// to its placeholders' type. + pub values: BTreeSet, +} + +/// A copy of `dag` with every slot's placeholders replaced by its bound +/// values, and the nodes whose contents changed. Fails when a bound value +/// does not convert to its placeholders' type, a comparison is bound to +/// other than one value, or a placeholder is left in a form not rewritten. +pub fn bind( + dag: &PhysicalASAPDAG, + slots: &[SlotBinding], +) -> Result<(PhysicalASAPDAG, BTreeSet), String> { + let _ = (dag, slots); + todo!("parameter slots: bind a DAG") +} + +/// Rewrites `json` (any serialized part of a plan) for `slot`; whether it +/// changed. Fails as [`bind`] does, a placeholder left over included. +pub fn bind_json(json: &mut Json, slot: &SlotBinding) -> Result { + let _ = (json, slot); + todo!("parameter slots: rewrite") +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn utf8(text: &str) -> ScalarValue { + ScalarValue::Utf8(text.into()) + } + + fn literal(value: &ScalarValue) -> Json { + json!({ "Literal": serde_json::to_value(value).unwrap() }) + } + + fn column() -> Json { + json!({"Column": {"name": "host"}}) + } + + fn slot(position: SlotPosition, placeholders: &[ScalarValue], values: &[&str]) -> SlotBinding { + SlotBinding { + position, + placeholders: placeholders.to_vec(), + values: values.iter().map(|v| v.to_string()).collect(), + } + } + + fn placeholders(n: usize) -> Vec { + (0..n).map(|i| utf8(&format!("__sil_Y_{i}"))).collect() + } + + /// `host IN (p0, p1, p2)` becomes `host IN ('a', 'b')`: the list takes + /// the bound values, however many. + #[test] + fn in_list_takes_the_bound_values() { + let p = placeholders(3); + let mut expr = json!({"Filter": {"pred": {"InList": { + "expr": column(), + "list": p.iter().map(literal).collect::>(), + "negated": false, + }}}}); + let changed = bind_json(&mut expr, &slot(SlotPosition::InList, &p, &["a", "b"])).unwrap(); + assert!(changed); + assert_eq!( + expr, + json!({"Filter": {"pred": {"InList": { + "expr": column(), + "list": [literal(&utf8("a")), literal(&utf8("b"))], + "negated": false, + }}}}) + ); + } + + /// The rollup compensation form `host = p0 OR host = p1` becomes + /// `host IN ('a', 'b', 'c')`. + #[test] + fn disjunction_of_equalities_becomes_an_in_list() { + let p = placeholders(2); + let eq = |value: &ScalarValue| { + json!({"Compare": {"left": column(), "op": "Eq", "right": literal(value), + "semantics": "Sql"}}) + }; + let mut expr = json!({"BoolAnd": [ + {"BoolOr": p.iter().map(eq).collect::>()}, + {"Literal": {"Boolean": true}}, + ]}); + bind_json(&mut expr, &slot(SlotPosition::InList, &p, &["a", "b", "c"])).unwrap(); + assert_eq!( + expr, + json!({"BoolAnd": [ + {"InList": { + "expr": column(), + "list": [literal(&utf8("a")), literal(&utf8("b")), literal(&utf8("c"))], + "negated": false, + }}, + {"Literal": {"Boolean": true}}, + ]}) + ); + } + + /// A selection property's list of placeholder values (not wrapped as + /// literals) takes the bound values too. + #[test] + fn bare_value_lists_take_the_bound_values() { + let p = placeholders(2); + let mut selection = + json!({"In": p.iter().map(|v| serde_json::to_value(v).unwrap()).collect::>()}); + bind_json(&mut selection, &slot(SlotPosition::InList, &p, &["z"])).unwrap(); + assert_eq!( + selection, + json!({"In": [serde_json::to_value(utf8("z")).unwrap()]}) + ); + } + + /// A comparison hole takes its one value, converted to the + /// placeholder's type; two values are an error. + #[test] + fn comparison_takes_exactly_one_value() { + let p = vec![ScalarValue::Float64(1.5e300)]; + let mut expr = json!({"Compare": {"left": {"Column": {"name": "value"}}, "op": "Gt", + "right": literal(&p[0]), "semantics": "Sql"}}); + let mut two = expr.clone(); + bind_json(&mut expr, &slot(SlotPosition::Comparison, &p, &["42.5"])).unwrap(); + assert_eq!( + expr["Compare"]["right"], + literal(&ScalarValue::Float64(42.5)) + ); + let error = + bind_json(&mut two, &slot(SlotPosition::Comparison, &p, &["1", "2"])).unwrap_err(); + assert!(error.contains("one value"), "{error}"); + } + + /// A bound value that is not of the placeholder's type is an error. + #[test] + fn values_convert_to_the_placeholder_type() { + let p = vec![ + ScalarValue::Int64(-7_000_000_001), + ScalarValue::Int64(-7_000_000_002), + ]; + let mut expr = json!({"InList": {"expr": column(), + "list": p.iter().map(literal).collect::>(), "negated": false}}); + let mut bad = expr.clone(); + bind_json(&mut expr, &slot(SlotPosition::InList, &p, &["3", "12"])).unwrap(); + assert_eq!( + expr["InList"]["list"], + json!([ + literal(&ScalarValue::Int64(12)), + literal(&ScalarValue::Int64(3)) + ]) + ); + let error = bind_json(&mut bad, &slot(SlotPosition::InList, &p, &["x"])).unwrap_err(); + assert!(error.contains("\"x\""), "{error}"); + } + + /// A placeholder in a form the rewrite does not know (here an IN-list + /// mixing a placeholder with another value) is an error, not a query + /// silently filtering on the placeholder. + #[test] + fn a_leftover_placeholder_is_an_error() { + let p = placeholders(2); + let mut expr = json!({"InList": {"expr": column(), + "list": [literal(&p[0]), literal(&utf8("other"))], "negated": false}}); + let error = bind_json(&mut expr, &slot(SlotPosition::InList, &p, &["a"])).unwrap_err(); + assert!(error.contains("__sil_Y_0"), "{error}"); + } + + /// An expression without the slot's placeholders is left as it is. + #[test] + fn other_expressions_are_unchanged() { + let p = placeholders(1); + let mut expr = json!({"InList": {"expr": column(), + "list": [literal(&utf8("a"))], "negated": false}}); + let before = expr.clone(); + assert!(!bind_json(&mut expr, &slot(SlotPosition::InList, &p, &["b"])).unwrap()); + assert_eq!(expr, before); + } +} diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 3b1099524..33042c07a 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -1455,6 +1455,22 @@ impl QueryTimeResults { } } + /// [`Self::get_or_compute`] for `node` computed under one binding of an + /// intent's holes (`binding`, a hash of the bound values; never 0, the + /// unbound result's key): kept apart from its result under any other + /// binding at the same time. + pub fn get_or_compute_bound( + &self, + node: PhysicalASAPNodeId, + time_ms: i64, + binding: u64, + watermark_ms: Option, + compute: impl FnOnce() -> Result, E>, + ) -> Result>, E> { + let _ = (node, time_ms, binding, watermark_ms, compute); + todo!("parameter slots: keyed query-time results") + } + /// `node`'s output at `time_ms`: stored, or computed now by `compute` /// (once, however many runs ask at once, when `time_ms` is at or /// before `watermark_ms`; by each run otherwise). @@ -2042,6 +2058,53 @@ mod tests { assert_eq!(results.bytes(), 0); } + /// A node's result under one binding of an intent's holes is kept + /// apart from its result under another binding and from its unbound + /// result at the same time: each is computed once, and a run reads + /// only its own binding's. + #[test] + fn bound_results_are_keyed_by_their_binding() { + let results = QueryTimeResults::<()>::new(10_000, usize::MAX); + let watermark = Some(1_000); + let rows = |n: usize| { + move || { + let schema = Arc::new(Schema::new(vec![Field::plain( + "value", + asap_executor::planner::ir::schema::DataType::Float64, + false, + )])); + let values = vec![vec![Value::Float64(1.0)]; n]; + Ok::<_, ()>(vec![Batch::try_new(schema, values).unwrap()]) + } + }; + let unbound = results + .get_or_compute(7, 1_000, watermark, rows(1)) + .unwrap(); + let a = results + .get_or_compute_bound(7, 1_000, 11, watermark, rows(2)) + .unwrap(); + let b = results + .get_or_compute_bound(7, 1_000, 22, watermark, rows(3)) + .unwrap(); + let a_again = results + .get_or_compute_bound(7, 1_000, 11, watermark, || panic!("recomputed")) + .unwrap(); + let rows_of = |r: &Arc>| r[0].num_rows(); + assert_eq!( + ( + rows_of(&unbound), + rows_of(&a), + rows_of(&b), + rows_of(&a_again) + ), + (1, 2, 3, 2) + ); + assert_eq!( + (results.computes(), results.hits(), results.len()), + (3, 1, 3) + ); + } + /// Runs waiting for a result being computed get its value, or its /// failure, without computing it themselves. #[test] diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs new file mode 100644 index 000000000..ab66eefa4 --- /dev/null +++ b/data_plane/tests/intent_sil_modes.rs @@ -0,0 +1,311 @@ +//! A SIL intent planned by the Planner in each planning mode +//! (query-at-a-time, intent with on-demand holes, full intent), installed +//! on the data plane and run round by round with its holes bound in the +//! plan (`BindMode::ParameterSlot`): every answer equals the exact answer, +//! the dependent query's for the binding it was issued. + +mod common; + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::time::Duration; + +use asap_executor::planner::ir::schema::{DataType, Field, Schema}; +use asap_planner::intent::{plan_intents, IntentPlanningMode, IntentPlanningOptions}; +use asap_planner::{PlanningModels, SqlCatalog}; +use data_plane::engine::EngineOptions; +use data_plane::intent::{ + BindMode, IntentLoop, IntentPlan, IntentSchedule, QueryRunner, QueryStatus, RoundRecord, +}; +use data_plane::placeholders::{SlotBinding, SlotPosition}; +use data_plane::remote_write::{Label, Sample, TimeSeries}; +use data_plane::{router, DataPlane}; + +/// The last round's evaluation time. +const EVALUATION_MS: i64 = 3_600_000; +/// Every query's window. +const WINDOW_MS: i64 = 100_000; + +/// q1 binds `$Y` to the two hosts with the largest `flows` sum; q2 sums +/// `auth` per user over those hosts only. +const INTENT: &str = "INTENT triage EVERY 10s; +q1: ($Y, _) := SELECT host, sum(value) AS s FROM flows + WHERE ts > $now - INTERVAL '100 seconds' GROUP BY host ORDER BY s DESC LIMIT 2 + REQUIRE EXACT; +q2: SELECT user, sum(value) AS s FROM auth + WHERE host IN $Y AND ts > $now - INTERVAL '100 seconds' GROUP BY user + REQUIRE EXACT;"; + +/// `(ts, host, user, value)`: the time series a table's rows are. +fn table_schema() -> Schema { + Schema::with_time_index( + vec![ + Field::plain("ts", DataType::Timestamp, false), + Field::plain("host", DataType::Utf8, false), + Field::plain("user", DataType::Utf8, false), + Field::plain("value", DataType::Float64, false), + ], + 0, + vec![], + ) +} + +/// One row of a table: its host, user, time and value. +#[derive(Clone)] +struct Row { + host: String, + user: String, + ts: i64, + value: f64, +} + +/// `flows`: 4 hosts x 2 users; `auth`: 4 hosts x 3 users; one row per +/// (host, user) every 10 s over the two minutes before `EVALUATION_MS`. +/// Host `h{i}`'s flows grow with `i`, but h1's is the largest, so the top +/// two hosts are h1 and h3. +fn tables() -> BTreeMap<&'static str, Vec> { + let mut tables: BTreeMap<&'static str, Vec> = BTreeMap::new(); + for step in 0..12 { + let ts = EVALUATION_MS - 120_000 + 5_000 + step * 10_000; + for h in 0..4 { + for u in 0..3 { + let host = format!("h{h}"); + let user = format!("u{u}"); + if u < 2 { + let scale = if h == 1 { 100.0 } else { (h + 1) as f64 * 10.0 }; + tables.entry("flows").or_default().push(Row { + host: host.clone(), + user: user.clone(), + ts, + value: scale + u as f64 + step as f64, + }); + } + tables.entry("auth").or_default().push(Row { + host, + user, + ts, + value: (u + 1) as f64 + h as f64 * 0.5 + step as f64 * 0.1, + }); + } + } + } + tables +} + +/// The rows of `table` in the window ending at `time_ms`. +fn window<'a>(rows: &'a [Row], time_ms: i64) -> impl Iterator { + rows.iter() + .filter(move |r| r.ts > time_ms - WINDOW_MS && r.ts <= time_ms) +} + +/// Exact q1 at `time_ms`: the two hosts with the largest sum, and the sums. +fn exact_q1(tables: &BTreeMap<&str, Vec>, time_ms: i64) -> BTreeMap { + let mut sums: BTreeMap = BTreeMap::new(); + for row in window(&tables["flows"], time_ms) { + *sums.entry(row.host.clone()).or_default() += row.value; + } + let mut ranked: Vec<(String, f64)> = sums.into_iter().collect(); + ranked.sort_by(|a, b| b.1.total_cmp(&a.1)); + ranked.into_iter().take(2).collect() +} + +/// Exact q2 at `time_ms` for the hosts `bound`: the sum per user. +fn exact_q2( + tables: &BTreeMap<&str, Vec>, + time_ms: i64, + bound: &BTreeSet, +) -> BTreeMap { + let mut sums: BTreeMap = BTreeMap::new(); + for row in window(&tables["auth"], time_ms).filter(|r| bound.contains(&r.host)) { + *sums.entry(row.user.clone()).or_default() += row.value; + } + sums +} + +/// `rows`' `label` -> value, compared with `exact` to 1e-9. +fn assert_answers( + what: &str, + rows: &[(BTreeMap, f64)], + label: &str, + exact: &BTreeMap, +) { + let answered: BTreeMap = rows + .iter() + .map(|(labels, value)| (labels[label].clone(), *value)) + .collect(); + assert_eq!( + answered.keys().collect::>(), + exact.keys().collect::>(), + "{what}: {answered:?} vs exact {exact:?}" + ); + for (key, value) in &answered { + assert!( + (value - exact[key]).abs() <= 1e-9 * exact[key].abs().max(1.0), + "{what} {key}: {value} vs exact {}", + exact[key] + ); + } +} + +fn rows_of(round: &RoundRecord, id: &str) -> Vec<(BTreeMap, f64)> { + let record = round.queries.iter().find(|q| q.query_id == id).unwrap(); + assert_eq!(record.status, QueryStatus::Answered, "{record:?}"); + record + .answer + .iter() + .map(|row| (row.labels.clone(), row.value)) + .collect() +} + +/// The planner's plan of [`INTENT`] in `mode`, as the data plane reads it. +async fn planned(mode: IntentPlanningMode) -> IntentPlan { + let catalog = SqlCatalog::new() + .with_table("flows", table_schema()) + .with_table("auth", table_schema()); + let data = serde_json::from_value(serde_json::json!({ + "arrival": {"ingesting": {"rows_per_second": 2.0}}, + "sources": { + "flows": {"distinct_values_per_label": {"host": 4, "user": 2}, "rows_held": 100_000}, + "auth": {"distinct_values_per_label": {"host": 4, "user": 3}, "rows_held": 100_000}, + }, + })) + .unwrap(); + let inputs = common::inputs(true); + let models = PlanningModels::builtin() + .with_deployment_capabilities(&inputs.deployment_capabilities) + .with_cost_inputs(&inputs.cost_inputs); + let intents = asap_frontend_sil::parse_intents(INTENT).unwrap(); + let options = IntentPlanningOptions { + mode, + ..IntentPlanningOptions::default() + }; + let (plan, _) = plan_intents(&intents, &catalog, &data, models, &options) + .await + .unwrap_or_else(|e| panic!("{mode:?}: {e}")); + serde_json::from_value(serde_json::to_value(&plan).unwrap()).unwrap() +} + +/// A data plane installing `plan`, the tables written by Remote Write (each +/// row a sample of the series `{__name__=table, host, user}`) and closed by +/// the barrier at `EVALUATION_MS`. +async fn install(plan: &IntentPlan, tables: &BTreeMap<&str, Vec>) -> Arc { + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan.plan).unwrap(), + "http://127.0.0.1:1".into(), + EngineOptions { + no_forward: true, + ..EngineOptions::default() + }, + ) + .unwrap(), + ); + let app = router(state.clone()); + let mut by_time: BTreeMap> = BTreeMap::new(); + for (table, rows) in tables { + for row in rows { + let labels = [ + ("__name__", *table), + ("host", &row.host), + ("user", &row.user), + ] + .iter() + .map(|(name, value)| Label { + name: name.to_string(), + value: value.to_string(), + }) + .collect(); + by_time.entry(row.ts).or_default().push(TimeSeries { + labels, + samples: vec![Sample { + timestamp: row.ts, + value: row.value, + }], + }); + } + } + for timeseries in by_time.into_values() { + common::remote_write(&app, timeseries).await; + } + for _ in 0..1000 { + if state.engine.queued_samples() == 0 { + break; + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + common::barrier(&app, EVALUATION_MS).await; + state +} + +/// In each planning mode: two rounds, each query's answer exact, q2's for +/// the hosts q1 issued; the planner's lightcone queries are never issued; +/// and q2 bound to different hosts at one evaluation time answers each +/// binding (a shared query-time result is keyed by its binding). +#[tokio::test(flavor = "multi_thread")] +async fn every_planning_mode_answers_exactly_round_by_round() { + let tables = tables(); + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentOnDemandHoles, + IntentPlanningMode::IntentFull, + ] { + let plan = planned(mode).await; + let schedule = IntentSchedule::from_intent_plan(&plan, "triage").unwrap(); + let issued: Vec<&str> = schedule.queries.iter().map(|q| q.query.as_str()).collect(); + for &index in &plan.lightcone_query_indices { + let lightcone = plan.plan.query_texts[index].trim(); + assert!(!issued.contains(&lightcone), "{mode:?} issues {lightcone}"); + } + let q2_text = schedule.queries[1].query.clone(); + let q2_slot = schedule.queries[1].bind_slots[0].clone(); + let state = install(&plan, &tables).await; + let intent = + IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(30)).unwrap(); + for time_ms in [EVALUATION_MS - 10_000, EVALUATION_MS] { + let round = intent.run_round(&state.engine, 0, time_ms).await; + let what = format!("{mode:?} at {time_ms}"); + let top = exact_q1(&tables, time_ms); + assert_answers(&format!("{what} q1"), &rows_of(&round, "q1"), "host", &top); + let q2 = round.queries.iter().find(|q| q.query_id == "q2").unwrap(); + let bound = &q2.bindings["Y"]; + assert_eq!( + bound, + &top.keys().cloned().collect::>(), + "{what}" + ); + let exact = exact_q2(&tables, time_ms, bound); + assert_answers( + &format!("{what} q2"), + &rows_of(&round, "q2"), + "user", + &exact, + ); + } + // Two other bindings at one time, then the first again. + for hosts in [&["h0"][..], &["h2", "h3"][..], &["h0"][..]] { + let values: BTreeSet = hosts.iter().map(|h| h.to_string()).collect(); + let slot = SlotBinding { + position: SlotPosition::InList, + placeholders: q2_slot.placeholder_values.clone(), + values: values.clone(), + }; + let answer = state + .engine + .answer_bound(&q2_text, EVALUATION_MS, &[slot]) + .await + .unwrap_or_else(|e| panic!("{mode:?} {hosts:?}: {e}")); + let rows: Vec<_> = answer + .iter() + .map(|s| ((*s.labels).clone(), s.value)) + .collect(); + let exact = exact_q2(&tables, EVALUATION_MS, &values); + assert_answers( + &format!("{mode:?} q2 bound to {hosts:?}"), + &rows, + "user", + &exact, + ); + } + state.engine.stop(); + } +} From 763ef25b28a9d06becc304400ffcc61315cd4258 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:39:36 +0000 Subject: [PATCH 12/20] feat(data_plane): bind an intent query's placeholders in a copy of the plan placeholders::bind rewrites the serialized DAG for each slot: `col IN (p..)` and bare placeholder lists take the bound values, the rollup form `col = p0 OR ..` becomes `col IN (v..)`, a comparison takes its one value; values convert to the placeholder's type. It returns the nodes that changed, and refuses a placeholder left anywhere in the plan. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/placeholders.rs | 191 ++++++++++++++++++++++++++++++++- 1 file changed, 187 insertions(+), 4 deletions(-) diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 0325a65d1..811963ad5 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -48,15 +48,198 @@ pub fn bind( dag: &PhysicalASAPDAG, slots: &[SlotBinding], ) -> Result<(PhysicalASAPDAG, BTreeSet), String> { - let _ = (dag, slots); - todo!("parameter slots: bind a DAG") + let mut json = serde_json::to_value(dag).map_err(|e| format!("the plan: {e}"))?; + let mut changed = BTreeSet::new(); + for slot in slots { + let nodes = json["nodes"] + .as_array_mut() + .ok_or("the plan has no node list")?; + for node in nodes { + if bind_json(node, slot)? { + let id = serde_json::from_value(node["id"].clone()) + .map_err(|e| format!("a node id: {e}"))?; + changed.insert(id); + } + } + // The edges, and anything else the plan holds; this also checks + // that no placeholder is left anywhere. + bind_json(&mut json, slot)?; + } + let bound = serde_json::from_value(json).map_err(|e| format!("the bound plan: {e}"))?; + Ok((bound, changed)) } /// Rewrites `json` (any serialized part of a plan) for `slot`; whether it /// changed. Fails as [`bind`] does, a placeholder left over included. pub fn bind_json(json: &mut Json, slot: &SlotBinding) -> Result { - let _ = (json, slot); - todo!("parameter slots: rewrite") + if slot.placeholders.is_empty() { + return Err("the slot has no placeholders".into()); + } + let placeholders: Vec = slot + .placeholders + .iter() + .map(|p| serde_json::to_value(p).map_err(|e| e.to_string())) + .collect::>()?; + let values = bound_values(slot)?; + if slot.position == SlotPosition::Comparison && values.len() != 1 { + return Err(format!( + "a comparison hole takes exactly one value, not {} ({:?})", + values.len(), + slot.values + )); + } + let rewrite = Rewrite { + placeholders: &placeholders, + values: &values, + position: slot.position, + }; + let changed = rewrite.apply(json); + if let Some(left) = rewrite.find(json) { + return Err(format!( + "placeholder {left} is left in a form the binding does not rewrite" + )); + } + Ok(changed) +} + +/// The slot's values as JSON scalars of its placeholders' type. +fn bound_values(slot: &SlotBinding) -> Result, String> { + let bad = |value: &str, kind: &str| format!("bound value {value:?} is not a {kind}"); + slot.values + .iter() + .map(|value| { + let scalar = match &slot.placeholders[0] { + ScalarValue::Utf8(_) => ScalarValue::Utf8(value.clone()), + ScalarValue::Int64(_) => { + ScalarValue::Int64(parse_integer(value).ok_or_else(|| bad(value, "integer"))?) + } + ScalarValue::Timestamp(_) => ScalarValue::Timestamp( + parse_integer(value).ok_or_else(|| bad(value, "timestamp"))?, + ), + ScalarValue::Float64(_) => { + ScalarValue::Float64(value.parse().map_err(|_| bad(value, "number"))?) + } + other => return Err(format!("a hole of type {other:?} cannot be bound")), + }; + serde_json::to_value(scalar).map_err(|e| e.to_string()) + }) + .collect() +} + +/// `text` as an integer: `12`, or a whole float such as `12` printed as `12.0`. +fn parse_integer(text: &str) -> Option { + text.parse().ok().or_else(|| { + let float: f64 = text.parse().ok()?; + (float.fract() == 0.0 && float.abs() < 9.0e15).then_some(float as i64) + }) +} + +/// One slot's rewrite of serialized plan parts. +struct Rewrite<'a> { + placeholders: &'a [Json], + values: &'a [Json], + position: SlotPosition, +} + +impl Rewrite<'_> { + /// Whether `json` is one of the placeholders, bare (`Some(false)`) or as + /// a literal expression (`Some(true)`). + fn placeholder(&self, json: &Json) -> Option { + if self.placeholders.contains(json) { + return Some(false); + } + let literal = json.as_object().filter(|o| o.len() == 1)?.get("Literal")?; + self.placeholders.contains(literal).then_some(true) + } + + /// The values, bare or as literal expressions. + fn values(&self, literal: bool) -> Vec { + self.values + .iter() + .map(|value| match literal { + true => serde_json::json!({ "Literal": value }), + false => value.clone(), + }) + .collect() + } + + /// `col = p_0 OR .. OR col = p_n-1`'s column side, when `json` is one. + fn disjunction_column(&self, json: &Json) -> Option { + let terms = json + .as_object() + .filter(|o| o.len() == 1)? + .get("BoolOr")? + .as_array()?; + let mut column: Option<&Json> = None; + for term in terms { + let compare = term.as_object().filter(|o| o.len() == 1)?.get("Compare")?; + if compare.get("op")? != "Eq" { + return None; + } + let (left, right) = (compare.get("left")?, compare.get("right")?); + let other = match (self.placeholder(left), self.placeholder(right)) { + (None, Some(true)) => left, + (Some(true), None) => right, + _ => return None, + }; + if column.is_some_and(|c| c != other) { + return None; + } + column = Some(other); + } + column.cloned() + } + + /// Rewrites every placeholder form in `json`; whether any was. + fn apply(&self, json: &mut Json) -> bool { + if self.position == SlotPosition::InList { + if let Some(column) = self.disjunction_column(json) { + *json = serde_json::json!({"InList": { + "expr": column, + "list": self.values(true), + "negated": false, + }}); + return true; + } + if let Some(items) = json.as_array() { + let kinds: Vec> = items.iter().map(|i| self.placeholder(i)).collect(); + if let Some(Some(literal)) = kinds.first().copied() { + if kinds.iter().all(|kind| *kind == Some(literal)) { + *json = Json::Array(self.values(literal)); + return true; + } + } + } + } else if let Some(literal) = self.placeholder(json) { + *json = self.values(literal).remove(0); + return true; + } + match json { + Json::Array(items) => items.iter_mut().fold(false, |any, i| self.apply(i) | any), + Json::Object(fields) => fields + .values_mut() + .fold(false, |any, f| self.apply(f) | any), + _ => false, + } + } + + /// A placeholder still in `json`, as text. + fn find(&self, json: &Json) -> Option { + if self.placeholders.contains(json) { + return Some(json.to_string()); + } + if let Json::String(text) = json { + let as_text = |p: &Json| p.get("Utf8").and_then(Json::as_str) == Some(text.as_str()); + if self.placeholders.iter().any(as_text) { + return Some(json.to_string()); + } + } + match json { + Json::Array(items) => items.iter().find_map(|i| self.find(i)), + Json::Object(fields) => fields.values().find_map(|f| self.find(f)), + _ => None, + } + } } #[cfg(test)] From b73c4bb73a0cfad5659daa5390d69a5e4e223a5a Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:40:11 +0000 Subject: [PATCH 13/20] feat(data_plane): key query-time results by intent binding A shared query-time node computed under an intent's binding is kept under (time, node, binding hash), apart from its unbound result and from its result under any other binding at the same time (QueryTimeResults::get_or_compute_bound). Co-Authored-By: Claude Opus 5.5 --- data_plane/src/store.rs | 35 ++++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 33042c07a..af4204f47 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -1434,8 +1434,13 @@ type QueryTimeEntry = Arc<(Mutex>, Condvar)>; /// one at a later time is computed by each run that needs it. A result is /// kept while `T` is within `retention_ms` of the watermark, and the /// oldest are dropped while more than `max_bytes` are held. +/// The binding key of a query-time result computed with no intent binding. +pub const UNBOUND: u64 = 0; + pub struct QueryTimeResults { - entries: Mutex>>, + /// By evaluation time, node and binding key ([`UNBOUND`]: no intent + /// binding). + entries: Mutex>>, retention_ms: i64, max_bytes: usize, bytes: AtomicU64, @@ -1467,8 +1472,8 @@ impl QueryTimeResults { watermark_ms: Option, compute: impl FnOnce() -> Result, E>, ) -> Result>, E> { - let _ = (node, time_ms, binding, watermark_ms, compute); - todo!("parameter slots: keyed query-time results") + debug_assert_ne!(binding, UNBOUND, "0 keys the unbound result"); + self.get_or_compute_keyed(node, time_ms, binding, watermark_ms, compute) } /// `node`'s output at `time_ms`: stored, or computed now by `compute` @@ -1480,6 +1485,18 @@ impl QueryTimeResults { time_ms: i64, watermark_ms: Option, compute: impl FnOnce() -> Result, E>, + ) -> Result>, E> { + self.get_or_compute_keyed(node, time_ms, UNBOUND, watermark_ms, compute) + } + + /// [`Self::get_or_compute`] under the binding key `binding`. + fn get_or_compute_keyed( + &self, + node: PhysicalASAPNodeId, + time_ms: i64, + binding: u64, + watermark_ms: Option, + compute: impl FnOnce() -> Result, E>, ) -> Result>, E> { if watermark_ms.is_none_or(|watermark| time_ms > watermark) { self.computes.fetch_add(1, Ordering::Relaxed); @@ -1487,12 +1504,12 @@ impl QueryTimeResults { } let (entry, computer) = { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); - match entries.get(&(time_ms, node)) { + match entries.get(&(time_ms, node, binding)) { Some(entry) => (entry.clone(), false), None => { let entry: QueryTimeEntry = Arc::new((Mutex::new(ResultState::Computing), Condvar::new())); - entries.insert((time_ms, node), entry.clone()); + entries.insert((time_ms, node, binding), entry.clone()); (entry, true) } } @@ -1514,7 +1531,7 @@ impl QueryTimeResults { let result = compute().map(Arc::new); let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); let held = entries - .get(&(time_ms, node)) + .get(&(time_ms, node, binding)) .is_some_and(|held| Arc::ptr_eq(held, &entry)); { let mut state = state.lock().unwrap_or_else(|e| e.into_inner()); @@ -1531,7 +1548,7 @@ impl QueryTimeResults { done.notify_all(); } if result.is_err() && held { - entries.remove(&(time_ms, node)); + entries.remove(&(time_ms, node, binding)); } if let Some(watermark_ms) = watermark_ms { self.drop_old(&mut entries, watermark_ms); @@ -1544,11 +1561,11 @@ impl QueryTimeResults { /// being computed (its computer finds it gone and does not count it). fn drop_old( &self, - entries: &mut BTreeMap<(i64, PhysicalASAPNodeId), QueryTimeEntry>, + entries: &mut BTreeMap<(i64, PhysicalASAPNodeId, u64), QueryTimeEntry>, watermark_ms: i64, ) { let oldest_kept_ms = watermark_ms.saturating_sub(self.retention_ms); - let keys: Vec<(i64, PhysicalASAPNodeId)> = entries.keys().copied().collect(); + let keys: Vec<(i64, PhysicalASAPNodeId, u64)> = entries.keys().copied().collect(); for key in keys { let expired = key.0 < oldest_kept_ms; let over = self.bytes.load(Ordering::Relaxed) as usize > self.max_bytes; From d5b2d39e9ae513ecdd0897e57bc684581eb833cd Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:47:38 +0000 Subject: [PATCH 14/20] feat(data_plane): store a SQL table's rows as the series named after it A Scan of a SQL table (Source::Table) reads the series whose __name__ is the table: its text columns are their labels, its time column their time and its `value` column their value. Before, the data plane refused any source but a PromQL time series, so no SQL plan (and no SIL intent) ran. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/ingestion.rs | 9 +++------ data_plane/src/push.rs | 8 ++------ data_plane/src/store.rs | 24 +++++++++++++++--------- 3 files changed, 20 insertions(+), 21 deletions(-) diff --git a/data_plane/src/ingestion.rs b/data_plane/src/ingestion.rs index 8602df6fa..f9b476a13 100644 --- a/data_plane/src/ingestion.rs +++ b/data_plane/src/ingestion.rs @@ -318,17 +318,14 @@ impl Ingestion { let mut query_time_lookback_ms: HashMap> = HashMap::new(); for scan in index.below(&dag.roots, &view_ids) { let node = index.nodes[&scan]; - if let Operator::NonASAP(NonASAPOp::Scan { - source: Source::TimeSeries { metric }, - .. - }) = &node.payload - { + if let Operator::NonASAP(NonASAPOp::Scan { source, .. }) = &node.payload { + let metric = crate::store::stored_series(source); let margin_ms = millis(options.view_retention_margin_ms); let lookback = node .retention_ms .map(|retention| millis(retention).saturating_add(margin_ms)); let entry = query_time_lookback_ms - .entry(metric.clone()) + .entry(metric.to_string()) .or_insert(Some(0)); *entry = match (*entry, lookback) { (Some(a), Some(b)) => Some(a.max(b)), diff --git a/data_plane/src/push.rs b/data_plane/src/push.rs index 03b0381eb..c617104cc 100644 --- a/data_plane/src/push.rs +++ b/data_plane/src/push.rs @@ -163,14 +163,10 @@ impl DataStore for PushStore { request: &RawDataRequest, _context: RunContext, ) -> Result, Error> { - let Source::TimeSeries { metric } = source else { - return Err(Error::Invalid(format!( - "the data plane stores time series only, not {source:?}" - ))); - }; + let metric = crate::store::stored_series(source); let (sender, receiver) = unbounded(); let reader = Reader { - metric: metric.clone(), + metric: metric.to_string(), schema: request.schema.clone(), schema_key: format!("{:?}", request.schema), sender: Some(sender), diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index af4204f47..2cd1fe9d7 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -509,6 +509,17 @@ impl RawReads { } } +/// The metric whose series hold a scan's rows: a time series' metric, or +/// a SQL table's name. A table's rows are the samples of the series named +/// after it (`__name__`), its text columns their labels, its time column +/// their time and its `value` column their value. +pub(crate) fn stored_series(source: &Source) -> &str { + match source { + Source::TimeSeries { metric } => metric, + Source::Table { table_ref } => table_ref, + } +} + /// What one column of a time series table holds. #[derive(Debug, Clone, PartialEq)] enum ColumnKind { @@ -627,11 +638,7 @@ impl DataStore for RunStore { request: &RawDataRequest, context: RunContext, ) -> Result, Error> { - let Source::TimeSeries { metric } = source else { - return Err(Error::Invalid(format!( - "the data plane stores time series only, not {source:?}" - ))); - }; + let metric = stored_series(source); let mut batches = Vec::new(); for shard in self.raw_data.iter() { let read = shard.read( @@ -1623,10 +1630,9 @@ pub fn scanned_metrics<'a>( nodes .into_iter() .filter_map(|node| match &node.payload { - Operator::NonASAP(NonASAPOp::Scan { - source: Source::TimeSeries { metric }, - .. - }) => Some(metric.clone()), + Operator::NonASAP(NonASAPOp::Scan { source, .. }) => { + Some(stored_series(source).to_string()) + } _ => None, }) .collect() From a02149c9657dbc8d626533c88d8e79e680d6fda2 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:50:48 +0000 Subject: [PATCH 15/20] chore: port the Planner API migration of the pending planner bump The planner API changes between 1d527bc and the SIL head, as the open planner-bump PR adapts them on the new crate layout, applied to this branch's layout in place of the partial adaptation in the pin commit: - storage: view bytes from each window batch's state column, cold reads via StateColumn::from_views, family_has_view_layout (VIEW_STATES). - state_codec: the compact DDSketch codec follows the new 64-byte DDSketch view head (no sum, min, max); FORMAT_VERSION 4 -> 5. - query: a shared query-time slot carries the plan's plan_id and a view_state_key, now required MaterializedView fields. Co-Authored-By: Claude Opus 5.5 --- data_plane/examples/tier_bench.rs | 11 +- data_plane/src/persist.rs | 100 ++++++++----- data_plane/src/query.rs | 16 ++- data_plane/src/segment.rs | 147 ++++++++++---------- data_plane/src/state_codec.rs | 125 ++++++++--------- data_plane/src/store.rs | 9 ++ data_plane/tests/planner_executor_parity.rs | 2 +- data_plane/tests/push_precompute.rs | 2 +- data_plane/tests/view_cache_charge.rs | 3 + data_plane/tests/view_persistence.rs | 2 +- docs/design/tiered-view-storage.md | 15 +- 11 files changed, 241 insertions(+), 191 deletions(-) diff --git a/data_plane/examples/tier_bench.rs b/data_plane/examples/tier_bench.rs index 3c136190c..e98b195d8 100644 --- a/data_plane/examples/tier_bench.rs +++ b/data_plane/examples/tier_bench.rs @@ -100,8 +100,15 @@ async fn main() { let plan_text = serde_json::to_string(&plan).unwrap(); println!( "plan states (mentions): {:?}", - ["DDSketch", "\"Kll\"", "Hll", "Cms", "Counter", "Max"] - .map(|k| (k, plan_text.matches(k).count())) + [ + "DDSketch", + "\"KLL\"", + "\"HLL\"", + "CountMinSketch", + "Counter", + "Max" + ] + .map(|k| (k, plan_text.matches(k).count())) ); let now_ms = std::time::SystemTime::now() diff --git a/data_plane/src/persist.rs b/data_plane/src/persist.rs index 3b996548c..7327607e9 100644 --- a/data_plane/src/persist.rs +++ b/data_plane/src/persist.rs @@ -447,8 +447,8 @@ impl ViewFiles { for (view, batches) in views { let (mark, grids_mark) = (texts.new.len(), grids.bytes.len()); let encoded = batches.first().and_then(|first| { - let rows = window_rows(batches)?; - encode_fragment(first.schema(), &rows, &mut texts, &mut grids) + let (rows, sources) = window_rows(batches)?; + encode_fragment(first.schema(), &rows, &sources, &mut texts, &mut grids) }); match encoded { Some(fragment) => fragments.push((*view, fragment)), @@ -631,10 +631,20 @@ impl ViewFiles { /// The rows of a window's `batches`. A window split by series is kept as /// one batch per part; its rows are written in the order one run over /// every series emits them (by their plain columns' values), so a window's -/// fragment is the same whichever way its run was split. `None` when a -/// plain value has no order. -fn window_rows(batches: &[Batch]) -> Option>> { - let mut rows: Vec> = batches.iter().flat_map(Batch::to_rows).collect(); +/// fragment is the same whichever way its run was split. With each row, +/// the batch and row it came from ([`crate::segment::RowSource`]). `None` +/// when a plain value has no order. +fn window_rows(batches: &[Batch]) -> Option<(Vec>, Vec>)> { + let mut rows: Vec<(Vec, crate::segment::RowSource<'_>)> = batches + .iter() + .flat_map(|batch| { + batch + .to_rows() + .into_iter() + .enumerate() + .map(move |(row, values)| (values, (batch, row))) + }) + .collect(); if batches.len() > 1 { let plain: Vec = batches[0] .schema() @@ -654,7 +664,7 @@ fn window_rows(batches: &[Batch]) -> Option>> { .map(|row| { let key = plain .iter() - .map(|&column| row[column].key()) + .map(|&column| row.0[column].key()) .collect::, _>>() .ok()?; Some((key, row)) @@ -663,7 +673,7 @@ fn window_rows(batches: &[Batch]) -> Option>> { keyed.sort_by(|a, b| a.0.cmp(&b.0)); rows = keyed.into_iter().map(|(_, row)| row).collect(); } - Some(rows) + Some(rows.into_iter().unzip()) } /// The state `value` stores, with the record's rebuilt `grids`. @@ -1117,15 +1127,9 @@ mod tests { }; use asap_executor::planner::summary_type::{ExactKind, ExactParams, SketchAlgorithm}; - /// One state's view bytes, as the segment writer stores them. - fn state_view_bytes(family: &FieldDataType, state: &Arc) -> Vec { - let row = vec![vec![Value::Summary { - family: family.clone(), - state: state.clone(), - }]]; - crate::segment::column_views(family, &row, 0) - .unwrap() - .remove(0) + /// Each row of `batch` as a fragment row's source. + fn sources_of(batch: &Batch) -> Vec> { + (0..batch.num_rows()).map(|row| (batch, row)).collect() } /// A fresh directory for one test's segments. @@ -1363,9 +1367,9 @@ mod tests { ) } - /// The window of [`ten_sample_ddsketch_window`] takes 30.2 kB on disk - /// (30 B a series, most of it the full-precision sum, min and max), not - /// the 126 kB of the mapped layout (106 kB of DDSketch views alone). + /// The window of [`ten_sample_ddsketch_window`] takes 8.3 kB on disk + /// (8 B a series), not the 82 kB its DDSketch views alone take in the + /// view layout. #[test] fn a_ten_sample_ddsketch_window_is_stored_compact() { let dir = segment_dir("dd-bytes"); @@ -1374,18 +1378,14 @@ mod tests { let written = files .append(0, (0, 1_000), &[(1, std::slice::from_ref(&batch))]) .unwrap(); - let views: usize = batch - .to_rows() - .iter() - .map(|row| match &row[4] { - Value::Summary { state, .. } => { - state_view_bytes(&batch.schema().fields[4].dtype, state).len() - } - _ => unreachable!(), - }) - .sum(); - assert_eq!(views, 106_176); - assert_eq!(location_of(&written, 1).len(), 30_196); + let views: usize = + crate::segment::view_bytes(&batch.schema().fields[4].dtype, &sources_of(&batch), 4) + .unwrap() + .iter() + .map(|view| view.len()) + .sum(); + assert_eq!(views, 82_176); + assert_eq!(location_of(&written, 1).len(), 8_309); let _ = std::fs::remove_dir_all(&dir); } @@ -1493,10 +1493,15 @@ mod tests { .map(|i| if i % 2 == 0 { a.clone() } else { b.clone() }) .collect(); let held = 4 * (states.len() + 1) - + states - .iter() - .map(|s| state_view_bytes(&kll, s).len().div_ceil(8) * 8) - .sum::(); + + crate::segment::view_bytes( + &kll, + &sources_of(&window_batch(10, kll.clone(), states.clone())), + 4, + ) + .unwrap() + .iter() + .map(|view| view.len().div_ceil(8) * 8) + .sum::(); let (first, second) = ( window_batch(10, kll.clone(), states.clone()), window_batch(20, kll, states), @@ -1514,7 +1519,10 @@ mod tests { let (r2, _) = l2.read(second.schema(), ViewRead::Mmap).unwrap(); assert_same_rows(&first, &r1, "mapped"); assert_eq!(state_bytes, held); - assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), 0); + // The column reports the bytes its views span, but a run reading + // it is charged none of them: they are the store's. + assert_eq!(r1.state_column(4).unwrap().state_memory_bytes(), held); + assert_eq!(r1.memory_bytes() + held, r1.stored_bytes()); let identity = |batch: &Batch| { batch .column(1) @@ -1647,6 +1655,9 @@ mod tests { serde_json::from_value(serde_json::json!({ "node_id": id, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": format!("v{id}"), "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": format!("v{id}"), "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1678,6 +1689,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1874,6 +1888,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1925,6 +1942,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1972,6 +1992,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -2014,6 +2037,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "v", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index 0c7ee5a16..596cb53a2 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -116,8 +116,11 @@ impl QueryEngine { BTreeSet::new() }; let mut slots: Vec = views.to_vec(); - for &node in &shared { - slots.push(query_time_slot(node)?); + if !shared.is_empty() { + let plan_id = dag.plan_id(); + for &node in &shared { + slots.push(query_time_slot(&plan_id, node)?); + } } let mut compiled: BTreeMap> = BTreeMap::new(); for &node in shared.iter().chain(&dag.roots) { @@ -429,11 +432,16 @@ fn scans_below( } /// The view slot a shared node is bound as: its whole output at the run's -/// evaluation time, refreshed on first read and kept for that evaluation. -fn query_time_slot(node: PhysicalASAPNodeId) -> anyhow::Result { +/// evaluation time, refreshed on first read and kept for that evaluation; +/// a view of plan `plan_id` (`PhysicalASAPDAG::plan_id`) whose state key +/// names only that node. +fn query_time_slot(plan_id: &str, node: PhysicalASAPNodeId) -> anyhow::Result { Ok(serde_json::from_value(serde_json::json!({ "node_id": node, "refresh": "on_first_read", + "plan_id": plan_id, + "view_state_key": {"definition_id": format!("query-time-result-{node}"), "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": format!("query-time-result-{node}"), "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 0, diff --git a/data_plane/src/segment.rs b/data_plane/src/segment.rs index d9755ce66..9d287cce9 100644 --- a/data_plane/src/segment.rs +++ b/data_plane/src/segment.rs @@ -12,10 +12,11 @@ //! A fragment holds one view's rows of one window by column, compressed //! (zstd), so a cold read decodes one (view, window) without the record's //! other views. State and text columns are stored compact -//! ([`crate::state_codec`]) and rebuilt in the executor's mapped state +//! ([`crate::state_codec`]) and rebuilt in the executor's view //! layout when read. A text column holding each row's series label is not //! stored: it is rebuilt from the series identity column. +use std::borrow::Cow; use std::cell::RefCell; use std::collections::{BTreeMap, HashMap}; use std::fs::File; @@ -37,7 +38,9 @@ use asap_executor::planner::ir::schema::{DataType, FieldDataType, Schema, PROMQL use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::planner::summary_type::{ExactKind, SketchAlgorithm}; use asap_executor::summary_kernels::HydraCms; -use asap_executor::values::{family_has_view_layout, Batch, BatchColumn, SchemaRef, Value}; +use asap_executor::values::{ + family_has_view_layout, Batch, BatchColumn, SchemaRef, StateColumn, Value, +}; use asap_executor::Error; use serde::{Deserialize, Serialize}; @@ -48,7 +51,11 @@ use crate::state_codec::{ }; /// The view file format version these segments are. -pub const FORMAT_VERSION: u32 = 4; +/// +/// 5: DDSketch states without `sum`, `min` and `max` (`asap_sketchlib` +/// ASAPv1 kind `0x05 0x01`; a 64-byte view head). A version 4 segment is +/// set aside on open, never read. +pub const FORMAT_VERSION: u32 = 5; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -67,16 +74,16 @@ const TIMESTAMP: u32 = 4; /// Any other plain column: MessagePack of its values. const GENERIC: u32 = 5; const STATES: u32 = 6; -/// A state column in the executor's mapped layout: `u32` offsets in the +/// A state column in the executor's view layout: `u32` offsets in the /// data section, the states (each 8-byte aligned) in the second section. -/// For a family with a mapped form but no compact one (KLL, Count-Min). -const MAPPED_STATES: u32 = 7; +/// For a family with a view layout but no compact form (KLL, Count-Min). +const VIEW_STATES: u32 = 7; /// A text column whose every row holds its series identity's label of the /// column's name (`""` when the series has none): no data, rebuilt on read /// from the identity column, whose index is the descriptor's flags. const IDENTITY_LABEL: u32 = 8; /// A state column in compact form ([`crate::state_codec`]); its flags are -/// the [`CompactKind`] code. Read back into the mapped layout. +/// the [`CompactKind`] code. Read back into the view layout. const COMPACT_STATES: u32 = 9; /// Flag: a timestamp column whose rows all hold one value, stored once. const CONSTANT: u32 = 1; @@ -760,7 +767,7 @@ impl WindowLocation { } /// The fragment's rows as one batch of `schema`, and the bytes its - /// state columns hold: they are rebuilt in the mapped layout, which + /// state columns hold: they are rebuilt in the view layout, which /// [`Batch::memory_bytes`] counts as held outside the run, so a cache /// holding the batch charges them itself. pub fn read(&self, schema: &SchemaRef, how: ViewRead) -> Result<(Batch, usize), Error> { @@ -868,11 +875,15 @@ fn validity(nulls: &[bool]) -> Option> { Some(bits) } -/// `rows` (of `schema`) as one compressed columnar fragment; `None` when a -/// state has no byte encoding. +/// Where a fragment row came from: a window's batch and its row there. +pub(crate) type RowSource<'a> = (&'a Batch, usize); + +/// `rows` (of `schema`) as one compressed columnar fragment, row `i` read +/// from `sources[i]`; `None` when a state has no byte encoding. pub(crate) fn encode_fragment( schema: &Schema, rows: &[Vec], + sources: &[RowSource<'_>], texts: &mut SegmentTexts, grids: &mut Grids, ) -> Option> { @@ -889,7 +900,7 @@ pub(crate) fn encode_fragment( .iter() .map(|row| matches!(row[column], Value::Null)) .collect(); - // The second section: the validity bitmap, or a mapped state + // The second section: the validity bitmap, or a view-layout state // column's states. let mut second: Option> = None; // The identity column, when this column holds its series' label. @@ -900,18 +911,17 @@ pub(crate) fn encode_fragment( && labels.holds_label(rows, column, &field.name) }) .map(|labels| labels.column as u32); + // Each state in its view layout (`None` when a state has none, e.g. + // a keyed exact state, or the family has no view layout). + let views = view_bytes(&field.dtype, sources, column); // A state column of a family with a compact form, compacted from - // each state's mapped layout (`None` when a state has none, e.g. a - // keyed exact state, or the column has no compact form). - let mut compact = compact_kind(&field.dtype).and_then(|kind| { - let views = column_views(&field.dtype, rows, column)?; - Some((kind, encode_states(kind, views.iter())?)) - }); - // Otherwise the column in the mapped layout, when it has one. - let mut mapped = match &field.dtype { - FieldDataType::Plain(_) => None, - _ if compact.is_some() => None, - family if family_has_view_layout(family) => mapped_states(&field.dtype, rows, column), + // the views (`None` when the column has no compact form). + let mut compact = compact_kind(&field.dtype) + .zip(views.as_ref()) + .and_then(|(kind, views)| Some((kind, encode_states(kind, views.iter())?))); + // Otherwise the column in the view layout, when it has one. + let mut view_column = match views { + Some(views) if compact.is_none() => view_column_of(views), _ => None, }; let (kind, mut flags, data): (u32, u32, Vec) = match &field.dtype { @@ -974,10 +984,10 @@ pub(crate) fn encode_fragment( let (compact_kind, compact) = compact.take().expect("checked"); (COMPACT_STATES, compact_kind.code(), compact) } - _ if mapped.is_some() => { - let (offsets, states) = mapped.take().expect("checked"); + _ if view_column.is_some() => { + let (offsets, states) = view_column.take().expect("checked"); second = Some(states); - (MAPPED_STATES, 0, offsets) + (VIEW_STATES, 0, offsets) } _ => { // States: u32 offsets[rows + 1], then each state's stored bytes. @@ -999,7 +1009,7 @@ pub(crate) fn encode_fragment( }; let (data_offset, data_len) = section(&mut out, &data); let (valid_offset, valid_len) = match (kind, validity(&nulls)) { - (MAPPED_STATES, _) => section(&mut out, &second.take().expect("states")), + (VIEW_STATES, _) => section(&mut out, &second.take().expect("states")), (STATES | GENERIC | COMPACT_STATES, _) => (0, 0), (_, Some(bits)) => section(&mut out, &bits), (_, None) => (0, 0), @@ -1094,52 +1104,51 @@ impl IdentityLabels { } } -/// Column `column` of `rows` in the executor's mapped state layout: the -/// `u32` offsets (`rows + 1`) and the states back to back, each padded to 8 -/// bytes; `None` when a state has no mapped form. -fn mapped_states( +/// Each source row's state in column `column` (of `family`) in the +/// executor's view layout, read from its batch's state column +/// ([`StateColumn::view_bytes`]: borrowed where that column holds views); +/// `None` when a row holds no state, the family has no view layout, or a +/// state has none (a keyed exact state). +pub(crate) fn view_bytes<'a>( family: &FieldDataType, - rows: &[Vec], + sources: &[RowSource<'a>], column: usize, -) -> Option<(Vec, Vec)> { - let mut offsets = Vec::with_capacity((rows.len() + 1) * 4); - let mut states = Vec::new(); +) -> Option>> { + if !family_has_view_layout(family) { + return None; + } + sources + .iter() + .map(|&(batch, row)| { + let states = batch.state_column(column)?; + let indices = batch + .column(column) + .as_any() + .downcast_ref::()?; + if indices.is_null(row) { + return None; + } + states.view_bytes(indices.value(row) as usize) + }) + .collect() +} + +/// State `views` in the executor's view layout as one column: the `u32` +/// offsets (`rows + 1`) and the states back to back, each padded to 8 +/// bytes. Each view is dropped once copied, so the column and the views +/// are not both held whole. +fn view_column_of(views: Vec>) -> Option<(Vec, Vec)> { + let mut offsets = Vec::with_capacity((views.len() + 1) * 4); + let mut states = Vec::with_capacity(views.iter().map(|view| padded(view.len())).sum()); offsets.extend_from_slice(&0u32.to_le_bytes()); - for view in column_views(family, rows, column)? { - states.extend(view); + for view in views { + states.extend_from_slice(&view); states.resize(padded(states.len()), 0); offsets.extend_from_slice(&u32::try_from(states.len()).ok()?.to_le_bytes()); } Some((offsets, states)) } -/// Each state of column `column` of `rows`, of `family`, in the executor's -/// view layout ([`asap_executor::values::StateColumn::view_bytes`]); `None` -/// when a value is not a state or a state has no view layout. -pub(crate) fn column_views( - family: &FieldDataType, - rows: &[Vec], - column: usize, -) -> Option>> { - if rows - .iter() - .any(|row| !matches!(row[column], Value::Summary { .. })) - { - return None; - } - let field = asap_executor::planner::ir::schema::Field { - name: "state".into(), - dtype: family.clone(), - nullable: true, - }; - let values = rows.iter().map(|row| vec![row[column].clone()]).collect(); - let (_, states) = one_column(&field, values).ok()?; - let states = states?; - (0..states.len()) - .map(|index| states.view_bytes(index).map(|view| view.into_owned())) - .collect() -} - /// A little-endian `u64` at `at` of `bytes`. fn word(bytes: &[u8], at: usize) -> Result { Ok(u64::from_le_bytes( @@ -1297,7 +1306,7 @@ fn decode_fragment( data, valid, } = descriptor(bytes, column)?; - let nulls = if valid.1 == 0 || kind == MAPPED_STATES || kind == COMPACT_STATES { + let nulls = if valid.1 == 0 || kind == VIEW_STATES || kind == COMPACT_STATES { None } else { if valid.1 != rows.div_ceil(8) { @@ -1389,7 +1398,7 @@ fn decode_fragment( decode_states(compact, &bytes[data.0..data.0 + data.1], rows) .ok_or_else(damaged)?; state_bytes += states.len() * 8 + offsets.len() * 4; - let column = asap_executor::values::StateColumn::from_views( + let column = StateColumn::from_views( field.dtype.clone(), Buffer::from(states), ScalarBuffer::from(offsets), @@ -1400,18 +1409,14 @@ fn decode_fragment( }); continue; } - MAPPED_STATES => { + VIEW_STATES => { if data.1 != (rows + 1) * 4 { return Err(damaged()); } state_bytes += data.1 + valid.1; let offsets = ScalarBuffer::::new(buffer(bytes, data.0, data.1)?, 0, rows + 1); let states = buffer(bytes, valid.0, valid.1)?; - let column = asap_executor::values::StateColumn::from_views( - field.dtype.clone(), - states, - offsets, - )?; + let column = StateColumn::from_views(field.dtype.clone(), states, offsets)?; out.push(BatchColumn::States { indices: UInt32Array::from_iter_values(0..rows as u32), states: Arc::new(column), diff --git a/data_plane/src/state_codec.rs b/data_plane/src/state_codec.rs index 1f8396781..06ac3cd5a 100644 --- a/data_plane/src/state_codec.rs +++ b/data_plane/src/state_codec.rs @@ -1,12 +1,12 @@ //! Compact encodings of a fragment's state and text columns //! (docs/design/tiered-view-storage.md, "On-disk format"). //! -//! A state column is written in the executor's mapped layout -//! ([`asap_executor::values::StateColumn::view_bytes`]): fixed-width fields and -//! 8-byte-aligned arrays. That layout is large for the small -//! states of narrow panes: a DDSketch of ten samples is an 88-byte header +//! A state column is written in the executor's view layout +//! ([`asap_executor::values::StateColumn::view_bytes`]): fixed-width fields +//! and 8-byte-aligned arrays. That layout is large for the small +//! states of narrow panes: a DDSketch of ten samples is a 64-byte header //! plus a dense run of 1-byte bucket counts, most of them empty. This module -//! stores the same states in a compact form and rebuilds the mapped layout, +//! stores the same states in a compact form and rebuilds the view layout, //! byte for byte, when a window is read cold: //! //! - DDSketch: only non-empty buckets, as a varint gap from the previous @@ -19,12 +19,12 @@ //! - Text keys: each row's dictionary key as a signed varint delta from //! the previous row's. //! -//! Everything here is lossless: decoding gives the bytes the mapped layout +//! Everything here is lossless: decoding gives the bytes the view layout //! held, so every answer read from a compact column is the one read from -//! the mapped column. A state the encoder does not recognize as canonical +//! the view-layout column. A state the encoder does not recognize as canonical //! is kept whole (a raw-record tag), never approximated. -/// The state families with a compact form, as the mapped layout names +/// The state families with a compact form, as the view layout names /// them: which fixed-size exact record, or which sketch. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CompactKind { @@ -68,7 +68,7 @@ impl CompactKind { }) } - /// The bytes of one record in the mapped layout, for an exact kind. + /// The bytes of one record in the view layout, for an exact kind. fn record_bytes(self) -> Option { Some(match self { Self::DDSketch => return None, @@ -138,9 +138,18 @@ fn padded(n: usize) -> usize { const DD_MAGIC: [u8; 4] = *b"DDV1"; const VIEW_LAYOUT_VERSION: u32 = 1; -/// Bytes of a DDSketch view before its arrays: magic and version, seven +/// Bytes of a DDSketch view before its arrays: magic and version, four /// 8-byte fields, six 4-byte fields. -const DD_HEAD_BYTES: usize = 88; +const DD_HEAD_BYTES: usize = 64; +/// Where a DDSketch view's 4-byte fields lie in its head: the count width, +/// the store form (1 sparse), and each store's first bucket index and +/// entry count. +const DD_WIDTH_AT: usize = 40; +const DD_SPARSE_AT: usize = 44; +const DD_POSITIVE_OFFSET_AT: usize = 48; +const DD_POSITIVE_ENTRIES_AT: usize = 52; +const DD_NEGATIVE_OFFSET_AT: usize = 56; +const DD_NEGATIVE_ENTRIES_AT: usize = 60; /// The widest store a DDSketch view may span, in buckets (the view /// reader's limit): bucket index arithmetic stays far inside `i32`. const MAX_SPAN: i64 = 1 << 20; @@ -152,9 +161,6 @@ type Buckets = Vec<(i32, u64)>; #[derive(Debug, Default, Clone, PartialEq)] struct DdContents { alpha: u64, - sum: u64, - min: u64, - max: u64, zero_count: u64, admission_rate: u64, positive: Buckets, @@ -194,13 +200,10 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { let mut at = 8; let alpha = u64_at(view, &mut at)?; let count = u64_at(view, &mut at)?; - let sum = u64_at(view, &mut at)?; - let min = u64_at(view, &mut at)?; - let max = u64_at(view, &mut at)?; let zero_count = u64_at(view, &mut at)?; let admission_rate = u64_at(view, &mut at)?; - let width = u32_at(view, 64)? as usize; - let sparse = match u32_at(view, 68)? { + let width = u32_at(view, DD_WIDTH_AT)? as usize; + let sparse = match u32_at(view, DD_SPARSE_AT)? { 0 => false, 1 => true, _ => return None, @@ -245,21 +248,16 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { } Some(()) }; - let (positive_offset, negative_offset) = (u32_at(view, 72)? as i32, u32_at(view, 80)? as i32); - store( - positive_offset, - u32_at(view, 76)? as usize, - &mut dd.positive, - )?; - store( - negative_offset, - u32_at(view, 84)? as usize, - &mut dd.negative, - )?; + let positive_offset = u32_at(view, DD_POSITIVE_OFFSET_AT)? as i32; + let positive_entries = u32_at(view, DD_POSITIVE_ENTRIES_AT)? as usize; + let negative_offset = u32_at(view, DD_NEGATIVE_OFFSET_AT)? as i32; + let negative_entries = u32_at(view, DD_NEGATIVE_ENTRIES_AT)? as usize; + store(positive_offset, positive_entries, &mut dd.positive)?; + store(negative_offset, negative_entries, &mut dd.negative)?; if at != view.len() { return None; } - (dd.alpha, dd.sum, dd.min, dd.max) = (alpha, sum, min, max); + dd.alpha = alpha; (dd.zero_count, dd.admission_rate) = (zero_count, admission_rate); let contents = &*dd; // Only the form the view writer writes, so the compact form rebuilds @@ -276,16 +274,8 @@ fn read_dd(view: &[u8], dd: &mut DdContents) -> Option<()> { && span(&contents.positive) as i64 <= MAX_SPAN && span(&contents.negative) as i64 <= MAX_SPAN && sparse == form_sparse - && trimmed( - &contents.positive, - positive_offset, - u32_at(view, 76)? as usize, - ) - && trimmed( - &contents.negative, - negative_offset, - u32_at(view, 84)? as usize, - ); + && trimmed(&contents.positive, positive_offset, positive_entries) + && trimmed(&contents.negative, negative_offset, negative_entries); (canonical && contents.count()? == count).then_some(()) } @@ -330,9 +320,6 @@ impl DdContents { for word in [ self.alpha, self.count()?, - self.sum, - self.min, - self.max, self.zero_count, self.admission_rate, ] { @@ -585,10 +572,10 @@ fn buckets(reader: &mut StreamReader, previous_first: &mut i32, out: &mut Bucket // ------------------------------------------------------------ the columns -/// The tag of an exact record kept whole, in its mapped layout. +/// The tag of an exact record kept whole, in its view layout. const RAW: u8 = 0xff; -/// A column of `states` (each the mapped-layout bytes of one state of +/// A column of `states` (each the view-layout bytes of one state of /// `kind`) in compact form; `None` when the column has no compact form /// (its sketches differ in index mapping or admission rate, or a state is /// not of `kind`'s layout). @@ -614,9 +601,6 @@ pub fn encode_states( Some(_) => {} } put_uvarint(&mut out.ints, dd.zero_count); - out.floats[0].push(dd.sum); - out.floats[1].push(dd.min); - out.floats[2].push(dd.max); put_buckets(&mut out.ints, &dd.positive, &mut previous.0); put_buckets(&mut out.ints, &dd.negative, &mut previous.1); } @@ -716,7 +700,7 @@ fn put_record( true } -/// Decodes `rows` states of `kind` from their compact form into the mapped +/// Decodes `rows` states of `kind` from their compact form into the view /// layout: the states back to back in 8-byte words (each state starting on /// a word), and their byte offsets (`rows + 1`). `None` when the bytes are /// damaged. @@ -745,8 +729,6 @@ pub fn decode_states(kind: CompactKind, bytes: &[u8], rows: usize) -> Option<(Ve dd.zero_count = reader.uvarint()?; buckets(&mut reader, &mut previous.0, &mut dd.positive)?; buckets(&mut reader, &mut previous.1, &mut dd.negative)?; - (dd.sum, dd.min, dd.max) = - (reader.float(0)?, reader.float(1)?, reader.float(2)?); view.clear(); dd.view_bytes(&mut view)?; let (view_words, _) = view.as_chunks::<8>(); @@ -770,7 +752,7 @@ pub fn decode_states(kind: CompactKind, bytes: &[u8], rows: usize) -> Option<(Ve reader.finished().then_some((words, offsets)) } -/// One exact record of `kind`, appended to `view` in its mapped layout. +/// One exact record of `kind`, appended to `view` in its view layout. fn record( kind: CompactKind, reader: &mut StreamReader, @@ -915,28 +897,28 @@ mod tests { } /// Ten samples per series in a 1 s pane at alpha 0.02 (the demo's - /// finest DDSketch view): the mapped layout takes 120 bytes a state (an - /// 88-byte head and a dense run of 1-byte counts, half of them empty), - /// the compact column 47 before compression. + /// finest DDSketch view): the view layout takes 96 bytes a state (a + /// 64-byte head and a dense run of 1-byte counts, half of them empty), + /// the compact column 23 before compression. #[test] - fn a_ten_sample_ddsketch_state_takes_47_compact_bytes() { + fn a_ten_sample_ddsketch_state_takes_23_compact_bytes() { let samples: Vec = (0..10).map(|i| 40.0 + 7.3 * f64::from(i)).collect(); let view = dd(0.02, &samples); - assert_eq!(view.len(), 120); + assert_eq!(view.len(), 96); let rows = 1000; let states = vec![view; rows]; let compact = encode_states(CompactKind::DDSketch, states.iter().map(Vec::as_slice)).unwrap(); // Per row, 23 varint bytes (the zero count, two store headers, the - // first bucket's delta from the previous row's, 9 gaps, 10 counts) - // and 24 float bytes (sum, min, max); per column, alpha and the - // admission rate (16), the stream lengths (9), and one more byte - // for the first row's first bucket (no previous row). - assert_eq!(compact.len(), rows * (23 + 24) + 16 + 9 + 1); + // first bucket's delta from the previous row's, 9 gaps, 10 counts); + // per column, alpha and the admission rate (16), the stream lengths + // (6: the int stream's, and the three empty float streams'), and one + // more byte for the first row's first bucket (no previous row). + assert_eq!(compact.len(), rows * 23 + 16 + 6 + 1); } - /// Decoding gives the mapped layout's bytes exactly, so every answer - /// read from a compact column is the answer read from the mapped one: + /// Decoding gives the view layout's bytes exactly, so every answer + /// read from a compact column is the answer read from the view-layout one: /// empty sketches, zeros, negative samples, counts past one byte, /// dense and sparse stores. #[test] @@ -953,7 +935,10 @@ mod tests { dd(0.02, &dense), dd(0.02, &[-1e300, 1e-300, 7.0]), ]; - assert_ne!(states[4][68], states[5][68], "both store forms are covered"); + assert_ne!( + states[4][DD_SPARSE_AT], states[5][DD_SPARSE_AT], + "both store forms are covered" + ); let back = round_trip(CompactKind::DDSketch, &states); assert_eq!(back, states); for (a, b) in states.iter().zip(&back) { @@ -966,7 +951,7 @@ mod tests { } /// Sketches of different index mappings have no shared column head: - /// the column keeps its mapped layout. + /// the column keeps its view layout. #[test] fn ddsketches_of_two_alphas_have_no_compact_column() { let states = [dd(0.02, &[1.0]), dd(0.05, &[1.0])]; @@ -974,13 +959,13 @@ mod tests { } /// Views the writer never writes (keys out of order, non-zero padding) - /// have no compact form: their column keeps the mapped layout rather + /// have no compact form: their column keeps the view layout rather /// than being rebuilt differently. #[test] fn non_writer_ddsketch_views_have_no_compact_form() { let spread: Vec = (0..5).map(|i| 1.5f64.powi(i * 3)).collect(); let view = dd(0.02, &spread); - assert_eq!(view[68], 1, "a sparse store"); + assert_eq!(view[DD_SPARSE_AT], 1, "a sparse store"); assert!(dd_contents(&view).is_some()); let mut swapped = view.clone(); // Swap the second and third sparse keys. @@ -1044,7 +1029,7 @@ mod tests { } } - /// A counter takes 56 bytes in the mapped layout and 20 in a compact + /// A counter takes 56 bytes in the view layout and 20 in a compact /// column: a tag, two timestamp deltas from the previous row's, the /// sample count, and the start and last value; the increase is their /// difference (no reset), so it is left out. diff --git a/data_plane/src/store.rs b/data_plane/src/store.rs index 2cd1fe9d7..58ddb848e 100644 --- a/data_plane/src/store.rs +++ b/data_plane/src/store.rs @@ -1847,6 +1847,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -1913,6 +1916,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, @@ -2003,6 +2009,9 @@ mod tests { let view: MaterializedView = serde_json::from_value(serde_json::json!({ "node_id": 1, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/data_plane/tests/planner_executor_parity.rs b/data_plane/tests/planner_executor_parity.rs index c3357fe46..61ad31abd 100644 --- a/data_plane/tests/planner_executor_parity.rs +++ b/data_plane/tests/planner_executor_parity.rs @@ -710,7 +710,7 @@ fn same_within(a: &[Answer], b: &[Answer], relative: f64) -> bool { fn tolerance(plan: &InstallablePlan) -> f64 { let randomized = serde_json::to_string(&plan.dag) .unwrap() - .contains("\"Kll\""); + .contains("\"KLL\""); if randomized { 0.05 } else { diff --git a/data_plane/tests/push_precompute.rs b/data_plane/tests/push_precompute.rs index b75e6ad46..a15bec3b8 100644 --- a/data_plane/tests/push_precompute.rs +++ b/data_plane/tests/push_precompute.rs @@ -462,7 +462,7 @@ async fn per_series_breakers_are_concatenated() { } let randomized = serde_json::to_string(&plan.dag) .unwrap() - .contains("\"Kll\""); + .contains("\"KLL\""); if randomized { // KLL compacts at random: same windows and keys, answers within 5% // (T1); here only the shape. diff --git a/data_plane/tests/view_cache_charge.rs b/data_plane/tests/view_cache_charge.rs index 556815a38..60a8e1ed6 100644 --- a/data_plane/tests/view_cache_charge.rs +++ b/data_plane/tests/view_cache_charge.rs @@ -101,6 +101,9 @@ fn view() -> MaterializedView { serde_json::from_value(serde_json::json!({ "node_id": VIEW, "refresh": "on_first_read", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "test-view", "window": null, + "logical_properties": {"parameters": null}}, "coverage": {"definition_id": "test-view", "selection": []}, "inputs": {"materialized_views": []}, "retention_ms": 1_000_000, diff --git a/data_plane/tests/view_persistence.rs b/data_plane/tests/view_persistence.rs index 02d3e92c1..d259783e1 100644 --- a/data_plane/tests/view_persistence.rs +++ b/data_plane/tests/view_persistence.rs @@ -140,7 +140,7 @@ async fn kll_views_answer_alike_after_a_restart() { .unwrap(); let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; let plan = serde_json::to_string(&plan).unwrap(); - assert!(plan.contains("Kll"), "the plan builds no KLL"); + assert!(plan.contains("\"KLL\""), "the plan builds no KLL"); answers_alike_after_a_restart("kll", query, &plan).await; } diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index 3f7f68fa6..d18ca6df7 100644 --- a/docs/design/tiered-view-storage.md +++ b/docs/design/tiered-view-storage.md @@ -204,7 +204,7 @@ it is deleted whole. A segment holds the existing framing (a little-endian 8-byte boundary (zero padding; format 2 borrowed fixed-width columns in place, format 4 decompresses each fragment): -- a header frame (MessagePack): plan hash, group, **format version 4**, +- a header frame (MessagePack): plan hash, group, **format version 5**, and the segment start; - one record frame per refreshed window. Its head is a small MessagePack map, followed by the parts it points at: @@ -262,7 +262,7 @@ dictionary; on disk it saves 4 B per row per label column. **Compact, compressed fragments (format version 4).** The mapped state layout is large for the small states of narrow panes. In the live demo a DDSketch of the ten samples one series has in a 1 s pane took 160 B a -row on disk (an 88-byte head with `alpha`, the admission rate and a count +row on disk (an 88-byte head, 64 bytes from format 5, with `alpha`, the admission rate and a count that every row repeats, then sparse `u32` keys), more than the raw samples; an exact counter took 72 B. Format 4 keeps the columnar fragment and changes two things (format 3 added the label columns above): @@ -317,6 +317,12 @@ finish. Disk use is then retention plus one segment, not unbounded. A file in the old format (`group-.log`, version 1) is renamed `*.stale` and not loaded, as a file of another plan is today. +**Format version 5.** The same layout as format 4, over the sketch library +version in which a DDSketch keeps no sum, minimum or maximum (`asap_sketchlib` +ASAPv1 kind `0x05 0x01`): its view head is 64 bytes, and a compact DDSketch +column has no float streams. The data plane sets a format 4 segment aside +(renamed `.stale`) when it opens it, and does not migrate it. + ### Read path `RunStore::read_materialized_view` returns a stream of the windows @@ -705,9 +711,10 @@ here changes the Planner. `pread` only for the active segment and as a fallback option. B3 still compares the two. - **Hot policy:** recency (CLOCK, idle time, byte budget). -- **Fragment encoding:** columnar, format version 4: label columns are +- **Fragment encoding:** columnar, format version 5: label columns are read back from the series identity, not stored (format 3); compact state - and text columns, zstd level 1 per fragment (format 4). + and text columns, zstd level 1 per fragment (format 4); DDSketch states + without sum, minimum or maximum (format 5). - **No cgroup limit:** no budget, plus idle eviction. - **Old view files:** renamed `*.stale`. - **Zero-copy revision:** states are used from the mapping From e925e6135fba6bca0b48dc960ba1dd97b72ad6f5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:54:28 +0000 Subject: [PATCH 16/20] test(data_plane): intent modes that differ, a shared bound node, the lightcone guard The first three-mode workload planned identically in every mode (no view, no shared node). Now q2 and q3 read `$Y` over the same table and the declared data is at production scale: q1's per-host state is kept, and the jointly planned modes share the query-time scan holding `$Y`'s placeholders, so q2 bound to other hosts at one evaluation time checks the binding keys that shared result. (Checked by mutation: with the key ignoring the binding, q2 bound to {h0} answers the {h1, h3} result.) A round listing one of the planner's lightcone queries is refused. Co-Authored-By: Claude Opus 5.5 --- data_plane/tests/intent_rounds.rs | 6 ++ data_plane/tests/intent_sil_modes.rs | 96 ++++++++++++++++------------ 2 files changed, 61 insertions(+), 41 deletions(-) diff --git a/data_plane/tests/intent_rounds.rs b/data_plane/tests/intent_rounds.rs index c2bbc6422..0b5f2d178 100644 --- a/data_plane/tests/intent_rounds.rs +++ b/data_plane/tests/intent_rounds.rs @@ -172,6 +172,12 @@ async fn round_over_installed_plan_filters_by_upstream_answer() { assert_eq!(schedule.queries[1].depends_on[0].output_column, "region"); assert_eq!(schedule.queries[1].bind_slots[0].column, "region"); assert!(IntentSchedule::from_intent_plan(&intent_plan, "other").is_err()); + // A lightcone query of the planner's is never issued: a round that + // lists one is refused. + let mut with_lightcone = intent_plan.clone(); + with_lightcone.lightcone_query_indices = vec![index(UPSTREAM)]; + let error = IntentSchedule::from_intent_plan(&with_lightcone, "triage").unwrap_err(); + assert!(error.to_string().contains("lightcone"), "{error}"); let intent = IntentLoop::new( schedule, BindMode::FilterGroupedResult, diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index ab66eefa4..a24604063 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -27,12 +27,16 @@ const EVALUATION_MS: i64 = 3_600_000; const WINDOW_MS: i64 = 100_000; /// q1 binds `$Y` to the two hosts with the largest `flows` sum; q2 sums -/// `auth` per user over those hosts only. +/// and q3 takes the largest `flows` value per user over those hosts only. +/// Planned jointly, q2 and q3 share the query-time scan of those hosts. const INTENT: &str = "INTENT triage EVERY 10s; q1: ($Y, _) := SELECT host, sum(value) AS s FROM flows WHERE ts > $now - INTERVAL '100 seconds' GROUP BY host ORDER BY s DESC LIMIT 2 REQUIRE EXACT; -q2: SELECT user, sum(value) AS s FROM auth +q2: SELECT user, sum(value) AS s FROM flows + WHERE host IN $Y AND ts > $now - INTERVAL '100 seconds' GROUP BY user + REQUIRE EXACT; +q3: SELECT user, max(value) AS m FROM flows WHERE host IN $Y AND ts > $now - INTERVAL '100 seconds' GROUP BY user REQUIRE EXACT;"; @@ -59,37 +63,26 @@ struct Row { value: f64, } -/// `flows`: 4 hosts x 2 users; `auth`: 4 hosts x 3 users; one row per -/// (host, user) every 10 s over the two minutes before `EVALUATION_MS`. -/// Host `h{i}`'s flows grow with `i`, but h1's is the largest, so the top -/// two hosts are h1 and h3. +/// `flows`: 4 hosts x 3 users, one row per (host, user) every 10 s over +/// the two minutes before `EVALUATION_MS`. Host `h{i}`'s rows grow with +/// `i`, but h1's are the largest, so the top two hosts are h1 and h3. fn tables() -> BTreeMap<&'static str, Vec> { - let mut tables: BTreeMap<&'static str, Vec> = BTreeMap::new(); + let mut rows = Vec::new(); for step in 0..12 { let ts = EVALUATION_MS - 120_000 + 5_000 + step * 10_000; for h in 0..4 { for u in 0..3 { - let host = format!("h{h}"); - let user = format!("u{u}"); - if u < 2 { - let scale = if h == 1 { 100.0 } else { (h + 1) as f64 * 10.0 }; - tables.entry("flows").or_default().push(Row { - host: host.clone(), - user: user.clone(), - ts, - value: scale + u as f64 + step as f64, - }); - } - tables.entry("auth").or_default().push(Row { - host, - user, + let scale = if h == 1 { 100.0 } else { (h + 1) as f64 * 10.0 }; + rows.push(Row { + host: format!("h{h}"), + user: format!("u{u}"), ts, - value: (u + 1) as f64 + h as f64 * 0.5 + step as f64 * 0.1, + value: scale + u as f64 + step as f64, }); } } } - tables + BTreeMap::from([("flows", rows)]) } /// The rows of `table` in the window ending at `time_ms`. @@ -109,17 +102,26 @@ fn exact_q1(tables: &BTreeMap<&str, Vec>, time_ms: i64) -> BTreeMap>, time_ms: i64, bound: &BTreeSet, + max: bool, ) -> BTreeMap { - let mut sums: BTreeMap = BTreeMap::new(); - for row in window(&tables["auth"], time_ms).filter(|r| bound.contains(&r.host)) { - *sums.entry(row.user.clone()).or_default() += row.value; + let mut per_user: BTreeMap = BTreeMap::new(); + for row in window(&tables["flows"], time_ms).filter(|r| bound.contains(&r.host)) { + let entry = per_user + .entry(row.user.clone()) + .or_insert(if max { f64::MIN } else { 0.0 }); + *entry = if max { + entry.max(row.value) + } else { + *entry + row.value + }; } - sums + per_user } /// `rows`' `label` -> value, compared with `exact` to 1e-9. @@ -159,14 +161,12 @@ fn rows_of(round: &RoundRecord, id: &str) -> Vec<(BTreeMap, f64) /// The planner's plan of [`INTENT`] in `mode`, as the data plane reads it. async fn planned(mode: IntentPlanningMode) -> IntentPlan { - let catalog = SqlCatalog::new() - .with_table("flows", table_schema()) - .with_table("auth", table_schema()); + let catalog = SqlCatalog::new().with_table("flows", table_schema()); + // Declared at production scale, so that keeping state pays off. let data = serde_json::from_value(serde_json::json!({ - "arrival": {"ingesting": {"rows_per_second": 2.0}}, + "arrival": {"ingesting": {"rows_per_second": 100_000.0}}, "sources": { - "flows": {"distinct_values_per_label": {"host": 4, "user": 2}, "rows_held": 100_000}, - "auth": {"distinct_values_per_label": {"host": 4, "user": 3}, "rows_held": 100_000}, + "flows": {"distinct_values_per_label": {"host": 300, "user": 1000}, "rows_held": 1_000_000_000u64}, }, })) .unwrap(); @@ -237,10 +237,10 @@ async fn install(plan: &IntentPlan, tables: &BTreeMap<&str, Vec>) -> Arc 0, "{mode:?} shares no node"); + } let intent = IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(30)).unwrap(); for time_ms in [EVALUATION_MS - 10_000, EVALUATION_MS] { @@ -273,13 +278,22 @@ async fn every_planning_mode_answers_exactly_round_by_round() { &top.keys().cloned().collect::>(), "{what}" ); - let exact = exact_q2(&tables, time_ms, bound); + let exact = exact_per_user(&tables, time_ms, bound, false); assert_answers( &format!("{what} q2"), &rows_of(&round, "q2"), "user", &exact, ); + let q3 = round.queries.iter().find(|q| q.query_id == "q3").unwrap(); + assert_eq!(&q3.bindings["Y"], bound, "{what}"); + let exact = exact_per_user(&tables, time_ms, bound, true); + assert_answers( + &format!("{what} q3"), + &rows_of(&round, "q3"), + "user", + &exact, + ); } // Two other bindings at one time, then the first again. for hosts in [&["h0"][..], &["h2", "h3"][..], &["h0"][..]] { @@ -298,7 +312,7 @@ async fn every_planning_mode_answers_exactly_round_by_round() { .iter() .map(|s| ((*s.labels).clone(), s.value)) .collect(); - let exact = exact_q2(&tables, EVALUATION_MS, &values); + let exact = exact_per_user(&tables, EVALUATION_MS, &values, false); assert_answers( &format!("{mode:?} q2 bound to {hosts:?}"), &rows, From c67e2496bc5a57cfa94d19bd670a40e76fcf9738 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:54:29 +0000 Subject: [PATCH 17/20] feat(data_plane): run intent queries with their holes bound in the plan BindMode::ParameterSlot, now the default for --intent: each round the loop hands the engine each slot's placeholders and bound values (QueryRunner::answer_bound). The query engine binds a copy of the plan (placeholders::bind over the plan's serialized DAG; the DAG itself is not Send), compiles the runs of the nodes that depend on the binding over it with their usual view slots, keeps a shared one under the binding's key, reads every other node as usual, and bypasses the result cache (QueryEngine::evaluate_bound, EngineHandle::evaluate_bound). A slot without placeholders fails rather than running unbound; a round listing a lightcone query is refused. FilterGroupedResult stays as the fallback. Co-Authored-By: Claude Opus 5.5 --- data_plane/src/engine.rs | 30 ++++++- data_plane/src/intent.rs | 34 +++++++- data_plane/src/main.rs | 6 +- data_plane/src/placeholders.rs | 6 +- data_plane/src/query.rs | 142 ++++++++++++++++++++++++++++++++- 5 files changed, 206 insertions(+), 12 deletions(-) diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index ea6fbb5bf..1bde8f09a 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -44,6 +44,7 @@ use crate::ingestion::{ }; use crate::metrics::{Gauges, Metrics, PushMetrics, Timer}; use crate::persist::{plan_hash, ViewFiles, ViewRead}; +use crate::placeholders::SlotBinding; use crate::push::{Partial, PushGroup, PushShard}; use crate::query::{QueryEngine, Snapshot, Unanswered}; use crate::result_cache::{Answer, ResultCache}; @@ -709,13 +710,25 @@ impl EngineHandle { pub async fn evaluate(&self, query: String, time_ms: i64) -> Result { let started = std::time::Instant::now(); let metrics = self.shared.metrics.query(&query); - let answer = self.run_on_worker(query, time_ms, None).await; + let answer = self.run_on_worker(query, time_ms, None, None).await; if let Some(metrics) = metrics { metrics.latency.observe(started.elapsed().as_secs_f64()); } answer } + /// Answers an intent's planned `query` at `time_ms` on a query worker + /// with its holes bound to `slots`' values + /// ([`QueryEngine::evaluate_bound`]); never from the result cache. + pub async fn evaluate_bound( + &self, + query: String, + time_ms: i64, + slots: Vec, + ) -> Result { + self.run_on_worker(query, time_ms, None, Some(slots)).await + } + /// Evaluates one step of a range query over `snapshot`, which every /// step of the request reads ([`Self::snapshot`]): as /// [`Self::evaluate`], counted as a range step rather than an instant @@ -727,7 +740,8 @@ impl EngineHandle { time_ms: i64, snapshot: Arc, ) -> Result { - self.run_on_worker(query, time_ms, Some(snapshot)).await + self.run_on_worker(query, time_ms, Some(snapshot), None) + .await } /// The newest published store, for the steps of one range request. @@ -746,6 +760,7 @@ impl EngineHandle { query: String, time_ms: i64, range_step: Option>, + bound: Option>, ) -> Result { let stopped = || Unanswered::Execution("the query workers have stopped".into()); let (reply, answer) = oneshot::channel(); @@ -754,6 +769,7 @@ impl EngineHandle { query, time_ms, range_step, + bound, reply, }) .map_err(|_| stopped())?; @@ -910,6 +926,9 @@ struct QueryJob { time_ms: i64, /// One step of a range query, and the snapshot every step reads. range_step: Option>, + /// An intent query's holes bound to these values + /// ([`QueryEngine::evaluate_bound`]); `None`: as planned. + bound: Option>, reply: Reply, } @@ -960,7 +979,12 @@ fn spawn_query_workers( Some(snapshot) => snapshot.clone(), None => Arc::new(query.snapshot(&shared.published)), }; - query.evaluate(&job.query, job.time_ms, &snapshot) + match &job.bound { + Some(slots) => { + query.evaluate_bound(&job.query, job.time_ms, &snapshot, slots) + } + None => query.evaluate(&job.query, job.time_ms, &snapshot), + } })) .unwrap_or_else(|panic| { let reason = panic diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index bd0eb1ad5..465b9cf63 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -371,6 +371,16 @@ impl IntentSchedule { }) }) .collect::>>()?; + if intent_plan + .lightcone_query_indices + .contains(&query.query_index) + { + anyhow::bail!( + "query {} is the planner's lightcone query {}, which is never issued", + query.query_id, + query.query_index + ); + } Ok(IntentQuery { query_id: query.query_id.clone(), query: query_text(query.query_index)?, @@ -681,7 +691,25 @@ async fn bind_and_run( Ok(filter_by_bindings(&grouped, &query.bind_slots, bindings)) } BindMode::ParameterSlot => { - todo!("parameter slots: bind and run") + let slots = query + .bind_slots + .iter() + .map(|slot| { + if slot.placeholder_values.is_empty() { + return Err(format!( + "the slot of ${} has no placeholders to bind in the plan", + slot.variable + )); + } + Ok(SlotBinding { + position: slot.position, + placeholders: slot.placeholder_values.clone(), + values: bindings.get(&slot.variable).cloned().unwrap_or_default(), + }) + }) + .collect::, String>>()?; + let answer = runner.answer_bound(&query.query, time_ms, &slots).await; + answer.map(|a| a.to_vec()).map_err(|e| e.to_string()) } } } @@ -704,8 +732,8 @@ impl QueryRunner for crate::engine::EngineHandle { time_ms: i64, slots: &[SlotBinding], ) -> Result { - let _ = (query, time_ms, slots); - todo!("parameter slots: engine") + self.evaluate_bound(query.to_string(), time_ms, slots.to_vec()) + .await } } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index ca31c0b10..5b74f09d6 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -198,8 +198,10 @@ struct Args { /// The longest one intent query may run before it fails as timed out. #[arg(long, default_value_t = 30_000)] intent_query_timeout_ms: u64, - /// How bound values reach a downstream query. - #[arg(long, value_enum, default_value_t = BindMode::FilterGroupedResult)] + /// How bound values reach a downstream query: `parameter-slot` (the + /// planner's placeholders replaced in the plan) or the fallback + /// `filter-grouped-result` (a grouped answer filtered by the values). + #[arg(long, value_enum, default_value_t = BindMode::ParameterSlot)] intent_bind_mode: BindMode, } diff --git a/data_plane/src/placeholders.rs b/data_plane/src/placeholders.rs index 811963ad5..9de8259a0 100644 --- a/data_plane/src/placeholders.rs +++ b/data_plane/src/placeholders.rs @@ -40,15 +40,15 @@ pub struct SlotBinding { pub values: BTreeSet, } -/// A copy of `dag` with every slot's placeholders replaced by its bound +/// A copy of `dag` (serialized) with every slot's placeholders replaced by its bound /// values, and the nodes whose contents changed. Fails when a bound value /// does not convert to its placeholders' type, a comparison is bound to /// other than one value, or a placeholder is left in a form not rewritten. pub fn bind( - dag: &PhysicalASAPDAG, + dag: &Json, slots: &[SlotBinding], ) -> Result<(PhysicalASAPDAG, BTreeSet), String> { - let mut json = serde_json::to_value(dag).map_err(|e| format!("the plan: {e}"))?; + let mut json = dag.clone(); let mut changed = BTreeSet::new(); for slot in slots { let nodes = json["nodes"] diff --git a/data_plane/src/query.rs b/data_plane/src/query.rs index 596cb53a2..f1a7cac6b 100644 --- a/data_plane/src/query.rs +++ b/data_plane/src/query.rs @@ -69,9 +69,30 @@ struct Run { compiled: CompiledPhysicalDAG, /// The shared nodes it binds as view slots. reads: Vec, + /// The view slots it was compiled with: materialized views and the + /// shared nodes it reads (an intent's bound run is compiled with them + /// again). + slots: Vec, +} + +/// A copy of the plan with an intent query's holes bound +/// ([`crate::placeholders::bind`]) and what it changes. +struct Bound { + dag: PhysicalASAPDAG, + /// The nodes holding a bound value and every node above them: their + /// outputs depend on the binding. + depends: BTreeSet, + /// The binding's key for shared query-time results (never + /// [`crate::store::UNBOUND`]). + key: u64, } pub struct QueryEngine { + /// The installed plan's DAG, serialized (the DAG itself is not `Send`), + /// which an intent's bound run copies. + dag_json: serde_json::Value, + /// The DAG's edges, producer to consumer. + edges: Vec<(PhysicalASAPNodeId, PhysicalASAPNodeId)>, /// Each query and its root, or why it cannot run. roots: Vec<(String, Result)>, /// The run of each query root and shared node. @@ -140,7 +161,11 @@ impl QueryEngine { .filter(|id| shared.contains(id)) .collect(); let run = compile(dag, &read, &[node as u64]) - .map(|compiled| Run { compiled, reads }) + .map(|compiled| Run { + compiled, + reads, + slots: read.clone(), + }) .map_err(|e| e.to_string()); compiled.insert(node, run); } @@ -158,6 +183,8 @@ impl QueryEngine { .filter_map(|(node, run)| Some((node, run.ok()?))) .collect(); Ok(Self { + dag_json: serde_json::to_value(dag)?, + edges: dag.edges.iter().map(|e| (e.producer, e.consumer)).collect(), roots, runs, shared, @@ -258,6 +285,107 @@ impl QueryEngine { Ok(answer) } + /// Answers `query` at `time_ms` with an intent's holes bound: each + /// slot's placeholders replaced by its values in a copy of the plan, + /// and the runs of the nodes that depend on them compiled over that + /// copy. Nodes that do not depend on the binding are read as for + /// [`Self::evaluate`] (shared query-time results included); a shared + /// node that does is kept under the binding's key. The result cache is + /// neither read nor written. + pub fn evaluate_bound( + &self, + query: &str, + time_ms: i64, + snapshot: &Snapshot, + slots: &[crate::placeholders::SlotBinding], + ) -> Result { + let root = self.root(query)?; + let (dag, changed) = + crate::placeholders::bind(&self.dag_json, slots).map_err(Unanswered::Execution)?; + // The changed nodes and every node above them. + let mut depends = changed.clone(); + let mut pending: Vec = changed.into_iter().collect(); + while let Some(id) = pending.pop() { + for &(_, consumer) in self.edges.iter().filter(|(producer, _)| *producer == id) { + if depends.insert(consumer) { + pending.push(consumer); + } + } + } + if !depends.contains(&root) { + return Err(Unanswered::Execution(format!( + "the plan of {query:?} holds none of the bound placeholders" + ))); + } + let bound = Bound { + dag, + depends, + key: binding_key(slots), + }; + let batches = self.output_bound(root, time_ms, snapshot, &bound)?; + let schema = self.runs[&root] + .compiled + .output_schema(root as u64) + .map_err(|e| Unanswered::Execution(e.to_string()))?; + Ok(Arc::new(result_samples(&schema, &batches)?)) + } + + /// [`Self::output`] under `bound`: a node that does not depend on the + /// binding as usual; one that does from its run over the bound plan, + /// kept under the binding's key when it is shared. + fn output_bound( + &self, + node: PhysicalASAPNodeId, + time_ms: i64, + snapshot: &Snapshot, + bound: &Bound, + ) -> Result>, Unanswered> { + if !bound.depends.contains(&node) { + return self.output(node, time_ms, snapshot); + } + if self.shared.contains(&node) { + self.results.get_or_compute_bound( + node, + time_ms, + bound.key, + snapshot.watermark_ms, + || self.run_bound(node, time_ms, snapshot, bound), + ) + } else { + self.run_bound(node, time_ms, snapshot, bound).map(Arc::new) + } + } + + /// [`Self::run`] of `node` compiled over the bound plan, with the same + /// view slots. + fn run_bound( + &self, + node: PhysicalASAPNodeId, + time_ms: i64, + snapshot: &Snapshot, + bound: &Bound, + ) -> Result, Unanswered> { + let run = &self.runs[&node]; + let compiled = compile(&bound.dag, &run.slots, &[node as u64]) + .map_err(|e| Unanswered::Execution(format!("compiling the bound plan: {e}")))?; + let mut shared = HashMap::new(); + for &read in &run.reads { + shared.insert(read, self.output_bound(read, time_ms, snapshot, bound)?); + } + let run_store = Arc::new(RunStore::with_query_time_results( + snapshot.raw_data.clone(), + snapshot.views.clone(), + Some(snapshot.raw_reads.clone()), + shared, + )); + run_compiled(&compiled, run_store.clone(), time_ms, &self.limits).map_err(|error| { + match run_store.missing_rows() { + Some(missing) => Unanswered::MissingRows(missing), + None => Unanswered::Execution(error.to_string()), + } + }) + } + /// `node`'s output at `time_ms`: from the query-time partition when it /// is shared (computed there by the first run that needs it), else /// from its own run. @@ -323,6 +451,18 @@ impl Snapshot { } } +/// The key of `slots`' binding for shared query-time results: a hash of +/// each slot's placeholders and values, never [`crate::store::UNBOUND`]. +fn binding_key(slots: &[crate::placeholders::SlotBinding]) -> u64 { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + for slot in slots { + format!("{:?}", slot.placeholders).hash(&mut hasher); + slot.values.hash(&mut hasher); + } + hasher.finish().max(1) +} + /// Whether `node`'s run, and every shared node's run it reads, compiled. fn runnable( node: PhysicalASAPNodeId, From 2cda7afc0452fde3b7d698076c77936c44720603 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:58:24 +0000 Subject: [PATCH 18/20] style(test): elide a lifetime clippy flags Co-Authored-By: Claude Opus 5.5 --- data_plane/tests/intent_sil_modes.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index a24604063..e5cefff8b 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -85,8 +85,8 @@ fn tables() -> BTreeMap<&'static str, Vec> { BTreeMap::from([("flows", rows)]) } -/// The rows of `table` in the window ending at `time_ms`. -fn window<'a>(rows: &'a [Row], time_ms: i64) -> impl Iterator { +/// The rows of `rows` in the window ending at `time_ms`. +fn window(rows: &[Row], time_ms: i64) -> impl Iterator { rows.iter() .filter(move |r| r.ts > time_ms - WINDOW_MS && r.ts <= time_ms) } From 70e33a15d11b6e80ba973fb647e39ef41cc5082c Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 08:58:31 +0000 Subject: [PATCH 19/20] docs(bench): intent rounds bind placeholders by default; SQL tables as series Co-Authored-By: Claude Opus 5.5 --- bench/demo/harness/README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/bench/demo/harness/README.md b/bench/demo/harness/README.md index dfe54364f..34215def8 100644 --- a/bench/demo/harness/README.md +++ b/bench/demo/harness/README.md @@ -247,9 +247,14 @@ JSON line. Inputs: the planner's intent output (`intent_plan.json`, its `IntentPlan`: the `plan` to install and the `intent_rounds`), and the data feed by Remote -Write as for any other arm (paced feeder, `stream_start_ms` S). Today's -binding filters the downstream query's answer by the bound values, so the -downstream query must be planned grouped by the label it is filtered on. +Write as for any other arm (paced feeder, `stream_start_ms` S). A SQL +table's rows are sent as the samples of the series named after the table +(`__name__`), its text columns as labels and its `value` column as the +value. Each round, a downstream query's placeholders are replaced by the +values its upstream answered, in a copy of the plan (`--intent-bind-mode +parameter-slot`, the default); `filter-grouped-result` instead filters a +grouped answer by the values, for a downstream query planned grouped by the +label it is filtered on. ```sh jq .plan intent_plan.json > plan.json From e7434ac3cb784d733ba5cac251e8afb8a0bea3a9 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 3 Dec 2026 09:34:18 +0000 Subject: [PATCH 20/20] test(parity): compare each view's windows within its retention (port) The pending planner-bump PR's fix to push_precompute_stores_the_window_paths_view_rows, which the new Planner pin makes fail on windows older than a view's retention that linger by timing: both sides are cut to the windows kept by retention. Co-Authored-By: Claude Opus 5.5 --- data_plane/tests/planner_executor_parity.rs | 58 +++++++++++++-------- 1 file changed, 37 insertions(+), 21 deletions(-) diff --git a/data_plane/tests/planner_executor_parity.rs b/data_plane/tests/planner_executor_parity.rs index 61ad31abd..72820c4f8 100644 --- a/data_plane/tests/planner_executor_parity.rs +++ b/data_plane/tests/planner_executor_parity.rs @@ -1054,26 +1054,41 @@ fn shapes(views: &BTreeMap>) -> BTreeMap>, - expected: &BTreeMap>, +/// Each view's windows within its retention of its newest window: those +/// ending less than `retention_ms` before it, and the newest itself (the +/// windows the store keeps by retention, `storage::store`'s +/// `oldest_kept_end`). Both data planes must hold exactly these: no window +/// that recent is skipped as expired or evicted. Older windows leave the +/// store lazily (at the view's next append), and a narrower level is held +/// until its readers commit, so how many such windows linger at the end of +/// a run depends on the order windows were committed in and on when each +/// shard reported, which differ between push and the window path and from +/// run to run; and no query reads them. +fn within_retention( + views: BTreeMap>, + plan: &InstallablePlan, ) -> BTreeMap> { - served + let retention_ms: BTreeMap = plan + .ingestion_refresh_groups() + .unwrap() + .iter() + .flat_map(|group| &group.views) + .map(|view| { + let retention = i64::try_from(view.retention_ms()).unwrap_or(i64::MAX); + (format!("{}", view.node_id), retention) + }) + .collect(); + views .into_iter() .map(|(view, windows)| { - let oldest = expected - .get(&view) - .and_then(|w| w.first()) - .map_or(i64::MIN, |w| w.0 .1); - let windows = windows.into_iter().filter(|w| w.0 .1 >= oldest).collect(); + let newest_end = windows.last().map_or(i64::MIN, |w| w.0 .1); + // A view of no refresh group keeps every window. + let retention = retention_ms.get(&view).copied().unwrap_or(i64::MAX); + let oldest_kept_end = newest_end.saturating_sub(retention); + let windows = windows + .into_iter() + .filter(|w| w.0 .1 > oldest_kept_end || w.0 .1 == newest_end) + .collect(); (view, windows) }) .collect() @@ -1119,8 +1134,9 @@ fn first_difference( "shapes differ".into() } -/// T2. Push precompute stores the same view rows as the window path: per -/// (view, window), the same keys and the same states (exact values, or +/// T2. Push precompute stores the same view rows as the window path: the +/// same windows within each view's retention, and per (view, window) the +/// same keys and the same states (exact values, or /// sketch bytes). KLL plans store the same windows and keys; their states /// may differ within the target, which T1 checks through the answers. #[tokio::test(flavor = "multi_thread")] @@ -1147,8 +1163,8 @@ async fn push_precompute_stores_the_window_paths_view_rows() { data_plane_over(&plan, &points, start_ms, false, window, Views::InMemory).await; let (_, by_push) = data_plane_over(&plan, &points, start_ms, false, push, Views::InMemory).await; - let expected = stored_views(&by_window); - let served = from_oldest_of(stored_views(&by_push), &expected); + let expected = within_retention(stored_views(&by_window), &plan); + let served = within_retention(stored_views(&by_push), &plan); compared_views += expected.len(); let equal = if tolerance(&plan) > 1e-9 { shapes(&expected) == shapes(&served)