From 96d93c7caa55f7b66e715f20943d23f54a4c355c Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:55:37 +0000 Subject: [PATCH 1/2] test(collector views): record lineages, deltas, incomplete windows, declared close delay (failing first) Tests for sequence numbers and delta transmission (docs/design/collector-sketch-ingest.md, section 8): the OTLP adapter decodes and checks each state's producer epoch, sequence, kind and base; two corrections with equal bytes both merge; open-window deltas answer and end at the at-close answer; a delta after a gap leaves its window unanswered; a restarted collector's full starts a new lineage and its delta without a full is never applied; the collector-views file carries the collector's window_close_delay_ms, which closes a stopped collector's windows. The existing tests' states carry a lineage. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/adapters/ingest/otlp/src/tests.rs | 72 +++- crates/control-plane/tests/collector_views.rs | 8 +- crates/data-plane/tests/collector_views.rs | 390 ++++++++++++++++-- 3 files changed, 427 insertions(+), 43 deletions(-) diff --git a/crates/adapters/ingest/otlp/src/tests.rs b/crates/adapters/ingest/otlp/src/tests.rs index b9d41e7d1..00e9ca148 100644 --- a/crates/adapters/ingest/otlp/src/tests.rs +++ b/crates/adapters/ingest/otlp/src/tests.rs @@ -892,23 +892,28 @@ fn consecutive_points_share_their_series() { const VIEW_KEY: &str = r#"{"definition_id":"5597d603bdf9f1a148d7c7e5344c1a97","window":{"tumbling":{"width_ms":5000}},"logical_properties":{"parameters":{"DDSketch":{"alpha":0.05}}}}"#; const WINDOW_END_MS: u64 = 1_700_000_005_000; -/// The metadata naming view `node` of plan `p1` with key `key`. +/// The metadata naming view `node` of plan `p1` with key `key`, sent by +/// collector instance (producer epoch) 7. fn view_metadata(node: i64, key: &str) -> Vec { vec![ text("asap.plan_id", "p1"), attribute("asap.node_id", any_value::Value::IntValue(node)), text("asap.view_state_key", key), + text("asap.producer_epoch", "7"), ] } /// A state point of the window ending at `WINDOW_END_MS`, as the collector -/// exports one: the series' attributes, then `sketch.envelope`. +/// exports one: the series' attributes, `sketch.envelope`, and its place +/// in its lineage (a full, sequence 0). fn state_point(attributes: Vec, envelope: &[u8], count: u64) -> SummaryDataPoint { let mut attributes = attributes; attributes.push(attribute( "sketch.envelope", any_value::Value::BytesValue(envelope.to_vec()), )); + attributes.push(attribute("asap.sequence", any_value::Value::IntValue(0))); + attributes.push(text("asap.state_kind", "full")); SummaryDataPoint { attributes, start_time_unix_nano: (WINDOW_END_MS - 5_000) * 1_000_000, @@ -986,6 +991,7 @@ fn a_view_metrics_points_are_states_labeled_as_raw_samples() { plan_id: "p1".into(), node_id: 1, key, + producer_epoch: 7, series: vec![CollectorSeriesStates { labels: raw_labels.into_iter().collect(), records: vec![ViewStateRecord { @@ -993,6 +999,8 @@ fn a_view_metrics_points_are_states_labeled_as_raw_samples() { window_end_ms: WINDOW_END_MS as i64, asapv1: vec![1, 2, 3], sample_count: 50, + sequence: 0, + kind: StateKind::Full, }], }], }], @@ -1065,7 +1073,9 @@ fn a_bad_view_identity_refuses_the_request() { .contains("asap.view_state_key") ); let mut no_envelope = point(); - no_envelope[0].attributes.pop(); + no_envelope[0] + .attributes + .retain(|attribute| attribute.key != "sketch.envelope"); assert!(refused(view_metric( "data", 1, @@ -1082,4 +1092,60 @@ fn a_bad_view_identity_refuses_the_request() { }), ); assert!(refused(unnamed).contains("names no view")); + let mut no_epoch = view_metadata(1, VIEW_KEY); + no_epoch.pop(); + assert!(refused(view_metric("data", 1, no_epoch, point())).contains("asap.producer_epoch")); +} + +/// A state point's lineage attributes: a delta carries its sequence and +/// base, and none of the three is a label. Missing ones, a full that is +/// not sequence 0, a delta whose base is not its sequence less one, and an +/// unknown kind refuse the request. +#[test] +fn lineage_attributes_are_decoded_and_checked() { + let delta = |sequence: i64, base: Option, kind: &str| { + let mut point = state_point(vec![text("region", "a")], &[1], 1); + point.attributes.truncate(2); + point.attributes.push(attribute( + "asap.sequence", + any_value::Value::IntValue(sequence), + )); + point.attributes.push(text("asap.state_kind", kind)); + if let Some(base) = base { + point.attributes.push(attribute( + "asap.base_sequence", + any_value::Value::IntValue(base), + )); + } + view_metric("data", 1, view_metadata(1, VIEW_KEY), vec![point]) + }; + let views = decoded(&encode(&request(vec![delta(3, Some(2), "delta")]))) + .unwrap() + .view_states + .views; + let series = &views[0].series[0]; + assert_eq!(views[0].producer_epoch, 7); + assert_eq!( + (series.records[0].sequence, series.records[0].kind), + (3, StateKind::Delta { base_sequence: 2 }) + ); + assert!(series.labels.keys().all(|name| !name.starts_with("asap"))); + let refused = |metric: Metric| match decoded(&encode(&request(vec![metric]))) { + Err(OtlpError::ViewIdentity { reason, .. }) => reason, + other => panic!("not refused: {other:?}"), + }; + assert!(refused(delta(3, Some(1), "delta")).contains("less one")); + assert!(refused(delta(3, None, "delta")).contains("asap.base_sequence")); + assert!(refused(delta(0, None, "delta")).contains("sequence 0")); + assert!(refused(delta(2, None, "full")).contains("sequence 0 alone")); + assert!(refused(delta(0, None, "partial")).contains("not full or delta")); + let mut no_sequence = state_point(vec![text("region", "a")], &[1], 1); + no_sequence.attributes.truncate(2); + assert!(refused(view_metric( + "data", + 1, + view_metadata(1, VIEW_KEY), + vec![no_sequence] + )) + .contains("asap.sequence")); } diff --git a/crates/control-plane/tests/collector_views.rs b/crates/control-plane/tests/collector_views.rs index 42f2949df..4eb5eed9b 100644 --- a/crates/control-plane/tests/collector_views.rs +++ b/crates/control-plane/tests/collector_views.rs @@ -276,13 +276,17 @@ fn an_operator_line_moves_the_cut_up() { } /// The written file reads back equal, and its sub-DAG is valid on its own: -/// its materialized views have the installed plan's view state keys. +/// its materialized views have the installed plan's view state keys. It +/// carries the collector's declared window close delay. #[test] fn the_file_reads_back_and_its_views_keep_their_keys() { let plan = plan(&["quantile_over_time(0.99, data[5m])"], false); - let (file, _) = collector_sub_dag(&plan, &parse(&capabilities())).unwrap(); + let mut declared = capabilities(); + declared["window_close_delay_ms"] = json!(2500); + let (file, _) = collector_sub_dag(&plan, &parse(&declared)).unwrap(); let text = serde_json::to_string(&file).unwrap(); let read: common::CollectorViewsFile = serde_json::from_str(&text).unwrap(); + assert_eq!(read.window_close_delay_ms, 2500); // Equal as written (the nodes' in-memory provenance is not in the file). assert_eq!(serde_json::to_string(&read).unwrap(), text); let installed = plan.materialized_views().unwrap(); diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs index fef365144..8fadf3a13 100644 --- a/crates/data-plane/tests/collector_views.rs +++ b/crates/data-plane/tests/collector_views.rs @@ -190,11 +190,34 @@ fn text(key: &str, value: &str) -> KeyValue { } } -/// One state: `job`'s state `asapv1` of the window ending at `end_ms`. +/// One state: `job`'s state `asapv1` of the window ending at `end_ms`, +/// record `sequence` of its lineage from collector instance `epoch`: a +/// full when 0, else a delta on the record before. struct State { job: &'static str, end_ms: i64, asapv1: Vec, + epoch: u64, + sequence: u64, +} + +/// The `asap.sequence`, `asap.state_kind` and (deltas) `asap.base_sequence` +/// attributes of record `sequence`. +fn lineage_attributes(sequence: u64) -> Vec { + let int = |key: &str, value: u64| KeyValue { + key: key.into(), + value: Some(AnyValue { + value: Some(any_value::Value::IntValue(value as i64)), + }), + }; + match sequence { + 0 => vec![int("asap.sequence", 0), text("asap.state_kind", "full")], + n => vec![ + int("asap.sequence", n), + text("asap.state_kind", "delta"), + int("asap.base_sequence", n - 1), + ], + } } /// The OTLP body of `states` of view `node` of `plan`, with the view @@ -207,43 +230,61 @@ fn body(plan: &InstallablePlan, node: usize, width_ms: i64, states: &[State]) -> .find(|view| view.node_id == node) .unwrap(); let key = serde_json::to_value(view.view_state_key()).unwrap(); - let metadata = vec![ - text("asap.plan_id", view.plan_id()), - KeyValue { - key: "asap.node_id".into(), - value: Some(AnyValue { - value: Some(any_value::Value::IntValue(node as i64)), - }), - }, - text("asap.view_state_key", &key.to_string()), - ]; - let data_points = states - .iter() - .map(|state| SummaryDataPoint { - attributes: vec![ - text("job", state.job), + // One metric per collector instance: the epoch is metric metadata. + let mut epochs: Vec = Vec::new(); + for state in states { + if !epochs.contains(&state.epoch) { + epochs.push(state.epoch); + } + } + let metrics = epochs + .into_iter() + .map(|epoch| { + let metadata = vec![ + text("asap.plan_id", view.plan_id()), KeyValue { - key: "sketch.envelope".into(), + key: "asap.node_id".into(), value: Some(AnyValue { - value: Some(any_value::Value::BytesValue(state.asapv1.clone())), + value: Some(any_value::Value::IntValue(node as i64)), }), }, - ], - start_time_unix_nano: ((state.end_ms - width_ms) * 1_000_000) as u64, - time_unix_nano: (state.end_ms * 1_000_000) as u64, - count: 1, - ..Default::default() + text("asap.view_state_key", &key.to_string()), + text("asap.producer_epoch", &epoch.to_string()), + ]; + let data_points = states + .iter() + .filter(|state| state.epoch == epoch) + .map(|state| SummaryDataPoint { + attributes: [ + text("job", state.job), + KeyValue { + key: "sketch.envelope".into(), + value: Some(AnyValue { + value: Some(any_value::Value::BytesValue(state.asapv1.clone())), + }), + }, + ] + .into_iter() + .chain(lineage_attributes(state.sequence)) + .collect(), + start_time_unix_nano: ((state.end_ms - width_ms) * 1_000_000) as u64, + time_unix_nano: (state.end_ms * 1_000_000) as u64, + count: 1, + ..Default::default() + }) + .collect(); + Metric { + name: format!("data.asap_view.{node}"), + metadata, + data: Some(Data::Summary(Summary { data_points })), + ..Default::default() + } }) .collect(); let request = ExportMetricsServiceRequest { resource_metrics: vec![ResourceMetrics { scope_metrics: vec![ScopeMetrics { - metrics: vec![Metric { - name: format!("data.asap_view.{node}"), - metadata, - data: Some(Data::Summary(Summary { data_points })), - ..Default::default() - }], + metrics, ..Default::default() }], ..Default::default() @@ -304,6 +345,8 @@ fn states(alpha: f64, width_ms: i64, time_ms: i64) -> Vec { job, end_ms, asapv1: sketch_state(alpha, &samples(job, end_ms - width_ms, end_ms)), + epoch: 1, + sequence: 0, }); end_ms += width_ms; } @@ -396,11 +439,12 @@ async fn a_view_reading_a_collector_view_is_built_from_its_states() { assert_eq!(answer, expected); } -/// A window's two partial states (a collector restarted inside it) are -/// merged into the window's state: it answers as the state of all its -/// samples does. A repeat of either partial, before or after the merge, -/// and after the window committed, is a duplicate; a state of a window -/// past its view's retention is dropped as late. +/// A window's two partial states (a collector restarted inside it: each +/// instance's full, of its own epoch) are merged into the window's state: +/// it answers as the state of all its samples does. A repeat of either +/// partial, before or after the merge, and after the window committed, is +/// a duplicate; a state of a window past its view's retention is dropped +/// as late. #[tokio::test(flavor = "multi_thread")] async fn partials_merge_repeats_are_duplicates_late_states_drop() { let (plan, node, width_ms, alpha) = plan(); @@ -422,21 +466,29 @@ async fn partials_merge_repeats_are_duplicates_late_states_drop() { job: "a", end_ms: time_ms, asapv1: sketch_state(alpha, second), + epoch: 2, + sequence: 0, }; let first_again = State { job: "a", end_ms: time_ms, asapv1: all[newest].asapv1.clone(), + epoch: 1, + sequence: 0, }; all.push(State { job: "a", end_ms: time_ms, asapv1: all[newest].asapv1.clone(), + epoch: 1, + sequence: 0, }); let second_again = State { job: "a", end_ms: time_ms, asapv1: second.asapv1.clone(), + epoch: 2, + sequence: 0, }; all.push(second); all.push(first_again); @@ -463,6 +515,8 @@ async fn partials_merge_repeats_are_duplicates_late_states_drop() { job: "b", end_ms: time_ms - 3_600_000, asapv1: sketch_state(alpha, &[(time_ms, 1.0)]), + epoch: 1, + sequence: 0, }; assert_eq!( post( @@ -573,10 +627,10 @@ async fn a_window_whose_first_states_come_after_a_later_windows_is_stored() { } /// A collector that got late samples of a window it already emitted sends -/// a correction: a state of the late samples alone, for the same series -/// and window. It is a new state (other bytes), so it merges into the -/// committed window, which then answers as if every sample had come on -/// time; the correction sent again is a duplicate. +/// a correction: a delta of the late samples alone, the next record of the +/// series' lineage in that window. It merges into the committed window, +/// which then answers as if every sample had come on time; the correction +/// sent again is a duplicate. #[tokio::test(flavor = "multi_thread")] async fn a_correction_state_merges_into_its_emitted_window() { let (plan, node, width_ms, alpha) = plan(); @@ -597,6 +651,8 @@ async fn a_correction_state_merges_into_its_emitted_window() { job: "a", end_ms: time_ms, asapv1: sketch_state(alpha, late), + epoch: 1, + sequence: 1, }; assert_eq!( post(&app, body(&plan, node, width_ms, &[correction()])).await, @@ -690,6 +746,8 @@ async fn bad_states_are_rejected_and_a_window_without_states_is_counted() { job: "a", end_ms, asapv1, + epoch: 1, + sequence: 0, }; let good = sketch_state(alpha, &[(time_ms, 1.0)]); let rejected = |reason: &str| { @@ -856,3 +914,259 @@ fn a_collector_views_file_of_another_plan_is_refused() { "{refused:#}" ); } + +// Sequence numbers and delta transmission +// (docs/design/collector-sketch-ingest.md, §8). + +/// `job`'s record `sequence` of epoch `epoch` in the window ending +/// `end_ms`, the DDSketch of `samples`. +fn record( + alpha: f64, + job: &'static str, + end_ms: i64, + samples: &[(i64, f64)], + epoch: u64, + sequence: u64, +) -> State { + State { + job, + end_ms, + asapv1: sketch_state(alpha, samples), + epoch, + sequence, + } +} + +/// `samples` in three non-empty parts, in order. +fn thirds(samples: &[(i64, f64)]) -> [&[(i64, f64)]; 3] { + let n = samples.len(); + [ + &samples[..n / 3], + &samples[n / 3..2 * n / 3], + &samples[2 * n / 3..], + ] +} + +/// `asap_collector_states_total` of `node` and `outcome`. +fn outcome_line(node: usize, outcome: &str) -> String { + format!("asap_collector_states_total{{view=\"{node}\",outcome=\"{outcome}\"}}") +} + +/// Two corrections of one window with equal bytes (two late samples of +/// equal value) are two records, sequences 1 and 2: both merge, and the +/// window answers as the one full of all its samples does. +#[tokio::test(flavor = "multi_thread")] +async fn corrections_with_equal_bytes_both_merge() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let late = [(time_ms - 1, 1.0e6)]; + let whole = samples("a", time_ms - width_ms, time_ms); + + // One full holding every sample, the late ones included. + let (one_app, _) = collector_data_plane(&plan, node); + let mut all = states(alpha, width_ms, time_ms); + let newest = all + .iter() + .position(|s| s.job == "a" && s.end_ms == time_ms) + .unwrap(); + let with_late: Vec<(i64, f64)> = whole.iter().chain(&late).chain(&late).copied().collect(); + all[newest].asapv1 = sketch_state(alpha, &with_late); + assert_eq!(post(&one_app, body(&plan, node, width_ms, &all)).await, 0); + let (status, _, expected) = + common::get(&one_app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{expected}"); + + // The on-time full, then the two corrections in two requests. + let (app, state) = collector_data_plane(&plan, node); + let emitted = states(alpha, width_ms, time_ms); + assert_eq!(post(&app, body(&plan, node, width_ms, &emitted)).await, 0); + for sequence in [1, 2] { + let correction = record(alpha, "a", time_ms, &late, 1, sequence); + assert_eq!( + post(&app, body(&plan, node, width_ms, &[correction])).await, + 0 + ); + } + assert_eq!(metric(&state, &outcome_line(node, "late_merged")), 2.0); + assert_eq!(metric(&state, &outcome_line(node, "duplicate")), 0.0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// A collector emits an open window as a full of its first samples and +/// deltas of the next ones (and the close): the window answers after the +/// first record, from the samples so far, and after the last as the +/// window's samples all at once do (DDSketch deltas are bucket-count +/// increments, so the merged state is the at-close state). +#[tokio::test(flavor = "multi_thread")] +async fn open_window_deltas_answer_and_end_at_the_close_answer() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + + let (app, state) = collector_data_plane(&plan, node); + let whole = samples("a", time_ms - width_ms, time_ms); + assert!(whole.len() >= 3, "a window of at least three samples"); + let parts = thirds(&whole); + let mut first = states(alpha, width_ms, time_ms); + let newest = first + .iter() + .position(|s| s.job == "a" && s.end_ms == time_ms) + .unwrap(); + first[newest] = record(alpha, "a", time_ms, parts[0], 1, 0); + assert_eq!(post(&app, body(&plan, node, width_ms, &first)).await, 0); + let (status, _, partial) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "the open window answers: {partial}"); + for (sequence, part) in parts.iter().enumerate().skip(1) { + let delta = record(alpha, "a", time_ms, part, 1, sequence as u64); + assert_eq!(post(&app, body(&plan, node, width_ms, &[delta])).await, 0); + } + assert_eq!( + metric(&state, &outcome_line(node, "late_merged")), + (parts.len() - 1) as f64 + ); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} + +/// A delta whose base never came (sequence 2 after 0) is not applied: the +/// window is incomplete, and a query reading it is not answered from the +/// plan, nor after a later full of another epoch; a query that does not +/// read it still answers. +#[tokio::test(flavor = "multi_thread")] +async fn a_gap_leaves_the_window_unanswered() { + let (plan, node, width_ms, alpha) = plan(); + assert!(width_ms <= 10_000, "the newest window is within 10 s"); + let time_ms = query_time_ms(); + let (app, state) = collector_data_plane(&plan, node); + // Windows through 10 s before the newest too, for the earlier query. + let earlier_ms = time_ms - 10_000; + let mut emitted = states(alpha, width_ms, earlier_ms); + emitted.extend( + states(alpha, width_ms, time_ms) + .into_iter() + .filter(|s| s.end_ms > earlier_ms), + ); + assert_eq!(post(&app, body(&plan, node, width_ms, &emitted)).await, 0); + let late = [(time_ms - 1, 1.0)]; + let after_gap = record(alpha, "a", time_ms, &late, 1, 2); + assert_eq!( + post(&app, body(&plan, node, width_ms, &[after_gap])).await, + 0 + ); + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 1.0); + let newest = common::instant_uri(QUERY, time_ms / 1000); + common::barrier(&app, 0).await; + let (status, _, body_text) = common::get(&app, &newest).await; + assert_ne!(status, StatusCode::OK, "{body_text}"); + let other_epoch = record(alpha, "a", time_ms, &late, 2, 0); + assert_eq!( + post(&app, body(&plan, node, width_ms, &[other_epoch])).await, + 0 + ); + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 2.0); + let (status, _, _) = common::get(&app, &newest).await; + assert_ne!(status, StatusCode::OK); + let (status, _, earlier) = + common::get(&app, &common::instant_uri(QUERY, earlier_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{earlier}"); +} + +/// A restarted collector (a new epoch) starts each window it emits with a +/// full: it merges with the previous instance's records of the window, +/// and its deltas apply onto it, so the window answers as all its samples +/// do. A new epoch's delta whose full was lost is never applied to the +/// previous instance's state: the window is incomplete. +#[tokio::test(flavor = "multi_thread")] +async fn a_restarted_collector_resynchronizes_with_a_full() { + let (plan, node, width_ms, alpha) = plan(); + let time_ms = query_time_ms(); + let expected = built_here(&plan, time_ms).await; + let whole = samples("a", time_ms - width_ms, time_ms); + assert!(whole.len() >= 3, "a window of at least three samples"); + let parts = thirds(&whole); + let before_restart = || { + let mut emitted = states(alpha, width_ms, time_ms); + let newest = emitted + .iter() + .position(|s| s.job == "a" && s.end_ms == time_ms) + .unwrap(); + emitted[newest] = record(alpha, "a", time_ms, parts[0], 1, 0); + emitted + }; + + let (app, state) = collector_data_plane(&plan, node); + assert_eq!( + post(&app, body(&plan, node, width_ms, &before_restart())).await, + 0 + ); + let restarted = [ + record(alpha, "a", time_ms, parts[1], 2, 0), + record(alpha, "a", time_ms, parts[2], 2, 1), + ]; + assert_eq!(post(&app, body(&plan, node, width_ms, &restarted)).await, 0); + assert_eq!(metric(&state, &outcome_line(node, "late_merged")), 2.0); + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 0.0); + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); + + // The restarted instance's full is lost: its delta has no base. + let (app, state) = collector_data_plane(&plan, node); + assert_eq!( + post(&app, body(&plan, node, width_ms, &before_restart())).await, + 0 + ); + let delta = record(alpha, "a", time_ms, parts[2], 2, 1); + assert_eq!(post(&app, body(&plan, node, width_ms, &[delta])).await, 0); + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 1.0); + common::barrier(&app, 0).await; + let (status, _, _) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; + assert_ne!(status, StatusCode::OK); +} + +/// The collector-views file carries the collector's declared close delay +/// (here 1 s): a stopped collector's windows close on the clock 1 s plus +/// the 2 s skew allowance after their end, not after the default 8 s. +#[tokio::test(flavor = "multi_thread")] +async fn windows_of_a_stopped_collector_close_after_the_declared_delay() { + let (plan, node, width_ms, alpha) = plan(); + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../control-plane/tests/data/collector-capabilities.json"); + let mut capabilities: Value = + serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap(); + capabilities["window_close_delay_ms"] = 1_000.into(); + let capabilities = CollectorCapabilities::from_json(&capabilities.to_string()).unwrap(); + let (file, _) = collector_sub_dag(&plan, &capabilities).unwrap(); + let file: ::common::CollectorViewsFile = + serde_json::from_str(&serde_json::to_string(&file).unwrap()).unwrap(); + assert_eq!(file.window_close_delay_ms, 1_000); + + let stopped_at = query_time_ms() - 30_000; + let at = stopped_at + 30_000; + let expected = built_here_without(&plan, at, (stopped_at, at)).await; + let clock = precompute::ingestion::WallClock::manual(stopped_at + 500); + let options = EngineOptions { + precompute_mode: PrecomputeMode::Push, + collector: CollectorViewOptions::from(&file), + clock: clock.clone(), + ..no_forward(0) + }; + let (app, _state) = data_plane(&plan, options); + let states: Vec = states(alpha, width_ms, at) + .into_iter() + .filter(|s| s.end_ms <= stopped_at) + .collect(); + assert_eq!(post(&app, body(&plan, node, width_ms, &states)).await, 0); + let (status, _, _) = common::get(&app, &common::instant_uri(QUERY, at / 1000)).await; + assert_ne!(status, StatusCode::OK, "the stop's windows are still open"); + // 3 s past the stop's last window end: closed with the declared delay + // (the default 8 s would keep it open). + clock.set(stopped_at + 500 + 30_000 + 3_000); + common::barrier(&app, 0).await; + let (status, _, answer) = common::get(&app, &common::instant_uri(QUERY, at / 1000)).await; + assert_eq!(status, StatusCode::OK, "{answer}"); + assert_eq!(answer, expected); +} From 9492be2908da4d254694b1d90111d231e0fd698c Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:55:37 +0000 Subject: [PATCH 2/2] feat(collector views): sequence numbers and deltas; idle close from the declared delay Each collector state is a record of its (view, series, window) lineage: the producer epoch is metric metadata (asap.producer_epoch), the sequence, kind and base are point attributes (asap.sequence, asap.state_kind, asap.base_sequence), decoded by the OTLP adapter into CollectorViewStates::producer_epoch and ViewStateRecord::{sequence, kind}. Staging replaces the envelope-hash set with per-series lineages (epoch, last applied sequence): a full of a new epoch or a delta onto its lineage's last record merges; an applied (epoch, sequence) is a duplicate, so two corrections with equal bytes are two records; a delta after a gap, with no lineage, or of a new epoch without its full is never applied and marks its window incomplete. The committer marks the window, and the windows of the groups reading it, in the view store (ViewStore::mark_incomplete); a read of a range holding a marked window fails as a missing window does (NotReady), and cached results reading it are stale. Later records of an incomplete window are dropped and counted (outcome incomplete). Marks go with retention. The control plane copies the capabilities' window_close_delay_ms into the collector-views file; CollectorViewOptions::from(file) closes idle windows after it plus a 2 s skew allowance instead of a fixed 8 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- README.md | 9 +- crates/adapters/ingest/otlp/src/lib.rs | 90 +++- crates/common/src/collector_views_file.rs | 5 + crates/common/src/lib.rs | 4 +- crates/common/src/view_states.rs | 31 +- crates/control-plane/src/collector_views.rs | 1 + crates/precompute/src/collector.rs | 532 ++++++++++++++------ crates/precompute/src/engine.rs | 23 +- crates/precompute/src/ingestion.rs | 15 + crates/storage/src/store.rs | 86 ++++ 10 files changed, 624 insertions(+), 172 deletions(-) diff --git a/README.md b/README.md index c117ee413..2a3ffb99e 100644 --- a/README.md +++ b/README.md @@ -244,14 +244,19 @@ Collector views (docs/design/collector-sketch-ingest.md): with `asap_sketches --print-capabilities`) and `--emit-collector-views cv.json`, the control plane also writes the part of the plan the collector runs: the views it builds instead of the data plane, the plan id, which metrics the data plane still reads raw (the collector stops forwarding the others), and +the collector's declared window close delay, and prints why each other node is not on the collector. `--plan plan.json` reads a plan written before instead of planning `--workload`. The data plane started with `--collector-views cv.json` does not build those views: their states arrive from the collector on `/v1/metrics`, in metrics named `.asap_view.`, and each window is committed when the request carrying its states ends; later states of a committed window merge -into it within retention (`asap_collector_states_*` on `/metrics`). It -refuses a file of another plan. +into it within retention (`asap_collector_states_*` on `/metrics`). Each +state is a record of its series' lineage in its window (a full, then +deltas, numbered per collector instance): a repeated record is ignored, and +a delta whose base is missing marks the window incomplete, so queries +reading it are forwarded. A stopped collector's windows close after its +declared delay plus 2 s. It refuses a file of another plan. `--cost-inputs costs.json` replaces the Planner's default `CostInputs` (Stage 3's cost model, resource speed and measured operation costs); an diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs index a29b1135e..7981a8599 100644 --- a/crates/adapters/ingest/otlp/src/lib.rs +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -62,14 +62,18 @@ //! view states, not samples (docs/design/collector-sketch-ingest.md, §4): //! each data point is one series' state in the window `(start_time_unix_nano, //! time_unix_nano]`, its ASAPv1 bytes in the `sketch.envelope` attribute and -//! its sample count in `count`. Resource, scope and the other point -//! attributes give the series' labels as for a sample, `__name__` being the -//! metric's name before `.asap_view.`. They are decoded into -//! [`Decoded::view_states`]; the state bytes are not read. A request whose -//! view identity is missing in part or does not parse, whose view metric is -//! not named `.asap_view.`, or that has a -//! `sketch.envelope` point outside such a metric, is refused -//! ([`OtlpError::ViewIdentity`]). +//! its sample count in `count`, and its place in its lineage in +//! `asap.sequence`, `asap.state_kind` and `asap.base_sequence` (§8; the +//! sending collector's `asap.producer_epoch` is metric metadata). Resource, +//! scope and the other point attributes give the series' labels as for a +//! sample, `__name__` being the metric's name before `.asap_view.`. They are +//! decoded into [`Decoded::view_states`]; the state bytes are not read. A +//! request whose view identity or producer epoch is missing in part or does +//! not parse, whose view metric is not named +//! `.asap_view.`, with a state point whose lineage +//! attributes are missing or disagree (a full is sequence 0, a delta's base +//! is its sequence less one), or that has a `sketch.envelope` point outside +//! such a metric, is refused ([`OtlpError::ViewIdentity`]). //! //! # Decoding //! @@ -85,9 +89,12 @@ use std::collections::btree_map::Entry; use std::collections::{BTreeMap, HashMap}; use std::io::Read; -use common::view_identity::{ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, VIEW_STATE_KEY}; +use common::view_identity::{ + BASE_SEQUENCE, ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, SEQUENCE, + STATE_KIND, VIEW_STATE_KEY, +}; use common::{ - CollectorSeriesStates, CollectorViewStates, LabelSet, ViewStateBatch, ViewStateKey, + CollectorSeriesStates, CollectorViewStates, LabelSet, StateKind, ViewStateBatch, ViewStateKey, ViewStateRecord, }; use prometheus_remote_write::series_cache::SeriesCache; @@ -677,13 +684,14 @@ impl Walk<'_, B> { /// for a metric whose metadata names no view (none of the identity /// keys). fn view_of(&mut self, name: &str, metadata: &[&[u8]]) -> Result, OtlpError> { - let (mut plan_id, mut node_id, mut key) = (None, None, None); + let (mut plan_id, mut node_id, mut key, mut epoch) = (None, None, None, None); for entry in metadata { let (entry_key, value) = key_value(entry)?; match entry_key { PLAN_ID => plan_id = Some(value.text().into_owned()), NODE_ID => node_id = Some(value.text().into_owned()), VIEW_STATE_KEY => key = Some(value.text().into_owned()), + PRODUCER_EPOCH => epoch = Some(value.text().into_owned()), _ => {} } } @@ -704,6 +712,10 @@ impl Walk<'_, B> { .map_err(|e| refused(format!("{NODE_ID}: {e}")))?; let key: ViewStateKey = serde_json::from_str(&key.ok_or_else(|| missing(VIEW_STATE_KEY))?) .map_err(|e| refused(format!("{VIEW_STATE_KEY}: {e}")))?; + let producer_epoch: u64 = epoch + .ok_or_else(|| missing(PRODUCER_EPOCH))? + .parse() + .map_err(|e| refused(format!("{PRODUCER_EPOCH}: {e}")))?; if !name .strip_suffix(&node_id.to_string()) .is_some_and(|source| source.ends_with(NAME_INFIX) && source.len() > NAME_INFIX.len()) @@ -713,16 +725,19 @@ impl Walk<'_, B> { ))); } let views = &mut self.decoded.view_states.views; - if let Some(index) = views - .iter() - .position(|view| view.node_id == node_id && view.plan_id == plan_id && view.key == key) - { + if let Some(index) = views.iter().position(|view| { + view.node_id == node_id + && view.producer_epoch == producer_epoch + && view.plan_id == plan_id + && view.key == key + }) { return Ok(Some(index)); } views.push(CollectorViewStates { plan_id, node_id, key, + producer_epoch, series: Vec::new(), }); Ok(Some(views.len() - 1)) @@ -743,6 +758,7 @@ impl Walk<'_, B> { let (attributes_field, flags_field) = kind.attributes_and_flags_fields(); let (mut start_nanos, mut time_nanos, mut count, mut flags) = (0u64, 0u64, 0u64, 0u64); let mut envelope = None; + let (mut sequence, mut state_kind, mut base) = (None, None, None); let mut pairs = Vec::new(); let mut reader = Reader::new(point); while let Some((field, value)) = reader.field()? { @@ -758,6 +774,9 @@ impl Walk<'_, B> { reason: format!("{ENVELOPE_ATTRIBUTE} is not bytes"), }) } + (SEQUENCE, value) => sequence = Some(value.text().into_owned()), + (STATE_KIND, value) => state_kind = Some(value.text().into_owned()), + (BASE_SEQUENCE, value) => base = Some(value.text().into_owned()), pair => pairs.push(pair), } } @@ -779,6 +798,11 @@ impl Walk<'_, B> { reason: format!("a point has no {ENVELOPE_ATTRIBUTE} bytes"), }); }; + let (sequence, kind) = + lineage(sequence, state_kind, base).map_err(|reason| OtlpError::ViewIdentity { + metric: name.to_string(), + reason, + })?; if self.decoded.samples.len() >= self.max_points { return Err(OtlpError::TooManyPoints(self.point_limit)); } @@ -803,11 +827,47 @@ impl Walk<'_, B> { window_end_ms: (time_nanos / 1_000_000) as i64, asapv1: envelope.to_vec(), sample_count: count, + sequence, + kind, }); Ok(()) } } +/// A state point's place in its lineage from its `asap.sequence`, +/// `asap.state_kind` and `asap.base_sequence` texts: a full is sequence 0 +/// with no base, a delta's base is its sequence less one. Why not, else. +fn lineage( + sequence: Option, + kind: Option, + base: Option, +) -> Result<(u64, StateKind), String> { + let number = |key: &str, text: Option| -> Result { + text.ok_or_else(|| format!("a state point has no {key}"))? + .parse() + .map_err(|e| format!("{key}: {e}")) + }; + let sequence = number(SEQUENCE, sequence)?; + match (kind.as_deref(), sequence, base) { + (Some("full"), 0, None) => Ok((0, StateKind::Full)), + (Some("delta"), 1.., base) => { + let base_sequence = number(BASE_SEQUENCE, base)?; + if base_sequence.checked_add(1) != Some(sequence) { + return Err(format!( + "a delta's {BASE_SEQUENCE} {base_sequence} is not {SEQUENCE} {sequence} less one" + )); + } + Ok((sequence, StateKind::Delta { base_sequence })) + } + (Some("full"), ..) => Err(format!( + "a full state has {SEQUENCE} {sequence} or a {BASE_SEQUENCE}; it is sequence 0 alone" + )), + (Some("delta"), ..) => Err(format!("a delta has {SEQUENCE} 0")), + (Some(other), ..) => Err(format!("{STATE_KIND} {other:?} is not full or delta")), + (None, ..) => Err(format!("a state point has no {STATE_KIND}")), + } +} + /// The error of a `sketch.envelope` point under a metric naming no view. #[cold] fn not_a_view(name: &str) -> OtlpError { diff --git a/crates/common/src/collector_views_file.rs b/crates/common/src/collector_views_file.rs index 8ccbde673..7234de528 100644 --- a/crates/common/src/collector_views_file.rs +++ b/crates/common/src/collector_views_file.rs @@ -21,6 +21,11 @@ pub struct CollectorViewsFile { /// reads its raw samples (a `Scan` of it feeds a node off the /// collector, or runs at query time). pub backend_reads_raw: BTreeMap, + /// The collector's declared `window_close_delay_ms` (its capabilities), + /// copied: the longest time after a window's end before it emits the + /// window. The data plane closes a stopped collector's windows on its + /// clock after it plus a skew allowance. + pub window_close_delay_ms: u64, /// The collector views: the sub-DAG's outputs whose states the backend /// ingests. pub outputs: Vec, diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 2f4e0f79d..56a774b79 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -27,8 +27,8 @@ pub use query_result::{ ResultSample, Sample, Table, TableValue, }; pub use view_states::{ - view_identity, CollectorSeriesStates, CollectorViewStates, ViewStateBatch, ViewStateKey, - ViewStateRecord, + view_identity, CollectorSeriesStates, CollectorViewStates, StateKind, ViewStateBatch, + ViewStateKey, ViewStateRecord, }; /// The largest time, in milliseconds either side of the epoch, the data diff --git a/crates/common/src/view_states.rs b/crates/common/src/view_states.rs index e44b5fcc8..6e1a6d1c5 100644 --- a/crates/common/src/view_states.rs +++ b/crates/common/src/view_states.rs @@ -32,6 +32,9 @@ pub struct CollectorViewStates { /// The view's `MaterializedView::view_state_key()`, as the collector /// read it from its copy of the plan. pub key: ViewStateKey, + /// The collector instance that sent the states (`asap.producer_epoch`): + /// a restarted collector has a new epoch, and new lineages (§8). + pub producer_epoch: u64, pub series: Vec, } @@ -44,15 +47,31 @@ pub struct CollectorSeriesStates { pub records: Vec, } -/// One state of one window `(window_start_ms, window_end_ms]` (Record tier). +/// One state of one window `(window_start_ms, window_end_ms]` (Record tier): +/// a record of its `(view, series, window)` lineage (§8). #[derive(Debug, Clone, PartialEq)] pub struct ViewStateRecord { pub window_start_ms: i64, pub window_end_ms: i64, - /// The full state, as `asap_sketchlib`'s ASAPv1 bytes. + /// `asap_sketchlib`'s ASAPv1 bytes: for a full, the lineage's state so + /// far; for a delta, the state of the samples since its base. pub asapv1: Vec, /// Samples folded into the state, as the collector counted them. pub sample_count: u64, + /// Its place in its lineage (`asap.sequence`): 0 for a full. + pub sequence: u64, + /// `asap.state_kind`, with `asap.base_sequence` for a delta. + pub kind: StateKind, +} + +/// Whether a record starts its lineage or applies onto its base. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StateKind { + /// Sequence 0: the lineage's state so far. + Full, + /// The state of the samples since record `base_sequence`, which is + /// `sequence - 1`. + Delta { base_sequence: u64 }, } /// The view identity's metric metadata keys and the reserved part of a @@ -65,4 +84,12 @@ pub mod view_identity { pub const NAME_INFIX: &str = ".asap_view."; /// The data point attribute holding a state's ASAPv1 bytes. pub const ENVELOPE_ATTRIBUTE: &str = "sketch.envelope"; + /// Metric metadata: the sending collector instance, decimal text. + pub const PRODUCER_EPOCH: &str = "asap.producer_epoch"; + /// Data point attributes: the record's place in its lineage. + pub const SEQUENCE: &str = "asap.sequence"; + /// `"full"` or `"delta"`. + pub const STATE_KIND: &str = "asap.state_kind"; + /// A delta's base: the sequence it applies onto. + pub const BASE_SEQUENCE: &str = "asap.base_sequence"; } diff --git a/crates/control-plane/src/collector_views.rs b/crates/control-plane/src/collector_views.rs index da12d3aa1..aaa8314ec 100644 --- a/crates/control-plane/src/collector_views.rs +++ b/crates/control-plane/src/collector_views.rs @@ -388,6 +388,7 @@ pub fn collector_sub_dag( planner_wire_version: INSTALLABLE_PLAN_WIRE_VERSION, plan_id: dag.plan_id(), backend_reads_raw, + window_close_delay_ms: capabilities.window_close_delay_ms, outputs, dag: sub_dag, }; diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 46b289d5f..9c17589cd 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -8,13 +8,17 @@ //! `(plan_id, node_id)`, checks its key, metric name and window, interns //! the series as a raw sample's, and decodes the ASAPv1 bytes into the //! view's kernel. A state failing a check is rejected with a reason. -//! 2. [`Staging::stage`], on the ingest coordinator: a state of a window -//! not yet committed is staged per `(view, series, window)`, a repeat of -//! a state seen (equal bytes) is a duplicate, and a different state of -//! the same series and window is merged into the staged one. A state of -//! a committed window still kept is merged into it later -//! ([`crate::ingestion::Precompute::merge_late`]); one of a window past -//! retention, or of one never stored, is dropped as late. +//! 2. [`Staging::stage`], on the ingest coordinator: each record is +//! checked against its `(view, series, window)` lineages (§8): a full +//! of a new producer epoch starts a lineage, a delta onto its lineage's +//! last applied record continues it, and either is merged into the +//! series' state (staged, or, for a committed window still kept, merged +//! into it later: [`crate::ingestion::Precompute::merge_late`]). A +//! record already applied is a duplicate. A delta with no known base or +//! after a gap is never applied: its window is marked incomplete +//! ([`crate::ingestion::Precompute::mark_incomplete`]), so no query +//! answers from it, and its later records are dropped. A state of a +//! window past retention is dropped as late. //! 3. The windows a request staged close when the request ends //! ([`crate::ingestion`]): their staged states become the window's rows //! ([`CollectorViews::rows`]), committed by the precompute committer as @@ -22,9 +26,7 @@ //! window with no state is not stored, so a query reading it is not //! answered from the plan. -use std::collections::hash_map::DefaultHasher; use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::hash::{Hash, Hasher}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -35,7 +37,7 @@ use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalA use asap_executor::summary_kernels::factory::create_planner_accumulator; use asap_executor::values::{Batch, SchemaRef, Value}; use asap_executor::AggregateCore; -use common::{ViewStateBatch, MAX_TIME_MS}; +use common::{StateKind, ViewStateBatch, MAX_TIME_MS}; use internal_metrics::Metrics; use storage::persist::Asapv1Decoder; use storage::series_ids::{intern_pairs, Series}; @@ -57,27 +59,33 @@ pub struct CollectorViewOptions { pub idle_close_ms: u64, } +/// What the idle close allows for clock skew between the collector and +/// the data plane, on top of the collector's close delay. +pub const CLOCK_SKEW_ALLOWANCE_MS: u64 = 2_000; + impl Default for CollectorViewOptions { /// No collector views; today's collector closes a window 6 s after its - /// end, and 2 s are allowed for clock skew. + /// end, plus the skew allowance. fn default() -> Self { Self { plan_id: None, views: BTreeSet::new(), - idle_close_ms: 8_000, + idle_close_ms: 6_000 + CLOCK_SKEW_ALLOWANCE_MS, } } } impl From<&common::CollectorViewsFile> for CollectorViewOptions { - /// The collector views a collector-views file lists, of its plan. - /// The file does not carry the collector's close delay: windows close - /// on the clock after the default allowance. + /// The collector views a collector-views file lists, of its plan; + /// windows close on the clock after the collector's declared close + /// delay plus the skew allowance. fn from(file: &common::CollectorViewsFile) -> Self { Self { plan_id: Some(file.plan_id.clone()), views: file.outputs.iter().copied().collect(), - ..Self::default() + idle_close_ms: file + .window_close_delay_ms + .saturating_add(CLOCK_SKEW_ALLOWANCE_MS), } } } @@ -117,6 +125,11 @@ pub struct CollectorStateIngestReport { pub late_merged: u64, /// Dropped: its window is past its view's retention. pub late_dropped: u64, + /// Not applied: a delta whose base is not its lineage's last applied + /// record (a gap, or no lineage: a lost full, a new epoch without its + /// full), or any record of a window already incomplete. Its window is + /// marked incomplete. + pub incomplete: u64, /// Rejected, by reason ([`reject`]). pub rejected: BTreeMap<&'static str, u64>, } @@ -135,6 +148,7 @@ impl std::ops::AddAssign for CollectorStateIngestReport { self.merged += other.merged; self.late_merged += other.late_merged; self.late_dropped += other.late_dropped; + self.incomplete += other.incomplete; for (reason, count) in other.rejected { *self.rejected.entry(reason).or_default() += count; } @@ -151,6 +165,8 @@ pub mod outcome { pub const LATE_MERGED: &str = "late_merged"; /// Its window was past its view's retention when it arrived. pub const LATE_DROPPED: &str = "late_dropped"; + /// Not applied: its lineage broke, or its window is incomplete. + pub const INCOMPLETE: &str = "incomplete"; /// Staged for a window skipped as past the view's retention. pub const EXPIRED: &str = "expired"; /// A window committed with its staged states. @@ -165,11 +181,62 @@ pub(crate) struct ArrivedState { pub node_id: PhysicalASAPNodeId, pub series: &'static Series, pub end_ms: i64, - /// The hash of its ASAPv1 bytes, which tells a repeat from a partial. - pub hash: u64, + /// The collector instance that sent it. + pub epoch: u64, + /// Its place in its lineage. + pub sequence: u64, + pub kind: StateKind, pub state: Arc, } +/// One lineage of a `(view, series, window)`: a collector instance's +/// records of it, applied through `last_sequence`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct Lineage { + epoch: u64, + last_sequence: u64, +} + +/// What a record does to its `(view, series, window)`'s lineages. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Applies { + /// A full of a new epoch, or a delta onto its lineage's last applied + /// record: its state is merged in. + Merged, + /// Its `(epoch, sequence)` was applied already. + Duplicate, + /// A delta whose base is not its lineage's last applied record, or of + /// an epoch with no lineage: never applied. + Broken, +} + +impl ArrivedState { + /// Applies this record to `lineages` (the series' lineages in its + /// window), §8's receiver rules. + fn apply_to(&self, lineages: &mut Vec) -> Applies { + match lineages.iter_mut().find(|l| l.epoch == self.epoch) { + Some(lineage) if self.sequence <= lineage.last_sequence => Applies::Duplicate, + Some(lineage) => match self.kind { + StateKind::Delta { base_sequence } if base_sequence == lineage.last_sequence => { + lineage.last_sequence = self.sequence; + Applies::Merged + } + _ => Applies::Broken, + }, + None => match self.kind { + StateKind::Full => { + lineages.push(Lineage { + epoch: self.epoch, + last_sequence: self.sequence, + }); + Applies::Merged + } + StateKind::Delta { .. } => Applies::Broken, + }, + } + } +} + /// One installed collector view. struct CollectorView { group: usize, @@ -312,6 +379,7 @@ impl CollectorViews { let mut arrived = Vec::new(); for states in batch.views { let node_id = states.node_id; + let epoch = states.producer_epoch; let mut reject = |reason: &'static str, count: u64, detail: &dyn Fn() -> String| { if count == 0 { return; @@ -387,14 +455,14 @@ impl CollectorViews { metrics .collector_states .arrived(node_id, (now_ms - end_ms).max(0)); - let mut hasher = DefaultHasher::new(); - record.asapv1.hash(&mut hasher); arrived.push(ArrivedState { group: view.group, node_id, series: interned, end_ms, - hash: hasher.finish(), + epoch, + sequence: record.sequence, + kind: record.kind, state, }); } @@ -465,44 +533,54 @@ impl CollectorViews { pub(crate) struct Staged { series: &'static Series, state: Arc, - /// The hashes of every state merged into it: a repeat of any is a - /// duplicate, even after a later partial was merged. - hashes: Vec, + /// The lineages merged into it: a record already applied is a + /// duplicate, and a delta applies only onto its lineage's last record. + lineages: Vec, } /// The collector states staged per window and series, on the ingest -/// coordinator, and the hashes of the states of each committed window -/// still kept. +/// coordinator, the lineages of each committed window still kept, and the +/// windows marked incomplete. #[derive(Default)] pub(crate) struct Staging { /// By `(group, window end)`, then by series id. windows: BTreeMap<(usize, i64), BTreeMap>, - /// Per committed window still kept, by `(group, window end)`, the - /// hashes of every state merged into each series' state: a repeat of - /// one is a duplicate. - committed: BTreeMap<(usize, i64), HashMap>>, + /// Per committed window still kept, by `(group, window end)`, each + /// series' lineages. + committed: BTreeMap<(usize, i64), HashMap>>, + /// The windows a broken lineage made incomplete, while kept: their + /// records are no longer applied. + incomplete: BTreeSet<(usize, i64)>, +} + +/// What [`Staging::stage`] did with a request's states. +#[derive(Default)] +pub(crate) struct StagedRequest { + pub report: CollectorStateIngestReport, + /// States of closed windows still kept, by window, to merge into them + /// (or to store them with, when they closed without states). + pub late: BTreeMap>, + /// Windows this request made incomplete, to mark in the view store. + pub incomplete: Vec, } impl Staging { - /// Stages `states`, merging and deduplicating per series and window. A - /// state of a closed window still kept that is no duplicate is - /// returned, by window, to merge into it (or to store it with, when it - /// closed without states); one of a window past retention is late. A view's group - /// starts at the oldest window of its first states, and each group - /// with staged windows is to close through its newest. Counts each - /// state's outcome in `metrics`. + /// Stages `states`, applying each to its series' lineages in its + /// window (§8): a merged one is staged, merged into the staged state, + /// or, for a closed window still kept, returned to merge into it; one + /// of a window past retention is late; a broken one marks its window + /// incomplete. A view's group starts at the oldest window of its first + /// states, and each group with staged windows is to close through its + /// newest. Counts each state's outcome in `metrics`. pub fn stage( &mut self, states: Vec, ingestion: &mut Ingestion, now: ClockReading, metrics: &Metrics, - ) -> ( - CollectorStateIngestReport, - BTreeMap>, - ) { - let mut report = CollectorStateIngestReport::default(); - let mut late: BTreeMap> = BTreeMap::new(); + ) -> StagedRequest { + let mut request = StagedRequest::default(); + let report = &mut request.report; let mut oldest: BTreeMap = BTreeMap::new(); for state in &states { let end = oldest.entry(state.group).or_insert(state.end_ms); @@ -513,100 +591,130 @@ impl Staging { } // Committed windows no longer kept take no more states. let kept_after = ingestion.kept_after_ms(); - self.committed - .retain(|&(group, end), _| kept_after[group].is_none_or(|kept_after| end > kept_after)); + let kept = |&(group, end): &(usize, i64)| kept_after[group].is_none_or(|after| end > after); + self.committed.retain(|window, _| kept(window)); + self.incomplete.retain(kept); let mut newest: BTreeMap = BTreeMap::new(); for arrived in states { let view = arrived.node_id; let key = (arrived.group, arrived.end_ms); - if ingestion + let window = ClosedWindow { + group: arrived.group, + end_ms: arrived.end_ms, + }; + let closed = ingestion .closed_through(arrived.group) - .is_some_and(|through| arrived.end_ms <= through) - { - // A window closed without states (its first come after a - // later window's) is stored with them, if still kept. - let kept = - kept_after[arrived.group].is_none_or(|kept_after| arrived.end_ms > kept_after); - if !kept { - report.late_dropped += 1; - metrics - .collector_states - .outcome(view, outcome::LATE_DROPPED, 1); - continue; - } - let series = self.committed.entry(key).or_default(); - let hashes = series.entry(arrived.series.id).or_default(); - if hashes.contains(&arrived.hash) { - report.duplicate += 1; - metrics - .collector_states - .outcome(view, outcome::DUPLICATE, 1); - continue; - } - hashes.push(arrived.hash); - report.late_merged += 1; + .is_some_and(|through| arrived.end_ms <= through); + if closed && !kept(&key) { + report.late_dropped += 1; metrics .collector_states - .outcome(view, outcome::LATE_MERGED, 1); - let window = ClosedWindow { - group: arrived.group, - end_ms: arrived.end_ms, - }; - late.entry(window).or_default().push(Staged { - series: arrived.series, - state: arrived.state, - hashes: vec![arrived.hash], - }); + .outcome(view, outcome::LATE_DROPPED, 1); continue; } - let newest = newest.entry(arrived.group).or_insert(arrived.end_ms); - *newest = (*newest).max(arrived.end_ms); - let window = self.windows.entry(key).or_default(); - let Some(staged) = window.get_mut(&arrived.series.id) else { - window.insert( - arrived.series.id, - Staged { - series: arrived.series, - state: arrived.state, - hashes: vec![arrived.hash], - }, - ); - report.staged += 1; - metrics.collector_states.outcome(view, outcome::STAGED, 1); - continue; - }; - if staged.hashes.contains(&arrived.hash) { - report.duplicate += 1; + if self.incomplete.contains(&key) { + report.incomplete += 1; metrics .collector_states - .outcome(view, outcome::DUPLICATE, 1); + .outcome(view, outcome::INCOMPLETE, 1); continue; } - match staged.state.merge_with(&*arrived.state) { - Ok(merged) => { - staged.state = Arc::from(merged); - staged.hashes.push(arrived.hash); - report.merged += 1; - metrics.collector_states.outcome(view, outcome::MERGED, 1); + let applies = if closed { + // A window closed without states (its first come after a + // later window's) is stored with them. + let lineages = self + .committed + .entry(key) + .or_default() + .entry(arrived.series.id) + .or_default(); + let applies = arrived.apply_to(lineages); + if applies == Applies::Merged { + report.late_merged += 1; + metrics + .collector_states + .outcome(view, outcome::LATE_MERGED, 1); + request.late.entry(window).or_default().push(Staged { + series: arrived.series, + state: arrived.state, + lineages: Vec::new(), + }); } - Err(error) => { - *report.rejected.entry(reject::MERGE).or_default() += 1; + applies + } else { + let newest = newest.entry(arrived.group).or_insert(arrived.end_ms); + *newest = (*newest).max(arrived.end_ms); + let series = self.windows.entry(key).or_default(); + match series.get_mut(&arrived.series.id) { + None => { + let mut lineages = Vec::new(); + let applies = arrived.apply_to(&mut lineages); + if applies == Applies::Merged { + series.insert( + arrived.series.id, + Staged { + series: arrived.series, + state: arrived.state, + lineages, + }, + ); + report.staged += 1; + metrics.collector_states.outcome(view, outcome::STAGED, 1); + } + applies + } + Some(staged) => { + let mut lineages = staged.lineages.clone(); + let applies = arrived.apply_to(&mut lineages); + if applies == Applies::Merged { + match staged.state.merge_with(&*arrived.state) { + Ok(merged) => { + staged.state = Arc::from(merged); + staged.lineages = lineages; + report.merged += 1; + metrics.collector_states.outcome(view, outcome::MERGED, 1); + } + Err(error) => { + *report.rejected.entry(reject::MERGE).or_default() += 1; + metrics + .collector_states + .rejected(Some(view), reject::MERGE, 1); + tracing::warn!(view, %error, "a collector state does not merge with the staged one"); + } + } + } + applies + } + } + }; + match applies { + Applies::Merged => {} + Applies::Duplicate => { + report.duplicate += 1; + metrics + .collector_states + .outcome(view, outcome::DUPLICATE, 1); + } + Applies::Broken => { + report.incomplete += 1; metrics .collector_states - .rejected(Some(view), reject::MERGE, 1); - tracing::warn!(view, %error, "a collector state does not merge with the staged one"); + .outcome(view, outcome::INCOMPLETE, 1); + self.incomplete.insert(key); + request.incomplete.push(window); } } } for (group, end_ms) in newest { ingestion.collector_arrived(group, end_ms, now); } - (report, late) + request } /// The states staged for `window`, removed, for it to commit; empty - /// when none is (it is then not stored). Their hashes are kept while - /// the window is, so a repeat is a duplicate. + /// when none is (it is then stored empty). Their lineages are kept + /// while the window is, so a record already applied is a duplicate and + /// a delta finds its base. pub fn take(&mut self, window: ClosedWindow) -> Vec { let key = (window.group, window.end_ms); let staged: Vec = self @@ -615,12 +723,12 @@ impl Staging { .map(|series| series.into_values().collect()) .unwrap_or_default(); if !staged.is_empty() { - let hashes = self.committed.entry(key).or_default(); + let lineages = self.committed.entry(key).or_default(); for state in &staged { - hashes + lineages .entry(state.series.id) .or_default() - .extend(&state.hashes); + .extend(&state.lineages); } } staged @@ -756,7 +864,7 @@ mod tests { staged.push(Staged { series: intern_pairs(&[("__name__", "data"), ("job", &job)]), state: view.decoder.decode(&sketch.to_asapv1().unwrap()).unwrap(), - hashes: Vec::new(), + lineages: Vec::new(), }); } let window = ClosedWindow { @@ -791,21 +899,31 @@ mod tests { assert_eq!(charge(collected), charge(computed)); } - fn state(group: usize, end_ms: i64, hash: u64) -> ArrivedState { + /// A record of the one series' lineage of epoch `epoch` in the window + /// ending `end_ms` of group `group`: sequence `sequence`, a full when 0, + /// else a delta on the record before. + fn record(group: usize, end_ms: i64, epoch: u64, sequence: u64) -> ArrivedState { ArrivedState { group, node_id: 0, series: intern_pairs(&[("__name__", "data"), ("job", "collector-unit")]), end_ms, - hash, + epoch, + sequence, + kind: match sequence { + 0 => StateKind::Full, + n => StateKind::Delta { + base_sequence: n - 1, + }, + }, state: Arc::new(DDSketchAccumulator::new(0.05)), } } /// A request's windows close through its newest when it ends, in any - /// order within it. A later state of a closed window still kept is - /// returned to merge into it (or to store it with) unless it repeats - /// one seen; a state of a window past retention is late. + /// order within it. A later record of a closed window still kept is + /// returned to merge into it (or to store it with) unless it was + /// applied already; a record of a window past retention is late. #[test] fn windows_close_through_the_newest_staged_and_later_states_merge() { let (mut ingestion, width) = ingestion(); @@ -813,21 +931,22 @@ mod tests { let mut staging = Staging::default(); let earlier = 100 * width; let newest = earlier + width; - // The newest window first, then the earlier one, and a partial and - // a repeat of the newest. - let (report, late) = staging.stage( + // The newest window first, then the earlier one, a second epoch's + // full of the newest (a restarted collector) and a repeat. + let request = staging.stage( vec![ - state(0, newest, 1), - state(0, earlier, 2), - state(0, newest, 4), - state(0, newest, 1), + record(0, newest, 1, 0), + record(0, earlier, 1, 0), + record(0, newest, 2, 0), + record(0, newest, 1, 0), ], &mut ingestion, ClockReading::default(), &metrics, ); + let report = request.report; assert_eq!((report.staged, report.merged, report.duplicate), (2, 1, 1)); - assert!(late.is_empty()); + assert!(request.late.is_empty()); let closed = ingestion.close(); assert_eq!( closed.iter().map(|w| w.end_ms).collect::>(), @@ -836,28 +955,32 @@ mod tests { for window in &closed { assert_eq!(staging.take(*window).len(), 1); } - // Later states of the committed windows: new ones merge, repeats - // (of a state committed, or merged later) are duplicates. - let (report, late) = staging.stage( + // Later records of the committed windows: a delta on its base + // merges, records applied already (committed, or merged later) + // are duplicates. + let request = staging.stage( vec![ - state(0, earlier, 3), - state(0, earlier, 3), - state(0, earlier, 2), - state(0, newest, 4), + record(0, earlier, 1, 1), + record(0, earlier, 1, 1), + record(0, earlier, 1, 0), + record(0, newest, 2, 0), ], &mut ingestion, ClockReading::default(), &metrics, ); - assert_eq!((report.late_merged, report.duplicate), (1, 3)); - let windows: Vec = late.keys().map(|w| w.end_ms).collect(); + assert_eq!( + (request.report.late_merged, request.report.duplicate), + (1, 3) + ); + let windows: Vec = request.late.keys().map(|w| w.end_ms).collect(); assert_eq!(windows, [earlier]); // A request two windows on: the window between closes with no - // state; its states coming later are to store it with, and a + // state; its records coming later are to store it with, and a // repeat of one is a duplicate. let latest = newest + 2 * width; staging.stage( - vec![state(0, latest, 5)], + vec![record(0, latest, 1, 0)], &mut ingestion, ClockReading::default(), &metrics, @@ -868,22 +991,135 @@ mod tests { staging.take(*window); } let between = newest + width; - let (report, late) = staging.stage( - vec![state(0, between, 6), state(0, between, 6)], + let request = staging.stage( + vec![record(0, between, 1, 0), record(0, between, 1, 0)], &mut ingestion, ClockReading::default(), &metrics, ); - assert_eq!((report.late_merged, report.duplicate), (1, 1)); - assert_eq!(late.keys().map(|w| w.end_ms).collect::>(), [between]); + assert_eq!( + (request.report.late_merged, request.report.duplicate), + (1, 1) + ); + assert_eq!( + request.late.keys().map(|w| w.end_ms).collect::>(), + [between] + ); // One past the view's retention is late. - let (report, late) = staging.stage( - vec![state(0, earlier - 100 * width, 7)], + let request = staging.stage( + vec![record(0, earlier - 100 * width, 1, 0)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!(request.report.late_dropped, 1); + assert!(request.late.is_empty()); + } + + /// Two corrections with equal bytes (two late samples of equal value) + /// are two records, sequences 1 and 2: both merge. The old duplicate + /// check by bytes kept only the first. + #[test] + fn corrections_with_equal_bytes_both_merge() { + let (mut ingestion, width) = ingestion(); + let metrics = Metrics::new(&[]); + let mut staging = Staging::default(); + let end = 100 * width; + staging.stage( + vec![record(0, end, 1, 0)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + for window in ingestion.close() { + staging.take(window); + } + let request = staging.stage( + vec![record(0, end, 1, 1), record(0, end, 1, 2)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + assert_eq!( + (request.report.late_merged, request.report.duplicate), + (2, 0) + ); + assert_eq!(request.late.values().map(Vec::len).sum::(), 2); + } + + /// A delta after a gap (sequence 2 with 1 lost), a delta of an epoch + /// whose full never came (a restarted collector's lost full), and a + /// delta of a window with no lineage are never applied: each marks its + /// window incomplete, once, and later records of the window are not + /// applied either. Windows with whole lineages are untouched, staged or + /// committed. + #[test] + fn a_broken_lineage_marks_its_window_incomplete() { + let (mut ingestion, width) = ingestion(); + let metrics = Metrics::new(&[]); + let mut staging = Staging::default(); + let (first, second, third) = (100 * width, 101 * width, 102 * width); + staging.stage( + vec![record(0, first, 1, 0), record(0, second, 1, 0)], + &mut ingestion, + ClockReading::default(), + &metrics, + ); + for window in ingestion.close() { + staging.take(window); + } + let request = staging.stage( + vec![ + // A gap in the committed first window. + record(0, first, 1, 2), + // The second window's lineage of epoch 1 is whole; a new + // epoch's delta has no full. + record(0, second, 1, 1), + record(0, second, 2, 1), + // A staged window: a delta before any full. + record(0, third, 1, 1), + // The first window again: incomplete, not applied. + record(0, first, 3, 0), + ], &mut ingestion, ClockReading::default(), &metrics, ); - assert_eq!(report.late_dropped, 1); - assert!(late.is_empty()); + let report = &request.report; + assert_eq!((report.late_merged, report.incomplete), (1, 4)); + assert_eq!( + request + .incomplete + .iter() + .map(|w| w.end_ms) + .collect::>(), + [first, second, third] + ); + // The first window's lineage stayed at sequence 0: the gap's delta + // was not taken as its base. + assert_eq!( + staging.committed[&(0, first)].values().next().unwrap(), + &vec![Lineage { + epoch: 1, + last_sequence: 0 + }] + ); + } + + /// A collector-views file's declared close delay, plus the skew + /// allowance, is the idle close. + #[test] + fn the_idle_close_is_the_files_close_delay_plus_skew() { + let plan = one_query_plan("sum_over_time(data[1m])", false); + let file = common::CollectorViewsFile { + planner_wire_version: 16, + plan_id: plan.dag.plan_id(), + backend_reads_raw: BTreeMap::new(), + window_close_delay_ms: 3_000, + outputs: Vec::new(), + dag: plan.dag.clone(), + }; + assert_eq!(CollectorViewOptions::from(&file).idle_close_ms, 5_000); + assert_eq!(CollectorViewOptions::default().idle_close_ms, 8_000); } } diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index bf07384d8..f0bc7cce9 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -194,6 +194,9 @@ enum PrecomputeJob { states: Vec, samples: u64, }, + /// A collector view's window a broken lineage made incomplete: marked, + /// with the windows built from it, so no query answers from them. + Incomplete { window: ClosedWindow }, /// A collector view's window, with the states staged for it. Collector { window: ClosedWindow, @@ -1283,14 +1286,16 @@ fn serve_ingest( } // The collector states this pass took: their windows close below. let mut collector_late: BTreeMap> = BTreeMap::new(); + let mut collector_incomplete = Vec::new(); let mut collector_committed = Vec::new(); for (states, reply, committed) in collector_requests.drain(..) { - let (report, late) = + let request = staging.stage(states, &mut ingestion, shared.clock.read(), &shared.metrics); - let _ = reply.send(report); - for (window, states) in late { + let _ = reply.send(request.report); + for (window, states) in request.late { collector_late.entry(window).or_default().extend(states); } + collector_incomplete.extend(request.incomplete); collector_committed.push(committed); } // The barriers first, so a window one of them closes is not @@ -1387,6 +1392,11 @@ fn serve_ingest( break 'serve; } } + for window in collector_incomplete { + if jobs.send(PrecomputeJob::Incomplete { window }).is_err() { + break 'serve; + } + } // Each collector request is answered once the windows its states // closed, and the merges queued before, are committed. for committed in collector_committed { @@ -1859,6 +1869,8 @@ fn serve_precompute( // closed so far (jobs come in the order windows close). let mut closed_through: Vec> = vec![None; precompute.groups().len()]; let mut closed = false; + // Collector view windows to mark incomplete in this pass. + let mut incomplete: Vec = Vec::new(); while !(closed && tasks.is_empty()) { let Ok(event) = inbox.recv() else { break; @@ -1912,6 +1924,7 @@ fn serve_precompute( pending.states.extend(states); pending.samples += samples; } + PoolEvent::Job(PrecomputeJob::Incomplete { window }) => incomplete.push(window), PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { tasks.barrier(barrier_ms, reply) } @@ -1972,6 +1985,10 @@ fn serve_precompute( committed = true; slots.release(); } + for window in incomplete.drain(..) { + precompute.mark_incomplete(window, &mut views); + committed = true; + } let ready: Vec = late .keys() .copied() diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 9b07e8d99..3b7e1f597 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -1685,6 +1685,21 @@ impl Precompute { found } + /// Marks the collector view window `window` incomplete in `views`, and + /// the window of each group reading its views, transitively, that + /// covers it: a query reading any of them is not answered from the + /// plan (§8). + pub(crate) fn mark_incomplete(&self, window: ClosedWindow, views: &mut Arc) { + let store = Arc::make_mut(views); + for group in self.readers_of(window.group) { + let run = &self.runs[group]; + let end = run.window_end(window.end_ms); + for view in &run.views { + store.mark_incomplete(view.node_id, end); + } + } + } + /// Takes the late samples `raw_data` of the committed `window` into it, /// and the change into the committed windows of the groups reading its /// views, transitively ([`Self::late_ready`] must hold), in plan order diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 7d3cedb72..ce2148dc4 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1439,6 +1439,10 @@ pub struct ViewStore { /// Where the producer's stream starts, when declared: no view has data /// before it, so a view with no window yet reads as empty there. stream_start_ms: Option, + /// The windows marked incomplete ([`Self::mark_incomplete`]), by view + /// and end, while within their view's retention: a read of a range + /// holding one fails as a read of a missing window does. + incomplete: BTreeSet<(PhysicalASAPNodeId, i64)>, /// How many windows late samples revised ([`Self::merge_late`]). revision: u64, /// Each revision of the newest [`REVISIONS_KEPT`]: the end of the @@ -1529,6 +1533,23 @@ impl ViewStore { } kept }); + if !self.incomplete.is_empty() { + let view = view.node_id; + self.incomplete + .retain(|&(marked, end)| marked != view || end > oldest_kept_end); + } + } + + /// Marks `view`'s window ending `end_ms` incomplete, stored or not: a + /// collector view window some of whose states were lost, or a window + /// built from one. A read of a range holding it fails, as a read of a + /// missing window does, so no query answers from it; a result cached + /// from it is stale. The mark goes when the window leaves the view's + /// retention. + pub fn mark_incomplete(&mut self, view: PhysicalASAPNodeId, end_ms: i64) { + if self.incomplete.insert((view, end_ms)) { + self.revised(end_ms); + } } /// Adds `view`'s window covering `time_range_ms` already written at @@ -1964,6 +1985,20 @@ impl ViewStore { if covered_to != end { return Err(missing()); } + let after_start = start.saturating_add(1); + if let Some((_, incomplete)) = (after_start <= end) + .then(|| { + self.incomplete + .range((view.node_id, after_start)..=(view.node_id, end)) + .next() + }) + .flatten() + { + return Err(Error::Invalid(format!( + "materialized view {}: its window ending {incomplete} is incomplete (a collector state was lost), so ({requested_start}, {end}] cannot be read whole", + view.node_id + ))); + } // Cold windows are decoded as the stream is pulled, so a run holds // one decoded window at a time beyond what the cache keeps. Ok( @@ -2975,6 +3010,57 @@ mod tests { } } + /// A window marked incomplete (a collector state of it was lost) fails + /// every read of a range holding it, stored or not, as a missing window + /// does; ranges beside it read. The mark goes once the window leaves + /// the view's retention. + #[test] + fn a_range_holding_an_incomplete_window_is_not_read() { + 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": 30, + })) + .unwrap(); + let mut views = ViewStore::default().with_stream_start(Some(0)); + for end in [10, 20, 30] { + views.append(&view, (end - 10, end), Vec::new()).unwrap(); + } + let revision = views.revision(); + views.mark_incomplete(1, 20); + assert!(views.changed_since(revision, 20)); + let context = RunContext::new( + asap_executor::runtime::Scope::Query { + evaluation_time_ms: 30, + }, + asap_executor::runtime::Limits::default(), + ) + .unwrap(); + let schema = schema(); + let read = |views: &ViewStore, range| { + let request = MaterializedViewRequest { + time_range_ms: range, + schema: &schema, + }; + views.read(&view, &request, context.clone()).is_ok() + }; + assert!(!read(&views, (10, 20))); + assert!(!read(&views, (0, 30))); + assert!(read(&views, (0, 10))); + assert!(read(&views, (20, 30))); + assert!(read(&views, (20, 20))); + // Two windows on, the window ending 20 is past retention. + for end in [40, 50] { + views.append(&view, (end - 10, end), Vec::new()).unwrap(); + } + assert!(views.incomplete.is_empty()); + } + /// When the watermark jumps past a view's retention, its windows that /// would already be dropped are never built, so its first stored window /// starts after the stream start: the skipped windows had data, and a