From ebcdb4289454e972ff15992cc98df52f494b8bb3 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 15:52:40 +0000 Subject: [PATCH 1/2] test(query-time results): queries sharing a merge of collector windows compute it once (failing first) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/collector_views.rs | 82 +++++++++++++++++++++- 1 file changed, 81 insertions(+), 1 deletion(-) diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs index fef365144..9fea16c3e 100644 --- a/crates/data-plane/tests/collector_views.rs +++ b/crates/data-plane/tests/collector_views.rs @@ -55,9 +55,30 @@ fn plan() -> (InstallablePlan, usize, i64, f64) { /// The plan of [`QUERY`] for `inputs`, with its DDSketch chain's node id, /// width and α. fn plan_for(inputs: &control_plane::DeploymentInputs) -> (InstallablePlan, usize, i64, f64) { + plan_of(&[QUERY], inputs) +} + +/// The plan of `queries` (each asked as [`QUERY`] is) for `inputs`, with +/// its DDSketch chain's node id, width and α. +fn plan_of( + queries: &[&str], + inputs: &control_plane::DeploymentInputs, +) -> (InstallablePlan, usize, i64, f64) { let path = Path::new(env!("CARGO_MANIFEST_DIR")) .join("tests/workloads/sketch-plan-quantile-single.json"); - let workload = serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let mut workload: Value = + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + let repeating = &mut workload["query_workload"]["repeating_queries"]; + let asked = repeating[0].clone(); + *repeating = queries + .iter() + .map(|query| { + let mut asked = asked.clone(); + asked["query"] = (*query).into(); + asked + }) + .collect(); + let workload = serde_json::from_value(workload).unwrap(); let plan = plan_workload(&workload, inputs).unwrap().0; let chain = plan .dag @@ -360,6 +381,65 @@ async fn collector_states_answer_as_the_view_built_here() { assert_eq!(state.engine.stats().samples_unrouted, 1); } +/// Two queries reading one merge of a collector view's windows share it: +/// with no raw data, so no watermark, the merge at an evaluation time is +/// still computed once and read by the other query, as it is over windows +/// built here, and both answer as over windows built here. +#[tokio::test(flavor = "multi_thread")] +async fn queries_sharing_a_merge_of_collector_windows_compute_it_once() { + const MEDIAN: &str = "quantile_over_time(0.5, data[5m])"; + let (plan, node, width_ms, alpha) = + plan_of(&[QUERY, MEDIAN], &common::inputs_without_levels(false)); + let time_ms = query_time_ms(); + let (app, state) = collector_data_plane(&plan, node); + let shared = state.engine.shared_nodes() as u64; + assert!( + shared > 0, + "the plan shares no query-time OneEvaluation node" + ); + let states = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let committed = + format!("asap_collector_states_windows_total{{view=\"{node}\",outcome=\"committed\"}}"); + wait_for(&state, &committed, (RANGE_MS / width_ms) as f64).await; + + let (reference_app, _reference) = data_plane(&plan, no_forward(time_ms - RANGE_MS)); + let timeseries = JOBS + .iter() + .map(|job| TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "data".into(), + }, + Label { + name: "job".into(), + value: (*job).into(), + }, + ], + samples: samples(job, time_ms - RANGE_MS, time_ms) + .into_iter() + .map(|(timestamp, value)| Sample { timestamp, value }) + .collect(), + }) + .collect(); + common::remote_write(&reference_app, timeseries).await; + common::barrier(&reference_app, time_ms).await; + + for query in [QUERY, MEDIAN] { + let uri = common::instant_uri(query, time_ms / 1000); + let (status, _, answer) = common::get(&app, &uri).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, common::get(&reference_app, &uri).await.2, "{query}"); + } + let results = state.engine.query_time_results(); + assert_eq!( + (results.computes(), results.hits()), + (shared, shared), + "the second query recomputed the shared merge" + ); +} + /// A view built here from a collector view (a wider level of the window /// chain, merged from the collector's narrower windows) waits for the /// collector view's windows, and answers as the levels built here from the From 61782299e1aa1af5f119ec737198df93d1d49e70 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:03:03 +0000 Subject: [PATCH 2/2] fix(query-time results): keep a shared node's result when it reads only views A query-time OneEvaluation result was kept only at a time at or before the raw-data watermark. A node reading only views (a merge of collector view windows; with no raw data there is no watermark at all) was then computed again by every query run that read it. Its run succeeding means every window it read was stored, and a stored window changes only by a revision, which the entry's revision check already catches: the same rule the result cache applies to a root's final answer. Retention counts back from the watermark or the newest time kept, never from a client's time no stored window reaches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/query/src/lib.rs | 19 ++++---- crates/storage/src/store.rs | 91 ++++++++++++++++++++++++++++--------- 2 files changed, 80 insertions(+), 30 deletions(-) diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index 228efba04..7a93ef802 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -94,8 +94,9 @@ pub struct CompiledQueries { shared: BTreeSet, results: QueryTimeResults, limits: Limits, - /// The query roots whose runs read raw data through a `Scan` (rather - /// than only materialized views). + /// The query roots and shared nodes whose runs read raw data through a + /// `Scan` (rather than only materialized views): their outputs at a + /// time past the watermark are not final. reads_raw_data: BTreeSet, /// Final answers of the query roots by evaluation time; `None`: off. result_cache: Option, @@ -118,17 +119,18 @@ impl CompiledQueries { ) -> anyhow::Result { let dag = &plan.dag; let view_ids: HashSet = views.iter().map(|v| v.node_id).collect(); - let reads_raw_data = dag - .roots - .iter() - .copied() - .filter(|&root| scans_below(dag, root, &view_ids)) - .collect(); let shared = if share_one_evaluation { shared_nodes(dag, &view_ids)? } else { BTreeSet::new() }; + let reads_raw_data = dag + .roots + .iter() + .chain(&shared) + .copied() + .filter(|&node| scans_below(dag, node, &view_ids)) + .collect(); let mut slots: Vec = views.to_vec(); if !shared.is_empty() { let plan_id = dag.plan_id(); @@ -316,6 +318,7 @@ impl CompiledQueries { node, time_ms, snapshot.watermark_ms, + self.reads_raw_data.contains(&node), &snapshot.views, || self.run(node, time_ms, snapshot), ) diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 7d3cedb72..b66fbd38e 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -2105,13 +2105,17 @@ type QueryTimeEntries = BTreeMap<(i64, PhysicalASAPNodeId), (u64, QueryTimeEn /// workers write it during their runs, so unlike the ingestion-time views /// it is not a published snapshot. A missing result is computed by the /// first run that needs it while the others wait for it (single flight); -/// a failure reaches the runs that waited and is not kept. Only a result -/// at a time the watermark has passed is kept (its inputs are complete); -/// 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. A result read -/// from views late samples revised since ([`ViewStore::changed_since`]) is -/// computed again. +/// a failure reaches the runs that waited and is not kept. A result of a +/// node that reads raw data is kept only at a time the watermark has +/// passed (its inputs are complete); one at a later time is computed by +/// each run that needs it. A result of a node that reads only views is +/// kept at any time: it was computed, so every view window it read was +/// stored, and a window never changes but by a revision (as a root's final +/// answer in the result cache). A result is kept while `T` is within +/// `retention_ms` of the watermark or of the newest time just kept, +/// whichever is later, and the oldest are dropped while more than +/// `max_bytes` are held. A result read from views revised since +/// ([`ViewStore::changed_since`]) is computed again. pub struct QueryTimeResults { entries: Mutex>, retention_ms: i64, @@ -2134,17 +2138,19 @@ impl QueryTimeResults { } /// `node`'s output at `time_ms`, as of `views`: 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). + /// by `compute` (once, however many runs ask at once, when `node` reads + /// only views, `reads_raw_data` false, or `time_ms` is at or before + /// `watermark_ms`; by each run otherwise). pub fn get_or_compute( &self, node: PhysicalASAPNodeId, time_ms: i64, watermark_ms: Option, + reads_raw_data: bool, views: &ViewStore, compute: impl FnOnce() -> Result, E>, ) -> Result>, E> { - if watermark_ms.is_none_or(|watermark| time_ms > watermark) { + if reads_raw_data && watermark_ms.is_none_or(|watermark| time_ms > watermark) { self.computes.fetch_add(1, Ordering::Relaxed); return compute().map(Arc::new); } @@ -2205,8 +2211,12 @@ impl QueryTimeResults { if result.is_err() && held { entries.remove(&(time_ms, node)); } - if let Some(watermark_ms) = watermark_ms { - self.drop_old(&mut entries, watermark_ms); + // Retention counts back from the watermark or from the time just + // kept, a time whose inputs were complete: never from a client's + // time no stored window reaches (its run failed). + let kept_ms = (held && result.is_ok()).then_some(time_ms); + if let Some(horizon_ms) = watermark_ms.max(kept_ms) { + self.drop_old(&mut entries, horizon_ms); } result } @@ -3186,40 +3196,77 @@ mod tests { let ok = || Ok::<_, ()>(Vec::new()); let watermark = Some(1_000); results - .get_or_compute(7, 1_000, watermark, &ViewStore::default(), ok) + .get_or_compute(7, 1_000, watermark, true, &ViewStore::default(), ok) .unwrap(); results - .get_or_compute(7, 1_000, watermark, &ViewStore::default(), ok) + .get_or_compute(7, 1_000, watermark, true, &ViewStore::default(), ok) .unwrap(); assert_eq!((results.computes(), results.hits()), (1, 1)); // Past the watermark (a client's far-future time): not kept. results - .get_or_compute(7, 99_000, watermark, &ViewStore::default(), ok) + .get_or_compute(7, 99_000, watermark, true, &ViewStore::default(), ok) .unwrap(); results - .get_or_compute(7, 99_000, watermark, &ViewStore::default(), ok) + .get_or_compute(7, 99_000, watermark, true, &ViewStore::default(), ok) .unwrap(); assert_eq!((results.computes(), results.len()), (3, 1)); assert!(results - .get_or_compute(8, 1_000, watermark, &ViewStore::default(), || Err(())) + .get_or_compute(8, 1_000, watermark, true, &ViewStore::default(), || Err(())) .is_err()); assert_eq!(results.len(), 1); results - .get_or_compute(8, 1_000, watermark, &ViewStore::default(), ok) + .get_or_compute(8, 1_000, watermark, true, &ViewStore::default(), ok) .unwrap(); assert_eq!(results.len(), 2); // Retention counts back from the watermark, not from client times. results - .get_or_compute(7, 11_000, Some(11_000), &ViewStore::default(), ok) + .get_or_compute(7, 11_000, Some(11_000), true, &ViewStore::default(), ok) .unwrap(); assert_eq!(results.len(), 3); results - .get_or_compute(7, 11_001, Some(11_001), &ViewStore::default(), ok) + .get_or_compute(7, 11_001, Some(11_001), true, &ViewStore::default(), ok) .unwrap(); assert_eq!(results.len(), 2); assert_eq!(results.bytes(), 0); } + /// A query-time result of a node that reads only views (a merge of + /// collector view windows, with no raw data and so no watermark) is + /// computed once and then read, past the watermark too; a failed run (a + /// client's time no stored window reaches) is not kept and does not + /// move the retention; retention counts back from the newest time kept. + #[test] + fn query_time_results_of_a_node_reading_only_views_need_no_watermark() { + let results = QueryTimeResults::<()>::new(10_000, usize::MAX); + let views = ViewStore::default(); + let ok = || Ok::<_, ()>(Vec::new()); + for _ in 0..2 { + results + .get_or_compute(7, 1_000, None, false, &views, ok) + .unwrap(); + } + assert_eq!((results.computes(), results.hits()), (1, 1)); + for _ in 0..2 { + results + .get_or_compute(7, 5_000, Some(2_000), false, &views, ok) + .unwrap(); + } + assert_eq!( + (results.computes(), results.hits(), results.len()), + (2, 2, 2) + ); + // A far-future time whose run fails evicts nothing. + assert!(results + .get_or_compute(7, 99_000, None, false, &views, || Err(())) + .is_err()); + assert_eq!(results.len(), 2); + // A newer time kept: results more than the retention behind it go. + results + .get_or_compute(7, 11_001, None, false, &views, ok) + .unwrap(); + assert_eq!(results.len(), 2); + } + /// Runs waiting for a result being computed get its value, or its /// failure, without computing it themselves. #[test] @@ -3231,7 +3278,7 @@ mod tests { let computer = { let results = results.clone(); std::thread::spawn(move || { - results.get_or_compute(1, 0, Some(0), &ViewStore::default(), || { + results.get_or_compute(1, 0, Some(0), true, &ViewStore::default(), || { started.send(()).unwrap(); released.recv().unwrap(); if fails { @@ -3246,7 +3293,7 @@ mod tests { let waiter = { let results = results.clone(); std::thread::spawn(move || { - results.get_or_compute(1, 0, Some(0), &ViewStore::default(), || { + results.get_or_compute(1, 0, Some(0), true, &ViewStore::default(), || { panic!("the waiter computed") }) })