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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion crates/data-plane/tests/collector_views.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
19 changes: 11 additions & 8 deletions crates/query/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ pub struct CompiledQueries {
shared: BTreeSet<PhysicalASAPNodeId>,
results: QueryTimeResults<Unanswered>,
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<PhysicalASAPNodeId>,
/// Final answers of the query roots by evaluation time; `None`: off.
result_cache: Option<ResultCache>,
Expand All @@ -118,17 +119,18 @@ impl CompiledQueries {
) -> anyhow::Result<Self> {
let dag = &plan.dag;
let view_ids: HashSet<PhysicalASAPNodeId> = 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<MaterializedView> = views.to_vec();
if !shared.is_empty() {
let plan_id = dag.plan_id();
Expand Down Expand Up @@ -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),
)
Expand Down
91 changes: 69 additions & 22 deletions crates/storage/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2105,13 +2105,17 @@ type QueryTimeEntries<E> = 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<E> {
entries: Mutex<QueryTimeEntries<E>>,
retention_ms: i64,
Expand All @@ -2134,17 +2138,19 @@ impl<E: Clone> QueryTimeResults<E> {
}

/// `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<i64>,
reads_raw_data: bool,
views: &ViewStore,
compute: impl FnOnce() -> Result<Vec<Batch>, E>,
) -> Result<Arc<Vec<Batch>>, 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);
}
Expand Down Expand Up @@ -2205,8 +2211,12 @@ impl<E: Clone> QueryTimeResults<E> {
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
}
Expand Down Expand Up @@ -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]
Expand All @@ -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 {
Expand All @@ -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")
})
})
Expand Down