From 03406863d2b481d8489dab2ad829bf82193d1862 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 15:57:05 +0000 Subject: [PATCH 1/4] test(collector views): reorder buffer, persisted incomplete marks, lineage frame (failing first) Tests for decisions 30, 31 and 34 of the design doc (section 8), with stubs for the new interfaces: - common: the lineage frame's pinned bytes for sequences 0, 1, 300 and u64::MAX (the collector's encoder holds the same vectors) and each refusal with its reason. - otlp: a state's sequence and kind come from the frame in sketch.envelope, the record's bytes are those behind it, and a bare ASAPv1 state, frame version 2, or a self-contradicting frame refuses the request. - storage: incomplete marks are indexed after a restart (stored windows or not, whatever revision is read later, not past retention); a version 5 segment reads with no marks. - precompute: records before their base wait for it and apply in order (closed and open windows, a new epoch's delta before its full); a base still missing past the reorder wait marks the window incomplete, not before; the reorder wait is the file's close delay. - data plane: a gap is held, then incomplete after the close delay; records out of order in separate requests answer as in-order ones; an incomplete window stays incomplete after a restart over the view files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/adapters/ingest/otlp/src/tests.rs | 73 +++----- crates/common/src/lib.rs | 4 +- crates/common/src/view_states.rs | 67 +++++++ crates/data-plane/tests/collector_views.rs | 175 +++++++++++++++--- crates/precompute/src/collector.rs | 202 +++++++++++++++++---- crates/storage/src/persist.rs | 126 ++++++++++++- crates/storage/src/segment.rs | 3 + 7 files changed, 534 insertions(+), 116 deletions(-) diff --git a/crates/adapters/ingest/otlp/src/tests.rs b/crates/adapters/ingest/otlp/src/tests.rs index 00e9ca148..817e547d2 100644 --- a/crates/adapters/ingest/otlp/src/tests.rs +++ b/crates/adapters/ingest/otlp/src/tests.rs @@ -1,4 +1,5 @@ use super::*; +use common::StateKind; use proto::collector::metrics::v1::{ExportMetricsServiceRequest, ExportMetricsServiceResponse}; use proto::common::v1::{any_value, AnyValue, InstrumentationScope, KeyValue}; use proto::metrics::v1::{ @@ -904,16 +905,19 @@ fn view_metadata(node: i64, key: &str) -> Vec { } /// A state point of the window ending at `WINDOW_END_MS`, as the collector -/// 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 { +/// exports one: the series' attributes and `sketch.envelope`, the state +/// `asapv1` behind a full's lineage frame (sequence 0). +fn state_point(attributes: Vec, asapv1: &[u8], count: u64) -> SummaryDataPoint { + framed_point(attributes, &common::frame_lineage(0, asapv1), count) +} + +/// [`state_point`] with `envelope` as the `sketch.envelope` bytes as is. +fn framed_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, @@ -1097,55 +1101,38 @@ fn a_bad_view_identity_refuses_the_request() { 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. +/// A state point's lineage frame: a delta carries its sequence and base, +/// the state's bytes are those behind the frame, and the frame is no label. +/// A bare ASAPv1 state (a collector from before the frame), another frame +/// version and a frame that disagrees with itself 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), - )); - } +fn lineage_frames_are_decoded_and_checked() { + let with_envelope = |envelope: Vec| { + let point = framed_point(vec![text("region", "a")], &envelope, 1); 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 asapv1 = b"ASAPv1\x01state".to_vec(); + let views = decoded(&encode(&request(vec![with_envelope( + common::frame_lineage(3, &asapv1), + )]))) + .unwrap() + .view_states + .views; let series = &views[0].series[0]; assert_eq!(views[0].producer_epoch, 7); + let record = &series.records[0]; assert_eq!( - (series.records[0].sequence, series.records[0].kind), + (record.sequence, record.kind), (3, StateKind::Delta { base_sequence: 2 }) ); + assert_eq!(record.asapv1, asapv1); 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")); + assert!(refused(with_envelope(asapv1.clone())).contains("without a lineage frame")); + assert!(refused(with_envelope(vec![0xA2, 0, 0])).contains("version 2")); + assert!(refused(with_envelope(vec![0xA1, 0x01, 0x03, 0x01])).contains("base 1")); + assert!(refused(with_envelope(vec![0xA1, 0x00, 0x02])).contains("a full has sequence 2")); } diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index 56a774b79..072a48ff8 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, StateKind, ViewStateBatch, - ViewStateKey, ViewStateRecord, + frame_lineage, unframe_lineage, view_identity, CollectorSeriesStates, CollectorViewStates, + StateKind, ViewStateBatch, ViewStateKey, ViewStateRecord, LINEAGE_FRAME_V1, }; /// 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 6e1a6d1c5..94d739a08 100644 --- a/crates/common/src/view_states.rs +++ b/crates/common/src/view_states.rs @@ -93,3 +93,70 @@ pub mod view_identity { /// A delta's base: the sequence it applies onto. pub const BASE_SEQUENCE: &str = "asap.base_sequence"; } + +/// The first byte of a version 1 lineage frame (not implemented yet). +pub const LINEAGE_FRAME_V1: u8 = 0xA1; + +/// Not implemented yet. +pub fn unframe_lineage(_bytes: &[u8]) -> Result<(u64, StateKind, &[u8]), String> { + Err("lineage frames are not implemented yet".into()) +} + +/// Not implemented yet: `asapv1` as is. +pub fn frame_lineage(_sequence: u64, asapv1: &[u8]) -> Vec { + asapv1.to_vec() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The collector's frame bytes, pinned: ASAPCollector-public's + /// `envelope::Lineage::frame` holds the same vectors. + #[test] + fn lineage_frames_are_these_bytes_and_round_trip() { + let asapv1 = b"ASAPv1\x01rest"; + let cases: [(u64, StateKind, &[u8]); 3] = [ + (0, StateKind::Full, &[0xA1, 0x00, 0x00]), + ( + 1, + StateKind::Delta { base_sequence: 0 }, + &[0xA1, 0x01, 0x01, 0x00], + ), + ( + 300, + StateKind::Delta { base_sequence: 299 }, + &[0xA1, 0x01, 0xAC, 0x02, 0xAB, 0x02], + ), + ]; + for (sequence, kind, head) in cases { + let framed = frame_lineage(sequence, asapv1); + assert_eq!(&framed[..head.len()], head, "sequence {sequence}"); + assert_eq!(&framed[head.len()..], asapv1); + assert_eq!(unframe_lineage(&framed), Ok((sequence, kind, &asapv1[..]))); + } + let max = frame_lineage(u64::MAX, asapv1); + assert_eq!(unframe_lineage(&max).unwrap().0, u64::MAX); + } + + /// Bytes that are no version 1 lineage frame, or whose kind disagrees + /// with its sequence and base, are refused, saying why. + #[test] + fn bad_lineage_frames_are_refused() { + let refused = |bytes: &[u8]| unframe_lineage(bytes).unwrap_err(); + assert!(refused(b"ASAPv1\x01rest").contains("without a lineage frame")); + assert!(refused(&[0xA2, 0x00, 0x00]).contains("version 2")); + assert!(refused(&[0x00]).contains("not a lineage frame")); + assert!(refused(&[]).contains("not a lineage frame")); + assert!(refused(&[0xA1]).contains("truncated")); + assert!(refused(&[0xA1, 0x02, 0x00]).contains("flags")); + assert!(refused(&[0xA1, 0x00, 0x80]).contains("truncated")); + assert!(refused(&[0xA1, 0x00, 0x01]).contains("a full has sequence 1")); + assert!(refused(&[0xA1, 0x01, 0x00, 0x00]).contains("base")); + assert!(refused(&[0xA1, 0x01, 0x03, 0x01]).contains("base 1")); + let overflow = [ + 0xA1, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x02, + ]; + assert!(refused(&overflow).contains("overflows")); + } +} diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs index 8fadf3a13..8f7a6b7cf 100644 --- a/crates/data-plane/tests/collector_views.rs +++ b/crates/data-plane/tests/collector_views.rs @@ -5,9 +5,10 @@ //! queries as the view the data plane builds from the same samples does. //! //! The OTLP bodies are built as the collector's OTAP codec writes a -//! summary point, with the view identity in the metric's metadata and the -//! state as `asap_sketchlib`'s ASAPv1 bytes of a `DdSketch` fed the samples -//! of one series and window, as the collector's processor builds it. +//! summary point, with the view identity and producer epoch in the +//! metric's metadata and the state as `asap_sketchlib`'s ASAPv1 bytes of a +//! `DdSketch` fed the samples of one series and window, as the collector's +//! processor builds it, behind its lineage frame. mod common; @@ -128,6 +129,34 @@ fn collector_data_plane(plan: &InstallablePlan, node: usize) -> (Router, Arc, +) -> (Router, Arc) { + let options = EngineOptions { + precompute_mode: PrecomputeMode::Push, + collector: CollectorViewOptions { + plan_id: Some(plan.dag.plan_id()), + views: BTreeSet::from([node]), + ..CollectorViewOptions::default() + }, + clock: clock.clone(), + view_dir: view_dir.map(Path::to_path_buf), + ..no_forward(0) + }; + data_plane(plan, options) +} + +/// The default collector's close delay: how long a record waits for its +/// base before its window is incomplete. +fn reorder_wait_ms() -> i64 { + CollectorViewOptions::default().reorder_wait_ms as i64 +} + /// One second's samples of each job in `(from_ms, to_ms]`. fn samples(job: &str, from_ms: i64, to_ms: i64) -> Vec<(i64, f64)> { (from_ms / 1000 + 1..=to_ms / 1000) @@ -201,25 +230,6 @@ struct State { 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 /// identity as the collector reads it from its copy of the plan. fn body(plan: &InstallablePlan, node: usize, width_ms: i64, states: &[State]) -> Vec { @@ -260,12 +270,14 @@ fn body(plan: &InstallablePlan, node: usize, width_ms: i64, states: &[State]) -> KeyValue { key: "sketch.envelope".into(), value: Some(AnyValue { - value: Some(any_value::Value::BytesValue(state.asapv1.clone())), + value: Some(any_value::Value::BytesValue(::common::frame_lineage( + state.sequence, + &state.asapv1, + ))), }), }, ] .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, @@ -1031,7 +1043,8 @@ async fn open_window_deltas_answer_and_end_at_the_close_answer() { assert_eq!(answer, expected); } -/// A delta whose base never came (sequence 2 after 0) is not applied: the +/// A delta whose base never came (sequence 2 after 0) is held for it; once +/// the collector's close delay passes without it, it 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. @@ -1040,7 +1053,8 @@ 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); + let clock = precompute::ingestion::WallClock::manual(time_ms + 1_000); + let (app, state) = collector_data_plane_on(&plan, node, &clock, None); // 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); @@ -1056,9 +1070,13 @@ async fn a_gap_leaves_the_window_unanswered() { post(&app, body(&plan, node, width_ms, &[after_gap])).await, 0 ); + assert_eq!(metric(&state, &outcome_line(node, "held")), 1.0); + common::barrier(&app, 0).await; + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 0.0); + clock.set(time_ms + 1_000 + reorder_wait_ms()); + common::barrier(&app, 0).await; 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); @@ -1113,16 +1131,20 @@ async fn a_restarted_collector_resynchronizes_with_a_full() { 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); + // The restarted instance's full is lost: its delta has no base, and + // its window is incomplete once the close delay passes. + let clock = precompute::ingestion::WallClock::manual(time_ms + 1_000); + let (app, state) = collector_data_plane_on(&plan, node, &clock, None); 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); + assert_eq!(metric(&state, &outcome_line(node, "held")), 1.0); + clock.set(time_ms + 1_000 + reorder_wait_ms()); common::barrier(&app, 0).await; + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 1.0); let (status, _, _) = common::get(&app, &common::instant_uri(QUERY, time_ms / 1000)).await; assert_ne!(status, StatusCode::OK); } @@ -1170,3 +1192,96 @@ async fn windows_of_a_stopped_collector_close_after_the_declared_delay() { assert_eq!(status, StatusCode::OK, "{answer}"); assert_eq!(answer, expected); } + +/// A collector exporting concurrently: its records of one window arrive +/// out of order, the full's deltas 2 then 1 and a restarted instance's +/// delta before its full, each in its own request. Each is held until its +/// base comes, then applied: nothing is incomplete, and the window answers +/// as all its samples do. +#[tokio::test(flavor = "multi_thread")] +async fn records_out_of_order_answer_as_in_order_ones() { + 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() >= 4, "a window of at least four samples"); + let n = whole.len(); + let parts = [ + &whole[..n / 4], + &whole[n / 4..n / 2], + &whole[n / 2..3 * n / 4], + &whole[3 * n / 4..], + ]; + let (app, state) = collector_data_plane(&plan, node); + 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); + assert_eq!(post(&app, body(&plan, node, width_ms, &emitted)).await, 0); + for state in [ + record(alpha, "a", time_ms, parts[2], 1, 2), + record(alpha, "a", time_ms, parts[3], 2, 1), + record(alpha, "a", time_ms, parts[1], 1, 1), + ] { + assert_eq!(post(&app, body(&plan, node, width_ms, &[state])).await, 0); + } + assert_eq!(metric(&state, &outcome_line(node, "held")), 2.0); + // The restarted instance's full of no samples, last. + let full = record(alpha, "a", time_ms, &[], 2, 0); + assert_eq!(post(&app, body(&plan, node, width_ms, &[full])).await, 0); + assert_eq!(metric(&state, &outcome_line(node, "late_merged")), 4.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); +} + +/// A window marked incomplete stays incomplete after the data plane +/// restarts over its view files: the windows it persisted are loaded and +/// answer, but a query reading the incomplete one is still not answered +/// from the plan (it is forwarded). +#[tokio::test(flavor = "multi_thread")] +async fn an_incomplete_window_stays_incomplete_after_a_restart() { + 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 earlier_ms = time_ms - 10_000; + let dir = + std::env::temp_dir().join(format!("asap-collector-incomplete-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let clock = precompute::ingestion::WallClock::manual(time_ms + 1_000); + let (app, state) = collector_data_plane_on(&plan, node, &clock, Some(&dir)); + 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 after_gap = record(alpha, "a", time_ms, &[(time_ms - 1, 1.0)], 1, 2); + assert_eq!( + post(&app, body(&plan, node, width_ms, &[after_gap])).await, + 0 + ); + clock.set(time_ms + 1_000 + reorder_wait_ms()); + common::barrier(&app, 0).await; + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 1.0); + let newest = common::instant_uri(QUERY, time_ms / 1000); + let earlier = common::instant_uri(QUERY, earlier_ms / 1000); + let (status, _, _) = common::get(&app, &newest).await; + assert_ne!(status, StatusCode::OK); + let (status, _, before) = common::get(&app, &earlier).await; + assert_eq!(status, StatusCode::OK, "{before}"); + drop((app, state)); + + let (app, state) = collector_data_plane_on(&plan, node, &clock, Some(&dir)); + assert!(metric(&state, "asap_view_windows_loaded_total") > 0.0); + let (status, _, after) = common::get(&app, &earlier).await; + assert_eq!(status, StatusCode::OK, "{after}"); + assert_eq!(after, before); + let (status, _, body_text) = common::get(&app, &newest).await; + assert_ne!(status, StatusCode::OK, "still incomplete: {body_text}"); + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 9c17589cd..475486c7e 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -57,6 +57,8 @@ pub struct CollectorViewOptions { /// window: the collector's window close delay and an allowance for /// clock skew. States of it coming later merge in. pub idle_close_ms: u64, + /// Not implemented yet: how long a record waits for its base. + pub reorder_wait_ms: u64, } /// What the idle close allows for clock skew between the collector and @@ -71,6 +73,7 @@ impl Default for CollectorViewOptions { plan_id: None, views: BTreeSet::new(), idle_close_ms: 6_000 + CLOCK_SKEW_ALLOWANCE_MS, + reorder_wait_ms: 0, } } } @@ -86,6 +89,7 @@ impl From<&common::CollectorViewsFile> for CollectorViewOptions { idle_close_ms: file .window_close_delay_ms .saturating_add(CLOCK_SKEW_ALLOWANCE_MS), + reorder_wait_ms: 0, } } } @@ -130,6 +134,8 @@ pub struct CollectorStateIngestReport { /// full), or any record of a window already incomplete. Its window is /// marked incomplete. pub incomplete: u64, + /// Not implemented yet: held for its base. + pub held: u64, /// Rejected, by reason ([`reject`]). pub rejected: BTreeMap<&'static str, u64>, } @@ -551,6 +557,8 @@ pub(crate) struct Staging { /// The windows a broken lineage made incomplete, while kept: their /// records are no longer applied. incomplete: BTreeSet<(usize, i64)>, + /// Not implemented yet: the reorder buffer. + held: BTreeMap<(usize, i64), ()>, } /// What [`Staging::stage`] did with a request's states. @@ -711,6 +719,16 @@ impl Staging { request } + /// Not implemented yet: nothing is held. + pub fn expire_held( + &mut self, + _ingestion: &Ingestion, + _now: ClockReading, + _metrics: &Metrics, + ) -> Vec { + Vec::new() + } + /// The states staged for `window`, removed, for it to commit; empty /// 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 @@ -1047,22 +1065,29 @@ mod tests { 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. + /// Monotonic (and wall-clock) time `ms`. + fn at(ms: i64) -> ClockReading { + ClockReading { + wall_ms: ms, + monotonic_ms: ms, + } + } + + /// A collector exporting concurrently: a delta that comes before its + /// lineage's previous record, and a new epoch's delta before its full, + /// are held, then applied in order once their bases come (in a closed + /// window through the late merge path, in an open one staged). A + /// repeat of a held record is a duplicate. Nothing is incomplete. #[test] - fn a_broken_lineage_marks_its_window_incomplete() { + fn records_before_their_base_wait_for_it() { let (mut ingestion, width) = ingestion(); let metrics = Metrics::new(&[]); let mut staging = Staging::default(); - let (first, second, third) = (100 * width, 101 * width, 102 * width); + let (first, second) = (100 * width, 101 * width); staging.stage( - vec![record(0, first, 1, 0), record(0, second, 1, 0)], + vec![record(0, first, 1, 0)], &mut ingestion, - ClockReading::default(), + at(0), &metrics, ); for window in ingestion.close() { @@ -1070,44 +1095,143 @@ mod tests { } let request = staging.stage( vec![ - // A gap in the committed first window. + record(0, first, 1, 3), 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), + record(0, first, 2, 1), + record(0, first, 1, 3), ], &mut ingestion, - ClockReading::default(), + at(10), &metrics, ); 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] + (report.held, report.duplicate, report.late_merged), + (3, 1, 0) ); - // The first window's lineage stayed at sequence 0: the gap's delta - // was not taken as its base. + assert!(request.late.is_empty()); + let request = staging.stage( + vec![record(0, first, 1, 1), record(0, first, 2, 0)], + &mut ingestion, + at(20), + &metrics, + ); + let report = &request.report; + assert_eq!( + (report.late_merged, report.held, report.incomplete), + (5, 0, 0) + ); + assert_eq!( + request.late[&ClosedWindow { + group: 0, + end_ms: first + }] + .len(), + 5 + ); + assert!(staging.held.is_empty()); assert_eq!( staging.committed[&(0, first)].values().next().unwrap(), - &vec![Lineage { - epoch: 1, - last_sequence: 0 + &vec![ + Lineage { + epoch: 1, + last_sequence: 3 + }, + Lineage { + epoch: 2, + last_sequence: 1 + } + ] + ); + // An open window: the delta first, then its full, in one request. + let request = staging.stage( + vec![record(0, second, 1, 1), record(0, second, 1, 0)], + &mut ingestion, + at(30), + &metrics, + ); + let report = &request.report; + assert_eq!((report.held, report.staged, report.merged), (1, 1, 1)); + assert!(staging + .expire_held(&ingestion, at(1_000_000), &metrics) + .is_empty()); + } + + /// A held record whose base has not come once the reorder wait (the + /// collector's declared close delay) has passed marks its window + /// incomplete, once, and the window's other held records are dropped; + /// later records of the window are not applied. Before the wait, + /// nothing is marked; other windows are untouched. + #[test] + fn a_base_missing_past_the_reorder_wait_marks_its_window_incomplete() { + let (mut ingestion, width) = ingestion(); + let wait = CollectorViewOptions::default().reorder_wait_ms as i64; + 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, + at(0), + &metrics, + ); + for window in ingestion.close() { + staging.take(window); + } + // A gap in the first window (sequence 1 lost), and a new epoch's + // delta whose full was lost. + let request = staging.stage( + vec![record(0, first, 1, 2), record(0, first, 2, 1)], + &mut ingestion, + at(100), + &metrics, + ); + assert_eq!(request.report.held, 2); + assert!(staging + .expire_held(&ingestion, at(100 + wait - 1), &metrics) + .is_empty()); + assert_eq!( + staging.expire_held(&ingestion, at(100 + wait), &metrics), + [ClosedWindow { + group: 0, + end_ms: first + }] + ); + assert!(staging.held.is_empty()); + // Its base, late: the window is incomplete, nothing is applied. + let request = staging.stage( + vec![record(0, first, 1, 1), record(0, second, 1, 1)], + &mut ingestion, + at(200 + wait), + &metrics, + ); + let report = &request.report; + assert_eq!((report.incomplete, report.late_merged), (1, 1)); + assert_eq!( + request.late.keys().map(|w| w.end_ms).collect::>(), + [second] + ); + // An open window's delta whose full never comes. + staging.stage( + vec![record(0, third, 1, 1)], + &mut ingestion, + at(300 + wait), + &metrics, + ); + assert_eq!( + staging.expire_held(&ingestion, at(300 + 2 * wait), &metrics), + [ClosedWindow { + group: 0, + end_ms: third }] ); + assert!(staging + .expire_held(&ingestion, at(400 + 2 * wait), &metrics) + .is_empty()); } /// A collector-views file's declared close delay, plus the skew - /// allowance, is the idle close. + /// allowance, is the idle close; the delay alone is the reorder wait. #[test] fn the_idle_close_is_the_files_close_delay_plus_skew() { let plan = one_query_plan("sum_over_time(data[1m])", false); @@ -1119,7 +1243,15 @@ mod tests { 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); + let options = CollectorViewOptions::from(&file); + assert_eq!( + (options.idle_close_ms, options.reorder_wait_ms), + (5_000, 3_000) + ); + let default = CollectorViewOptions::default(); + assert_eq!( + (default.idle_close_ms, default.reorder_wait_ms), + (8_000, 6_000) + ); } } diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index 851a3813e..e7ddaeb5e 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -400,6 +400,21 @@ impl ViewFiles { Ok(written) } + /// Not implemented yet: writes nothing. + pub fn mark_incomplete( + &mut self, + _group: usize, + _range_ms: (i64, i64), + _views: &[PhysicalASAPNodeId], + ) -> std::io::Result { + Ok(0) + } + + /// Not implemented yet: none. + pub fn take_incomplete(&mut self) -> BTreeSet<(PhysicalASAPNodeId, i64)> { + BTreeSet::new() + } + /// Appends one record of `group`'s views of `retention_ms`. fn append_record( &mut self, @@ -1759,12 +1774,8 @@ mod tests { drop(written); drop(files); // The header frame's payload ends with the version (a MessagePack - // fixint): rewrite it as the previous one. - let mut bytes = std::fs::read(&path).unwrap(); - let header_len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize; - assert_eq!(u32::from(bytes[8 + header_len - 1]), FORMAT_VERSION); - bytes[8 + header_len - 1] = (FORMAT_VERSION - 1) as u8; - std::fs::write(&path, bytes).unwrap(); + // fixint): rewrite it as the one before the oldest read. + set_version(&path, crate::segment::OLDEST_READ_VERSION - 1); let index = ViewFiles::open(&dir, 7, Duration::ZERO) .unwrap() .index(&groups) @@ -1932,6 +1943,109 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// Rewrites the format version in the header of the segment at `path` + /// (the header frame's payload ends with it, a MessagePack fixint). + fn set_version(path: &Path, version: u32) { + let mut bytes = std::fs::read(path).unwrap(); + let header_len = u32::from_le_bytes(bytes[..4].try_into().unwrap()) as usize; + assert_eq!(u32::from(bytes[8 + header_len - 1]), FORMAT_VERSION); + bytes[8 + header_len - 1] = version as u8; + std::fs::write(path, bytes).unwrap(); + } + + /// A view whose windows are kept `retention_ms` past its newest. + fn view_kept(node_id: PhysicalASAPNodeId, retention_ms: i64) -> MaterializedView { + serde_json::from_value(serde_json::json!({ + "node_id": node_id, + "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": format!("v{node_id}"), "window": null, + "logical_properties": {"parameters": null}}, + "coverage": {"definition_id": format!("v{node_id}"), "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": retention_ms, + })) + .unwrap() + } + + /// Windows marked incomplete are found again after a restart, stored + /// or not and whatever revision of the window is read later; a mark + /// past its view's retention of its newest window is not. Each view's + /// marks are its own, in its retention's files. + #[test] + fn incomplete_marks_are_indexed_after_a_restart() { + let dir = segment_dir("incomplete-marks"); + let (_, batch) = every_family().remove(0); + let groups = vec![vec![ + (view_kept(1, 1_000_000), batch.schema().clone()), + (view_kept(2, 30), batch.schema().clone()), + ]]; + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .with_view_retention_ms(BTreeMap::from([(1, 1_000_000), (2, 30)])); + for end in [10, 20, 30] { + files + .append( + 0, + (end - 10, end), + &[ + (1, std::slice::from_ref(&batch)), + (2, std::slice::from_ref(&batch)), + ], + 0, + ) + .unwrap(); + } + assert!(files.mark_incomplete(0, (10, 20), &[1, 2]).unwrap() > 0); + // A window not stored (yet) is marked too. + files.mark_incomplete(0, (40, 50), &[1]).unwrap(); + // A later revision of the marked window: it stays marked. + files + .append(0, (10, 20), &[(1, std::slice::from_ref(&batch))], 1) + .unwrap(); + // View 2's newest window moves on: (10, 20] leaves its retention. + for end in [40, 50, 60] { + files + .append(0, (end - 10, end), &[(2, std::slice::from_ref(&batch))], 0) + .unwrap(); + } + drop(files); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let index = files.index(&groups).unwrap(); + assert_eq!(index[&1].len(), 3, "the marks are no windows"); + assert_eq!(files.take_incomplete(), BTreeSet::from([(1, 20), (1, 50)])); + assert!(files.take_incomplete().is_empty(), "taken once"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A version 5 segment (before incomplete marks) is read, its windows + /// unmarked; appends after the restart go to a new version 6 segment. + #[test] + fn a_version_5_segment_reads_with_no_marks() { + let dir = segment_dir("version-5"); + let (_, batch) = every_family().remove(0); + let groups = vec![vec![(view_kept(1, 1_000_000), batch.schema().clone())]]; + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let written = files + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) + .unwrap(); + let path = location_of(&written, 1).segment_path().to_path_buf(); + drop(written); + drop(files); + set_version(&path, 5); + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + let index = files.index(&groups).unwrap(); + assert_eq!(index[&1].len(), 1); + assert!(path.exists(), "not set aside"); + assert!(files.take_incomplete().is_empty()); + assert_same_rows( + &batch, + &index[&1][0].1.read(batch.schema(), ViewRead::Mmap).unwrap(), + "a version 5 window", + ); + let _ = std::fs::remove_dir_all(&dir); + } + /// A window revised by late samples is appended again at a higher /// revision, here after a restart into a segment named by an older end /// than the original's: indexing reads the highest revision, whatever diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index c04a90b44..21daba69c 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -57,6 +57,9 @@ use crate::state_codec::{ /// set aside on open, never read. pub(crate) const FORMAT_VERSION: u32 = 5; +/// Not implemented yet: only this version is read. +pub(crate) const OLDEST_READ_VERSION: u32 = FORMAT_VERSION; + /// Frame kinds. const HEADER_FRAME: u32 = 0; const RECORD_FRAME: u32 = 1; From 0fe4d8f000b6633d7930715bb76adc697067dbac Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:22:06 +0000 Subject: [PATCH 2/4] feat(collector views): reorder buffer, persisted incomplete marks, lineage frame Decisions 30, 31 and 34 of the design doc (section 8): - Reorder buffer (31): a delta whose base has not been applied (a later sequence, or a new epoch's delta before its full) is held per lineage and sequence, and applied as soon as its base is, with the records held after it. A record held for the collector's declared close delay (CollectorViewOptions::reorder_wait_ms, the file's window_close_delay_ms; 6 s by default) with its base still missing marks its window incomplete (Staging::expire_held, every ingest pass); the window's other held records are dropped. New outcome "held". - Persisted incomplete marks (30): Precompute::mark_incomplete returns the marks, the committer queues them to the persist thread (PersistPool::queue_incomplete), which appends a marks-only record (RecordHead::incomplete) per retention; ViewFiles::index collects them within retention and startup re-marks the store. FORMAT_VERSION 5 -> 6 so a version 5 data plane sets the new segments aside rather than cutting them at the first new head; version 5 segments still read. - Lineage frame (34): the otlp adapter reads the record's sequence and kind from the frame in front of its ASAPv1 bytes in sketch.envelope (common::unframe_lineage) instead of three point attributes; a bare ASAPv1 state, another frame version or a self-contradicting frame refuses the request. The attribute constants are removed. 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 | 67 +--- crates/common/src/view_states.rs | 117 ++++++- crates/precompute/src/collector.rs | 406 +++++++++++++++++-------- crates/precompute/src/engine.rs | 21 +- crates/precompute/src/ingestion.rs | 28 +- crates/storage/src/persist.rs | 65 +++- crates/storage/src/persist_pool.rs | 40 +++ crates/storage/src/segment.rs | 32 +- 9 files changed, 557 insertions(+), 228 deletions(-) diff --git a/README.md b/README.md index 2a3ffb99e..0bcd12e3b 100644 --- a/README.md +++ b/README.md @@ -253,9 +253,12 @@ their states arrive from the collector on `/v1/metrics`, in metrics named request carrying its states ends; later states of a committed window merge 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 +deltas, numbered per collector instance, in a binary lineage frame in +front of the state's bytes): a repeated record is ignored, a delta that +comes before its base is held until the base comes, and a base still +missing after the collector's declared close delay marks the window +incomplete, so queries reading it are forwarded (also after a restart: +the mark is kept in the view files). 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` diff --git a/crates/adapters/ingest/otlp/src/lib.rs b/crates/adapters/ingest/otlp/src/lib.rs index 7981a8599..449f0ccea 100644 --- a/crates/adapters/ingest/otlp/src/lib.rs +++ b/crates/adapters/ingest/otlp/src/lib.rs @@ -62,18 +62,20 @@ //! 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`, 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, +//! behind its lineage frame (its sequence, and full or delta: §8, +//! [`common::unframe_lineage`]; the sending collector's +//! `asap.producer_epoch` is metric metadata), 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 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`]). +//! frame is missing (a bare ASAPv1 state), of another version, or +//! disagrees with itself (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 //! @@ -90,12 +92,11 @@ use std::collections::{BTreeMap, HashMap}; use std::io::Read; use common::view_identity::{ - BASE_SEQUENCE, ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, SEQUENCE, - STATE_KIND, VIEW_STATE_KEY, + ENVELOPE_ATTRIBUTE, NAME_INFIX, NODE_ID, PLAN_ID, PRODUCER_EPOCH, VIEW_STATE_KEY, }; use common::{ - CollectorSeriesStates, CollectorViewStates, LabelSet, StateKind, ViewStateBatch, ViewStateKey, - ViewStateRecord, + unframe_lineage, CollectorSeriesStates, CollectorViewStates, LabelSet, ViewStateBatch, + ViewStateKey, ViewStateRecord, }; use prometheus_remote_write::series_cache::SeriesCache; use prometheus_remote_write::wire::{Reader, Value}; @@ -758,7 +759,6 @@ 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()? { @@ -774,9 +774,6 @@ 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), } } @@ -798,10 +795,10 @@ 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 { + let (sequence, kind, asapv1) = + unframe_lineage(envelope).map_err(|reason| OtlpError::ViewIdentity { metric: name.to_string(), - reason, + reason: format!("{ENVELOPE_ATTRIBUTE}: {reason}"), })?; if self.decoded.samples.len() >= self.max_points { return Err(OtlpError::TooManyPoints(self.point_limit)); @@ -825,7 +822,7 @@ impl Walk<'_, B> { series[index].records.push(ViewStateRecord { window_start_ms: (start_nanos / 1_000_000) as i64, window_end_ms: (time_nanos / 1_000_000) as i64, - asapv1: envelope.to_vec(), + asapv1: asapv1.to_vec(), sample_count: count, sequence, kind, @@ -834,40 +831,6 @@ impl Walk<'_, B> { } } -/// 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/view_states.rs b/crates/common/src/view_states.rs index 94d739a08..d26ab48ef 100644 --- a/crates/common/src/view_states.rs +++ b/crates/common/src/view_states.rs @@ -58,9 +58,9 @@ pub struct ViewStateRecord { 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. + /// Its place in its lineage: 0 for a full. pub sequence: u64, - /// `asap.state_kind`, with `asap.base_sequence` for a delta. + /// Full or delta, with a delta's base. pub kind: StateKind, } @@ -84,27 +84,112 @@ 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. + /// Metric metadata: the sending collector instance, decimal text. The + /// rest of a record's lineage is in the lineage frame in front of its + /// ASAPv1 bytes ([`super::unframe_lineage`]). 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"; } -/// The first byte of a version 1 lineage frame (not implemented yet). +/// The first byte of a version 1 lineage frame: the high nibble `0xA` marks +/// a lineage frame, the low one is its version. An ASAPv1 envelope starts +/// with `b'A'` (`0x41`), so a bare one is never taken for a frame. pub const LINEAGE_FRAME_V1: u8 = 0xA1; +/// The frame's flags bit of a delta; the other bits are 0. +const LINEAGE_FRAME_DELTA: u8 = 0x01; -/// Not implemented yet. -pub fn unframe_lineage(_bytes: &[u8]) -> Result<(u64, StateKind, &[u8]), String> { - Err("lineage frames are not implemented yet".into()) +/// A record's sequence, kind and ASAPv1 bytes from its `sketch.envelope` +/// bytes, the collector's lineage frame (§8): +/// +/// ```text +/// [ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128 +/// | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ] +/// ``` +/// +/// A full is `A1 00 00` and its ASAPv1 bytes. Errs, saying why, for bytes +/// that are no version 1 frame (a bare ASAPv1 state from a collector +/// without lineage frames, or another frame version), with unknown flags, +/// a truncated or overflowing varint, or a kind that disagrees with its +/// sequence and base (a full is sequence 0, a delta `n >= 1` has base +/// `n - 1`). +pub fn unframe_lineage(bytes: &[u8]) -> Result<(u64, StateKind, &[u8]), String> { + match bytes.first() { + Some(&LINEAGE_FRAME_V1) => {} + Some(_) if bytes.starts_with(b"ASAPv1") => { + return Err("a bare ASAPv1 state without a lineage frame".into()) + } + Some(&first) if first >> 4 == 0xA => { + return Err(format!( + "lineage frame version {}; this reader reads version 1", + first & 0x0F + )) + } + _ => return Err("not a lineage frame".into()), + } + let flags = *bytes.get(1).ok_or("a truncated lineage frame")?; + if flags & !LINEAGE_FRAME_DELTA != 0 { + return Err(format!("unknown lineage frame flags {flags:#04x}")); + } + let mut rest = &bytes[2..]; + let sequence = read_uleb128(&mut rest)?; + if flags & LINEAGE_FRAME_DELTA == 0 { + if sequence != 0 { + return Err(format!("a full has sequence {sequence}, not 0")); + } + return Ok((0, StateKind::Full, rest)); + } + let base_sequence = read_uleb128(&mut rest)?; + if sequence == 0 || base_sequence != sequence - 1 { + return Err(format!( + "a delta of sequence {sequence} has base {base_sequence}, not its sequence - 1" + )); + } + Ok((sequence, StateKind::Delta { base_sequence }, rest)) +} + +/// `asapv1` behind the lineage frame of record `sequence` (a full when 0, +/// else a delta on `sequence - 1`), as the collector sends it: the inverse +/// of [`unframe_lineage`], for tests and tools. +pub fn frame_lineage(sequence: u64, asapv1: &[u8]) -> Vec { + let mut framed = Vec::with_capacity(asapv1.len() + 22); + framed.push(LINEAGE_FRAME_V1); + match sequence.checked_sub(1) { + None => framed.extend([0, 0]), + Some(base) => { + framed.push(LINEAGE_FRAME_DELTA); + push_uleb128(&mut framed, sequence); + push_uleb128(&mut framed, base); + } + } + framed.extend_from_slice(asapv1); + framed } -/// Not implemented yet: `asapv1` as is. -pub fn frame_lineage(_sequence: u64, asapv1: &[u8]) -> Vec { - asapv1.to_vec() +fn push_uleb128(out: &mut Vec, mut value: u64) { + loop { + let byte = (value & 0x7F) as u8; + value >>= 7; + if value == 0 { + out.push(byte); + return; + } + out.push(byte | 0x80); + } +} + +fn read_uleb128(bytes: &mut &[u8]) -> Result { + let mut value = 0u64; + for (i, &byte) in bytes.iter().enumerate().take(10) { + let bits = u64::from(byte & 0x7F); + if i == 9 && bits > 1 { + return Err("a lineage frame varint overflows u64".into()); + } + value |= bits << (7 * i); + if byte & 0x80 == 0 { + *bytes = &bytes[i + 1..]; + return Ok(value); + } + } + Err("a truncated lineage frame varint".into()) } #[cfg(test)] diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 475486c7e..5162a7ba7 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -14,11 +14,15 @@ //! 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. +//! record already applied is a duplicate. A delta that comes before its +//! base (a collector exporting concurrently, or retrying) is held in a +//! reorder buffer and applied when its base is. Once one has waited the +//! collector's declared close delay with its base still missing +//! ([`Staging::expire_held`]), its window is marked incomplete +//! ([`crate::ingestion::Precompute::mark_incomplete`], kept in the view +//! files across a restart), 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 @@ -57,10 +61,16 @@ pub struct CollectorViewOptions { /// window: the collector's window close delay and an allowance for /// clock skew. States of it coming later merge in. pub idle_close_ms: u64, - /// Not implemented yet: how long a record waits for its base. + /// How long a record that came before its base (a collector exporting + /// concurrently) is held for its base, on the monotonic clock: the + /// collector's declared window close delay. Its window is marked + /// incomplete only once this has passed with the base still missing. pub reorder_wait_ms: u64, } +/// The default collector's window close delay. +const DEFAULT_WINDOW_CLOSE_DELAY_MS: u64 = 6_000; + /// 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; @@ -72,8 +82,8 @@ impl Default for CollectorViewOptions { Self { plan_id: None, views: BTreeSet::new(), - idle_close_ms: 6_000 + CLOCK_SKEW_ALLOWANCE_MS, - reorder_wait_ms: 0, + idle_close_ms: DEFAULT_WINDOW_CLOSE_DELAY_MS + CLOCK_SKEW_ALLOWANCE_MS, + reorder_wait_ms: DEFAULT_WINDOW_CLOSE_DELAY_MS, } } } @@ -81,7 +91,8 @@ impl Default for CollectorViewOptions { impl From<&common::CollectorViewsFile> for CollectorViewOptions { /// 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. + /// delay plus the skew allowance, and a record is held for its base + /// for the close delay. fn from(file: &common::CollectorViewsFile) -> Self { Self { plan_id: Some(file.plan_id.clone()), @@ -89,7 +100,7 @@ impl From<&common::CollectorViewsFile> for CollectorViewOptions { idle_close_ms: file .window_close_delay_ms .saturating_add(CLOCK_SKEW_ALLOWANCE_MS), - reorder_wait_ms: 0, + reorder_wait_ms: file.window_close_delay_ms, } } } @@ -129,13 +140,14 @@ 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, - /// Not implemented yet: held for its base. + /// Held for its base: a delta that came before its lineage's previous + /// record (or before its lineage's full). It is applied when the base + /// comes, or its window is marked incomplete once the reorder wait + /// passes ([`CollectorViewOptions::reorder_wait_ms`]); either is + /// counted then, in the outcome metric. pub held: u64, + /// Not applied: a record of a window already incomplete. + pub incomplete: u64, /// Rejected, by reason ([`reject`]). pub rejected: BTreeMap<&'static str, u64>, } @@ -154,6 +166,7 @@ impl std::ops::AddAssign for CollectorStateIngestReport { self.merged += other.merged; self.late_merged += other.late_merged; self.late_dropped += other.late_dropped; + self.held += other.held; self.incomplete += other.incomplete; for (reason, count) in other.rejected { *self.rejected.entry(reason).or_default() += count; @@ -171,7 +184,10 @@ 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. + /// Held for its base (counted again when applied or not). + pub const HELD: &str = "held"; + /// Not applied: its base never came within the reorder wait, 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"; @@ -211,9 +227,9 @@ enum Applies { 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, + /// A delta past its lineage's next record, or of an epoch with no + /// lineage yet: its base has not come, so it waits for it. + Ahead, } impl ArrivedState { @@ -227,7 +243,7 @@ impl ArrivedState { lineage.last_sequence = self.sequence; Applies::Merged } - _ => Applies::Broken, + _ => Applies::Ahead, }, None => match self.kind { StateKind::Full => { @@ -237,10 +253,24 @@ impl ArrivedState { }); Applies::Merged } - StateKind::Delta { .. } => Applies::Broken, + StateKind::Delta { .. } => Applies::Ahead, }, } } + + /// Where it is held while it waits for its base. + fn held_key(&self) -> HeldKey { + (self.group, self.end_ms, self.series.id, self.epoch) + } +} + +/// A held record's lineage: `(group, window end, series id, epoch)`. +type HeldKey = (usize, i64, u32, u64); + +/// A record held for its base, since monotonic `since_ms`. +struct Held { + state: ArrivedState, + since_ms: i64, } /// One installed collector view. @@ -557,8 +587,11 @@ pub(crate) struct Staging { /// The windows a broken lineage made incomplete, while kept: their /// records are no longer applied. incomplete: BTreeSet<(usize, i64)>, - /// Not implemented yet: the reorder buffer. - held: BTreeMap<(usize, i64), ()>, + /// The records that came before their base, by lineage and sequence: + /// the reorder buffer. Each is applied when its base is, or marks its + /// window incomplete once the reorder wait passes + /// ([`Self::expire_held`]). + held: BTreeMap>, } /// What [`Staging::stage`] did with a request's states. @@ -568,18 +601,35 @@ pub(crate) struct StagedRequest { /// 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, +} + +/// What applying one record needs of the ingestion, read once per request. +struct WindowsNow { + /// Per group, its windows ending after this are kept. + kept_after: Vec>, + /// Per group, its windows ending at or before this are closed. + closed_through: Vec>, +} + +impl WindowsNow { + fn kept(&self, &(group, end): &(usize, i64)) -> bool { + self.kept_after[group].is_none_or(|after| end > after) + } + + fn closed(&self, group: usize, end_ms: i64) -> bool { + self.closed_through[group].is_some_and(|through| end_ms <= through) + } } impl Staging { /// 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`. + /// of a window past retention is late; one that came before its base + /// is held until the base comes, and applied then (with the records + /// held after it), at `now`. 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, @@ -588,7 +638,6 @@ impl Staging { metrics: &Metrics, ) -> 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); @@ -597,136 +646,227 @@ impl Staging { for (group, end_ms) in oldest { ingestion.start_collector_group(group, end_ms); } + let windows = WindowsNow { + kept_after: ingestion.kept_after_ms(), + closed_through: (0..ingestion.group_count()) + .map(|group| ingestion.closed_through(group)) + .collect(), + }; // Committed windows no longer kept take no more states. - let kept_after = ingestion.kept_after_ms(); - 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); + self.committed.retain(|window, _| windows.kept(window)); + self.incomplete.retain(|window| windows.kept(window)); let mut newest: BTreeMap = BTreeMap::new(); for arrived in states { - let view = arrived.node_id; - let key = (arrived.group, arrived.end_ms); - 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); - if closed && !kept(&key) { - report.late_dropped += 1; - metrics - .collector_states - .outcome(view, outcome::LATE_DROPPED, 1); - continue; + if !windows.closed(arrived.group, arrived.end_ms) { + let newest = newest.entry(arrived.group).or_insert(arrived.end_ms); + *newest = (*newest).max(arrived.end_ms); + } + // Applied, it releases the record held after it, if any. + let mut next = Some(arrived); + while let Some(arrived) = next.take() { + let (key, sequence) = (arrived.held_key(), arrived.sequence); + let applies = self.apply(arrived, &windows, now, &mut request, metrics); + if applies == Some(Applies::Merged) { + if let Some(held) = self.held.get_mut(&key) { + next = held.remove(&(sequence + 1)).map(|held| held.state); + if held.is_empty() { + self.held.remove(&key); + } + } + } } - if self.incomplete.contains(&key) { - report.incomplete += 1; + } + for (group, end_ms) in newest { + ingestion.collector_arrived(group, end_ms, now); + } + request + } + + /// Applies one record (see [`Self::stage`]); what it did to its + /// lineages, `None` when it was dropped before any lineage rule (late, + /// or of an incomplete window) or did not merge. + fn apply( + &mut self, + arrived: ArrivedState, + windows: &WindowsNow, + now: ClockReading, + request: &mut StagedRequest, + metrics: &Metrics, + ) -> Option { + let view = arrived.node_id; + let key = (arrived.group, arrived.end_ms); + let report = &mut request.report; + let closed = windows.closed(arrived.group, arrived.end_ms); + if closed && !windows.kept(&key) { + report.late_dropped += 1; + metrics + .collector_states + .outcome(view, outcome::LATE_DROPPED, 1); + return None; + } + if self.incomplete.contains(&key) { + report.incomplete += 1; + metrics + .collector_states + .outcome(view, outcome::INCOMPLETE, 1); + return None; + } + let series = arrived.series.id; + let mut lineages_after = if closed { + self.committed + .get(&key) + .and_then(|lineages| lineages.get(&series)) + .cloned() + } else { + self.windows + .get(&key) + .and_then(|staged| staged.get(&series)) + .map(|staged| staged.lineages.clone()) + } + .unwrap_or_default(); + let applies = arrived.apply_to(&mut lineages_after); + match applies { + Applies::Duplicate => { + report.duplicate += 1; metrics .collector_states - .outcome(view, outcome::INCOMPLETE, 1); - continue; + .outcome(view, outcome::DUPLICATE, 1); } - let applies = if closed { + Applies::Ahead => { + let held = self.held.entry(arrived.held_key()).or_default(); + match held.entry(arrived.sequence) { + std::collections::btree_map::Entry::Occupied(_) => { + report.duplicate += 1; + metrics + .collector_states + .outcome(view, outcome::DUPLICATE, 1); + } + std::collections::btree_map::Entry::Vacant(slot) => { + report.held += 1; + metrics.collector_states.outcome(view, outcome::HELD, 1); + slot.insert(Held { + state: arrived, + since_ms: now.monotonic_ms, + }); + } + } + } + Applies::Merged if closed => { // A window closed without states (its first come after a // later window's) is stored with them. - let lineages = self - .committed + 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 { + .insert(series, lineages_after); + report.late_merged += 1; + metrics + .collector_states + .outcome(view, outcome::LATE_MERGED, 1); + request + .late + .entry(ClosedWindow { + group: arrived.group, + end_ms: arrived.end_ms, + }) + .or_default() + .push(Staged { series: arrived.series, state: arrived.state, lineages: Vec::new(), }); - } - applies - } else { - let newest = newest.entry(arrived.group).or_insert(arrived.end_ms); - *newest = (*newest).max(arrived.end_ms); + } + Applies::Merged => { 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 + series.insert( + arrived.series.id, + Staged { + series: arrived.series, + state: arrived.state, + lineages: lineages_after, + }, + ); + report.staged += 1; + metrics.collector_states.outcome(view, outcome::STAGED, 1); } - 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"); - } - } + Some(staged) => match staged.state.merge_with(&*arrived.state) { + Ok(merged) => { + staged.state = Arc::from(merged); + staged.lineages = lineages_after; + report.merged += 1; + metrics.collector_states.outcome(view, outcome::MERGED, 1); } - 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 - .outcome(view, outcome::INCOMPLETE, 1); - self.incomplete.insert(key); - request.incomplete.push(window); + 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"); + return None; + } + }, } } } - for (group, end_ms) in newest { - ingestion.collector_arrived(group, end_ms, now); - } - request + Some(applies) } - /// Not implemented yet: nothing is held. + /// Gives up on the records held longer than the reorder wait at `now` + /// (their base never came): each one's window, if still kept, is marked + /// incomplete, and every record held for it is dropped, counted + /// `incomplete` (or `late_dropped` for a window past retention). + /// Returns the windows newly marked, for the view store. pub fn expire_held( &mut self, - _ingestion: &Ingestion, - _now: ClockReading, - _metrics: &Metrics, + ingestion: &Ingestion, + now: ClockReading, + metrics: &Metrics, ) -> Vec { - Vec::new() + let wait_ms = ingestion.collector_reorder_wait_ms(); + let expired: BTreeSet<(usize, i64)> = self + .held + .iter() + .filter(|(_, held)| { + held.values() + .any(|h| now.monotonic_ms.saturating_sub(h.since_ms) >= wait_ms) + }) + .map(|(&(group, end_ms, ..), _)| (group, end_ms)) + .collect(); + if expired.is_empty() { + return Vec::new(); + } + let kept_after = ingestion.kept_after_ms(); + let mut marked = Vec::new(); + for (group, end_ms) in expired { + let kept = kept_after[group].is_none_or(|after| end_ms > after); + let keys: Vec = self + .held + .range((group, end_ms, 0, 0)..=(group, end_ms, u32::MAX, u64::MAX)) + .map(|(&key, _)| key) + .collect(); + for key in keys { + for held in self + .held + .remove(&key) + .into_iter() + .flat_map(|h| h.into_values()) + { + let what = if kept { + outcome::INCOMPLETE + } else { + outcome::LATE_DROPPED + }; + metrics + .collector_states + .outcome(held.state.node_id, what, 1); + } + } + if kept && self.incomplete.insert((group, end_ms)) { + marked.push(ClosedWindow { group, end_ms }); + } + } + marked } /// The states staged for `window`, removed, for it to commit; empty diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index f0bc7cce9..73647e51f 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -495,7 +495,12 @@ impl InstalledPrecompute { } } } - tracing::info!(dir = %dir.display(), windows = loaded, "indexed persisted views"); + // Windows marked incomplete before the restart stay so. + let incomplete = files.take_incomplete(); + for &(view, end_ms) in &incomplete { + views.mark_incomplete(view, end_ms); + } + tracing::info!(dir = %dir.display(), windows = loaded, incomplete = incomplete.len(), "indexed persisted views"); if loaded > 0 { ingestion.restarted(); views.restarted(); @@ -1295,9 +1300,15 @@ fn serve_ingest( for (window, states) in request.late { collector_late.entry(window).or_default().extend(states); } - collector_incomplete.extend(request.incomplete); collector_committed.push(committed); } + // Records held past the reorder wait without their base: their + // windows are incomplete. + collector_incomplete.extend(staging.expire_held( + &ingestion, + shared.clock.read(), + &shared.metrics, + )); // The barriers first, so a window one of them closes is not // counted as closed by wall-clock time. let mut closed = Vec::new(); @@ -1986,7 +1997,11 @@ fn serve_precompute( slots.release(); } for window in incomplete.drain(..) { - precompute.mark_incomplete(window, &mut views); + for (group, range_ms, nodes) in precompute.mark_incomplete(window, &mut views) { + if let Some(persist) = &persist { + persist.queue_incomplete(group, range_ms, nodes); + } + } committed = true; } let ready: Vec = late diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 3b7e1f597..298305b46 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -275,6 +275,9 @@ pub(crate) struct Ingestion { /// How long after a collector view's window end, with no state /// arriving, it closes on the clock ([`CollectorViewOptions`]). collector_idle_close_ms: i64, + /// How long a collector state is held for its base + /// ([`CollectorViewOptions::reorder_wait_ms`]). + collector_reorder_wait_ms: i64, pub stats: IngestionStats, } @@ -466,6 +469,7 @@ impl Ingestion { idle_watermark_ms: None, push_groups: Vec::new(), collector_idle_close_ms: millis(collector.idle_close_ms), + collector_reorder_wait_ms: millis(collector.reorder_wait_ms), stats: IngestionStats::default(), }; // Each view's readers: the groups whose runs read it. @@ -1006,6 +1010,17 @@ impl Ingestion { group.collector_arrived = Some((newest, now)); } + /// How many refresh groups there are. + pub(crate) fn group_count(&self) -> usize { + self.groups.len() + } + + /// How long a collector state that came before its base is held for + /// it ([`CollectorViewOptions::reorder_wait_ms`]). + pub(crate) fn collector_reorder_wait_ms(&self) -> i64 { + self.collector_reorder_wait_ms + } + /// End of group `group`'s newest window closed or skipped. pub(crate) fn closed_through(&self, group: usize) -> Option { self.groups[group].refreshed_through @@ -1688,16 +1703,25 @@ impl Precompute { /// 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) { + /// plan (§8). Returns the marks by group, window range and views, for + /// the view files to keep them across a restart. + pub(crate) fn mark_incomplete( + &self, + window: ClosedWindow, + views: &mut Arc, + ) -> Vec<(usize, (i64, i64), Vec)> { let store = Arc::make_mut(views); + let mut marked = Vec::new(); 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); } + let nodes = run.views.iter().map(|view| view.node_id).collect(); + marked.push((group, (end - run.width_ms, end), nodes)); } + marked } /// Takes the late samples `raw_data` of the committed `window` into it, diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index e7ddaeb5e..1c22d430c 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -186,6 +186,9 @@ pub struct ViewFiles { last_sync: Instant, /// The (group, retention) files written since the last sync. unsynced: BTreeSet<(usize, i64)>, + /// The windows [`Self::index`] found marked incomplete, by view and end, + /// until [`Self::take_incomplete`]. + incomplete_indexed: BTreeSet<(PhysicalASAPNodeId, i64)>, } /// A stable 64-bit FNV-1a hash of `bytes`. @@ -220,6 +223,7 @@ impl ViewFiles { sync_interval, last_sync: Instant::now(), unsynced: BTreeSet::new(), + incomplete_indexed: BTreeSet::new(), }) } @@ -262,6 +266,7 @@ impl ViewFiles { sync_interval: self.sync_interval, last_sync: Instant::now(), unsynced: BTreeSet::new(), + incomplete_indexed: BTreeSet::new(), }) .collect(); for ((group, retention_ms), files) in self.files { @@ -390,7 +395,7 @@ impl ViewFiles { } let mut written = Written::default(); for (retention_ms, views) in by_retention { - let part = self.append_record(group, retention_ms, range_ms, &views, revision)?; + let part = self.append_record(group, retention_ms, range_ms, &views, revision, &[])?; written.bytes += part.bytes; written.not_persisted += part.not_persisted; written.locations.extend(part.locations); @@ -400,22 +405,43 @@ impl ViewFiles { Ok(written) } - /// Not implemented yet: writes nothing. + /// Marks `views`' (of `group`) window `range_ms` incomplete in the + /// files: one record per retention of the views, holding the marks + /// alone, to the active segment of that retention. [`Self::index`] + /// finds the marks after a restart, whatever revision of the window is + /// read; they are deleted with their segment. Returns the bytes added. pub fn mark_incomplete( &mut self, - _group: usize, - _range_ms: (i64, i64), - _views: &[PhysicalASAPNodeId], + group: usize, + range_ms: (i64, i64), + views: &[PhysicalASAPNodeId], ) -> std::io::Result { - Ok(0) + let mut by_retention: BTreeMap> = BTreeMap::new(); + for &view in views { + by_retention + .entry(self.retention_of(view)) + .or_default() + .push(view); + } + let mut bytes = 0; + for (retention_ms, views) in by_retention { + bytes += self + .append_record(group, retention_ms, range_ms, &[], 0, &views)? + .bytes; + } + self.sync_if_due()?; + Ok(bytes) } - /// Not implemented yet: none. + /// The windows found marked incomplete by [`Self::index`] (within their + /// view's retention of its newest window), by view and end; taken once. pub fn take_incomplete(&mut self) -> BTreeSet<(PhysicalASAPNodeId, i64)> { - BTreeSet::new() + std::mem::take(&mut self.incomplete_indexed) } - /// Appends one record of `group`'s views of `retention_ms`. + /// Appends one record of `group`'s views of `retention_ms`: the rows of + /// `views`, and the marks of `incomplete` (no record when both are + /// empty). fn append_record( &mut self, group: usize, @@ -423,6 +449,7 @@ impl ViewFiles { (start_ms, end_ms): (i64, i64), views: &[(PhysicalASAPNodeId, &[Batch])], revision: u64, + incomplete: &[PhysicalASAPNodeId], ) -> std::io::Result { let mut written = Written::default(); let segment_ms = self.segment_ms; @@ -484,7 +511,7 @@ impl ViewFiles { } } } - if fragments.is_empty() { + if fragments.is_empty() && incomplete.is_empty() { return Ok(written); } let new_texts = texts.new; @@ -530,6 +557,7 @@ impl ViewFiles { .map(|((view, _), (offset, len))| (*view, *offset, *len)) .collect(), revision, + incomplete: incomplete.to_vec(), })?; for (i, text) in new_texts.into_iter().enumerate() { active.texts.insert(text, base + i as u32); @@ -563,7 +591,8 @@ impl ViewFiles { /// a new one. Records each view's retention, by which its windows are /// written and deleted from now on. A version 1 file, and a /// segment of another plan, group or version, is renamed `*.stale`; a - /// torn record at a segment's end is cut off. + /// torn record at a segment's end is cut off. The windows found marked + /// incomplete are kept for [`Self::take_incomplete`]. pub fn index( &mut self, groups: &[Vec<(MaterializedView, SchemaRef)>], @@ -615,6 +644,7 @@ impl ViewFiles { version: FORMAT_VERSION, }; let mut by_view = ViewIndex::new(); + let mut marks: BTreeMap> = BTreeMap::new(); for (retention_ms, _, path) in paths { let Some((segment, heads)) = Segment::open(&path, &expected)? else { set_aside( @@ -627,6 +657,9 @@ impl ViewFiles { continue; }; for head in heads { + for &view in &head.incomplete { + marks.entry(view).or_default().push(head.end_ms); + } for &(view, offset, len) in &head.views { by_view.entry(view).or_default().push(( (head.start_ms, head.end_ms), @@ -649,7 +682,11 @@ impl ViewFiles { files.cool(); } for (view, _) in group_views { + let marked = marks.remove(&view.node_id).unwrap_or_default(); let Some(mut windows) = by_view.remove(&view.node_id) else { + // No window stored: every mark stands. + self.incomplete_indexed + .extend(marked.into_iter().map(|end| (view.node_id, end))); continue; }; // A window revised by late samples has a record per @@ -667,6 +704,12 @@ impl ViewFiles { }; let oldest_kept_end = crate::store::oldest_kept_end(view, newest_end); windows.retain(|((_, end), _)| *end > oldest_kept_end || *end == newest_end); + self.incomplete_indexed.extend( + marked + .into_iter() + .filter(|&end| end > oldest_kept_end) + .map(|end| (view.node_id, end)), + ); index.insert(view.node_id, windows); } } diff --git a/crates/storage/src/persist_pool.rs b/crates/storage/src/persist_pool.rs index 16d3409b9..94bc60974 100644 --- a/crates/storage/src/persist_pool.rs +++ b/crates/storage/src/persist_pool.rs @@ -30,6 +30,13 @@ enum PersistJob { revision: u64, bytes: u64, }, + /// Mark `views`' window `range_ms` of `group` incomplete in the files + /// ([`ViewFiles::mark_incomplete`]). + Incomplete { + group: usize, + range_ms: (i64, i64), + views: Vec, + }, /// Done once every window queued to this thread before is written. Barrier(Arc), } @@ -186,6 +193,24 @@ impl PersistPool { } } + /// Queues marking `views`' window `range_ms` of `group` incomplete for + /// the group's persist thread, so the marks survive a restart. + pub fn queue_incomplete( + &self, + group: usize, + range_ms: (i64, i64), + views: Vec, + ) { + let job = PersistJob::Incomplete { + group, + range_ms, + views, + }; + if self.shards[group % self.shards.len()].send(job).is_err() { + tracing::error!(group, "the persist thread has stopped"); + } + } + /// Runs `reached` once every persist thread has written the windows /// queued before. pub fn barrier(&self, reached: impl FnOnce() + Send + 'static) { @@ -301,6 +326,21 @@ fn serve_persist( } backlog.release(bytes); } + PersistJob::Incomplete { + group, + range_ms, + views, + } => match files.mark_incomplete(group, range_ms, &views) { + Ok(bytes) => { + metrics + .view_persisted_bytes + .fetch_add(bytes, Ordering::Relaxed); + metrics.view_file_bytes.fetch_add(bytes, Ordering::Relaxed); + } + Err(error) => { + tracing::error!(group, ?range_ms, %error, "persisting incomplete marks failed") + } + }, PersistJob::Barrier(barrier) => barrier.reached(), } } diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index 21daba69c..ad4deecc5 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -52,13 +52,18 @@ use crate::state_codec::{ /// The view file format version these segments are. /// +/// 6: a record head lists the views whose window it marks incomplete +/// ([`RecordHead::incomplete`]); a record may hold marks alone. A data +/// plane reading version 5 sets a version 6 segment aside instead of +/// cutting it at the first head it cannot decode. /// 5: DDSketch states without `sum`, `min` and `max` (`asap_sketchlib` -/// ASAPv1 kind `0x05 0x01`; a 64-byte view head). A version 4 segment is -/// set aside on open, never read. -pub(crate) const FORMAT_VERSION: u32 = 5; +/// ASAPv1 kind `0x05 0x01`; a 64-byte view head). +pub(crate) const FORMAT_VERSION: u32 = 6; -/// Not implemented yet: only this version is read. -pub(crate) const OLDEST_READ_VERSION: u32 = FORMAT_VERSION; +/// The oldest version read: a version 5 segment's heads have no marks, and +/// its records read as version 6 ones. A version 4 segment is set aside on +/// open, never read. +pub(crate) const OLDEST_READ_VERSION: u32 = 5; /// Frame kinds. const HEADER_FRAME: u32 = 0; @@ -134,6 +139,11 @@ pub(crate) struct RecordHead { /// written before revisions existed read as 0. #[serde(default)] pub revision: u64, + /// The views whose window `(start_ms, end_ms]` is incomplete (a + /// collector state of it was lost), whatever its records' revisions: + /// no query answers from it. Version 5 records read as none. + #[serde(default)] + pub incomplete: Vec, } /// A read-only mapping of a sealed segment, unmapped when dropped. @@ -300,8 +310,9 @@ impl Segment { /// Opens the segment at `path` written earlier, sealed: its header and /// every whole record up to the first that is torn or does not decode, /// which is cut off with everything after it (before anything maps the - /// file). `None` when its header is not `expected` (the file - /// is then left for the caller to set aside). + /// file). `None` when its header is not `expected`, or of `expected`'s + /// plan and group but a version from [`OLDEST_READ_VERSION`] up to + /// `expected`'s (the file is then left for the caller to set aside). pub(crate) fn open( path: &Path, expected: &SegmentHeader, @@ -330,7 +341,12 @@ impl Segment { let header: Option = (kind == HEADER_FRAME) .then(|| rmp_serde::from_slice(&payload).ok()) .flatten(); - if header.as_ref() != Some(expected) { + let readable = header.is_some_and(|header| { + header.plan_hash == expected.plan_hash + && header.group == expected.group + && (OLDEST_READ_VERSION..=expected.version).contains(&header.version) + }); + if !readable { return Ok(None); } header_ok = true; From 5c189c78cc60305e8bc1d7cf1d8c6dc2b640ece8 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:24:01 +0000 Subject: [PATCH 3/4] test(collector views): the reorder wait includes the skew allowance (failing first) The reorder wait is to be the declared window close delay plus the same 2 s clock-skew allowance as the idle close: the file's 3 s delay gives a 5 s wait, the default 8 s. In the data plane, a held record is not yet incomplete at the declared delay alone (6 s), only at 8 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/collector_views.rs | 8 ++++++-- crates/precompute/src/collector.rs | 6 +++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/data-plane/tests/collector_views.rs b/crates/data-plane/tests/collector_views.rs index 8f7a6b7cf..cd27a8a4e 100644 --- a/crates/data-plane/tests/collector_views.rs +++ b/crates/data-plane/tests/collector_views.rs @@ -151,8 +151,8 @@ fn collector_data_plane_on( data_plane(plan, options) } -/// The default collector's close delay: how long a record waits for its -/// base before its window is incomplete. +/// The default collector's close delay plus the skew allowance (8 s): how +/// long a record waits for its base before its window is incomplete. fn reorder_wait_ms() -> i64 { CollectorViewOptions::default().reorder_wait_ms as i64 } @@ -1073,6 +1073,10 @@ async fn a_gap_leaves_the_window_unanswered() { assert_eq!(metric(&state, &outcome_line(node, "held")), 1.0); common::barrier(&app, 0).await; assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 0.0); + // The declared close delay alone (6 s) is within the skew allowance. + clock.set(time_ms + 1_000 + 6_000); + common::barrier(&app, 0).await; + assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 0.0); clock.set(time_ms + 1_000 + reorder_wait_ms()); common::barrier(&app, 0).await; assert_eq!(metric(&state, &outcome_line(node, "incomplete")), 1.0); diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 5162a7ba7..760186c45 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -1371,7 +1371,7 @@ mod tests { } /// A collector-views file's declared close delay, plus the skew - /// allowance, is the idle close; the delay alone is the reorder wait. + /// allowance, is the idle close and the reorder wait. #[test] fn the_idle_close_is_the_files_close_delay_plus_skew() { let plan = one_query_plan("sum_over_time(data[1m])", false); @@ -1386,12 +1386,12 @@ mod tests { let options = CollectorViewOptions::from(&file); assert_eq!( (options.idle_close_ms, options.reorder_wait_ms), - (5_000, 3_000) + (5_000, 5_000) ); let default = CollectorViewOptions::default(); assert_eq!( (default.idle_close_ms, default.reorder_wait_ms), - (8_000, 6_000) + (8_000, 8_000) ); } } From 60127a2e6345fedee0b803fb6e864d5e5d2f468f Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:38:51 +0000 Subject: [PATCH 4/4] feat(collector views): the reorder wait adds the skew allowance A held record's window is marked incomplete after the declared window close delay plus the same 2 s clock-skew allowance as the idle close (CollectorViewOptions::reorder_wait_ms: the file's delay + 2 s, default 8 s), for consistency with how long a stopped collector's windows wait. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- README.md | 2 +- crates/precompute/src/collector.rs | 19 ++++++++++++------- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 0bcd12e3b..eee427933 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ state is a record of its series' lineage in its window (a full, then deltas, numbered per collector instance, in a binary lineage frame in front of the state's bytes): a repeated record is ignored, a delta that comes before its base is held until the base comes, and a base still -missing after the collector's declared close delay marks the window +missing after the collector's declared close delay plus 2 s marks the window incomplete, so queries reading it are forwarded (also after a restart: the mark is kept in the view files). A stopped collector's windows close after its declared delay plus 2 s. It refuses a file of another plan. diff --git a/crates/precompute/src/collector.rs b/crates/precompute/src/collector.rs index 760186c45..41b465681 100644 --- a/crates/precompute/src/collector.rs +++ b/crates/precompute/src/collector.rs @@ -17,7 +17,8 @@ //! record already applied is a duplicate. A delta that comes before its //! base (a collector exporting concurrently, or retrying) is held in a //! reorder buffer and applied when its base is. Once one has waited the -//! collector's declared close delay with its base still missing +//! collector's declared close delay plus the skew allowance with its +//! base still missing //! ([`Staging::expire_held`]), its window is marked incomplete //! ([`crate::ingestion::Precompute::mark_incomplete`], kept in the view //! files across a restart), so no query answers from it, and its later @@ -63,8 +64,9 @@ pub struct CollectorViewOptions { pub idle_close_ms: u64, /// How long a record that came before its base (a collector exporting /// concurrently) is held for its base, on the monotonic clock: the - /// collector's declared window close delay. Its window is marked - /// incomplete only once this has passed with the base still missing. + /// collector's declared window close delay plus the skew allowance, as + /// the idle close. Its window is marked incomplete only once this has + /// passed with the base still missing. pub reorder_wait_ms: u64, } @@ -83,7 +85,7 @@ impl Default for CollectorViewOptions { plan_id: None, views: BTreeSet::new(), idle_close_ms: DEFAULT_WINDOW_CLOSE_DELAY_MS + CLOCK_SKEW_ALLOWANCE_MS, - reorder_wait_ms: DEFAULT_WINDOW_CLOSE_DELAY_MS, + reorder_wait_ms: DEFAULT_WINDOW_CLOSE_DELAY_MS + CLOCK_SKEW_ALLOWANCE_MS, } } } @@ -92,7 +94,7 @@ impl From<&common::CollectorViewsFile> for CollectorViewOptions { /// 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, and a record is held for its base - /// for the close delay. + /// as long. fn from(file: &common::CollectorViewsFile) -> Self { Self { plan_id: Some(file.plan_id.clone()), @@ -100,7 +102,9 @@ impl From<&common::CollectorViewsFile> for CollectorViewOptions { idle_close_ms: file .window_close_delay_ms .saturating_add(CLOCK_SKEW_ALLOWANCE_MS), - reorder_wait_ms: file.window_close_delay_ms, + reorder_wait_ms: file + .window_close_delay_ms + .saturating_add(CLOCK_SKEW_ALLOWANCE_MS), } } } @@ -1298,7 +1302,8 @@ mod tests { } /// A held record whose base has not come once the reorder wait (the - /// collector's declared close delay) has passed marks its window + /// collector's declared close delay plus the skew allowance) has passed + /// marks its window /// incomplete, once, and the window's other held records are dropped; /// later records of the window are not applied. Before the wait, /// nothing is marked; other windows are untouched.