From 9d3bd8fc6dfcc7dae5c7d8464508deba2767875f Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:09:48 +0000 Subject: [PATCH 01/19] test(precompute): late samples merge into committed windows (failing first) A sample of a window already committed, still within its view's retention, is to merge into that window: after a producer's pause past the idle close, after a barrier, through the result cache, and across a restart over the view files. One past retention is still dropped and counted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/ingest_shards.rs | 111 ++++++++++++-------- crates/data-plane/tests/result_cache.rs | 24 +++++ crates/data-plane/tests/view_persistence.rs | 43 ++++++++ 3 files changed, 136 insertions(+), 42 deletions(-) diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index b52dba129..a59171cef 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -209,50 +209,58 @@ async fn samples_at_a_window_end_in_a_later_request_join_the_window() { } } -/// A sample older than a window already closed is dropped and counted, -/// and the window keeps its answer, over one shard or eight. Ported from -/// the ASAPQuery precompute worker's `test_late_data_drop`. +/// A sample of a window already closed is merged into it, over one shard +/// or eight: the window then answers as if the sample had come on time. +/// (The ASAPQuery precompute worker drops it: `test_late_data_drop`.) #[tokio::test(flavor = "multi_thread")] -async fn a_late_sample_is_dropped_on_any_shard_count() { +async fn a_late_sample_merges_into_its_closed_window_on_any_shard_count() { for shards in [1, 8] { let (app, state) = data_plane(shards); - write_seconds(&app, 0..64, 1..=40).await; + // Every sample at 1..=40 s but series 5's at 25 s. + write_seconds(&app, 0..64, 1..=24).await; + write_seconds(&app, 0..5, 25..=25).await; + write_seconds(&app, 6..64, 25..=25).await; + write_seconds(&app, 0..64, 26..=40).await; common::barrier(&app, 40_000).await; - // Series 5 at 25 s again, with another value: the window (20, 30] is - // closed. - let timeseries = vec![TimeSeries { - labels: [("__name__", "data"), ("instance", "i5"), ("job", "job1")] - .into_iter() - .map(|(name, value)| Label { - name: name.into(), - value: value.into(), - }) - .collect(), - samples: vec![Sample { - timestamp: 25_000, - value: 1000.0, - }], - }]; - common::remote_write(&app, timeseries).await; - common::barrier(&app, 40_000).await; - let started = std::time::Instant::now(); - while state.engine.stats().samples_dropped_late < 1 { - assert!(started.elapsed().as_secs() < 10, "{shards} shards"); - tokio::time::sleep(std::time::Duration::from_millis(20)).await; - } - assert_eq!( - state.engine.stats().samples_dropped_late, - 1, + assert_ne!( + common::per_job(&answer(&app, 30).await), + expected(30), "{shards} shards" ); + // Series 5 at 25 s: the window (20, 30] is closed. + write_seconds(&app, 5..6, 25..=25).await; + common::barrier(&app, 40_000).await; assert_eq!( - common::per_job(&answer(&app, 30).await), - expected(30), + state.engine.stats().samples_dropped_late, + 0, "{shards} shards" ); + for time_s in [30, 40] { + assert_eq!( + common::per_job(&answer(&app, time_s).await), + expected(time_s), + "{shards} shards, at {time_s} s" + ); + } } } +/// A sample of a closed window already past its view's retention (30 s +/// plus the 60 s margin) has no window to merge into: it is dropped and +/// counted, and the answers stay as they were. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_sample_past_retention_is_dropped() { + let (app, state) = data_plane(2); + write_seconds(&app, 0..64, 1..=200).await; + common::barrier(&app, 200_000).await; + let before = common::per_job(&answer(&app, 200).await); + write_seconds(&app, 5..6, 25..=25).await; + common::barrier(&app, 200_000).await; + assert_eq!(state.engine.stats().samples_dropped_late, 1); + assert_eq!(common::per_job(&answer(&app, 200).await), before); + assert_eq!(before, expected(200)); +} + /// With one series, three of four shards never get a sample; the windows /// still close as the busy shard's samples pass them, without a barrier. /// A shard with no samples does not hold the watermark, as the ASAPQuery @@ -629,18 +637,37 @@ async fn a_wall_clock_step_closes_no_window_early() { wait_for_answer_at_40s(&app, &state).await; } -/// A sample for a window closed by wall-clock time is late: dropped and -/// counted, and the window keeps its answer. +/// A producer pauses past the idle close of `(30, 40]`, then resumes with +/// that window's other samples: they merge into the committed window, so +/// every answer, read before the pause or after, equals the answer of a +/// stream that never paused. #[tokio::test(flavor = "multi_thread")] -async fn a_sample_after_a_wall_clock_close_is_late() { +async fn samples_after_a_pause_merge_into_the_window_closed_by_wall_clock() { let clock = WallClock::manual(0); let (app, state) = idle_data_plane(&clock); - write_through_40s(&app, &clock, 40_000).await; - clock.set(41_000); - wait_for_answer_at_40s(&app, &state).await; - let dropped = state.engine.stats().samples_dropped_late; - write_seconds(&app, 5..6, 35..=35).await; + clock.set(35_000); + write_seconds(&app, 0..64, 1..=35).await; pass(&app).await; - assert_eq!(state.engine.stats().samples_dropped_late, dropped + 1); - assert_eq!(common::per_job(&answer(&app, 40).await), expected(40)); + // The pause: the idle watermark reaches 35 + 15 − 0 − 1 = 49 s, which + // closes (30, 40] with the samples at 31..=35 s only. + clock.set(50_000); + let started = std::time::Instant::now(); + while status_and_answer(&app, 40).await.0 != StatusCode::OK { + assert!(started.elapsed().as_secs() < 10, "{:?}", state.engine.stats()); + pass(&app).await; + } + assert!(state.engine.stats().windows_closed_by_wall_clock > 0); + assert_ne!(common::per_job(&answer(&app, 40).await), expected(40)); + // The producer resumes where it stopped. + clock.set(60_000); + write_seconds(&app, 0..64, 36..=60).await; + common::barrier(&app, 60_000).await; + for time_s in [40, 50, 60] { + assert_eq!( + common::per_job(&answer(&app, time_s).await), + expected(time_s), + "at {time_s} s" + ); + } + assert_eq!(state.engine.stats().samples_dropped_late, 0); } diff --git a/crates/data-plane/tests/result_cache.rs b/crates/data-plane/tests/result_cache.rs index c4f64fae8..3cba7053b 100644 --- a/crates/data-plane/tests/result_cache.rs +++ b/crates/data-plane/tests/result_cache.rs @@ -228,6 +228,30 @@ async fn a_step_reaching_evicted_samples_is_refused() { ); } +/// A late sample merged into a committed window makes the cached answers +/// that read the window stale: the next request computes them again and +/// answers what a data plane that got the sample on time answers. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_merge_drops_the_cached_answers_reading_its_window() { + let all: Vec = (1..=60).map(|s| s * 1000).collect(); + let (app, _) = data_plane(views_plan_json(), true); + write(&app, "data", &all, 60_000).await; + let on_time = get(&app, range_uri(VIEWS_QUERY, 30, 60, 10)).await; + + let (app, state) = data_plane(views_plan_json(), true); + let without_25s: Vec = all.iter().copied().filter(|&t| t != 25_000).collect(); + write(&app, "data", &without_25s, 60_000).await; + let before = get(&app, range_uri(VIEWS_QUERY, 30, 60, 10)).await; + assert_ne!(before, on_time); + assert_eq!(get(&app, range_uri(VIEWS_QUERY, 30, 60, 10)).await, before); + assert_eq!(step_runs(&state), 4, "the repeat came from the cache"); + // The window (20, 30] is closed: the samples at 25 s merge into it. + write(&app, "data", &[25_000], 60_000).await; + let after = get(&app, range_uri(VIEWS_QUERY, 30, 60, 10)).await; + assert_eq!(after, on_time); + assert!(step_runs(&state) > 4, "the stale steps ran again"); +} + /// A sample at or before the watermark already published comes too late: /// answers at times the watermark has passed are final (kept in the result /// cache), so it is dropped and counted rather than changing what a data diff --git a/crates/data-plane/tests/view_persistence.rs b/crates/data-plane/tests/view_persistence.rs index a99f091f7..d4f71be9c 100644 --- a/crates/data-plane/tests/view_persistence.rs +++ b/crates/data-plane/tests/view_persistence.rs @@ -101,6 +101,49 @@ async fn answers_alike_after_a_restart(test: &str, query_text: &str, plan: &str) std::fs::remove_dir_all(&dir).unwrap(); } +/// A late sample merged into a written window writes the window again: a +/// data plane restarted over the files answers from the merged window, as +/// one that got the sample on time does. +#[tokio::test(flavor = "multi_thread")] +async fn a_merged_window_is_loaded_merged_after_a_restart() { + let plan = plan_json(SUM); + let dir = view_dir("late-merge"); + let (app, _) = data_plane(&plan, &dir); + write(&app, "data", 0, 600).await; + let before = query(&app, SUM, 600).await.1; + // Job `c` at 595 s, in the closed window ending at 600 s. + let late = vec![TimeSeries { + labels: vec![ + Label { + name: "__name__".into(), + value: "data".into(), + }, + Label { + name: "job".into(), + value: "c".into(), + }, + ], + samples: vec![Sample { + timestamp: 595_000, + value: 7.0, + }], + }]; + common::remote_write(&app, late).await; + common::barrier(&app, 600_000).await; + let (status, merged) = query(&app, SUM, 600).await; + assert_eq!(status, StatusCode::OK, "{merged}"); + assert_ne!(merged, before); + let jobs: Vec<(String, f64)> = common::per_job(&merged); + assert!(jobs.contains(&("c".to_string(), 7.0)), "{jobs:?}"); + drop(app); + + let (app, _) = data_plane(&plan, &dir); + let (status, after) = query(&app, SUM, 600).await; + assert_eq!(status, StatusCode::OK, "{after}"); + assert_eq!(after, merged); + std::fs::remove_dir_all(&dir).unwrap(); +} + /// Exact sums are loaded back and answer as before. #[tokio::test(flavor = "multi_thread")] async fn exact_views_answer_alike_after_a_restart() { From edb84056a83aced52954f6dfee6363b3d5a20c78 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:35:18 +0000 Subject: [PATCH 02/19] feat(precompute): merge late samples into committed windows within retention A sample of a window already committed, while that window (or a window of a group reading it) is within retention, is merged into it instead of being dropped. The ingest coordinator batches a window's late samples per pass; the precompute committer runs the window's views over them alone and merges the rows into the stored window (equal plain columns merge their states by each kernel's merge), then the change into the committed windows of the groups reading those views. It applies a merge once those groups have committed through it, so no run in flight read the window first. Push shards hand the samples of their sealed windows to the same merge. The merged window replaces the stored one in memory and is written again as a record of a higher revision; the view files index the highest revision of each window (record heads without one read as 0, so the format stays 5). The window cache keys windows by revision, and the result cache and query-time results record the views' revision they were computed from and recompute an answer that read a window revised since. Beyond retention a late sample is still dropped and counted. The samples_late_for_views counter becomes samples_merged_late (asap_samples_total{outcome="merged_late"}). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/src/metrics_endpoint.rs | 2 +- crates/data-plane/tests/ingest_shards.rs | 24 +- crates/data-plane/tests/push_precompute.rs | 10 +- crates/data-plane/tests/window_levels.rs | 78 +++++ crates/precompute/src/engine.rs | 157 ++++++++-- crates/precompute/src/ingestion.rs | 336 ++++++++++++++++++--- crates/precompute/src/push.rs | 41 ++- crates/query/src/lib.rs | 30 +- crates/query/src/result_cache.rs | 63 ++-- crates/query/src/workers.rs | 10 +- crates/storage/src/persist.rs | 167 ++++++++-- crates/storage/src/persist_pool.rs | 14 +- crates/storage/src/segment.rs | 23 +- crates/storage/src/store.rs | 224 ++++++++++++-- crates/storage/src/window_cache.rs | 11 +- crates/storage/tests/view_cache_charge.rs | 5 +- 16 files changed, 1006 insertions(+), 189 deletions(-) diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index d9d3ea6b8..a86061c5b 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -137,7 +137,7 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { ("dropped_late", stats.samples_dropped_late), ("dropped_future", stats.samples_dropped_future), ("unrouted", stats.samples_unrouted), - ("late_for_views", stats.samples_late_for_views), + ("merged_late", stats.samples_merged_late), ] { let _ = writeln!(out, "asap_samples_total{{outcome=\"{outcome}\"}} {count}"); } diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index a59171cef..64214612e 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -230,9 +230,10 @@ async fn a_late_sample_merges_into_its_closed_window_on_any_shard_count() { // Series 5 at 25 s: the window (20, 30] is closed. write_seconds(&app, 5..6, 25..=25).await; common::barrier(&app, 40_000).await; + let stats = state.engine.stats(); assert_eq!( - state.engine.stats().samples_dropped_late, - 0, + (stats.samples_merged_late, stats.samples_dropped_late), + (1, 0), "{shards} shards" ); for time_s in [30, 40] { @@ -256,7 +257,11 @@ async fn a_late_sample_past_retention_is_dropped() { let before = common::per_job(&answer(&app, 200).await); write_seconds(&app, 5..6, 25..=25).await; common::barrier(&app, 200_000).await; - assert_eq!(state.engine.stats().samples_dropped_late, 1); + let stats = state.engine.stats(); + assert_eq!( + (stats.samples_merged_late, stats.samples_dropped_late), + (0, 1) + ); assert_eq!(common::per_job(&answer(&app, 200).await), before); assert_eq!(before, expected(200)); } @@ -653,7 +658,11 @@ async fn samples_after_a_pause_merge_into_the_window_closed_by_wall_clock() { clock.set(50_000); let started = std::time::Instant::now(); while status_and_answer(&app, 40).await.0 != StatusCode::OK { - assert!(started.elapsed().as_secs() < 10, "{:?}", state.engine.stats()); + assert!( + started.elapsed().as_secs() < 10, + "{:?}", + state.engine.stats() + ); pass(&app).await; } assert!(state.engine.stats().windows_closed_by_wall_clock > 0); @@ -669,5 +678,10 @@ async fn samples_after_a_pause_merge_into_the_window_closed_by_wall_clock() { "at {time_s} s" ); } - assert_eq!(state.engine.stats().samples_dropped_late, 0); + // Series 0..64 at 36..=40 s, into (30, 40]. + let stats = state.engine.stats(); + assert_eq!( + (stats.samples_merged_late, stats.samples_dropped_late), + (64 * 5, 0) + ); } diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index 0f1d53d23..0cadd3df7 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -939,7 +939,7 @@ async fn pushed_pipelines_buffer_no_raw_samples() { /// T13. With 5 s allowed lateness, samples 4 s late (their window still /// open) and 20 s late (sealed) count in the same windows as on the window /// path, counters included, raw data kept and not; the 20 s-late samples -/// are counted as `late_for_views`. +/// merge into their sealed window, counted as `merged_late`. #[tokio::test(flavor = "multi_thread")] async fn late_samples_count_in_the_window_paths_windows() { let queries: [Query; 2] = [ @@ -983,11 +983,11 @@ async fn late_samples_count_in_the_window_paths_windows() { post(&app, late).await; barrier(&app, 61_000).await; let text = metrics_text(&app).await; - let late_for_views = - metric_sum(&text, "asap_samples_total", &["outcome=\"late_for_views\""]); - results.push((answers(&app, &plan, ×).await, late_for_views)); + let merged_late = metric_sum(&text, "asap_samples_total", &["outcome=\"merged_late\""]); + results.push((answers(&app, &plan, ×).await, merged_late)); } assert_eq!(results[1].0, results[0].0, "raw kept {raw}: same windows"); + assert_eq!(results[1].1, results[0].1, "raw kept {raw}: same counters"); // 4 late samples per metric an ingestion-time view reads (with raw // data kept, the Planner may answer from raw data at query time, // and then no view holds them). @@ -1007,7 +1007,7 @@ async fn late_samples_count_in_the_window_paths_windows() { assert_eq!( results[1].1, Some(4.0 * viewed_metrics as f64), - "raw kept {raw}: 4 samples late for views per metric a view reads" + "raw kept {raw}: 4 samples merged per metric a view reads" ); assert!( raw || viewed_metrics == 2, diff --git a/crates/data-plane/tests/window_levels.rs b/crates/data-plane/tests/window_levels.rs index 38e410818..da5842c9d 100644 --- a/crates/data-plane/tests/window_levels.rs +++ b/crates/data-plane/tests/window_levels.rs @@ -187,6 +187,84 @@ async fn wider_levels_and_covers_answer_after_one_pass_closes_every_window() { } } +/// A late sample merges into the narrowest level's window and, through it, +/// into the wider levels built from that window, even after the narrow +/// window itself was dropped once its readers read it: series 0's sample +/// 40 min before the end comes after every window closed, and the 1 h sum +/// then answers as if it had come on time. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_sample_reaches_the_wider_levels_built_from_its_window() { + const LATE_S: i64 = END_S - 2_400; + let plan = plan(); + let options = EngineOptions { + precompute_threads: 4, + ..common::no_forward_options() + }; + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan).unwrap(), + "http://127.0.0.1:1".into(), + options, + ) + .unwrap(), + ); + let app = router(state.clone()); + let write = |late: bool| { + let timeseries: Vec = (0..SERIES) + .map(|i| TimeSeries { + labels: [ + ("__name__", "data".to_string()), + ("instance", format!("i{i}")), + ("job", format!("job{}", i % 3)), + ] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(), + samples: (1..=END_S / 15) + .filter(|step| (i == 0 && step * 15 == LATE_S) == late) + .map(|step| Sample { + timestamp: step * 15_000, + value: value(i, step * 15), + }) + .collect(), + }) + .filter(|series| !series.samples.is_empty()) + .collect(); + encode(&WriteRequest { timeseries }) + }; + let barrier = format!("/api/v1/precompute/watermark?time_ms={}", END_S * 1000); + assert_eq!( + post(&app, "/api/v1/write".into(), write(false)).await, + StatusCode::NO_CONTENT + ); + assert_eq!(post(&app, barrier.clone(), Vec::new()).await, StatusCode::OK); + assert_ne!( + common::per_job(&answer(&app, SUM, END_S).await.1), + expected(SUM, END_S) + ); + assert_eq!( + post(&app, "/api/v1/write".into(), write(true)).await, + StatusCode::NO_CONTENT + ); + assert_eq!(post(&app, barrier, Vec::new()).await, StatusCode::OK); + let stats = state.engine.stats(); + assert_eq!(stats.samples_dropped_late, 0, "{stats:?}"); + for query in [SUM, MAX] { + for time_s in (END_S - 60..=END_S).step_by(15) { + let (status, body) = answer(&app, query, time_s).await; + assert_eq!(status, StatusCode::OK, "{query} at {time_s}: {body}"); + assert_eq!( + common::per_job(&body), + expected(query, time_s), + "{query} at {time_s}" + ); + } + } +} + /// Before a window has filled, a query answers from the samples there are, /// as PromQL does: the stream starts at 0, 20 minutes of samples arrive, /// and the 1 h sum and the 30 min max are exact at every 15 s step from the diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 3e8aa4f9a..bd3a6f59c 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -38,7 +38,7 @@ use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; use storage::persist_pool::{PersistBacklog, PersistOptions, PersistPool}; use storage::store::{ - PublishedStore, RawData, RawSample, RawShards, SeriesPartition, ViewStore, ViewTier, + PublishedStore, RawData, RawSample, RawShards, SeriesPartition, ViewStore, ViewTier, WindowSlot, }; use tokio::sync::oneshot; @@ -119,6 +119,8 @@ struct ShardReport { /// Whether the batch had a sample ingestion kept (not unrouted, late /// or in the future): a sample arrived, so the stream is not idle. accepted_any: bool, + /// Samples of closed windows still kept, to merge into them. + late: Vec<(ClosedWindow, RawSample)>, } /// What an ingest shard does next. @@ -154,6 +156,13 @@ enum PrecomputeJob { window: ClosedWindow, closed_at: Instant, }, + /// Late samples of a closed window (one or more ingest shards' worth), + /// to merge into it once committed. + Late { + window: ClosedWindow, + raw_data: RawShards, + samples: u64, + }, /// Answers `barrier_ms` once every window queued before is refreshed. Barrier { barrier_ms: i64, @@ -826,6 +835,7 @@ fn serve_shard( let mut count = 0; let mut accepted_any = false; let mut first_seen = Vec::new(); + let mut late = Vec::new(); loop { if !delay.is_zero() { std::thread::sleep(delay); @@ -841,19 +851,28 @@ fn serve_shard( Arc::make_mut(&mut raw_data).append(&routed.accepted); accepted_any |= !routed.accepted.is_empty(); newest_ms = newest_ms.max(routed.newest_ms); + let mut push_dropped = 0; if let Some(push) = &mut push { push.push(&routed.accepted, &shared.metrics); + for (window, sample) in push.take_late() { + if routing.keeps(window) { + late.push((window, sample)); + } else { + push_dropped += 1; + } + } } { let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); + stats.samples_dropped_late += push_dropped; stats.samples_accepted += routed.stats.samples_accepted; stats.samples_dropped_late += routed.stats.samples_dropped_late; stats.samples_dropped_future += routed.stats.samples_dropped_future; stats.samples_unrouted += routed.stats.samples_unrouted; - stats.samples_late_for_views += routed.stats.samples_late_for_views; } shared.metrics.append.record(timer); first_seen.extend(routed.first_seen); + late.extend(routed.late); match messages.try_recv() { Ok(ShardMessage::Samples(more)) => samples = more, Ok(other) => { @@ -869,6 +888,7 @@ fn serve_shard( first_seen, samples: count, accepted_any, + late, }; // The coordinator counts the samples out of the queues when it // applies the report, so samples stay counted while it cannot keep @@ -906,8 +926,17 @@ fn serve_ingest( const TICK: std::time::Duration = std::time::Duration::from_millis(100); let mut newest: Vec> = vec![None; shards.len()]; let mut sealed_through: Option = None; + // Late samples taken in this pass, by window: queued as one merge per + // window at its end. + let mut late: BTreeMap> = BTreeMap::new(); // Takes in a report; whether it ran a sample ingestion kept. - let apply = |report: ShardReport, ingestion: &mut Ingestion, newest: &mut Vec>| { + let apply = |report: ShardReport, + ingestion: &mut Ingestion, + newest: &mut Vec>, + late: &mut BTreeMap>| { + for (window, sample) in report.late { + late.entry(window).or_default().push(sample); + } ingestion.observe(&report.first_seen); shared.shard_queued[report.shard].fetch_sub(report.samples, Ordering::SeqCst); shared @@ -941,12 +970,12 @@ fn serve_ingest( // Whether a report taken this pass ran a sample. let mut arrived = false; for report in held.drain(..) { - arrived |= apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest, &mut late); } if !moved { match commands.recv_timeout(TICK) { Ok(Command::Report(report)) => { - arrived |= apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest, &mut late); moved = true; } Ok(Command::Flushed(..)) => {} @@ -965,7 +994,7 @@ fn serve_ingest( while let Ok(command) = commands.try_recv() { match command { Command::Report(report) => { - arrived |= apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest, &mut late); moved = true; } Command::Flushed(..) => {} @@ -996,7 +1025,7 @@ fn serve_ingest( held.push(report) } Ok(Command::Report(report)) => { - arrived |= apply(report, &mut ingestion, &mut newest) + arrived |= apply(report, &mut ingestion, &mut newest, &mut late) } Ok(Command::Flushed(shard, raw_data)) => { flushed[shard] = true; @@ -1056,6 +1085,18 @@ fn serve_ingest( if !queue_refreshes(&closed, &snapshot, &jobs, shared, pushed) { break; } + for (window, samples) in std::mem::take(&mut late) { + let mut raw_data = ingestion.late_raw_data(); + raw_data.append(&samples); + let job = PrecomputeJob::Late { + window, + raw_data: Arc::new(vec![Arc::new(raw_data)]), + samples: samples.len() as u64, + }; + if jobs.send(job).is_err() { + break 'serve; + } + } let routing = Arc::new(ingestion.routing()); *shared.routing.write().unwrap_or_else(|e| e.into_inner()) = routing.clone(); let watermark_ms = ingestion.watermark_ms(); @@ -1497,6 +1538,9 @@ fn serve_precompute( 1 }; let mut tasks = WindowTasks::new(precompute.tasks().clone(), parts as u32); + // Late samples by window, merged once it and the windows built from it + // are committed: each window's raw data parts and sample count. + let mut late: BTreeMap>, u64)> = BTreeMap::new(); let mut closed = false; while !(closed && tasks.is_empty()) { let Ok(event) = inbox.recv() else { @@ -1518,6 +1562,15 @@ fn serve_precompute( tasks.push_window(window, closed_at, options.push_parts) } PoolEvent::Partial(partial) => tasks.partial(partial), + PoolEvent::Job(PrecomputeJob::Late { + window, + raw_data, + samples, + }) => { + let (parts, count) = late.entry(window).or_default(); + parts.extend(raw_data.iter().cloned()); + *count += samples; + } PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { tasks.barrier(barrier_ms, reply) } @@ -1578,6 +1631,23 @@ fn serve_precompute( committed = true; slots.release(); } + let ready: Vec = late + .keys() + .copied() + .filter(|&window| precompute.late_ready(window, &views)) + .collect(); + for window in ready { + let (parts, samples) = late.remove(&window).expect("listed"); + merge_late( + precompute, + window, + (Arc::new(parts), samples), + &mut views, + &mut to_persist, + shared, + ); + committed = true; + } if committed { shared.published.publish_views(views.clone()); shared @@ -1586,12 +1656,8 @@ fn serve_precompute( .store(views.bytes() as u64, Ordering::Relaxed); } if let Some(persist) = &persist { - for (group, range_ms, appended) in to_persist { - let slots = appended - .iter() - .map(|(view, _)| views.slot(*view, range_ms.1)) - .collect(); - persist.queue(group, range_ms, appended, slots); + for (group, range_ms, revision, appended, slots) in to_persist { + persist.queue(group, range_ms, appended, slots, revision); } } for (barrier_ms, reply) in tasks.passed_barriers() { @@ -1611,9 +1677,62 @@ fn serve_precompute( tracing::warn!("precompute stopped"); } -/// A window persisted after the views are published: its group, range -/// and each view's rows. -type ToPersist = (usize, (i64, i64), Vec<(PhysicalASAPNodeId, Vec)>); +/// A window persisted after the views are published: its group, range, +/// revision, each view's rows, and each view's stored window as committed +/// (told where it was written; a later merge in the same pass replaces it +/// with a slot of its own). +type ToPersist = ( + usize, + (i64, i64), + u64, + Vec<(PhysicalASAPNodeId, Vec)>, + Vec>>, +); + +/// Merges the late samples of the committed `window` (its raw data parts +/// and how many samples they hold) into it and into the windows built from +/// it, and queues the changed windows to be written again. Samples whose +/// window is no longer stored, or whose merge fails, are dropped and +/// counted. +fn merge_late( + precompute: &Precompute, + window: ClosedWindow, + (raw_data, samples): (RawShards, u64), + views: &mut Arc, + to_persist: &mut Vec, + shared: &Shared, +) { + let merged = precompute.merge_late(window, raw_data, views); + let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); + match merged { + Ok(changed) => { + let merged_any = changed.iter().any(|c| !c.rows.is_empty()); + if merged_any { + stats.samples_merged_late += samples; + } else { + stats.samples_dropped_late += samples; + } + for change in changed.into_iter().filter(|c| !c.rows.is_empty()) { + let slots = change + .rows + .iter() + .map(|(view, _)| views.slot(*view, change.range_ms.1)) + .collect(); + to_persist.push(( + change.group, + change.range_ms, + change.revision, + change.rows, + slots, + )); + } + } + Err(error) => { + tracing::error!(group = window.group, end = window.end_ms, %error, "merging late samples failed"); + stats.samples_dropped_late += samples; + } + } +} /// Stores a computed window's rows in `views` and counts it. fn commit_window( @@ -1694,7 +1813,11 @@ fn commit_window( Ok(Refreshed::Ran(appended)) => { stats.windows_refreshed += 1; let start_ms = window.end_ms - precompute.width_ms(window.group); - to_persist.push((window.group, (start_ms, window.end_ms), appended)); + let slots = appended + .iter() + .map(|(view, _)| views.slot(*view, window.end_ms)) + .collect(); + to_persist.push((window.group, (start_ms, window.end_ms), 0, appended, slots)); } Ok(Refreshed::AlreadyStored) => stats.windows_already_stored += 1, Err(error) => { diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 52bcd9f8d..4b36a75be 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -91,16 +91,17 @@ impl Default for IngestionOptions { pub struct IngestionStats { /// Samples stored as raw data. pub samples_accepted: u64, - /// Samples older than every window still to be refreshed and every - /// query-time `Scan`'s retention. + /// Samples with nowhere to go: older than every window still to be + /// refreshed and every query-time `Scan`'s retention, and in no + /// committed window still within its views' retention. pub samples_dropped_late: u64, /// Samples more than `max_future_ms` ahead of the wall clock. pub samples_dropped_future: u64, /// Samples of a metric no `Scan` reads. pub samples_unrouted: u64, - /// Samples accepted after every window of every group scanning their - /// metric that holds them was closed: in no view. - pub samples_late_for_views: u64, + /// Samples merged into a window already committed (late, within its + /// views' retention), counted once per group window they changed. + pub samples_merged_late: u64, /// Ingestion runs that refreshed a group's window and stored its rows. pub windows_refreshed: u64, /// Ingestion runs that failed; their window is not stored. @@ -140,7 +141,7 @@ const IDLE_GRACE_MS: i64 = 1_000; /// A refresh group's window `(end_ms - W, end_ms]` that the watermark has /// passed, to refresh; `group` indexes the plan's ingestion refresh groups. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub(crate) struct ClosedWindow { pub group: usize, pub end_ms: i64, @@ -153,6 +154,7 @@ struct RefreshGroupRun { views: Vec, compiled: CompiledPhysicalDAG, width_ms: i64, + phase_ms: i64, /// The views of other groups its runs read. reads: Vec, /// For each of its views, the groups that read it. @@ -179,6 +181,13 @@ struct RefreshGroup { refreshed_through: Option, } +impl RefreshGroupRun { + /// The end of the group's window holding `timestamp_ms`. + fn window_end(&self, timestamp_ms: i64) -> i64 { + window_end(timestamp_ms - self.phase_ms, self.width_ms) + self.phase_ms + } +} + impl RefreshGroup { /// The end of the group's window holding `timestamp_ms`. fn window_end(&self, timestamp_ms: i64) -> i64 { @@ -315,6 +324,7 @@ impl Ingestion { views, compiled, width_ms: millis(window.width_ms), + phase_ms: millis(window.phase_ms), reads: read.iter().copied().collect(), readers: Vec::new(), }); @@ -419,6 +429,12 @@ impl Ingestion { RawData::for_metrics(kept, self.pane_width_ms) } + /// An empty raw store for every metric the plan scans, push groups' + /// included: what a late merge's run reads its late samples from. + pub(crate) fn late_raw_data(&self) -> RawData { + RawData::for_metrics(self.scanned_metrics.iter(), self.pane_width_ms) + } + /// Builds groups `push` (by index) by push: their windows read no raw /// data. Call before [`Self::raw_data`]. pub(crate) fn set_push_groups(&mut self, push: Vec) { @@ -553,6 +569,7 @@ impl Ingestion { .map(|metric| (metric.clone(), self.oldest_kept_ms(metric))) .collect(); let watermark_ms = self.watermark_ms(); + let kept_after_ms = self.kept_after_ms(); let late_through = cutoffs .iter() .map(|(metric, &cutoff)| { @@ -579,21 +596,53 @@ impl Ingestion { cutoffs, late_through, groups_waiting: self.groups.iter().any(|g| g.refreshed_through.is_none()), - views_closed_through: self + committed: self .scanned_metrics .iter() .map(|metric| { - let closed = self + let groups = self .groups .iter() - .filter(|g| g.metrics.contains(metric)) - .map(|g| g.refreshed_through) - .min() - .flatten(); - (metric.clone(), closed) + .enumerate() + .filter(|(index, g)| !self.is_push(*index) && g.metrics.contains(metric)) + .filter_map(|(index, g)| { + Some(CommittedWindows { + group: index, + width_ms: g.width_ms, + phase_ms: g.phase_ms, + through_ms: g.refreshed_through?, + kept_after_ms: kept_after_ms[index]?, + }) + }) + .collect(); + (metric.clone(), groups) }) .collect(), + kept_after_ms, + } + } + + /// Per group, the end after which a closed window of it still changes + /// a stored window when late samples merge into it: its views keep + /// their windows ending after their longest retention back from its + /// newest closed one, and the groups reading them (transitively) keep + /// theirs, which the change reaches though the group's own window is + /// gone. `None` before the group's first window. + fn kept_after_ms(&self) -> Vec> { + let mut kept: Vec> = self + .groups + .iter() + .map(|g| Some(g.refreshed_through?.saturating_sub(g.retention_ms))) + .collect(); + // Readers come after the groups they read. + for reader in (0..self.groups.len()).rev() { + for &read in &self.groups[reader].reads { + if let (Some(own), Some(theirs)) = (kept[read], kept[reader]) { + kept[read] = Some(own.min(theirs)); + } + } } + kept } /// Takes in what a shard routed: each metric's first sample starts @@ -788,9 +837,26 @@ pub(crate) struct Routing { /// Some group has not seen its first sample: report each metric's /// first sample. groups_waiting: bool, - /// Each scanned metric's samples at or before this are in a window - /// every group scanning it has closed (`None`: no group closed one). - views_closed_through: HashMap>, + /// Each scanned metric's groups (built from raw data, not by push) with + /// windows closed: a sample in one of their closed windows still kept + /// is merged into it ([`Precompute::merge_late`]). + committed: HashMap>, + /// Per group, a closed window ending after this changes a stored + /// window ([`Ingestion::kept_after_ms`]). + kept_after_ms: Vec>, +} + +/// A refresh group's closed windows, as the ingest shards route by them. +#[derive(Debug, Clone)] +struct CommittedWindows { + group: usize, + width_ms: i64, + phase_ms: i64, + /// Its windows ending at or before this are closed. + through_ms: i64, + /// A closed window ending after this changes a stored window + /// ([`Ingestion::kept_after_ms`]). + kept_after_ms: i64, } /// One batch of samples routed by a shard. @@ -803,13 +869,18 @@ pub(crate) struct Routed { pub newest_ms: Option, /// Each metric's first routed sample, while a group waits for one. pub first_seen: Vec<(Arc, i64)>, + /// Samples of windows already closed and still kept, by window: to + /// merge into them. + pub late: Vec<(ClosedWindow, RawSample)>, } impl Routing { /// Routes `samples` at `now_ms`: drops samples of metrics no `Scan` - /// reads, samples more than `max_future_ms` ahead of `now_ms` or - /// further from the epoch than [`MAX_TIME_MS`], and late samples (at - /// or before their metric's `late_through`). + /// reads, and samples more than `max_future_ms` ahead of `now_ms` or + /// further from the epoch than [`MAX_TIME_MS`]. A sample in a closed + /// window still kept is routed to that window's late merge; one at or + /// before its metric's `late_through` is not stored as raw data, and + /// is dropped when no window takes it either. pub(crate) fn route(&self, samples: Vec, now_ms: i64) -> Routed { let latest_allowed_ms = now_ms.saturating_add(self.max_future_ms); let mut routed = Routed { @@ -818,7 +889,7 @@ impl Routing { }; // Samples of one metric usually come together: the last metric is // checked by pointer first. - let mut metrics: Vec<(Arc, bool, Option, bool)> = Vec::new(); + let mut metrics: Vec<(Arc, bool, Option, bool, &[CommittedWindows])> = Vec::new(); let mut last: Option = None; for sample in samples { let metric = &sample.labels.metric; @@ -830,12 +901,13 @@ impl Routing { None => { let routed = self.scanned_metrics.contains(&**metric); let late_through = self.late_through.get(&**metric).copied().flatten(); - metrics.push((metric.clone(), routed, late_through, false)); + let committed = self.committed.get(&**metric).map_or(&[][..], Vec::as_slice); + metrics.push((metric.clone(), routed, late_through, false, committed)); metrics.len() - 1 } }; last = Some(index); - let (_, is_routed, late_through, seen) = &mut metrics[index]; + let (_, is_routed, late_through, seen, committed) = &mut metrics[index]; if !*is_routed { routed.stats.samples_unrouted += 1; continue; @@ -856,26 +928,42 @@ impl Routing { .first_seen .push((metric.clone(), sample.timestamp_ms)); } + let mut merged = false; + for group in committed.iter() { + let end = window_end(sample.timestamp_ms - group.phase_ms, group.width_ms) + + group.phase_ms; + if end <= group.through_ms && end > group.kept_after_ms { + let window = ClosedWindow { + group: group.group, + end_ms: end, + }; + routed.late.push((window, sample.clone())); + merged = true; + } + } if late_through.is_some_and(|late| sample.timestamp_ms <= late) { - routed.stats.samples_dropped_late += 1; + if !merged { + routed.stats.samples_dropped_late += 1; + } continue; } routed.newest_ms = routed.newest_ms.max(Some(sample.timestamp_ms)); - if self - .views_closed_through - .get(&**metric) - .copied() - .flatten() - .is_some_and(|closed| sample.timestamp_ms <= closed) - { - routed.stats.samples_late_for_views += 1; - } routed.accepted.push(sample); routed.stats.samples_accepted += 1; } routed } + /// Whether late samples of `window`, closed, still change a stored + /// window, so they are merged. + pub(crate) fn keeps(&self, window: ClosedWindow) -> bool { + self.kept_after_ms + .get(window.group) + .copied() + .flatten() + .is_some_and(|kept_after| window.end_ms > kept_after) + } + /// Seals and evicts `raw_data` as the ingestion stands: compacts the /// panes the watermark has passed and drops the panes at or before /// each metric's cutoff. @@ -891,6 +979,19 @@ impl Routing { } } +/// A committed window late samples changed ([`Precompute::merge_late`]). +#[derive(Debug)] +pub(crate) struct LateMerged { + pub group: usize, + pub range_ms: (i64, i64), + /// The window's revision after the change. + pub revision: u64, + /// Each of its views' merged rows, as now stored. + pub rows: Vec<(PhysicalASAPNodeId, Vec)>, + /// Each of its views' change: the rows of the run over the change alone. + late: Vec<(PhysicalASAPNodeId, Vec)>, +} + /// What a refresh did. #[derive(Debug)] pub enum Refreshed { @@ -1020,7 +1121,6 @@ impl Precompute { ) -> Result { let group = &self.runs[window.group]; let end = window.end_ms; - let start = end - group.width_ms; // Views loaded from files may already store the window. let missing: Vec = (0..group.views.len()) .filter(|&index| { @@ -1032,22 +1132,34 @@ impl Precompute { if missing.is_empty() { return Ok(Computed::AlreadyStored); } - let outputs = { - let store = Arc::new(RunStore::for_partition(raw_data, views, partition)); - let instance = group.compiled.instantiate(store)?; - let context = RunContext::new( - Scope::Ingestion { - window_start_ms: start, - window_end_ms: end, - }, - self.limits.clone(), - )?; - let outputs = block_on(instance.execute_ingestion(group.compiled.roots(), context)?)?; - outputs - }; + let outputs = self.run(window.group, end, raw_data, views, partition)?; Ok(self.computed(window.group, missing, outputs)) } + /// Group `group`'s ingestion run over its window ending `end`, reading + /// `raw_data` and `views`: one output per root. + fn run( + &self, + group: usize, + end: i64, + raw_data: RawShards, + views: Arc, + partition: Option, + ) -> Result, asap_executor::Error> { + let group = &self.runs[group]; + let store = Arc::new(RunStore::for_partition(raw_data, views, partition)); + let instance = group.compiled.instantiate(store)?; + let context = RunContext::new( + Scope::Ingestion { + window_start_ms: end - group.width_ms, + window_end_ms: end, + }, + self.limits.clone(), + )?; + let outputs = block_on(instance.execute_ingestion(group.compiled.roots(), context)?)?; + Ok(outputs) + } + /// The rows of views `missing` (by index in the group) from a run's /// outputs, one per root. fn computed>( @@ -1198,6 +1310,138 @@ impl Precompute { Ok(Refreshed::Ran(appended)) } + /// Whether late samples of `window` may be merged now: its group's views + /// and those of every group reading them (transitively) are committed + /// through the window of theirs holding it, so no run still in flight + /// read the window before the merge, and every window built from it is + /// committed to take the change ([`Self::merge_late`]). + pub(crate) fn late_ready(&self, window: ClosedWindow, views: &ViewStore) -> bool { + self.readers_of(window.group).into_iter().all(|group| { + let run = &self.runs[group]; + let end = run.window_end(window.end_ms); + run.views + .iter() + .all(|view| views.stored_through(view.node_id) >= Some(end)) + }) + } + + /// `group` and the groups reading its views, transitively, in plan + /// order (a reader comes after what it reads). + fn readers_of(&self, group: usize) -> BTreeSet { + let mut found = BTreeSet::from([group]); + let mut pending = vec![group]; + while let Some(group) = pending.pop() { + for &reader in self.runs[group].readers.iter().flatten() { + if found.insert(reader) { + pending.push(reader); + } + } + } + found + } + + /// Merges `raw_data`, the late samples 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). Each + /// group's change is its run over the change alone: its late samples, + /// or the rows the windows it reads gained, with nothing else in its + /// raw data or views; [`ViewStore::merge_late`] merges those rows into + /// the window's, so the window ends as if the samples had come on + /// time (each state merge is its kernel's). Returns each changed + /// window, to write again; a view whose window is no longer stored + /// takes no change. + pub(crate) fn merge_late( + &self, + window: ClosedWindow, + raw_data: RawShards, + views: &mut Arc, + ) -> Result, asap_executor::Error> { + let empty_raw: RawShards = + Arc::new(raw_data.iter().map(|r| Arc::new(r.emptied())).collect()); + // Per group to change, the window and the raw data its change reads. + let mut changed: Vec = Vec::new(); + for group in self.readers_of(window.group) { + let run = &self.runs[group]; + let end = run.window_end(window.end_ms); + let raw = if group == window.group { + raw_data.clone() + } else { + empty_raw.clone() + }; + // The windows it reads, as the change left them: the rows each + // gained, empty elsewhere. + let mut read = ViewStore::default(); + let start = end - run.width_ms; + let mut reads_change = false; + for &view_id in &run.reads { + let Some((source, width_ms)) = self.view(view_id) else { + continue; + }; + read.hold_for_readers(view_id, &[group]); + let mut window_start = start; + while window_start < end { + let window_end = window_start + width_ms; + let rows = changed + .iter() + .filter(|c| c.range_ms.1 == window_end) + .flat_map(|c| &c.late) + .find(|(v, _)| *v == view_id) + .map(|(_, rows)| rows.clone()) + .unwrap_or_default(); + reads_change |= !rows.is_empty(); + read.append(source, (window_start, window_end), rows)?; + window_start = window_end; + } + } + if group != window.group && !reads_change { + continue; + } + let outputs = self.run(group, end, raw, Arc::new(read), None)?; + let Computed::Ran(late) = self.computed(group, (0..run.views.len()).collect(), outputs) + else { + continue; + }; + let late: Vec<(PhysicalASAPNodeId, Vec)> = late + .into_iter() + .map(|(index, batches)| (run.views[index].node_id, batches)) + .filter(|(_, batches)| batches.iter().any(|b| b.num_rows() > 0)) + .collect(); + if late.is_empty() { + continue; + } + let revision = late + .iter() + .filter_map(|(view, _)| views.window_revision(*view, end)) + .max() + .map_or(0, |revision| revision + 1); + let store = Arc::make_mut(views); + let mut rows = Vec::new(); + for (view, batches) in &late { + if let Some(merged) = store.merge_late(*view, end, revision, batches.clone())? { + rows.push((*view, merged)); + } + } + changed.push(LateMerged { + group, + range_ms: (end - run.width_ms, end), + revision, + rows, + late, + }); + } + Ok(changed) + } + + /// View `id` of some group, with that group's window width. + fn view(&self, id: PhysicalASAPNodeId) -> Option<(&MaterializedView, i64)> { + self.runs.iter().find_map(|run| { + run.views + .iter() + .find(|view| view.node_id == id) + .map(|view| (view, run.width_ms)) + }) + } + /// Which windows may be computed at once. pub(crate) fn tasks(&self) -> &RefreshTaskGraph { &self.tasks diff --git a/crates/precompute/src/push.rs b/crates/precompute/src/push.rs index ed7e87e3f..763385aa9 100644 --- a/crates/precompute/src/push.rs +++ b/crates/precompute/src/push.rs @@ -324,6 +324,9 @@ pub(crate) struct PushShard { /// Accepted samples not folded yet, and when the oldest came. pending: Vec, pending_since: Option, + /// Samples pushed for windows this shard already sealed, by window: to + /// merge into the committed windows ([`Self::take_late`]). + late: Vec<(ClosedWindow, RawSample)>, } /// How a shard coalesces its routed samples into morsels before folding: @@ -377,6 +380,7 @@ impl PushShard { batching, pending: Vec::new(), pending_since: None, + late: Vec::new(), } } @@ -388,6 +392,21 @@ impl PushShard { if self.metrics.is_empty() { return; } + // A window is sealed only after what is pending is folded, so a + // sample of a window sealed now is late whenever it is folded. + for sample in samples { + for (group, spec) in self.groups.iter().enumerate() { + let Some(spec) = spec else { continue }; + if !spec.metrics.contains(&*sample.labels.metric) { + continue; + } + let end = spec.window_end(sample.timestamp_ms); + if self.sealed_through[group].is_some_and(|sealed| end <= sealed) { + let window = ClosedWindow { group, end_ms: end }; + self.late.push((window, sample.clone())); + } + } + } if self.batching.max_samples <= 1 { self.fold(samples, metrics); return; @@ -452,40 +471,31 @@ impl PushShard { } /// Folds `samples` (accepted, of this shard's series) into the open - /// windows they fall in; returns the samples late for every push - /// group's views (their window already sealed), which are not folded. - fn fold(&mut self, samples: &[RawSample], metrics: &Metrics) -> u64 { + /// windows they fall in, not into a window already sealed. + fn fold(&mut self, samples: &[RawSample], metrics: &Metrics) { if samples.is_empty() || self.metrics.is_empty() { - return 0; + return; } // Each group's samples by the window they fall in: a window's // instance gets a morsel of its own samples only, so a large // window does not cost a small one's run. - let mut late = 0; let mut by_window: Vec>> = vec![BTreeMap::new(); self.groups.len()]; for sample in samples { - let mut late_for_all = true; - let mut any = false; for (group, spec) in self.groups.iter().enumerate() { let Some(spec) = spec else { continue }; if !spec.metrics.contains(&*sample.labels.metric) { continue; } - any = true; let end = spec.window_end(sample.timestamp_ms); if self.sealed_through[group].is_some_and(|sealed| end <= sealed) { continue; } - late_for_all = false; by_window[group] .entry(end) .or_default() .push(sample.clone()); } - if any && late_for_all { - late += 1; - } } for (group, windows) in by_window.into_iter().enumerate() { if windows.is_empty() { @@ -524,7 +534,12 @@ impl PushShard { } } self.account(metrics); - late + } + + /// The samples pushed so far for windows already sealed, each with its + /// window, taken. + pub fn take_late(&mut self) -> Vec<(ClosedWindow, RawSample)> { + std::mem::take(&mut self.late) } /// Publishes this shard's open state and, over the memory budget, diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index df46270bc..228efba04 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -232,10 +232,15 @@ impl CompiledQueries { } /// The result cache's answer at `time_ms` of the query planned at - /// `root`, if it keeps one. - pub fn cached(&self, root: PhysicalASAPNodeId, time_ms: i64) -> Option { + /// `root`, if it keeps one that `snapshot`'s views have not revised. + pub fn cached( + &self, + root: PhysicalASAPNodeId, + time_ms: i64, + snapshot: &Snapshot, + ) -> Option { let cache = self.result_cache.as_ref()?; - cache.get(self.root(root).ok()?, time_ms) + cache.get(self.root(root).ok()?, time_ms, &snapshot.views) } /// The result cache, when it is on. @@ -285,7 +290,13 @@ impl CompiledQueries { let final_answer = !self.reads_raw_data.contains(&root) || watermark_ms.is_some_and(|watermark| time_ms <= watermark); if final_answer { - cache.insert(root, time_ms, answer.clone(), watermark_ms); + cache.insert( + root, + time_ms, + answer.clone(), + watermark_ms, + snapshot.views.revision(), + ); } } Ok(answer) @@ -301,10 +312,13 @@ impl CompiledQueries { snapshot: &Snapshot, ) -> Result>, Unanswered> { if self.shared.contains(&node) { - self.results - .get_or_compute(node, time_ms, snapshot.watermark_ms, || { - self.run(node, time_ms, snapshot) - }) + self.results.get_or_compute( + node, + time_ms, + snapshot.watermark_ms, + &snapshot.views, + || self.run(node, time_ms, snapshot), + ) } else { self.run(node, time_ms, snapshot).map(Arc::new) } diff --git a/crates/query/src/result_cache.rs b/crates/query/src/result_cache.rs index 10dd75b2e..84f5fbdc9 100644 --- a/crates/query/src/result_cache.rs +++ b/crates/query/src/result_cache.rs @@ -7,7 +7,9 @@ //! ([`crate::CompiledQueries`] decides). Entries are dropped once `T` //! falls further behind the watermark than any planned evaluation reaches //! back (the plan's longest retention plus the view retention margin), and -//! the least recently used while more than `max_bytes` are held. +//! the least recently used while more than `max_bytes` are held. An answer +//! read from views late samples revised since ([`ViewStore::changed_since`]) +//! is stale: a lookup drops it. use std::collections::{BTreeMap, BTreeSet, HashMap}; use std::sync::atomic::{AtomicU64, Ordering}; @@ -17,12 +19,15 @@ use asap_executor::planner::ir::{NonASAPOp, Operator}; use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; use common::{Answer, ResultSample}; +use storage::store::ViewStore; /// An entry's key: the query root and the evaluation time. type Key = (PhysicalASAPNodeId, i64); struct Entry { answer: Answer, + /// The revision of the views it was computed from. + revision: u64, bytes: usize, /// When it was last read or stored, on the cache's use clock. used: u64, @@ -88,12 +93,20 @@ impl ResultCache { i64::try_from(longest.saturating_add(margin_ms)).ok() } - /// `root`'s answer at `time_ms`, if kept. - pub fn get(&self, root: PhysicalASAPNodeId, time_ms: i64) -> Option { + /// `root`'s answer at `time_ms`, if kept and no window it read was + /// revised since, as of `views` (a stale answer is dropped). + pub fn get(&self, root: PhysicalASAPNodeId, time_ms: i64, views: &ViewStore) -> Option { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); let entries = &mut *entries; entries.clock += 1; let clock = entries.clock; + if entries + .by_key + .get(&(root, time_ms)) + .is_some_and(|entry| views.changed_since(entry.revision, time_ms)) + { + entries.remove((root, time_ms)); + } let Some(entry) = entries.by_key.get_mut(&(root, time_ms)) else { self.misses.fetch_add(1, Ordering::Relaxed); return None; @@ -105,15 +118,17 @@ impl ResultCache { Some(entry.answer.clone()) } - /// Keeps `answer`, `root`'s final answer at `time_ms`, then drops what - /// is older than the horizon behind `watermark_ms` and the least - /// recently used beyond `max_bytes`. + /// Keeps `answer`, `root`'s final answer at `time_ms` computed from + /// views at `revision`, then drops what is older than the horizon + /// behind `watermark_ms` and the least recently used beyond + /// `max_bytes`. pub fn insert( &self, root: PhysicalASAPNodeId, time_ms: i64, answer: Answer, watermark_ms: Option, + revision: u64, ) { let bytes = answer_bytes(&answer); let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); @@ -125,6 +140,7 @@ impl ResultCache { (root, time_ms), Entry { answer, + revision, bytes, used, }, @@ -221,15 +237,19 @@ mod tests { /// horizon behind the watermark is dropped. #[test] fn evicts_by_age() { + let views = ViewStore::default(); let cache = ResultCache::new(Some(60_000), usize::MAX); - cache.insert(1, 10_000, answer(2), Some(10_000)); - assert_eq!(cache.get(1, 10_000).unwrap().len(), 2); - assert!(cache.get(2, 10_000).is_none()); - assert!(cache.get(1, 20_000).is_none()); - cache.insert(1, 70_000, answer(1), Some(70_000)); - assert!(cache.get(1, 10_000).is_some(), "exactly at the horizon"); - cache.insert(1, 71_000, answer(1), Some(71_000)); - assert!(cache.get(1, 10_000).is_none()); + cache.insert(1, 10_000, answer(2), Some(10_000), 0); + assert_eq!(cache.get(1, 10_000, &views).unwrap().len(), 2); + assert!(cache.get(2, 10_000, &views).is_none()); + assert!(cache.get(1, 20_000, &views).is_none()); + cache.insert(1, 70_000, answer(1), Some(70_000), 0); + assert!( + cache.get(1, 10_000, &views).is_some(), + "exactly at the horizon" + ); + cache.insert(1, 71_000, answer(1), Some(71_000), 0); + assert!(cache.get(1, 10_000, &views).is_none()); assert_eq!(cache.evictions(), 1); assert_eq!((cache.hits(), cache.misses()), (2, 3)); assert_eq!(cache.len(), 2); @@ -239,14 +259,15 @@ mod tests { #[test] fn evicts_least_recently_used_by_bytes() { let one = answer_bytes(&answer(10)); + let views = ViewStore::default(); let cache = ResultCache::new(None, 2 * one); - cache.insert(1, 1, answer(10), None); - cache.insert(1, 2, answer(10), None); - cache.get(1, 1); - cache.insert(1, 3, answer(10), None); - assert!(cache.get(1, 1).is_some()); - assert!(cache.get(1, 2).is_none(), "least recently used"); - assert!(cache.get(1, 3).is_some()); + cache.insert(1, 1, answer(10), None, 0); + cache.insert(1, 2, answer(10), None, 0); + cache.get(1, 1, &views); + cache.insert(1, 3, answer(10), None, 0); + assert!(cache.get(1, 1, &views).is_some()); + assert!(cache.get(1, 2, &views).is_none(), "least recently used"); + assert!(cache.get(1, 3, &views).is_some()); assert_eq!(cache.bytes(), 2 * one); assert_eq!(cache.evictions(), 1); } diff --git a/crates/query/src/workers.rs b/crates/query/src/workers.rs index e57683c8b..f07123e3c 100644 --- a/crates/query/src/workers.rs +++ b/crates/query/src/workers.rs @@ -74,7 +74,7 @@ impl InstalledQueries { time_ms: i64, ) -> Result { let root = self.root(source)?; - if let Some(answer) = self.compiled.cached(root, time_ms) { + if let Some(answer) = self.compiled.cached(root, time_ms, &self.snapshot()) { return Ok(answer); } let started = std::time::Instant::now(); @@ -100,14 +100,14 @@ impl InstalledQueries { let root = self.root(source)?; let started = std::time::Instant::now(); let metrics = self.compiled.metrics_index(query); + // Every step reads the same snapshot, so the raw data they share is + // converted once ([`storage::store::RawReads`]). + let snapshot = self.snapshot(); // The steps the result cache answers; only the others run. let cached: Vec<(i64, Option)> = times_ms - .map(|time_ms| (time_ms, self.compiled.cached(root, time_ms))) + .map(|time_ms| (time_ms, self.compiled.cached(root, time_ms, &snapshot))) .collect(); let from_cache = cached.iter().filter(|(_, hit)| hit.is_some()).count(); - // Every step reads the same snapshot, so the raw data they share is - // converted once ([`storage::store::RawReads`]). - let snapshot = self.snapshot(); // At most one step per query worker in flight, so a long range neither // floods the workers' queue nor starves instant queries; the client // going away drops the rest unrun. Every step runs even when one fails: diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index e49fdafee..2d0fe406d 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -371,12 +371,15 @@ impl ViewFiles { /// per retention of `group`'s views, each to the active segment of that /// retention (rolling to a new one when due), synced with the other /// files once the sync interval has passed. A view holding a state with - /// no byte encoding is left out of the record and counted. + /// no byte encoding is left out of the record and counted. `revision` + /// is the window's: a window revised by late samples is appended again + /// with a higher one, and [`Self::index`] reads the highest. pub fn append( &mut self, group: usize, range_ms: (i64, i64), views: &[(PhysicalASAPNodeId, &[Batch])], + revision: u64, ) -> std::io::Result { let mut by_retention: BTreeMap> = BTreeMap::new(); for &(view, batches) in views { @@ -387,7 +390,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)?; + 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); @@ -404,6 +407,7 @@ impl ViewFiles { retention_ms: i64, (start_ms, end_ms): (i64, i64), views: &[(PhysicalASAPNodeId, &[Batch])], + revision: u64, ) -> std::io::Result { let mut written = Written::default(); let segment_ms = self.segment_ms; @@ -510,6 +514,7 @@ impl ViewFiles { .zip(&placed[2..]) .map(|((view, _), (offset, len))| (*view, *offset, *len)) .collect(), + revision, })?; for (i, text) in new_texts.into_iter().enumerate() { active.texts.insert(text, base + i as u32); @@ -520,7 +525,12 @@ impl ViewFiles { .map(|&(view, offset, len)| { ( view, - WindowLocation::new(active.segment.clone(), (offset, len), head.grids), + WindowLocation::new( + active.segment.clone(), + (offset, len), + head.grids, + head.revision, + ), ) }) .collect(); @@ -532,7 +542,9 @@ impl ViewFiles { /// The windows of `groups` (each refresh group's views with their /// output schemas) within each view's retention of its newest window, /// with their locations, oldest first, read from record heads only: - /// no fragment is decoded. Every segment found is sealed; appends start + /// no fragment is decoded; of a window written more than once (revised + /// by late samples), the record of the highest revision. Every segment + /// found is sealed; appends start /// 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 @@ -603,7 +615,12 @@ impl ViewFiles { for &(view, offset, len) in &head.views { by_view.entry(view).or_default().push(( (head.start_ms, head.end_ms), - WindowLocation::new(segment.clone(), (offset, len), head.grids), + WindowLocation::new( + segment.clone(), + (offset, len), + head.grids, + head.revision, + ), )); } } @@ -620,7 +637,16 @@ impl ViewFiles { let Some(mut windows) = by_view.remove(&view.node_id) else { continue; }; - windows.sort_by_key(|(range, _)| *range); + // A window revised by late samples has a record per + // revision: the highest is its rows. + windows.sort_by_key(|(range, location)| (*range, location.revision())); + windows.dedup_by(|later, earlier| { + let same = later.0 == earlier.0; + if same { + std::mem::swap(later, earlier); + } + same + }); let Some(newest_end) = windows.last().map(|(range, _)| range.1) else { continue; }; @@ -1381,7 +1407,7 @@ mod tests { let batch = ten_sample_ddsketch_window(); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let written = files - .append(0, (0, 1_000), &[(1, std::slice::from_ref(&batch))]) + .append(0, (0, 1_000), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); let views: usize = crate::segment::view_bytes(&batch.schema().fields[4].dtype, &sources_of(&batch), 4) @@ -1404,7 +1430,7 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let written = files - .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); assert_eq!(written.not_persisted, 0, "{what}"); let location = location_of(&written, 1); @@ -1435,7 +1461,7 @@ mod tests { assert_eq!(empty.num_rows(), 0); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let written = files - .append(0, (0, 10), &[(1, std::slice::from_ref(&empty))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&empty))], 0) .unwrap(); let location = location_of(&written, 1); for how in [ViewRead::Pread, ViewRead::Mmap] { @@ -1460,7 +1486,7 @@ mod tests { .enumerate() .map(|(i, batch)| (i as PhysicalASAPNodeId + 1, std::slice::from_ref(batch))) .collect(); - let written = files.append(0, (0, 10), &views).unwrap(); + let written = files.append(0, (0, 10), &views, 0).unwrap(); files.seal(0).unwrap(); let damaged = location_of(&written, 2); let mut file = OpenOptions::new() @@ -1513,10 +1539,10 @@ mod tests { ); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let w1 = files - .append(0, (0, 10), &[(1, std::slice::from_ref(&first))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&first))], 0) .unwrap(); let w2 = files - .append(0, (10, 20), &[(1, std::slice::from_ref(&second))]) + .append(0, (10, 20), &[(1, std::slice::from_ref(&second))], 0) .unwrap(); files.seal(0).unwrap(); let (l1, l2) = (location_of(&w1, 1), location_of(&w2, 1)); @@ -1622,6 +1648,7 @@ mod tests { (1, std::slice::from_ref(&labeled)), (2, std::slice::from_ref(&other)), ], + 0, ) .unwrap(); let (l1, l2) = (location_of(&written, 1), location_of(&written, 2)); @@ -1638,7 +1665,7 @@ mod tests { // values built for the first read are extended by the new texts. let later = labeled_window(20, series + 50, true); let later_written = files - .append(0, (10, 20), &[(1, std::slice::from_ref(&later))]) + .append(0, (10, 20), &[(1, std::slice::from_ref(&later))], 0) .unwrap(); let l3 = location_of(&later_written, 1); assert!(!l3.is_sealed()); @@ -1705,7 +1732,7 @@ mod tests { let groups = vec![vec![(view, 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))]) + .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); @@ -1738,7 +1765,7 @@ mod tests { let (_, batch) = every_family().remove(0); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let written = files - .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); files.seal(0).unwrap(); let location = location_of(&written, 1); @@ -1781,7 +1808,7 @@ mod tests { .with_view_retention_ms(BTreeMap::from([(1, 20)])); for end in (10..=60).step_by(10) { files - .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))]) + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); } assert_eq!(segment_files(&dir).len(), 3, "(0, 20], (20, 40], (40, 60]"); @@ -1816,6 +1843,7 @@ mod tests { (short, std::slice::from_ref(&batch)), (long, std::slice::from_ref(&batch)), ], + 0, ) .unwrap(); oldest.get_or_insert((location_of(&written, short), location_of(&written, long))); @@ -1856,7 +1884,7 @@ mod tests { let mut marked_cold = 0; for end in (10..=80).step_by(10) { let written = files - .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))]) + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); marked_cold += written.segments_marked_cold; locations.push(location_of(&written, 1)); @@ -1883,6 +1911,88 @@ mod tests { 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 + /// the segments' order. A record head written before revisions existed + /// reads as revision 0. + #[test] + fn the_highest_revision_of_a_window_is_indexed() { + let dir = segment_dir("revisions"); + let families = every_family(); + let (first, second) = (families[0].1.clone(), families[1].1.clone()); + let view: MaterializedView = serde_json::from_value(serde_json::json!({ + "node_id": 1, + "refresh": "at_ingestion", + "plan_id": "test-plan", + "view_state_key": {"definition_id": "v", "window": null, + "logical_properties": {"parameters": null}}, + "coverage": {"definition_id": "v", "selection": []}, + "inputs": {"materialized_views": []}, + "retention_ms": 1_000_000, + })) + .unwrap(); + let groups = vec![vec![(view, first.schema().clone())]]; + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + for end in [10, 20, 30] { + files + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&first))], 0) + .unwrap(); + } + files + .append(0, (10, 20), &[(1, std::slice::from_ref(&second))], 2) + .unwrap(); + drop(files); + // After a restart: no active segment, so revision 1 of (0, 10] + // starts one named `10.seg`, older than the original's. + let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); + files.index(&groups).unwrap(); + files + .append(0, (0, 10), &[(1, std::slice::from_ref(&second))], 1) + .unwrap(); + files + .append(0, (20, 30), &[(1, std::slice::from_ref(&second))], 0) + .unwrap(); + let index = ViewFiles::open(&dir, 7, Duration::ZERO) + .unwrap() + .index(&groups) + .unwrap(); + let revisions: Vec<((i64, i64), u64)> = index[&1] + .iter() + .map(|(range, location)| (*range, location.revision())) + .collect(); + assert_eq!(revisions, [((0, 10), 1), ((10, 20), 2), ((20, 30), 0)]); + assert_same_rows( + &second, + &index[&1][0] + .1 + .read(second.schema(), ViewRead::Mmap) + .unwrap() + .0, + "revision 1", + ); + + #[derive(Serialize)] + struct UnrevisedHead { + start_ms: i64, + end_ms: i64, + texts: (u64, u32), + grids: (u64, u32), + views: Vec<(PhysicalASAPNodeId, u64, u32)>, + } + let bytes = rmp_serde::to_vec(&UnrevisedHead { + start_ms: 0, + end_ms: 10, + texts: (1, 2), + grids: (3, 4), + views: vec![(1, 5, 6)], + }) + .unwrap(); + let head: RecordHead = rmp_serde::from_slice(&bytes).unwrap(); + assert_eq!((head.end_ms, head.revision), (10, 0)); + let _ = std::fs::remove_dir_all(&dir); + } + /// V12 (unit). A torn record at the end of the active segment is cut /// off before indexing (so before any mapping), and later appends stay /// aligned; indexing decodes no fragment. @@ -1904,10 +2014,10 @@ mod tests { let groups = vec![vec![(view, 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))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); files - .append(0, (10, 20), &[(1, std::slice::from_ref(&batch))]) + .append(0, (10, 20), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); let path = location_of(&written, 1).segment_path().to_path_buf(); drop(files); @@ -1919,7 +2029,7 @@ mod tests { let ranges: Vec<(i64, i64)> = index[&1].iter().map(|(range, _)| *range).collect(); assert_eq!(ranges, [(0, 10), (10, 20)]); files - .append(0, (20, 30), &[(1, std::slice::from_ref(&batch))]) + .append(0, (20, 30), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); let index = ViewFiles::open(&dir, 7, Duration::ZERO) .unwrap() @@ -1957,18 +2067,18 @@ mod tests { .unwrap(); let groups = vec![vec![(view, batch.schema().clone())]]; let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); - files.append(0, (0, 10), &[(1, &[])]).unwrap(); + files.append(0, (0, 10), &[(1, &[])], 0).unwrap(); assert!(segment_files(&dir).is_empty(), "nothing encoded"); for end in [10, 20] { files - .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))]) + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); } drop(files); let mut files = ViewFiles::open(&dir, 7, Duration::ZERO).unwrap(); let recovered = files.index(&groups).unwrap(); files - .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); assert_eq!(segment_files(&dir).len(), 2); for (_, location) in &recovered[&1] { @@ -1982,7 +2092,8 @@ mod tests { .unwrap() .index(&groups) .unwrap(); - assert_eq!(index[&1].len(), 3); + // (0, 10) written twice is one window, read from one of its records. + assert_eq!(index[&1].len(), 2); let _ = std::fs::remove_dir_all(&dir); } @@ -2008,13 +2119,13 @@ mod tests { let groups = vec![vec![(view, 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))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); let path = location_of(&written, 1).segment_path().to_path_buf(); let one_record = std::fs::metadata(&path).unwrap().len(); for end in [20, 30] { files - .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))]) + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); } drop(files); @@ -2098,7 +2209,7 @@ mod tests { assert!(!v1.exists() && dir.join("group-0.log.stale").exists()); // A segment of plan 7 is set aside by a data plane of plan 8. let written = files - .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))]) + .append(0, (0, 10), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); let segment = location_of(&written, 1).segment_path().to_path_buf(); drop(files); @@ -2124,7 +2235,7 @@ mod tests { .with_view_retention_ms(BTreeMap::from([(1, 20)])); for end in (10..=100).step_by(10) { files - .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))]) + .append(0, (end - 10, end), &[(1, std::slice::from_ref(&batch))], 0) .unwrap(); } assert_eq!(segment_files(&dir).len(), 5); diff --git a/crates/storage/src/persist_pool.rs b/crates/storage/src/persist_pool.rs index 7cacf83c8..16d3409b9 100644 --- a/crates/storage/src/persist_pool.rs +++ b/crates/storage/src/persist_pool.rs @@ -26,6 +26,8 @@ enum PersistJob { views: Vec<(PhysicalASAPNodeId, Vec)>, /// Each view's stored window, told where it was written. slots: Vec>>, + /// The window's revision ([`ViewFiles::append`]). + revision: u64, bytes: u64, }, /// Done once every window queued to this thread before is written. @@ -139,15 +141,17 @@ impl PersistPool { }) } - /// Queues a refreshed window for its group's persist thread, waiting - /// while the queue holds more than `max_bytes` (the wait is exported; - /// a window larger than the bound is still queued into an empty queue). + /// Queues a refreshed window of `revision` (0, or how many times late + /// samples revised it) for its group's persist thread, waiting while + /// the queue holds more than `max_bytes` (the wait is exported; a + /// window larger than the bound is still queued into an empty queue). pub fn queue( &self, group: usize, range_ms: (i64, i64), views: Vec<(PhysicalASAPNodeId, Vec)>, slots: Vec>>, + revision: u64, ) { let bytes: u64 = views .iter() @@ -173,6 +177,7 @@ impl PersistPool { range_ms, views, slots, + revision, bytes, }; if self.shards[group % self.shards.len()].send(job).is_err() { @@ -232,6 +237,7 @@ fn serve_persist( range_ms, views, slots, + revision, bytes, } => { // A slow disk, for tests. @@ -245,7 +251,7 @@ fn serve_persist( .collect(); let skipped = (views.len() - records.len()) as u64; let files_before = files.bytes(); - let locations = match files.append(group, range_ms, &records) { + let locations = match files.append(group, range_ms, &records, revision) { Ok(written) => { metrics .view_persisted_bytes diff --git a/crates/storage/src/segment.rs b/crates/storage/src/segment.rs index 29a2bf368..45586b1a8 100644 --- a/crates/storage/src/segment.rs +++ b/crates/storage/src/segment.rs @@ -126,6 +126,11 @@ pub(crate) struct RecordHead { /// states read, as ASAPv1. pub grids: (u64, u32), pub views: Vec<(PhysicalASAPNodeId, u64, u32)>, + /// How many times its window was revised by late samples: a record of + /// a window written again supersedes those of lower revision. Records + /// written before revisions existed read as 0. + #[serde(default)] + pub revision: u64, } /// A read-only mapping of a sealed segment, unmapped when dropped. @@ -662,13 +667,14 @@ fn record_head(payload: &[u8]) -> Option { } /// Where one view's rows of one window are on disk: its fragment in a -/// segment, and its record's grids. +/// segment, its record's grids and its record's revision. #[derive(Debug, Clone)] pub struct WindowLocation { segment: Arc, offset: u64, len: u32, grids: (u64, u32), + revision: u64, } /// Bytes read for a decode: borrowed from a mapping, or owned. @@ -687,15 +693,26 @@ impl Bytes { } impl WindowLocation { - pub(crate) fn new(segment: Arc, (offset, len): (u64, u32), grids: (u64, u32)) -> Self { + pub(crate) fn new( + segment: Arc, + (offset, len): (u64, u32), + grids: (u64, u32), + revision: u64, + ) -> Self { Self { segment, offset, len, grids, + revision, } } + /// Its record's revision ([`RecordHead::revision`]). + pub fn revision(&self) -> u64 { + self.revision + } + /// The segment file holding the fragment. pub fn segment_path(&self) -> &Path { &self.segment.path @@ -1522,7 +1539,7 @@ mod tests { 0, vec![], )); - let location = WindowLocation::new(segment, (u64::MAX - 2, 10), (0, 0)); + let location = WindowLocation::new(segment, (u64::MAX - 2, 10), (0, 0), 0); assert!(location.read(&schema, ViewRead::Pread).is_err()); // u32::MAX rows of one constant timestamp, in 56 bytes. diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index c091cea15..153d764d6 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -29,7 +29,7 @@ //! published ([`PublishedStore`]; raw data by the ingest coordinator), so //! a run never sees a change and never blocks one. -use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; use std::ops::Bound; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Condvar, Mutex, RwLock}; @@ -45,7 +45,7 @@ use asap_executor::planner::plan::materialized_view::MaterializedView; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::runtime::{OutputStream, RunContext}; use asap_executor::sources::{DataStore, MaterializedViewRequest, RawDataRequest}; -use asap_executor::values::{Batch, BatchColumn, SchemaRef}; +use asap_executor::values::{Batch, BatchColumn, SchemaRef, Value}; use asap_executor::Error; use futures::{stream, StreamExt}; use internal_metrics::{PhaseStats, Timer}; @@ -272,6 +272,11 @@ impl RawData { } } + /// The same metrics, in the same panes, with no sample. + pub fn emptied(&self) -> Self { + Self::for_metrics(self.by_metric.keys(), self.pane_width_ms) + } + /// Whether some `Scan` reads `metric`. pub fn reads(&self, metric: &str) -> bool { self.by_metric.contains_key(metric) @@ -991,8 +996,19 @@ 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, + /// How many windows late samples revised ([`Self::merge_late`]). + revision: u64, + /// Each revision of the newest [`REVISIONS_KEPT`]: the end of the + /// window it changed, oldest first. A result cached from this store + /// names the revision it read; it is stale once a window it read + /// changed after that ([`Self::changed_since`]). + revisions: Arc>, } +/// How many revisions [`ViewStore`] remembers the window of: a result +/// cached before the oldest of them is taken as stale. +const REVISIONS_KEPT: usize = 4096; + impl ViewStore { /// Declares where the producer's stream starts (see `stream_start_ms`). pub fn with_stream_start(mut self, stream_start_ms: Option) -> Self { @@ -1086,6 +1102,7 @@ impl ViewStore { key: WindowKey { view: view.node_id, end_ms: time_range_ms.1, + revision: location.revision(), }, schema, bytes: 0, @@ -1158,10 +1175,26 @@ impl ViewStore { .unwrap_or_else(|| { Arc::new(asap_executor::planner::ir::schema::Schema::new(Vec::new())) }); + let slot = self.committed_slot(view.node_id, time_range_ms.1, 0, schema, batches)?; + self.push(view, time_range_ms, slot); + Ok(()) + } + + /// A committed window's slot of `view` ending `end_ms`, at `revision`: + /// its batches (keyed into the view's shared texts) in memory until + /// written. + fn committed_slot( + &mut self, + view: PhysicalASAPNodeId, + end_ms: i64, + revision: u64, + schema: SchemaRef, + batches: Vec, + ) -> Result { let batches = batches .into_iter() .enumerate() - .map(|(part, batch)| self.share_texts(view.node_id, part, batch)) + .map(|(part, batch)| self.share_texts(view, part, batch)) .collect::, Error>>()?; let bytes = batches.iter().map(window_batch_bytes).sum::() as u64; let batches = Arc::new(batches); @@ -1172,18 +1205,90 @@ impl ViewStore { } None => SlotState::Pinned(batches), }; - let slot = WindowSlot { + Ok(WindowSlot { key: WindowKey { - view: view.node_id, - end_ms: time_range_ms.1, + view, + end_ms, + revision, }, schema, bytes, state: Mutex::new((state, false)), tier: self.tier.clone(), + }) + } + + /// The revision of `view`'s stored window ending `end_ms` (0 until late + /// samples revise it); `None` when it is not stored. + pub fn window_revision(&self, view: PhysicalASAPNodeId, end_ms: i64) -> Option { + self.slot(view, end_ms).map(|slot| slot.key.revision) + } + + /// Merges `late`, the rows of `view`'s window ending `end_ms` computed + /// from late samples alone, into the stored window: a row whose plain + /// columns equal a stored row's merges its states into that row's + /// (each kernel's `merge_with`), any other row is added. The window is + /// replaced by the merged rows at `revision` (in memory until written + /// again, as a committed window), and a result cached from an earlier + /// revision that read it is stale ([`Self::changed_since`]). Returns + /// the merged rows, to write; `None` when the window is not stored + /// (past the view's retention, skipped or failed), so `late` is lost. + /// `late` holds at least one batch. + pub fn merge_late( + &mut self, + view: PhysicalASAPNodeId, + end_ms: i64, + revision: u64, + late: Vec, + ) -> Result>, Error> { + let Some(old) = self.slot(view, end_ms) else { + return Ok(None); }; - self.push(view, time_range_ms, slot); - Ok(()) + let stored = old.batches()?; + let schema = late + .first() + .ok_or_else(|| Error::Invalid("no late rows to merge".into()))? + .schema() + .clone(); + let rows = merged_rows(stored.iter().chain(&late))?; + let merged = if rows.is_empty() { + Vec::new() + } else { + vec![Batch::try_new(schema.clone(), rows)?] + }; + let slot = Arc::new(self.committed_slot(view, end_ms, revision, schema, merged.clone())?); + let rows = self.by_view.get_mut(&view).expect("the window is stored"); + let at = rows.partition_point(|window| window.time_range_ms.1 < end_ms); + rows[at].slot = slot; + old.left_store(); + self.revision += 1; + let revisions = Arc::make_mut(&mut self.revisions); + if revisions.len() == REVISIONS_KEPT { + revisions.pop_front(); + } + revisions.push_back((self.revision, end_ms)); + Ok(Some(merged)) + } + + /// How many windows late samples revised so far. + pub fn revision(&self) -> u64 { + self.revision + } + + /// Whether a window ending at or before `time_ms` was revised after + /// `revision` (true when that is older than the revisions remembered): + /// a result at `time_ms` computed from `revision` may then be stale. + pub fn changed_since(&self, revision: u64, time_ms: i64) -> bool { + if revision >= self.revision { + return false; + } + match self.revisions.front() { + Some(&(oldest, _)) if oldest <= revision + 1 => self + .revisions + .iter() + .any(|&(changed, end)| changed > revision && end <= time_ms), + _ => true, + } } /// `batch`, part `part` of its window, with each text column keyed into @@ -1359,6 +1464,38 @@ impl ViewStore { } } +/// The rows of `batches`, one per distinct value of their plain columns: +/// rows with equal plain columns are one row whose states are merged. +fn merged_rows<'a>(batches: impl Iterator) -> Result>, Error> { + let mut rows: Vec> = Vec::new(); + let mut row_of: HashMap, usize> = HashMap::new(); + for batch in batches { + for row in batch.to_rows() { + let mut key = Vec::new(); + for value in row.iter().filter(|v| !matches!(v, Value::Summary { .. })) { + key.extend(value.key()?); + } + let Some(&at) = row_of.get(&key) else { + row_of.insert(key, rows.len()); + rows.push(row); + continue; + }; + for (stored, late) in rows[at].iter_mut().zip(row) { + if let (Value::Summary { state, .. }, Value::Summary { state: other, .. }) = + (stored, late) + { + *state = Arc::from( + state + .merge_with(&*other) + .map_err(|e| Error::Invalid(format!("merging a late state: {e}")))?, + ); + } + } + } + } + Ok(rows) +} + /// A window batch's bytes apart from its shared texts: its own buffers and /// states ([`Batch::memory_bytes`]) less each text column's values array, /// which is shared and counted once by its owner: the view's @@ -1448,9 +1585,12 @@ type QueryTimeEntry = Arc<(Mutex>, Condvar)>; /// at a time the watermark has passed is kept (its inputs are complete); /// one at a later time is computed by each run that needs it. A result is /// kept while `T` is within `retention_ms` of the watermark, and the -/// oldest are dropped while more than `max_bytes` are held. +/// oldest are dropped while more than `max_bytes` are held. A result read +/// from views late samples revised since ([`ViewStore::changed_since`]) is +/// computed again. pub struct QueryTimeResults { - entries: Mutex>>, + /// Each result, with the revision of the views it was computed from. + entries: Mutex)>>, retention_ms: i64, max_bytes: usize, bytes: AtomicU64, @@ -1470,14 +1610,15 @@ impl QueryTimeResults { } } - /// `node`'s output at `time_ms`: stored, or computed now by `compute` - /// (once, however many runs ask at once, when `time_ms` is at or - /// before `watermark_ms`; by each run otherwise). + /// `node`'s output at `time_ms`, as of `views`: stored, or computed now + /// by `compute` (once, however many runs ask at once, when `time_ms` is + /// at or before `watermark_ms`; by each run otherwise). pub fn get_or_compute( &self, node: PhysicalASAPNodeId, time_ms: i64, watermark_ms: Option, + views: &ViewStore, compute: impl FnOnce() -> Result, E>, ) -> Result>, E> { if watermark_ms.is_none_or(|watermark| time_ms > watermark) { @@ -1487,11 +1628,20 @@ impl QueryTimeResults { let (entry, computer) = { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); match entries.get(&(time_ms, node)) { - Some(entry) => (entry.clone(), false), - None => { + Some((revision, entry)) if !views.changed_since(*revision, time_ms) => { + (entry.clone(), false) + } + stale => { + if let Some((_, stale)) = stale { + let bytes = match &*stale.0.lock().unwrap_or_else(|e| e.into_inner()) { + ResultState::Done(_, bytes) => *bytes, + _ => 0, + }; + self.bytes.fetch_sub(bytes as u64, Ordering::Relaxed); + } let entry: QueryTimeEntry = Arc::new((Mutex::new(ResultState::Computing), Condvar::new())); - entries.insert((time_ms, node), entry.clone()); + entries.insert((time_ms, node), (views.revision(), entry.clone())); (entry, true) } } @@ -1514,7 +1664,7 @@ impl QueryTimeResults { let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner()); let held = entries .get(&(time_ms, node)) - .is_some_and(|held| Arc::ptr_eq(held, &entry)); + .is_some_and(|(_, held)| Arc::ptr_eq(held, &entry)); { let mut state = state.lock().unwrap_or_else(|e| e.into_inner()); *state = match &result { @@ -1543,7 +1693,7 @@ impl QueryTimeResults { /// being computed (its computer finds it gone and does not count it). fn drop_old( &self, - entries: &mut BTreeMap<(i64, PhysicalASAPNodeId), QueryTimeEntry>, + entries: &mut BTreeMap<(i64, PhysicalASAPNodeId), (u64, QueryTimeEntry)>, watermark_ms: i64, ) { let oldest_kept_ms = watermark_ms.saturating_sub(self.retention_ms); @@ -1555,7 +1705,7 @@ impl QueryTimeResults { break; } let bytes = { - let Ok(state) = entries[&key].0.try_lock() else { + let Ok(state) = entries[&key].1 .0.try_lock() else { continue; }; match &*state { @@ -2093,23 +2243,37 @@ mod tests { let results = QueryTimeResults::<()>::new(10_000, usize::MAX); let ok = || Ok::<_, ()>(Vec::new()); let watermark = Some(1_000); - results.get_or_compute(7, 1_000, watermark, ok).unwrap(); - results.get_or_compute(7, 1_000, watermark, ok).unwrap(); + results + .get_or_compute(7, 1_000, watermark, &ViewStore::default(), ok) + .unwrap(); + results + .get_or_compute(7, 1_000, watermark, &ViewStore::default(), ok) + .unwrap(); assert_eq!((results.computes(), results.hits()), (1, 1)); // Past the watermark (a client's far-future time): not kept. - results.get_or_compute(7, 99_000, watermark, ok).unwrap(); - results.get_or_compute(7, 99_000, watermark, ok).unwrap(); + results + .get_or_compute(7, 99_000, watermark, &ViewStore::default(), ok) + .unwrap(); + results + .get_or_compute(7, 99_000, watermark, &ViewStore::default(), ok) + .unwrap(); assert_eq!((results.computes(), results.len()), (3, 1)); assert!(results - .get_or_compute(8, 1_000, watermark, || Err(())) + .get_or_compute(8, 1_000, watermark, &ViewStore::default(), || Err(())) .is_err()); assert_eq!(results.len(), 1); - results.get_or_compute(8, 1_000, watermark, ok).unwrap(); + results + .get_or_compute(8, 1_000, watermark, &ViewStore::default(), ok) + .unwrap(); assert_eq!(results.len(), 2); // Retention counts back from the watermark, not from client times. - results.get_or_compute(7, 11_000, Some(11_000), ok).unwrap(); + results + .get_or_compute(7, 11_000, Some(11_000), &ViewStore::default(), ok) + .unwrap(); assert_eq!(results.len(), 3); - results.get_or_compute(7, 11_001, Some(11_001), ok).unwrap(); + results + .get_or_compute(7, 11_001, Some(11_001), &ViewStore::default(), ok) + .unwrap(); assert_eq!(results.len(), 2); assert_eq!(results.bytes(), 0); } @@ -2125,7 +2289,7 @@ mod tests { let computer = { let results = results.clone(); std::thread::spawn(move || { - results.get_or_compute(1, 0, Some(0), || { + results.get_or_compute(1, 0, Some(0), &ViewStore::default(), || { started.send(()).unwrap(); released.recv().unwrap(); if fails { @@ -2140,7 +2304,9 @@ mod tests { let waiter = { let results = results.clone(); std::thread::spawn(move || { - results.get_or_compute(1, 0, Some(0), || panic!("the waiter computed")) + results.get_or_compute(1, 0, Some(0), &ViewStore::default(), || { + panic!("the waiter computed") + }) }) }; // Let the waiter block on the entry before the result is set. diff --git a/crates/storage/src/window_cache.rs b/crates/storage/src/window_cache.rs index 945c2202f..ffc446ca5 100644 --- a/crates/storage/src/window_cache.rs +++ b/crates/storage/src/window_cache.rs @@ -16,11 +16,14 @@ use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::values::Batch; use asap_executor::Error; -/// One view's window, by the end of its range. +/// One view's window, by the end of its range and its revision. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct WindowKey { pub view: PhysicalASAPNodeId, pub end_ms: i64, + /// The window's revision: a window revised by late samples is another + /// entry, so a decode of the old rows never stands for the new. + pub revision: u64, } /// What the cache holds and has done. @@ -318,7 +321,11 @@ mod tests { use std::sync::atomic::{AtomicU64, Ordering}; fn key(end_ms: i64) -> WindowKey { - WindowKey { view: 1, end_ms } + WindowKey { + view: 1, + end_ms, + revision: 0, + } } fn batches() -> Arc> { diff --git a/crates/storage/tests/view_cache_charge.rs b/crates/storage/tests/view_cache_charge.rs index 922fc4d2e..9dd99e991 100644 --- a/crates/storage/tests/view_cache_charge.rs +++ b/crates/storage/tests/view_cache_charge.rs @@ -149,7 +149,7 @@ fn sealed_windows_read_back(how: ViewRead) { .unwrap(); let slot = views.slot(VIEW, range.1).unwrap(); let batches = views.rows()[&VIEW].last().unwrap().1.clone(); - let written = files.append(0, range, &[(VIEW, &batches)]).unwrap(); + let written = files.append(0, range, &[(VIEW, &batches)], 0).unwrap(); slot.stored(written.locations[0].1.clone()); } files.seal(0).unwrap(); @@ -217,11 +217,12 @@ fn active_windows_read_back_while_the_dictionary_grows() { .unwrap(); let slot = views.slot(VIEW, range.1).unwrap(); let batches = views.rows()[&VIEW].last().unwrap().1.clone(); - let written = files.append(0, range, &[(VIEW, &batches)]).unwrap(); + let written = files.append(0, range, &[(VIEW, &batches)], 0).unwrap(); slot.stored(written.locations[0].1.clone()); tier.cache.remove(WindowKey { view: VIEW, end_ms: range.1, + revision: 0, }); let (heap, added) = held_by(&views, || { views.rows(); From f68d4e88ab6f74fc705c7d9ad9fc05d5ec0209b5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:37:26 +0000 Subject: [PATCH 03/19] chore: clippy: name the per-metric route and the query-time entries; bench call site Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- benchmarks/micro/view_read_bench.rs | 7 ++++- crates/data-plane/tests/window_levels.rs | 5 +++- crates/precompute/src/ingestion.rs | 33 ++++++++++++++++++++---- crates/storage/src/store.rs | 13 +++++----- 4 files changed, 44 insertions(+), 14 deletions(-) diff --git a/benchmarks/micro/view_read_bench.rs b/benchmarks/micro/view_read_bench.rs index e5f87f57a..44d1601d6 100644 --- a/benchmarks/micro/view_read_bench.rs +++ b/benchmarks/micro/view_read_bench.rs @@ -101,7 +101,12 @@ fn main() { let batch = Batch::try_new(schema.clone(), rows).unwrap(); let started = Instant::now(); let written = files - .append(0, (end - 15_000, end), &[(1, std::slice::from_ref(&batch))]) + .append( + 0, + (end - 15_000, end), + &[(1, std::slice::from_ref(&batch))], + 0, + ) .unwrap(); write += started.elapsed(); let location = written diff --git a/crates/data-plane/tests/window_levels.rs b/crates/data-plane/tests/window_levels.rs index da5842c9d..8559f7494 100644 --- a/crates/data-plane/tests/window_levels.rs +++ b/crates/data-plane/tests/window_levels.rs @@ -240,7 +240,10 @@ async fn a_late_sample_reaches_the_wider_levels_built_from_its_window() { post(&app, "/api/v1/write".into(), write(false)).await, StatusCode::NO_CONTENT ); - assert_eq!(post(&app, barrier.clone(), Vec::new()).await, StatusCode::OK); + assert_eq!( + post(&app, barrier.clone(), Vec::new()).await, + StatusCode::OK + ); assert_ne!( common::per_job(&answer(&app, SUM, END_S).await.1), expected(SUM, END_S) diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 4b36a75be..165f501fb 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -846,6 +846,17 @@ pub(crate) struct Routing { kept_after_ms: Vec>, } +/// How one metric's samples are routed, looked up once per batch. +struct MetricRoute<'a> { + metric: Arc, + /// Some `Scan` reads it. + routed: bool, + late_through: Option, + /// Its first sample of the batch was reported. + seen: bool, + committed: &'a [CommittedWindows], +} + /// A refresh group's closed windows, as the ingest shards route by them. #[derive(Debug, Clone)] struct CommittedWindows { @@ -889,25 +900,37 @@ impl Routing { }; // Samples of one metric usually come together: the last metric is // checked by pointer first. - let mut metrics: Vec<(Arc, bool, Option, bool, &[CommittedWindows])> = Vec::new(); + let mut metrics: Vec> = Vec::new(); let mut last: Option = None; for sample in samples { let metric = &sample.labels.metric; let known = last - .filter(|&i| Arc::ptr_eq(&metrics[i].0, metric)) - .or_else(|| metrics.iter().position(|(m, ..)| m == metric)); + .filter(|&i| Arc::ptr_eq(&metrics[i].metric, metric)) + .or_else(|| metrics.iter().position(|m| m.metric == *metric)); let index = match known { Some(index) => index, None => { let routed = self.scanned_metrics.contains(&**metric); let late_through = self.late_through.get(&**metric).copied().flatten(); let committed = self.committed.get(&**metric).map_or(&[][..], Vec::as_slice); - metrics.push((metric.clone(), routed, late_through, false, committed)); + metrics.push(MetricRoute { + metric: metric.clone(), + routed, + late_through, + seen: false, + committed, + }); metrics.len() - 1 } }; last = Some(index); - let (_, is_routed, late_through, seen, committed) = &mut metrics[index]; + let MetricRoute { + routed: is_routed, + late_through, + seen, + committed, + .. + } = &mut metrics[index]; if !*is_routed { routed.stats.samples_unrouted += 1; continue; diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 153d764d6..ca485401b 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -1575,6 +1575,10 @@ enum ResultState { /// One query-time result and the condition its waiters wait on. type QueryTimeEntry = Arc<(Mutex>, Condvar)>; +/// The query-time results by `(T, node)`, each with the revision of the +/// views it was computed from. +type QueryTimeEntries = BTreeMap<(i64, PhysicalASAPNodeId), (u64, QueryTimeEntry)>; + /// The materialized view store's query-time partition: the output of each /// query-time `OneEvaluation` node at one evaluation time `T`, shared by /// every query run at `T` that reads it, keyed by `(T, node)`. Query @@ -1589,8 +1593,7 @@ type QueryTimeEntry = Arc<(Mutex>, Condvar)>; /// from views late samples revised since ([`ViewStore::changed_since`]) is /// computed again. pub struct QueryTimeResults { - /// Each result, with the revision of the views it was computed from. - entries: Mutex)>>, + entries: Mutex>, retention_ms: i64, max_bytes: usize, bytes: AtomicU64, @@ -1691,11 +1694,7 @@ impl QueryTimeResults { /// Drops the results more than the retention behind `watermark_ms`, /// then the oldest while more than `max_bytes` are held; never one /// being computed (its computer finds it gone and does not count it). - fn drop_old( - &self, - entries: &mut BTreeMap<(i64, PhysicalASAPNodeId), (u64, QueryTimeEntry)>, - watermark_ms: i64, - ) { + fn drop_old(&self, entries: &mut QueryTimeEntries, watermark_ms: i64) { let oldest_kept_ms = watermark_ms.saturating_sub(self.retention_ms); let keys: Vec<(i64, PhysicalASAPNodeId)> = entries.keys().copied().collect(); for key in keys { From 521a2a8566b380c25122945c67fabe01cf3039dc Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:47:51 +0000 Subject: [PATCH 04/19] docs: asap_samples_total{outcome="merged_late"} replaces late_for_views Push mode merges the samples of sealed windows as the window path does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- README.md | 2 +- docs/design/parallel-precompute.md | 13 +++++++------ 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index a2a519c97..617cc175b 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ name; the view tier and push precompute add `asap_view_cache_*`, `asap_view_cold_read_bytes_total`, `asap_view_segments_marked_cold_total`, `phase="view_decode"`, `asap_precompute_state_bytes`, `asap_precompute_open_instances`, `asap_window_commit_lag_seconds` and -`asap_samples_total{outcome="late_for_views"}`. `benchmarks/scripts/profile.sh` records a flamegraph of a running data plane; +`asap_samples_total{outcome="merged_late"}`. `benchmarks/scripts/profile.sh` records a flamegraph of a running data plane; `cargo run --release -p data_plane --example ingest_bench -- 10000 300` measures ingest throughput in process (the micro benchmarks are in `benchmarks/micro/`). diff --git a/docs/design/parallel-precompute.md b/docs/design/parallel-precompute.md index a2867f7d3..187eb6724 100644 --- a/docs/design/parallel-precompute.md +++ b/docs/design/parallel-precompute.md @@ -400,10 +400,11 @@ In push mode: - A sample for a window that is still open on its shard (within the allowed lateness) is pushed into that window's instance. -- A sample for a window already sealed does not change the stored window, - as today. It is still appended to the raw data if a query-time `Scan` - reads its metric. `asap_samples_total{outcome="late_for_views"}` counts - it. +- A sample for a window already sealed is merged into the committed + window while it is within retention, as on the window path (late + samples, `docs/design/repo-layout.md`). It is still appended to the raw + data if a query-time `Scan` reads its metric. + `asap_samples_total{outcome="merged_late"}` counts it. - Counter states see each series' samples in arrival order. A series is on one shard, and each shard's queue is FIFO. This is the same order as the chunks the window path reads. @@ -441,7 +442,7 @@ In push mode: New gauges and counters: `asap_precompute_state_bytes{group,shard}`, `asap_precompute_open_instances{shard}`, `asap_window_commit_lag_seconds` (from window end to commit: the newest - window's lag), and `asap_samples_total{outcome="late_for_views"}`. + window's lag), and `asap_samples_total{outcome="merged_late"}`. - **Failures.** - When an instance fails (an operator error, or a memory reservation that cannot be met, see D8), its shard sends `Err`. The window is @@ -1081,7 +1082,7 @@ path of the same build. | T10 | Seal is exact under shard skew: each instance gets exactly the samples admitted before the flush that seals it. | `shard_delay_ms` slowing all shards but the first, 8 shards; samples stamped up to 1 s ahead of the clock (the demo design's two race tests, run in push mode). | No late drops, and every window equals the 1-shard result. | Fails: no push mode. The window-path versions pass. | | T11 | Idle shards seal empty and hold nothing back. | One series, K = 8. A selective plan whose series all hash to two shards. | Every window commits when the barrier passes it. Each shard sends one partial per window; idle shards send empty ones. | Fails: no push mode. | | T12 | Pushed pipelines do not buffer raw samples. | The dashboard plan, raw data not kept, 10k series at 1 sample/s, W = 15 s, K = 4. `/metrics` is sampled before each close. With a query-time `Scan`, raw data is kept. | `asap_raw_data_bytes` stays below one request's samples, not rate × W × 20 B (3 MB per metric here), and `asap_precompute_state_bytes` is reported. With a `Scan`, raw bytes follow its lookback only. | Fails: raw panes grow until the window closes. | -| T13 | Late and out-of-order samples count in the same windows as the window path. | 5 s allowed lateness; samples 4 s late (window still open) and 20 s late (window sealed); counters included; K = 4; raw kept and not kept. | Stored windows equal the window path. The 20 s-late samples are counted as `late_for_views` and are read by query-time `Scan`s when raw is kept. | Fails: no push mode; the counter is new. | +| T13 | Late and out-of-order samples count in the same windows as the window path. | 5 s allowed lateness; samples 4 s late (window still open) and 20 s late (window sealed); counters included; K = 4; raw kept and not kept. | Stored windows equal the window path. The 20 s-late samples are merged into their sealed window, counted as `merged_late`, and are read by query-time `Scan`s when raw is kept. | Fails: no push mode; the counter is new. | | T14 | Backpressure goes from the commit backlog to the shard queues to 503, and loses nothing. | A gated combine, `--max-precompute-backlog 2`, a small `--max-queued-samples`, K = 4. | 503 once full. After the gate opens, every window commits and the answers equal an ungated run. | Fails: no push mode. | | T15 | A memory reservation waits while older windows are open, and fails the window only when nothing else is open. | A precompute budget that fits one open window; lateness so that two windows overlap; then a single window over budget. | The first case delays ingest (queue then 503) with no failed window. The second fails that window only, and later windows commit. | Fails: no reservation exists. | | T16 | Seal work is chunked, so ingest keeps running during a large seal. | 100k series, one 1 s DDSketch view, K = 2; requests sent continuously across window ends. | The longest gap between two ingested requests on a shard during a seal stays below the chunk bound times a small factor (the bound is set by E5). | Fails: no push mode. | From 10659b356f033b2ccf72f1ee2d57c9ac66942770 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:11:50 +0000 Subject: [PATCH 05/19] test(precompute): a late counter sample recomputes its window; a sample routed while its window closes is kept (failing first) The second test needs a test hook, routing_delay_after_flush_ms: the coordinator waits between the flush every shard answered and the routing it publishes, which is when the race happens. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/src/engine.rs | 6 ++ crates/data-plane/tests/ingest_shards.rs | 116 +++++++++++++++++++++++ crates/precompute/src/engine.rs | 12 +++ 3 files changed, 134 insertions(+) diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index d9c6456f0..487955393 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -54,6 +54,10 @@ pub struct EngineOptions { /// running each batch, so the first runs ahead of the others. #[doc(hidden)] pub shard_delay_ms: u64, + /// For tests: how long the ingest coordinator waits, after every shard + /// answered a flush, before it closes windows and publishes the routing. + #[doc(hidden)] + pub routing_delay_after_flush_ms: u64, /// Persist threads, each writing the view files of every /// `persist_threads`-th refresh group. pub persist_threads: usize, @@ -154,6 +158,7 @@ impl Default for EngineOptions { ingest_threads: std::thread::available_parallelism() .map_or(1, |cores| (usize::from(cores) / 4).max(1)), shard_delay_ms: 0, + routing_delay_after_flush_ms: 0, precompute_threads: std::thread::available_parallelism() .map_or(1, |cores| (usize::from(cores) / 4).clamp(1, 4)), slow_refreshes: Vec::new(), @@ -356,6 +361,7 @@ impl EngineOptions { slow_refreshes: self.slow_refreshes.clone(), check_task_inputs: self.check_task_inputs, shard_delay_ms: self.shard_delay_ms, + routing_delay_after_flush_ms: self.routing_delay_after_flush_ms, precompute_mode: self.precompute_mode, push_batching: self.push_batching, precompute_memory_budget_bytes: self.precompute_memory_budget_bytes, diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index 64214612e..a502a9dfd 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -685,3 +685,119 @@ async fn samples_after_a_pause_merge_into_the_window_closed_by_wall_clock() { (64 * 5, 0) ); } + +/// A counter series' samples: `increase` reads its window's samples in +/// time order, resets included. +const COUNTER_QUERY: &str = "sum by (job) (increase(c_total[30s]))"; + +/// The plan of `COUNTER_QUERY`, every 10 s, over one counter series. +fn counter_plan_json() -> String { + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": COUNTER_QUERY, + "demand": {"fixed_interval_at": {"interval": 10000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 1.0}}, + "sources": {"c_total": {"series_count": 1, "sample_interval": 1000, + "metric_type": "counter", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + serde_json::to_string(&plan_workload(&workload, &common::inputs(false)).unwrap().0).unwrap() +} + +/// Writes `samples` (time ms, value) of the counter `c_total{job="a"}`. +async fn write_counter(app: &Router, samples: &[(i64, f64)]) { + let timeseries = vec![TimeSeries { + labels: [("__name__", "c_total"), ("job", "a")] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value: value.into(), + }) + .collect(), + samples: samples + .iter() + .map(|&(timestamp, value)| Sample { timestamp, value }) + .collect(), + }]; + common::remote_write(app, timeseries).await; +} + +/// A late counter sample between two on-time ones (10 at 2 s, 12 at 8 s; +/// 3 at 5 s comes late, a reset) is not merged as a later sample would be +/// (an increase of 2): its window is computed again from the raw samples +/// kept, so `increase` is 3 + 9 = 12, as when every sample came on time. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_counter_sample_recomputes_its_window_from_the_raw_samples() { + let data_plane = || { + let state = Arc::new( + DataPlane::with_options( + counter_plan_json(), + "http://127.0.0.1:1".into(), + common::no_forward_options(), + ) + .unwrap(), + ); + (router(state.clone()), state) + }; + let (app, _) = data_plane(); + write_counter( + &app, + &[(2_000, 10.0), (5_000, 3.0), (8_000, 12.0), (35_000, 20.0)], + ) + .await; + common::barrier(&app, 40_000).await; + let (status, on_time) = status_and_answer_of(&app, COUNTER_QUERY, 30_000).await; + assert_eq!(status, StatusCode::OK, "{on_time}"); + + let (app, state) = data_plane(); + write_counter(&app, &[(2_000, 10.0), (8_000, 12.0), (35_000, 20.0)]).await; + common::barrier(&app, 40_000).await; + let (_, before) = status_and_answer_of(&app, COUNTER_QUERY, 30_000).await; + assert_ne!(before, on_time); + write_counter(&app, &[(5_000, 3.0)]).await; + common::barrier(&app, 40_000).await; + let (status, after) = status_and_answer_of(&app, COUNTER_QUERY, 30_000).await; + assert_eq!(status, StatusCode::OK, "{after}"); + assert_eq!(after, on_time, "{:?}", state.engine.stats()); + assert_eq!(state.engine.stats().samples_dropped_late, 0); +} + +/// A sample routed right after its shard answered the flush of the pass +/// that closes its window, before that pass publishes its routing: the +/// shard waits for the new routing, so the sample goes to the window's late +/// merge rather than only to the raw data the closed window no longer +/// reads. The coordinator here waits 1 s between the flush and the routing. +#[tokio::test(flavor = "multi_thread")] +async fn a_sample_routed_while_its_window_closes_is_not_lost() { + let options = EngineOptions { + ingest_threads: 1, + routing_delay_after_flush_ms: 1_000, + ..common::no_forward_options() + }; + let state = Arc::new( + DataPlane::with_options(plan_json(), "http://127.0.0.1:1".into(), options).unwrap(), + ); + let app = router(state.clone()); + // Every sample at 1..=30 s but series 5's at 25 s: (20, 30] is open. + write_seconds(&app, 0..64, 1..=24).await; + write_seconds(&app, 0..5, 25..=25).await; + write_seconds(&app, 6..64, 25..=25).await; + write_seconds(&app, 0..64, 26..=30).await; + common::barrier(&app, 20_000).await; + // The barrier at 30 s closes (20, 30]; series 5's sample at 25 s comes + // while its pass waits between the flush and the routing. + let closing = { + let app = app.clone(); + tokio::spawn(async move { common::barrier(&app, 30_000).await }) + }; + tokio::time::sleep(std::time::Duration::from_millis(300)).await; + write_seconds(&app, 5..6, 25..=25).await; + closing.await.unwrap(); + common::barrier(&app, 30_000).await; + pass(&app).await; + assert_eq!(common::per_job(&answer(&app, 30).await), expected(30)); + assert_eq!(state.engine.stats().samples_dropped_late, 0); +} diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index bd3a6f59c..6e29737f9 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -211,6 +211,8 @@ struct Shared { precompute_gate: Mutex<()>, metrics: Arc, clock: WallClock, + /// For tests ([`PrecomputeOptions::routing_delay_after_flush_ms`]). + routing_delay_after_flush: std::time::Duration, } /// Marks the engine stopped when its thread exits, panics included. @@ -245,6 +247,9 @@ pub struct PrecomputeOptions { pub check_task_inputs: bool, /// For tests: how long every shard but the first waits per batch. pub shard_delay_ms: u64, + /// For tests: how long the coordinator waits, after every shard + /// answered a flush, before it closes windows and publishes the routing. + pub routing_delay_after_flush_ms: u64, /// How the views of a closed window are built. pub precompute_mode: PrecomputeMode, /// Push mode: how each shard coalesces samples into morsels. @@ -468,6 +473,9 @@ impl InstalledPrecompute { precompute_gate: Mutex::new(()), metrics, clock: options.clock.clone(), + routing_delay_after_flush: std::time::Duration::from_millis( + options.routing_delay_after_flush_ms, + ), }); let (commands, command_receiver) = channel(); let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); @@ -1045,6 +1053,9 @@ fn serve_ingest( Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break 'serve, } } + if !shared.routing_delay_after_flush.is_zero() { + std::thread::sleep(shared.routing_delay_after_flush); + } ingestion.advance_clock(flush_sent.wall_ms); if arrived { ingestion.sample_arrived(flush_sent); @@ -2323,6 +2334,7 @@ mod tests { slow_refreshes: Vec::new(), check_task_inputs: false, shard_delay_ms: 0, + routing_delay_after_flush_ms: 0, precompute_mode: PrecomputeMode::Window, push_batching: crate::push::MorselBatching::default(), precompute_memory_budget_bytes: None, From 712272cd150d0a14b948c21981fcfefc2a9db174 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:19:16 +0000 Subject: [PATCH 06/19] feat(precompute): recompute order-sensitive windows from raw samples; insert missing windows; shards wait for a pass's routing - A group whose states depend on the order of their samples (Counter for rate/increase, IRate) keeps its raw samples for its views' retention. A late sample of it is stored as raw data too, and its window is computed again from the raw data whole and replaces the stored one; the windows built from it are computed again from the views. Such a group is not built by push. KLL and float sums keep the merge. - A pane's raw rows stay in time order: an out-of-order append (a late sample) rebuilds the pane as one chunk sorted by time. - ViewStore::replace_window replaces a window, or inserts one missing behind the newest within retention (for a collector view's window whose first states come late, #890); merge_late can insert likewise. - After answering a flush, a shard holds its samples until the routing of that pass (the Maintain the coordinator now sends after every flushed pass), so no sample is routed by windows a pass has closed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/engine.rs | 51 +++++-- crates/precompute/src/ingestion.rs | 221 +++++++++++++++++++++-------- crates/storage/src/store.rs | 174 ++++++++++++++++++++--- 3 files changed, 361 insertions(+), 85 deletions(-) diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 6e29737f9..14c518302 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -385,7 +385,10 @@ impl InstalledPrecompute { let tasks = precompute.tasks(); let candidates: Vec = (0..tasks.split_by_series.len()) .map(|g| { - tasks.split_by_series[g] && !tasks.serial[g] && tasks.reads[g].is_empty() + tasks.split_by_series[g] + && !tasks.serial[g] + && tasks.reads[g].is_empty() + && !precompute.recomputes(g) }) .collect(); crate::push::probe( @@ -799,6 +802,12 @@ fn serve_shard( let mut newest_ms: Option = None; // A message taken while draining a batch, to run next. let mut next: Option = None; + // Between answering a flush and getting the routing of that pass (the + // `Maintain` after it), samples are held, not routed: the pass may + // close their windows, and a routing from before it would take them + // for open windows the closed ones no longer read. + let mut awaiting_routing = false; + let mut held: Vec = Vec::new(); loop { let message = match next.take() { Some(message) => message, @@ -808,15 +817,24 @@ fn serve_shard( }, }; let mut samples = match message { + ShardMessage::Samples(samples) if awaiting_routing => { + held.extend(samples); + continue; + } ShardMessage::Samples(samples) => samples, // Eviction changes no sample time: no report (each would start - // another coordinator pass). + // another coordinator pass). The samples held since the last + // flush are routed now. ShardMessage::Maintain { routing, watermark_ms, } => { routing.maintain(Arc::make_mut(&mut raw_data), watermark_ms); - continue; + awaiting_routing = false; + if held.is_empty() { + continue; + } + std::mem::take(&mut held) } ShardMessage::Flush => { // The raw data travels only with a flush, which a window @@ -828,6 +846,7 @@ fn serve_shard( { break; } + awaiting_routing = true; continue; } ShardMessage::Seal { windows, through } => { @@ -1097,11 +1116,18 @@ fn serve_ingest( break; } for (window, samples) in std::mem::take(&mut late) { - let mut raw_data = ingestion.late_raw_data(); - raw_data.append(&samples); + // A group computed again reads the raw data whole, which holds + // the late samples since this pass's flush. + let raw_data = if ingestion.recomputes(window.group) { + snapshot.clone() + } else { + let mut raw_data = ingestion.late_raw_data(); + raw_data.append(&samples); + Arc::new(vec![Arc::new(raw_data)]) + }; let job = PrecomputeJob::Late { window, - raw_data: Arc::new(vec![Arc::new(raw_data)]), + raw_data, samples: samples.len() as u64, }; if jobs.send(job).is_err() { @@ -1111,7 +1137,8 @@ fn serve_ingest( let routing = Arc::new(ingestion.routing()); *shared.routing.write().unwrap_or_else(|e| e.into_inner()) = routing.clone(); let watermark_ms = ingestion.watermark_ms(); - if watermark_ms != sealed_through || !closed.is_empty() { + // After a flush, always: the shards hold their samples until then. + if flushed_at.is_some() || watermark_ms != sealed_through || !closed.is_empty() { sealed_through = watermark_ms; for shard in &shards { let _ = shard.send(ShardMessage::Maintain { @@ -1579,7 +1606,13 @@ fn serve_precompute( samples, }) => { let (parts, count) = late.entry(window).or_default(); - parts.extend(raw_data.iter().cloned()); + if precompute.recomputes(window.group) { + // The raw data whole, as of the newest pass: it + // holds the late samples of the earlier ones. + *parts = raw_data.iter().cloned().collect(); + } else { + parts.extend(raw_data.iter().cloned()); + } *count += samples; } PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { @@ -1713,7 +1746,7 @@ fn merge_late( to_persist: &mut Vec, shared: &Shared, ) { - let merged = precompute.merge_late(window, raw_data, views); + let merged = precompute.merge_late(window, raw_data, views, false); let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); match merged { Ok(changed) => { diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 165f501fb..956efad65 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -38,11 +38,13 @@ use std::sync::Arc; use asap_executor::physical_planner::{compile, CompiledPhysicalDAG}; use asap_executor::planner::ir::operator::Source; +use asap_executor::planner::ir::schema::FieldDataType; use asap_executor::planner::ir::{NonASAPOp, Operator}; use asap_executor::planner::plan::materialized_view::{ IngestionRefreshGroup, MaterializedView, MaterializedViewRefresh, }; use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; +use asap_executor::planner::summary_type::ExactKind; use asap_executor::runtime::{Limits, RunContext, Scope}; use asap_executor::values::{Batch, SchemaRef}; use futures::executor::block_on; @@ -159,12 +161,31 @@ struct RefreshGroupRun { reads: Vec, /// For each of its views, the groups that read it. readers: Vec>, + /// Its windows are computed again, not merged, when late samples come + /// ([`order_sensitive`]). + recomputes: bool, +} + +/// Whether a view of `schema` holds a state whose merge depends on the +/// order of the samples merged (a counter's resets, an instant rate's last +/// two samples): merging a late sample's state into it would differ from +/// the state of the samples in time order. +fn order_sensitive(schema: &asap_executor::values::SchemaRef) -> bool { + schema.fields.iter().any(|field| { + matches!( + field.dtype, + FieldDataType::ExactAggregate(ExactKind::Counter | ExactKind::IRate, _) + ) + }) } /// One refresh group's windows. struct RefreshGroup { width_ms: i64, phase_ms: i64, + /// Its windows are computed again from the raw samples when late + /// samples come, so it keeps them for its views' retention. + recomputes: bool, /// The metrics its runs scan: their raw samples it needs kept. metrics: BTreeSet, /// The groups whose views its runs read. @@ -320,6 +341,11 @@ impl Ingestion { .map(|v| millis(v.retention_ms())) .max() .unwrap_or(0); + let recomputes = ids.iter().any(|&id| { + compiled + .output_schema(id as u64) + .is_ok_and(|schema| order_sensitive(&schema)) + }); runs.push(RefreshGroupRun { views, compiled, @@ -327,10 +353,12 @@ impl Ingestion { phase_ms: millis(window.phase_ms), reads: read.iter().copied().collect(), readers: Vec::new(), + recomputes, }); clocks.push(RefreshGroup { width_ms: millis(window.width_ms), phase_ms: millis(window.phase_ms), + recomputes, metrics, reads: tasks.reads.last().cloned().unwrap_or_default(), started_by, @@ -463,6 +491,12 @@ impl Ingestion { self.groups.iter().map(|g| g.refreshed_through).collect() } + /// Whether group `group`'s windows are computed again, not merged, + /// when late samples come: its late merges read the raw data whole. + pub(crate) fn recomputes(&self, group: usize) -> bool { + self.groups[group].recomputes + } + /// Whether a query run reads raw samples (a query-time `Scan`); if not, /// only the refresh windows read them. pub(crate) fn queries_read_raw_data(&self) -> bool { @@ -634,9 +668,13 @@ impl Ingestion { .iter() .map(|g| Some(g.refreshed_through?.saturating_sub(g.retention_ms))) .collect(); - // Readers come after the groups they read. + // Readers come after the groups they read. A group whose windows are + // computed again needs its own window kept. for reader in (0..self.groups.len()).rev() { for &read in &self.groups[reader].reads { + if self.groups[read].recomputes { + continue; + } if let (Some(own), Some(theirs)) = (kept[read], kept[reader]) { kept[read] = Some(own.min(theirs)); } @@ -737,8 +775,19 @@ impl Ingestion { .enumerate() .filter(|(index, g)| !self.is_push(*index) && g.metrics.contains(metric)) { - // A group not started yet needs every sample. - if !lower(group.refreshed_through) { + // A group not started yet needs every sample; one whose windows + // are computed again from late samples, those of every window + // its views keep. + let needed_after = group.refreshed_through.map(|through| { + if group.recomputes { + through + .saturating_sub(group.retention_ms) + .saturating_sub(group.width_ms) + } else { + through + } + }); + if !lower(needed_after) { return None; } } @@ -1011,8 +1060,11 @@ pub(crate) struct LateMerged { pub revision: u64, /// Each of its views' merged rows, as now stored. pub rows: Vec<(PhysicalASAPNodeId, Vec)>, - /// Each of its views' change: the rows of the run over the change alone. + /// Each of its views' change, when merged: the rows of the run over + /// the change alone. late: Vec<(PhysicalASAPNodeId, Vec)>, + /// Its window was computed again (replaced), not merged. + recomputed: bool, } /// What a refresh did. @@ -1363,72 +1415,106 @@ impl Precompute { found } - /// Merges `raw_data`, the late samples 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). Each - /// group's change is its run over the change alone: its late samples, - /// or the rows the windows it reads gained, with nothing else in its - /// raw data or views; [`ViewStore::merge_late`] merges those rows into - /// the window's, so the window ends as if the samples had come on - /// time (each state merge is its kernel's). Returns each changed - /// window, to write again; a view whose window is no longer stored - /// takes no change. + /// 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 + /// (a reader after what it reads). A group's change is one of: + /// + /// - **merged**: its run over the change alone (its late samples, or + /// the rows the windows it reads gained, with nothing else in its raw + /// data or views), whose rows [`ViewStore::merge_late`] merges into + /// the window's: the window ends as if the samples had come on time + /// when every state's merge is a fold of its samples; + /// - **computed again**: for a group whose states depend on the order + /// of their samples ([`order_sensitive`]), and every group reading a + /// window computed again, its run over the views as they now stand + /// and `raw_data`, which is then the raw data whole (late samples + /// included), replacing the window ([`ViewStore::replace_window`]). + /// + /// With `insert`, a window not stored is stored with the change. Returns + /// each changed window, to write again; a view whose window is no + /// longer stored takes no change (a merged change still reaches its + /// readers). pub(crate) fn merge_late( &self, window: ClosedWindow, raw_data: RawShards, views: &mut Arc, + insert: bool, ) -> Result, asap_executor::Error> { let empty_raw: RawShards = Arc::new(raw_data.iter().map(|r| Arc::new(r.emptied())).collect()); - // Per group to change, the window and the raw data its change reads. let mut changed: Vec = Vec::new(); for group in self.readers_of(window.group) { let run = &self.runs[group]; let end = run.window_end(window.end_ms); - let raw = if group == window.group { - raw_data.clone() - } else { - empty_raw.clone() - }; - // The windows it reads, as the change left them: the rows each - // gained, empty elsewhere. - let mut read = ViewStore::default(); - let start = end - run.width_ms; - let mut reads_change = false; - for &view_id in &run.reads { - let Some((source, width_ms)) = self.view(view_id) else { + let range = (end - run.width_ms, end); + let source = group == window.group; + // The changes of windows it reads, inside its window. + let reads: Vec<&LateMerged> = changed + .iter() + .filter(|c| { + range.0 < c.range_ms.1 + && c.range_ms.1 <= end + && self.runs[c.group] + .views + .iter() + .any(|view| run.reads.contains(&view.node_id)) + }) + .collect(); + if !source && reads.is_empty() { + continue; + } + let recompute = run.recomputes || reads.iter().any(|c| c.recomputed); + let late: Vec<(PhysicalASAPNodeId, Vec)> = if recompute { + let outputs = self.run(group, end, raw_data.clone(), views.clone(), None)?; + let Computed::Ran(rows) = + self.computed(group, (0..run.views.len()).collect(), outputs) + else { continue; }; - read.hold_for_readers(view_id, &[group]); - let mut window_start = start; - while window_start < end { - let window_end = window_start + width_ms; - let rows = changed - .iter() - .filter(|c| c.range_ms.1 == window_end) - .flat_map(|c| &c.late) - .find(|(v, _)| *v == view_id) - .map(|(_, rows)| rows.clone()) - .unwrap_or_default(); - reads_change |= !rows.is_empty(); - read.append(source, (window_start, window_end), rows)?; - window_start = window_end; + rows.into_iter() + .map(|(index, batches)| (run.views[index].node_id, batches)) + .collect() + } else { + // The windows it reads, as the change left them: the rows + // each gained, empty elsewhere. + let mut read = ViewStore::default(); + for &view_id in &run.reads { + let Some((source_view, width_ms)) = self.view(view_id) else { + continue; + }; + read.hold_for_readers(view_id, &[group]); + let mut window_start = range.0; + while window_start < end { + let window_end = window_start + width_ms; + let rows = reads + .iter() + .filter(|c| c.range_ms.1 == window_end) + .flat_map(|c| &c.late) + .find(|(v, _)| *v == view_id) + .map(|(_, rows)| rows.clone()) + .unwrap_or_default(); + read.append(source_view, (window_start, window_end), rows)?; + window_start = window_end; + } } - } - if group != window.group && !reads_change { - continue; - } - let outputs = self.run(group, end, raw, Arc::new(read), None)?; - let Computed::Ran(late) = self.computed(group, (0..run.views.len()).collect(), outputs) - else { - continue; + let raw = if source { + raw_data.clone() + } else { + empty_raw.clone() + }; + let outputs = self.run(group, end, raw, Arc::new(read), None)?; + let Computed::Ran(rows) = + self.computed(group, (0..run.views.len()).collect(), outputs) + else { + continue; + }; + rows.into_iter() + .map(|(index, batches)| (run.views[index].node_id, batches)) + .filter(|(_, batches)| batches.iter().any(|b| b.num_rows() > 0)) + .collect() }; - let late: Vec<(PhysicalASAPNodeId, Vec)> = late - .into_iter() - .map(|(index, batches)| (run.views[index].node_id, batches)) - .filter(|(_, batches)| batches.iter().any(|b| b.num_rows() > 0)) - .collect(); if late.is_empty() { continue; } @@ -1439,22 +1525,39 @@ impl Precompute { .map_or(0, |revision| revision + 1); let store = Arc::make_mut(views); let mut rows = Vec::new(); - for (view, batches) in &late { - if let Some(merged) = store.merge_late(*view, end, revision, batches.clone())? { - rows.push((*view, merged)); + for (view_id, batches) in &late { + let view = run + .views + .iter() + .find(|view| view.node_id == *view_id) + .expect("a view of the group"); + let stored = if recompute { + store.replace_window(view, range, revision, batches.clone(), insert)? + } else { + store.merge_late(view, range, revision, batches.clone(), insert)? + }; + if let Some(stored) = stored { + rows.push((*view_id, stored)); } } changed.push(LateMerged { group, - range_ms: (end - run.width_ms, end), + range_ms: range, revision, rows, - late, + late: if recompute { Vec::new() } else { late }, + recomputed: recompute, }); } Ok(changed) } + /// Whether group `group`'s windows are computed again, not merged, when + /// late samples come ([`Self::merge_late`]). + pub(crate) fn recomputes(&self, group: usize) -> bool { + self.runs[group].recomputes + } + /// View `id` of some group, with that group's window width. fn view(&self, id: PhysicalASAPNodeId) -> Option<(&MaterializedView, i64)> { self.runs.iter().find_map(|run| { diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index ca485401b..eb954ac0f 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -283,7 +283,11 @@ impl RawData { } /// Appends `samples`, in order, as one chunk per metric and pane; - /// samples of a metric no `Scan` reads are not stored. + /// samples of a metric no `Scan` reads are not stored. A pane's rows + /// stay in time order (runs read a series' samples in time order): rows + /// older than the pane's newest, or out of order among themselves (a + /// late sample), make the pane one chunk sorted by time, equal times in + /// arrival order. pub fn append(&mut self, samples: &[RawSample]) { let mut by_pane: BTreeMap<(&str, i64), Vec<&RawSample>> = BTreeMap::new(); for sample in samples { @@ -297,12 +301,28 @@ impl RawData { let Some(metric) = self.by_metric.get_mut(metric) else { continue; }; - let chunk = Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))); - metric - .panes - .entry(pane_end) - .or_default() - .extend(chunk.map(Arc::new)); + let pane = metric.panes.entry(pane_end).or_default(); + let in_order = rows + .windows(2) + .all(|pair| pair[0].timestamp_ms <= pair[1].timestamp_ms) + && pane + .last() + .is_none_or(|last| last.time_bounds_ms.1 <= rows[0].timestamp_ms); + if in_order { + let chunk = Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))); + pane.extend(chunk.map(Arc::new)); + continue; + } + let mut all: Vec<(&'static Series, i64, f64)> = pane + .iter() + .flat_map(|chunk| chunk.rows()) + .chain(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))) + .collect(); + all.sort_by_key(|row| row.1); + *pane = Chunk::new(all.into_iter()) + .map(Arc::new) + .into_iter() + .collect(); } } @@ -1231,25 +1251,34 @@ impl ViewStore { /// replaced by the merged rows at `revision` (in memory until written /// again, as a committed window), and a result cached from an earlier /// revision that read it is stale ([`Self::changed_since`]). Returns - /// the merged rows, to write; `None` when the window is not stored - /// (past the view's retention, skipped or failed), so `late` is lost. - /// `late` holds at least one batch. + /// the merged rows, to write. A window not stored is stored with + /// `late`'s rows alone when `insert` is set ([`Self::replace_window`]); + /// otherwise (past the view's retention, skipped or failed) `late` is + /// lost and the result is `None`. `late` holds at least one batch. pub fn merge_late( &mut self, - view: PhysicalASAPNodeId, - end_ms: i64, + view: &MaterializedView, + time_range_ms: (i64, i64), revision: u64, late: Vec, + insert: bool, ) -> Result>, Error> { - let Some(old) = self.slot(view, end_ms) else { - return Ok(None); - }; - let stored = old.batches()?; + let end_ms = time_range_ms.1; let schema = late .first() .ok_or_else(|| Error::Invalid("no late rows to merge".into()))? .schema() .clone(); + let Some(old) = self.slot(view.node_id, end_ms) else { + if !insert { + return Ok(None); + } + let rows = merged_rows(late.iter())?; + let batches = vec![Batch::try_new(schema, rows)?]; + return self.replace_window(view, time_range_ms, revision, batches, true); + }; + let view = view.node_id; + let stored = old.batches()?; let rows = merged_rows(stored.iter().chain(&late))?; let merged = if rows.is_empty() { Vec::new() @@ -1261,13 +1290,81 @@ impl ViewStore { let at = rows.partition_point(|window| window.time_range_ms.1 < end_ms); rows[at].slot = slot; old.left_store(); + self.revised(end_ms); + Ok(Some(merged)) + } + + /// Replaces `view`'s window covering `time_range_ms` by `batches` (its + /// rows computed again) at `revision`, or, when it is not stored and + /// `insert` is set, stores it behind the newest window: the window of + /// a collector view whose first states came after a later window's. + /// A result cached from an earlier revision that read it is stale. + /// Returns the stored rows, to write; `None` when the window is not + /// stored and is not inserted (not `insert`, past the view's + /// retention of its newest window, or overlapping a stored one). + pub fn replace_window( + &mut self, + view: &MaterializedView, + time_range_ms: (i64, i64), + revision: u64, + batches: Vec, + insert: bool, + ) -> Result>, Error> { + let (start, end) = time_range_ms; + let rows = self.by_view.entry(view.node_id).or_default(); + let at = rows.partition_point(|window| window.time_range_ms.1 < end); + let stored = rows + .get(at) + .is_some_and(|window| window.time_range_ms == time_range_ms); + if !stored { + let newest = rows.last().map(|window| window.time_range_ms.1); + let fits = start < end + && at + .checked_sub(1) + .is_none_or(|before| rows[before].time_range_ms.1 <= start) + && rows + .get(at) + .is_none_or(|after| end <= after.time_range_ms.0) + && newest.is_none_or(|newest| end > oldest_kept_end(view, newest)); + if !insert || !fits { + return Ok(None); + } + } + let schema = batches + .first() + .map(|batch| batch.schema().clone()) + .unwrap_or_else(|| { + Arc::new(asap_executor::planner::ir::schema::Schema::new(Vec::new())) + }); + let slot = + Arc::new(self.committed_slot(view.node_id, end, revision, schema, batches.clone())?); + let rows = self.by_view.get_mut(&view.node_id).expect("entered above"); + if stored { + let old = std::mem::replace(&mut rows[at].slot, slot); + old.left_store(); + } else { + rows.insert( + at, + ViewWindow { + time_range_ms, + slot, + }, + ); + let first = self.first_start.entry(view.node_id).or_insert(start); + *first = (*first).min(start); + } + self.revised(end); + Ok(Some(batches)) + } + + /// Notes a revision of a window ending `end_ms`. + fn revised(&mut self, end_ms: i64) { self.revision += 1; let revisions = Arc::make_mut(&mut self.revisions); if revisions.len() == REVISIONS_KEPT { revisions.pop_front(); } revisions.push_back((self.revision, end_ms)); - Ok(Some(merged)) } /// How many windows late samples revised so far. @@ -1967,6 +2064,49 @@ mod tests { /// A view read returns exactly the stored windows that tile the /// requested range, and fails when they do not. + /// A window missing behind the newest (a collector view's whose first + /// states came late) is inserted in order, so a range across it tiles + /// again; one overlapping a stored window, or past the view's retention + /// of its newest, is not; without `insert`, nothing missing is stored. + #[test] + fn a_missing_window_is_inserted_behind_the_newest() { + 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": 100, + })) + .unwrap(); + let mut views = ViewStore::default(); + for end in [110, 130] { + views.append(&view, (end - 10, end), Vec::new()).unwrap(); + } + assert!(views + .replace_window(&view, (110, 120), 0, Vec::new(), false) + .unwrap() + .is_none()); + let revision = views.revision(); + assert!(views + .replace_window(&view, (110, 120), 0, Vec::new(), true) + .unwrap() + .is_some()); + assert!(views.changed_since(revision, 120)); + let ends: Vec = views.rows()[&1].iter().map(|(range, _)| range.1).collect(); + assert_eq!(ends, [110, 120, 130]); + // Overlapping (115, 125], and (20, 30], past retention (130 − 100). + for range in [(115, 125), (20, 30)] { + assert!(views + .replace_window(&view, range, 0, Vec::new(), true) + .unwrap() + .is_none()); + } + assert_eq!(views.rows()[&1].len(), 3); + } + #[test] fn view_reads_select_the_windows_tiling_the_range() { let view: MaterializedView = serde_json::from_value(serde_json::json!({ From dc0a7e52c8e0f01bee773a3de01f487e1391ad59 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:21:24 +0000 Subject: [PATCH 07/19] fix(precompute): a late merge waits only for windows in flight; readers not closed yet take no change A merge waited until every reader group had committed through the window holding it, which never happens when that reader's window failed (it read a window still missing). It now waits while a window holding it is closed and not committed, and a reader's window not closed yet takes no change: it reads the changed window when it closes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/engine.rs | 22 +++++++++++++++--- crates/precompute/src/ingestion.rs | 37 +++++++++++++++++++----------- 2 files changed, 43 insertions(+), 16 deletions(-) diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 14c518302..7dd06c77a 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -1579,6 +1579,9 @@ fn serve_precompute( // Late samples by window, merged once it and the windows built from it // are committed: each window's raw data parts and sample count. let mut late: BTreeMap>, u64)> = BTreeMap::new(); + // Per group, the end of the newest window whose job came: the windows + // closed so far (jobs come in the order windows close). + let mut closed_through: Vec> = vec![None; precompute.groups().len()]; let mut closed = false; while !(closed && tasks.is_empty()) { let Ok(event) = inbox.recv() else { @@ -1595,8 +1598,14 @@ fn serve_precompute( window, raw_data, closed_at, - }) => tasks.push(window, raw_data, closed_at), + }) => { + closed_through[window.group] = + closed_through[window.group].max(Some(window.end_ms)); + tasks.push(window, raw_data, closed_at) + } PoolEvent::Job(PrecomputeJob::Push { window, closed_at }) => { + closed_through[window.group] = + closed_through[window.group].max(Some(window.end_ms)); tasks.push_window(window, closed_at, options.push_parts) } PoolEvent::Partial(partial) => tasks.partial(partial), @@ -1678,7 +1687,7 @@ fn serve_precompute( let ready: Vec = late .keys() .copied() - .filter(|&window| precompute.late_ready(window, &views)) + .filter(|&window| precompute.late_ready(window, |w| tasks.pending(w))) .collect(); for window in ready { let (parts, samples) = late.remove(&window).expect("listed"); @@ -1687,6 +1696,7 @@ fn serve_precompute( window, (Arc::new(parts), samples), &mut views, + &closed_through, &mut to_persist, shared, ); @@ -1743,10 +1753,11 @@ fn merge_late( window: ClosedWindow, (raw_data, samples): (RawShards, u64), views: &mut Arc, + closed_through: &[Option], to_persist: &mut Vec, shared: &Shared, ) { - let merged = precompute.merge_late(window, raw_data, views, false); + let merged = precompute.merge_late(window, raw_data, views, false, closed_through); let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); match merged { Ok(changed) => { @@ -1930,6 +1941,11 @@ struct WindowTasks { } impl WindowTasks { + /// Whether `window` is closed and not yet committed. + fn pending(&self, window: ClosedWindow) -> bool { + self.tasks.values().any(|task| task.window == window) + } + fn new(graph: RefreshTaskGraph, parts: u32) -> Self { Self { graph, diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 956efad65..66f922a5c 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -1385,18 +1385,21 @@ impl Precompute { Ok(Refreshed::Ran(appended)) } - /// Whether late samples of `window` may be merged now: its group's views - /// and those of every group reading them (transitively) are committed - /// through the window of theirs holding it, so no run still in flight - /// read the window before the merge, and every window built from it is - /// committed to take the change ([`Self::merge_late`]). - pub(crate) fn late_ready(&self, window: ClosedWindow, views: &ViewStore) -> bool { + /// Whether late samples of `window` may be merged now: no window of + /// its group, or of a group reading its views (transitively), holding + /// it is closed and not yet committed (`pending`), so no run in flight + /// read the window before the merge. A reader's window not closed yet + /// reads the merged window when it closes. + pub(crate) fn late_ready( + &self, + window: ClosedWindow, + pending: impl Fn(ClosedWindow) -> bool, + ) -> bool { self.readers_of(window.group).into_iter().all(|group| { - let run = &self.runs[group]; - let end = run.window_end(window.end_ms); - run.views - .iter() - .all(|view| views.stored_through(view.node_id) >= Some(end)) + !pending(ClosedWindow { + group, + end_ms: self.runs[group].window_end(window.end_ms), + }) }) } @@ -1431,7 +1434,9 @@ impl Precompute { /// and `raw_data`, which is then the raw data whole (late samples /// included), replacing the window ([`ViewStore::replace_window`]). /// - /// With `insert`, a window not stored is stored with the change. Returns + /// A reader's window not closed yet (past `closed_through`, by group) + /// takes no change: it reads the changed window when it closes. With + /// `insert`, a window not stored is stored with the change. Returns /// each changed window, to write again; a view whose window is no /// longer stored takes no change (a merged change still reaches its /// readers). @@ -1441,6 +1446,7 @@ impl Precompute { raw_data: RawShards, views: &mut Arc, insert: bool, + closed_through: &[Option], ) -> Result, asap_executor::Error> { let empty_raw: RawShards = Arc::new(raw_data.iter().map(|r| Arc::new(r.emptied())).collect()); @@ -1462,7 +1468,12 @@ impl Precompute { .any(|view| run.reads.contains(&view.node_id)) }) .collect(); - if !source && reads.is_empty() { + let closed = closed_through + .get(group) + .copied() + .flatten() + .is_some_and(|through| end <= through); + if !source && (reads.is_empty() || !closed) { continue; } let recompute = run.recomputes || reads.iter().any(|c| c.recomputed); From 8f5588f97a3eb1c0e8a307170cfa6d540c3241e5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:58:28 +0000 Subject: [PATCH 08/19] fix(precompute): a reader that cannot be computed again keeps its rows; T12 over the gauge queries A window read from a late-changed window is computed again from the views; when that run fails (a window it reads is already gone) the reader keeps its rows and the change already made stays, instead of failing the whole merge after the store changed. T12 measures the raw buffer of pushed pipelines over the dashboard's gauge queries: its counter queries are no longer pushed (their windows are computed again from raw samples kept for retention). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/push_precompute.rs | 23 +++++++++++++++------- crates/precompute/src/ingestion.rs | 11 ++++++++++- 2 files changed, 26 insertions(+), 8 deletions(-) diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index 0cadd3df7..8cd10753a 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -887,18 +887,27 @@ async fn idle_shards_seal_empty_and_hold_nothing_back() { // ── T12: no raw buffer for pushed pipelines ───────────────────────────── -/// T12. Pushed pipelines buffer no raw samples: the dashboard plan, raw -/// data not kept, 10k series at 1 sample/s, W = 15 s, 4 shards. Before each -/// close, raw bytes stay below one request's samples (not rate × W × 20 B, -/// 3 MB per metric) and the open state is reported. With raw data kept, -/// push holds no more raw data than the window path. +/// T12. Pushed pipelines buffer no raw samples: the dashboard plan's +/// queries over `lat`, raw data not kept, 10k series at 1 sample/s, +/// W = 15 s, 4 shards. Before each close, raw bytes stay below one +/// request's samples (not rate × W × 20 B, 3 MB per metric) and the open +/// state is reported. (Its counter queries over `reqs` are not pushed: +/// their windows are computed again from raw samples kept for their +/// retention when a late sample comes.) With raw data kept, push holds no +/// more raw data than the window path. #[tokio::test(flavor = "multi_thread")] async fn pushed_pipelines_buffer_no_raw_samples() { const SERIES: usize = 10_000; let workload = workload_file("dashboard", SERIES); + let mut gauges = serde_json::to_value(&workload).unwrap(); + gauges["query_workload"]["repeating_queries"] + .as_array_mut() + .unwrap() + .retain(|query| query["query"].as_str().unwrap().contains("lat")); + let gauges: asap_planner::PlanningWorkload = serde_json::from_value(gauges).unwrap(); let metrics = ["lat", "reqs"]; - let one_request_bytes = (SERIES * metrics.len() * 20) as f64; - let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; + let one_request_bytes = (SERIES * 20) as f64; + let plan = plan_workload(&gauges, &common::inputs(false)).unwrap().0; let (app, _) = install(&plan, options(PUSH, 4)); for second in 1..=44i64 { assert_eq!( diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 66f922a5c..3b4488692 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -1478,7 +1478,16 @@ impl Precompute { } let recompute = run.recomputes || reads.iter().any(|c| c.recomputed); let late: Vec<(PhysicalASAPNodeId, Vec)> = if recompute { - let outputs = self.run(group, end, raw_data.clone(), views.clone(), None)?; + // A reader whose run fails (a window it reads is gone) keeps + // its rows; the change already made stays. + let outputs = match self.run(group, end, raw_data.clone(), views.clone(), None) { + Ok(outputs) => outputs, + Err(error) if !source => { + tracing::warn!(group, end, %error, "a window read from a late-changed window was not computed again"); + continue; + } + Err(error) => return Err(error), + }; let Computed::Ran(rows) = self.computed(group, (0..run.views.len()).collect(), outputs) else { From 4c4987ee34a486019f4ce5f22f02e1fdd081356b Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 01:53:20 +0000 Subject: [PATCH 09/19] test(precompute): a late counter sample past the narrow level's retention reaches the wide level (failing first) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/window_levels.rs | 130 +++++++++++++++++++++++ 1 file changed, 130 insertions(+) diff --git a/crates/data-plane/tests/window_levels.rs b/crates/data-plane/tests/window_levels.rs index 8559f7494..b760d62f3 100644 --- a/crates/data-plane/tests/window_levels.rs +++ b/crates/data-plane/tests/window_levels.rs @@ -116,6 +116,20 @@ async fn wider_levels_and_covers_answer_after_one_pass_closes_every_window() { // The narrowest group holds a view kept less than the group's longest // retention: the case a view's readers must hold. let groups = plan.ingestion_refresh_groups().unwrap(); + for g in &groups { + eprintln!( + "GROUP width {:?} views {:?}", + g.refresh_window.map(|w| w.width_ms), + g.views + .iter() + .map(|v| ( + v.node_id, + v.retention_ms(), + v.inputs.materialized_views.clone() + )) + .collect::>() + ); + } let narrow = groups .iter() .min_by_key(|g| g.refresh_window.unwrap().width_ms) @@ -335,3 +349,119 @@ async fn queries_answer_from_the_samples_there_are_before_their_window_fills() { } } } + +/// A late counter sample older than the narrow chain level's own retention +/// (1 h and the 60 s margin back from the newest window, 7 200 s), at +/// 3 495 s, inside the 15 min window `(2 700, 3 600]` the wide level still +/// keeps: the narrow windows are kept as long as the levels built from them +/// read them, so every level's window holding the sample is computed again, +/// and `increase` over the hour ending at 6 300 s, read from that wide +/// window, answers as if the sample had come on time. +#[tokio::test(flavor = "multi_thread")] +async fn a_late_counter_sample_reaches_the_wide_level_past_the_narrow_retention() { + const QUERY: &str = "sum by (job) (increase(c_total[1h]))"; + const LATE_S: i64 = 3_495; + const AT_S: i64 = 6_300; + let workload = serde_json::from_value(json!({ + "query_workload": {"language": "promql", "repeating_queries": [{ + "query": QUERY, + "demand": {"fixed_interval_at": {"interval": 15000, "evaluation_phase": 0}}, + "requirements": {}, + "predictability": {"predictable": {"known_at": null}}, + }]}, + "data_workload": {"arrival": {"ingesting": {"rows_per_second": 0.8}}, + "sources": {"c_total": {"series_count": SERIES, "sample_interval": 15000, + "metric_type": "counter", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; + let text = serde_json::to_string(&plan.dag).unwrap(); + assert!(text.contains("SummaryMergeWindows"), "no wider level"); + // A counter rising by 7 a step; the late sample jumps 1 000 higher, + // and the counter resets right after it. + let value = |series: usize, step: i64| -> f64 { + let s = step * 15; + let rate = 7 * (series as i64 + 1); + match s.cmp(&LATE_S) { + std::cmp::Ordering::Less => (s / 15 * rate) as f64, + std::cmp::Ordering::Equal => (s / 15 * rate + 1_000) as f64, + std::cmp::Ordering::Greater => ((s - LATE_S) / 15 * rate) as f64, + } + }; + let body = |late: Option| { + let timeseries: Vec = (0..SERIES) + .map(|i| TimeSeries { + labels: [ + ("__name__", "c_total".to_string()), + ("instance", format!("i{i}")), + ("job", format!("job{}", i % 3)), + ] + .into_iter() + .map(|(name, value)| Label { + name: name.into(), + value, + }) + .collect(), + samples: (1..=END_S / 15) + .filter(|step| match late { + None => true, + Some(late) => (i == 0 && step * 15 == LATE_S) == late, + }) + .map(|step| Sample { + timestamp: step * 15_000, + value: value(i, step), + }) + .collect(), + }) + .filter(|series| !series.samples.is_empty()) + .collect(); + encode(&WriteRequest { timeseries }) + }; + let data_plane = || { + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan).unwrap(), + "http://127.0.0.1:1".into(), + EngineOptions { + precompute_threads: 4, + ..common::no_forward_options() + }, + ) + .unwrap(), + ); + (router(state.clone()), state) + }; + let barrier = format!("/api/v1/precompute/watermark?time_ms={}", END_S * 1000); + + let (app, _) = data_plane(); + assert_eq!( + post(&app, "/api/v1/write".into(), body(None)).await, + StatusCode::NO_CONTENT + ); + assert_eq!( + post(&app, barrier.clone(), Vec::new()).await, + StatusCode::OK + ); + let (status, on_time) = answer(&app, QUERY, AT_S).await; + assert_eq!(status, StatusCode::OK, "{on_time}"); + + let (app, state) = data_plane(); + assert_eq!( + post(&app, "/api/v1/write".into(), body(Some(false))).await, + StatusCode::NO_CONTENT + ); + assert_eq!( + post(&app, barrier.clone(), Vec::new()).await, + StatusCode::OK + ); + assert_ne!(answer(&app, QUERY, AT_S).await.1, on_time); + assert_eq!( + post(&app, "/api/v1/write".into(), body(Some(true))).await, + StatusCode::NO_CONTENT + ); + assert_eq!(post(&app, barrier, Vec::new()).await, StatusCode::OK); + let (status, after) = answer(&app, QUERY, AT_S).await; + assert_eq!(status, StatusCode::OK, "{after}"); + assert_eq!(after, on_time, "{:?}", state.engine.stats()); + assert_eq!(state.engine.stats().samples_dropped_late, 0); +} From 3b3eaac4a613c9038fdea02602ae1ac2204af6c4 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 01:55:56 +0000 Subject: [PATCH 10/19] feat(precompute): raw samples kept for recompute as XOR chunks; narrow levels kept as long as the levels computed again from them - storage::xor_chunk: one series' samples as a Prometheus-style XOR (Gorilla) chunk, delta-of-delta timestamps and XOR'd value bits, lossless on any bit pattern. - RawData keeps a metric's closed panes that only windows computed again read (behind every window still to close, within an order-sensitive group's floor) as CompressedPanes, one XOR chunk per series; a read decodes them, and a late sample of one makes the pane columnar again. The routing carries both cutoffs: compress, then evict. - A group a chain computed again reads keeps its windows as long as the readers' windows reach back (their retention plus their width), and the late-sample floor of an order-sensitive group takes its readers' floors, so a late sample within the widest level's retention always has the narrow windows to compute every level again from. The path that kept a reader's old rows when its run failed is gone. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/ingestion.rs | 111 ++++++++++----- crates/storage/src/lib.rs | 1 + crates/storage/src/store.rs | 151 ++++++++++++++++++-- crates/storage/src/xor_chunk.rs | 217 +++++++++++++++++++++++++++++ 4 files changed, 440 insertions(+), 40 deletions(-) create mode 100644 crates/storage/src/xor_chunk.rs diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 3b4488692..7e80d0f55 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -393,7 +393,7 @@ impl Ingestion { }; } } - let ingestion = Self { + let mut ingestion = Self { groups: clocks, scanned_metrics: Arc::new(storage::store::scanned_metrics(&dag.nodes)), pane_width_ms, @@ -421,6 +421,37 @@ impl Ingestion { .map(|view| readers.get(&view.node_id).cloned().unwrap_or_default()) .collect(); } + // A window computed again from late samples, and every window read + // from it, is computed again from the windows it reads: a group + // such a reader reads keeps its windows as long as that reader's + // windows (its retention plus its width), so a late sample within + // the widest level's retention can always be taken. + let mut computed_again = vec![false; runs.len()]; + for group in 0..runs.len() { + computed_again[group] = runs[group].recomputes + || tasks.reads[group].iter().any(|&read| computed_again[read]); + } + let mut needed: Vec = ingestion.groups.iter().map(|g| g.retention_ms).collect(); + for reader in (0..runs.len()).rev().filter(|&g| computed_again[g]) { + for &read in &tasks.reads[reader] { + needed[read] = + needed[read].max(needed[reader].saturating_add(runs[reader].width_ms)); + } + } + for (group, run) in runs.iter_mut().enumerate() { + if needed[group] <= ingestion.groups[group].retention_ms { + continue; + } + run.views = run + .views + .iter() + .map(|view| { + let extra = needed[group].saturating_sub(millis(view.retention_ms())); + with_retention_margin(view, extra.max(0) as u64) + }) + .collect::, _>>()?; + ingestion.groups[group].retention_ms = needed[group]; + } Ok(( ingestion, Precompute { @@ -597,13 +628,29 @@ impl Ingestion { /// to be closed read it), unless a push group scans it: push shards /// drop the samples of sealed windows themselves. pub fn routing(&self) -> Routing { + let kept_after_ms = self.kept_after_ms(); let cutoffs: HashMap> = self .scanned_metrics .iter() - .map(|metric| (metric.clone(), self.oldest_kept_ms(metric))) + .map(|metric| { + ( + metric.clone(), + self.oldest_kept_ms(metric, &kept_after_ms, true), + ) + }) + .collect(); + // Behind this, a metric's samples are only for windows computed + // again: they are kept compressed. + let compress_through: HashMap = self + .scanned_metrics + .iter() + .filter_map(|metric| { + let through = self.oldest_kept_ms(metric, &kept_after_ms, false)?; + (cutoffs[metric].is_none_or(|cutoff| cutoff < through)) + .then(|| (metric.clone(), through)) + }) .collect(); let watermark_ms = self.watermark_ms(); - let kept_after_ms = self.kept_after_ms(); let late_through = cutoffs .iter() .map(|(metric, &cutoff)| { @@ -628,6 +675,7 @@ impl Ingestion { scanned_metrics: self.scanned_metrics.clone(), max_future_ms: millis(self.options.max_future_ms), cutoffs, + compress_through, late_through, groups_waiting: self.groups.iter().any(|g| g.refreshed_through.is_none()), committed: self @@ -668,13 +716,9 @@ impl Ingestion { .iter() .map(|g| Some(g.refreshed_through?.saturating_sub(g.retention_ms))) .collect(); - // Readers come after the groups they read. A group whose windows are - // computed again needs its own window kept. + // Readers come after the groups they read. for reader in (0..self.groups.len()).rev() { for &read in &self.groups[reader].reads { - if self.groups[read].recomputes { - continue; - } if let (Some(own), Some(theirs)) = (kept[read], kept[reader]) { kept[read] = Some(own.min(theirs)); } @@ -759,7 +803,16 @@ impl Ingestion { /// every window still to be refreshed and than what a query-time `Scan` /// reads back from the watermark (less the allowed lateness, for /// evaluations up to the newest sample). `None` while all are kept. - fn oldest_kept_ms(&self, metric: &str) -> Option { + /// With `for_recompute`, a group whose windows are computed again from + /// late samples needs those of every window it, or a group reading it, + /// keeps (`kept_after_ms`, [`Self::kept_after_ms`]); without, only + /// those of its windows still to close, as any group. + fn oldest_kept_ms( + &self, + metric: &str, + kept_after_ms: &[Option], + for_recompute: bool, + ) -> Option { let mut cutoff: Option = None; let mut lower = |bound: Option| { cutoff = Some(match (cutoff, bound) { @@ -769,24 +822,21 @@ impl Ingestion { }); true }; - for (_, group) in self + for (index, group) in self .groups .iter() .enumerate() .filter(|(index, g)| !self.is_push(*index) && g.metrics.contains(metric)) { - // A group not started yet needs every sample; one whose windows - // are computed again from late samples, those of every window - // its views keep. - let needed_after = group.refreshed_through.map(|through| { - if group.recomputes { - through - .saturating_sub(group.retention_ms) - .saturating_sub(group.width_ms) - } else { - through - } - }); + // A group not started yet needs every sample. + let needed_after = if group.recomputes && for_recompute { + group + .refreshed_through + .and(kept_after_ms[index]) + .map(|kept_after| kept_after.saturating_sub(group.width_ms)) + } else { + group.refreshed_through + }; if !lower(needed_after) { return None; } @@ -880,6 +930,9 @@ pub(crate) struct Routing { max_future_ms: i64, /// Each scanned metric's eviction cutoff (`None`: all are kept). cutoffs: HashMap>, + /// Each metric whose samples behind its newest closed windows are kept + /// only for windows computed again: compressed at or before this. + compress_through: HashMap, /// Each scanned metric's samples at or before this are late (`None`: /// none are). late_through: HashMap>, @@ -1043,6 +1096,9 @@ impl Routing { if let Some(watermark_ms) = watermark_ms { raw_data.seal_through(watermark_ms); } + for (metric, through) in &self.compress_through { + raw_data.compress_through(metric, *through); + } for (metric, cutoff) in &self.cutoffs { if let Some(cutoff) = cutoff { raw_data.evict_through(metric, *cutoff); @@ -1478,16 +1534,7 @@ impl Precompute { } let recompute = run.recomputes || reads.iter().any(|c| c.recomputed); let late: Vec<(PhysicalASAPNodeId, Vec)> = if recompute { - // A reader whose run fails (a window it reads is gone) keeps - // its rows; the change already made stays. - let outputs = match self.run(group, end, raw_data.clone(), views.clone(), None) { - Ok(outputs) => outputs, - Err(error) if !source => { - tracing::warn!(group, end, %error, "a window read from a late-changed window was not computed again"); - continue; - } - Err(error) => return Err(error), - }; + let outputs = self.run(group, end, raw_data.clone(), views.clone(), None)?; let Computed::Ran(rows) = self.computed(group, (0..run.views.len()).collect(), outputs) else { diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index fc40e80cb..4a291a64e 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -12,3 +12,4 @@ pub mod series_ids; mod state_codec; pub mod store; pub mod window_cache; +pub mod xor_chunk; diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index eb954ac0f..957091b80 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -236,11 +236,73 @@ impl Chunk { /// The samples of one pane `(end - width, end]` of a metric, as chunks. type Pane = Vec>; +/// A closed pane's samples kept only for windows computed again from raw +/// samples (late samples of an order-sensitive view): one XOR chunk per +/// series ([`crate::xor_chunk`]), decoded when read. +#[derive(Debug)] +struct CompressedPane { + series: Vec<(&'static Series, Vec)>, + samples: usize, +} + +impl CompressedPane { + /// `pane`'s rows, per series in time order. + fn new(pane: &Pane) -> Self { + type SeriesSamples = (&'static Series, Vec<(i64, f64)>); + let mut by_series: BTreeMap = BTreeMap::new(); + let mut samples = 0; + for (series, time, value) in pane.iter().flat_map(|chunk| chunk.rows()) { + by_series + .entry(series.id) + .or_insert_with(|| (series, Vec::new())) + .1 + .push((time, value)); + samples += 1; + } + Self { + series: by_series + .into_values() + .map(|(series, mut rows)| { + rows.sort_by_key(|row| row.0); + (series, crate::xor_chunk::encode(&rows)) + }) + .collect(), + samples, + } + } + + /// Its rows as one chunk in time order (equal times by series). + fn chunk(&self) -> Option> { + let mut rows: Vec<(&'static Series, i64, f64)> = self + .series + .iter() + .flat_map(|(series, chunk)| { + crate::xor_chunk::decode(chunk) + .unwrap_or_default() + .into_iter() + .map(move |(time, value)| (*series, time, value)) + }) + .collect(); + rows.sort_by_key(|row| row.1); + Chunk::new(rows.into_iter()).map(Arc::new) + } + + fn bytes(&self) -> usize { + self.series + .iter() + .map(|(_, chunk)| chunk.capacity() + std::mem::size_of::<(&Series, Vec)>()) + .sum() + } +} + /// One metric's samples. #[derive(Debug, Clone, Default)] struct MetricPanes { /// Panes by end. panes: BTreeMap, + /// Closed panes kept compressed ([`RawData::compress_through`]), by end; + /// never also in `panes`. + compressed: BTreeMap>, /// Samples at or before this are evicted: a read never returns them, /// though the oldest pane kept may still hold some. evicted_through_ms: Option, @@ -301,6 +363,12 @@ impl RawData { let Some(metric) = self.by_metric.get_mut(metric) else { continue; }; + // A late sample of a compressed pane: the pane is columnar again. + if let Some(compressed) = metric.compressed.remove(&pane_end) { + metric + .panes + .insert(pane_end, compressed.chunk().into_iter().collect()); + } let pane = metric.panes.entry(pane_end).or_default(); let in_order = rows .windows(2) @@ -345,10 +413,30 @@ impl RawData { pub fn evict_through(&mut self, metric: &str, oldest_kept_ms: i64) { if let Some(metric) = self.by_metric.get_mut(metric) { metric.panes = metric.panes.split_off(&oldest_kept_ms.saturating_add(1)); + metric.compressed = metric + .compressed + .split_off(&oldest_kept_ms.saturating_add(1)); metric.evicted_through_ms = metric.evicted_through_ms.max(Some(oldest_kept_ms)); } } + /// Compresses `metric`'s panes ending at or before `through_ms` + /// ([`CompressedPane`]): only windows computed again from raw samples + /// read them, and reads decode them. + pub fn compress_through(&mut self, metric: &str, through_ms: i64) { + let Some(metric) = self.by_metric.get_mut(metric) else { + return; + }; + let newer = metric.panes.split_off(&through_ms.saturating_add(1)); + for (end, pane) in std::mem::replace(&mut metric.panes, newer) { + if !pane.is_empty() { + metric + .compressed + .insert(end, Arc::new(CompressedPane::new(&pane))); + } + } + } + fn chunks(&self) -> impl Iterator> { self.by_metric .values() @@ -358,12 +446,22 @@ impl RawData { /// Panes held, over every metric. pub fn panes(&self) -> usize { - self.by_metric.values().map(|m| m.panes.len()).sum() + self.by_metric + .values() + .map(|m| m.panes.len() + m.compressed.len()) + .sum() + } + + fn compressed(&self) -> impl Iterator> { + self.by_metric + .values() + .flat_map(|metric| metric.compressed.values()) } /// Samples held, over every metric. pub fn len(&self) -> usize { - self.chunks().map(|chunk| chunk.len()).sum() + self.chunks().map(|chunk| chunk.len()).sum::() + + self.compressed().map(|pane| pane.samples).sum::() } pub fn is_empty(&self) -> bool { @@ -372,7 +470,8 @@ impl RawData { /// Bytes of the samples held. pub fn bytes(&self) -> usize { - self.chunks().map(|chunk| chunk.bytes()).sum() + self.chunks().map(|chunk| chunk.bytes()).sum::() + + self.compressed().map(|pane| pane.bytes()).sum::() } /// `metric`'s samples in `time_range_ms` (`(start, end]`, every sample @@ -405,17 +504,27 @@ impl RawData { } // Pane `(e - w, e]` overlaps `(start, end]` when // `start < e < end + w`. - let panes = metric_data.panes.range(( + let range = ( Bound::Excluded(start), Bound::Excluded(end.saturating_add(self.pane_width_ms)), - )); + ); + // Compressed panes are decoded for this read only. + let decoded: Vec> = metric_data + .compressed + .range(range) + .filter_map(|(_, pane)| pane.chunk()) + .collect(); let mut batches = Vec::new(); - for stored in panes.flat_map(|(_, pane)| pane) { + let stored_chunks = metric_data.panes.range(range).flat_map(|(_, pane)| pane); + for (stored, cached) in stored_chunks + .map(|chunk| (chunk, true)) + .chain(decoded.iter().map(|chunk| (chunk, false))) + { let Some(chunk) = stored.in_range((start, end)) else { continue; }; let Some(chunk) = (match partition { - Some(partition) if Arc::ptr_eq(stored, &chunk) => partition.chunk(stored), + Some(partition) if cached && Arc::ptr_eq(stored, &chunk) => partition.chunk(stored), Some(partition) => chunk.in_partition(partition.partition), None => Some(chunk), }) else { @@ -429,7 +538,7 @@ impl RawData { Batch::try_from_columns(request.schema.clone(), columns) }; let batch = match reads { - Some(reads) if Arc::ptr_eq(stored, &chunk) => { + Some(reads) if cached && Arc::ptr_eq(stored, &chunk) => { reads.get_or_convert(stored, request.schema, convert)? } _ => convert()?, @@ -2028,6 +2137,32 @@ mod tests { /// before the cutoff: a read of a range starting before it fails (its /// window would be partial), a read of every sample returns the kept /// ones. + /// Panes kept compressed read back as the columnar panes did, row for + /// row, take fewer bytes, and a late sample of a compressed pane joins + /// it in time order. + #[test] + fn compressed_panes_read_as_the_columnar_ones() { + let schema = schema(); + let mut columnar = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in samples() { + columnar.append(&request); + } + let mut compressed = columnar.clone(); + compressed.compress_through("m_store_test", 20_000); + let read = |raw: &RawData| sorted(read_rows(raw, &schema, Some((0, 30_000)), None)); + assert_eq!(read(&compressed), read(&columnar)); + assert!(compressed.bytes() < columnar.bytes()); + assert_eq!(compressed.len(), columnar.len()); + let late = RawSample { + timestamp_ms: 7_350, + value: 99.0, + ..samples()[0][0].clone() + }; + columnar.append(std::slice::from_ref(&late)); + compressed.append(std::slice::from_ref(&late)); + assert_eq!(read(&compressed), read(&columnar)); + } + #[test] fn evicts_whole_panes() { let schema = schema(); diff --git a/crates/storage/src/xor_chunk.rs b/crates/storage/src/xor_chunk.rs new file mode 100644 index 000000000..08ea13695 --- /dev/null +++ b/crates/storage/src/xor_chunk.rs @@ -0,0 +1,217 @@ +//! One series' samples, in time order, as a Prometheus-style XOR chunk +//! (Gorilla): timestamps as deltas of deltas, values as the XOR of their +//! `f64` bits with the previous value's. Lossless on any bit pattern (NaN +//! payloads, signed zeros, infinities). +//! +//! Layout: a header of the sample count (`u32`), the first timestamp +//! (`i64`, ms) and the first value's bits (`u64`), little-endian; then, for +//! each later sample, most significant bit first, its timestamp code then +//! its value code: +//! +//! - timestamp: `d = t - t_prev` (the first delta taken against +//! `d_prev = 0`), `dod = d - d_prev`: `0` → `0`; [-64, 63] → `10` + 7 +//! bits; [-256, 255] → `110` + 9; [-2048, 2047] → `1110` + 12; otherwise +//! `1111` + 64; two's complement; +//! - value: `x = bits(v) ^ bits(v_prev)`: `0` → `0`; else, with +//! `lead = min(leading_zeros(x), 31)` and `trail = trailing_zeros(x)`, if +//! the window `(L, T)` of the last value written in full has `lead >= L` +//! and `trail >= T`, `10` + the `64 - L - T` bits `x >> T`; else `11` + +//! `lead` (5 bits) + `width - 1` (6 bits, `width = 64 - lead - trail`) + +//! the `width` bits `x >> trail`, and `(lead, trail)` becomes the window. + +/// The header's bytes. +const HEADER_BYTES: usize = 4 + 8 + 8; + +/// Writes bits, most significant first. +#[derive(Default)] +struct BitWriter { + bytes: Vec, + /// Bits used in the last byte (0: the last byte is full or absent). + used: u32, +} + +impl BitWriter { + fn bit(&mut self, bit: bool) { + if self.used == 0 { + self.bytes.push(0); + } + if bit { + *self.bytes.last_mut().expect("pushed") |= 0x80 >> self.used; + } + self.used = (self.used + 1) % 8; + } + + /// The low `count` bits of `value`, most significant first. + fn bits(&mut self, value: u64, count: u32) { + for shift in (0..count).rev() { + self.bit((value >> shift) & 1 == 1); + } + } +} + +/// Reads bits, most significant first. +struct BitReader<'a> { + bytes: &'a [u8], + at: usize, +} + +impl BitReader<'_> { + fn bit(&mut self) -> Option { + let byte = self.bytes.get(self.at / 8)?; + let bit = byte & (0x80 >> (self.at % 8)) != 0; + self.at += 1; + Some(bit) + } + + fn bits(&mut self, count: u32) -> Option { + let mut value = 0u64; + for _ in 0..count { + value = (value << 1) | u64::from(self.bit()?); + } + Some(value) + } +} + +/// `samples` (time ms, value), in time order, as one chunk. +pub fn encode(samples: &[(i64, f64)]) -> Vec { + let mut out = Vec::with_capacity(HEADER_BYTES + samples.len() * 2); + out.extend_from_slice(&(samples.len() as u32).to_le_bytes()); + let Some(&(first_time, first_value)) = samples.first() else { + out.extend_from_slice(&[0; 16]); + return out; + }; + out.extend_from_slice(&first_time.to_le_bytes()); + out.extend_from_slice(&first_value.to_bits().to_le_bytes()); + let mut writer = BitWriter::default(); + let (mut time, mut delta, mut bits) = (first_time, 0i64, first_value.to_bits()); + let mut window: Option<(u32, u32)> = None; + for &(next_time, value) in &samples[1..] { + let next_delta = next_time.wrapping_sub(time); + let dod = next_delta.wrapping_sub(delta); + match dod { + 0 => writer.bit(false), + -64..=63 => { + writer.bits(0b10, 2); + writer.bits(dod as u64, 7); + } + -256..=255 => { + writer.bits(0b110, 3); + writer.bits(dod as u64, 9); + } + -2048..=2047 => { + writer.bits(0b1110, 4); + writer.bits(dod as u64, 12); + } + _ => { + writer.bits(0b1111, 4); + writer.bits(dod as u64, 64); + } + } + let x = value.to_bits() ^ bits; + if x == 0 { + writer.bit(false); + } else { + let lead = x.leading_zeros().min(31); + let trail = x.trailing_zeros(); + match window { + Some((l, t)) if lead >= l && trail >= t => { + writer.bits(0b10, 2); + writer.bits(x >> t, 64 - l - t); + } + _ => { + let width = 64 - lead - trail; + writer.bits(0b11, 2); + writer.bits(u64::from(lead), 5); + writer.bits(u64::from(width - 1), 6); + writer.bits(x >> trail, width); + window = Some((lead, trail)); + } + } + } + (time, delta, bits) = (next_time, next_delta, value.to_bits()); + } + out.extend_from_slice(&writer.bytes); + out +} + +/// The samples of a chunk [`encode`] wrote; `None` when it is damaged. +pub fn decode(chunk: &[u8]) -> Option> { + let count = u32::from_le_bytes(chunk.get(0..4)?.try_into().ok()?) as usize; + let mut samples = Vec::with_capacity(count); + if count == 0 { + return Some(samples); + } + let mut time = i64::from_le_bytes(chunk.get(4..12)?.try_into().ok()?); + let mut bits = u64::from_le_bytes(chunk.get(12..20)?.try_into().ok()?); + samples.push((time, f64::from_bits(bits))); + let mut reader = BitReader { + bytes: chunk.get(HEADER_BYTES..)?, + at: 0, + }; + let (mut delta, mut window) = (0i64, (0u32, 0u32)); + let signed = |value: u64, width: u32| ((value << (64 - width)) as i64) >> (64 - width); + for _ in 1..count { + let dod = if !reader.bit()? { + 0 + } else if !reader.bit()? { + signed(reader.bits(7)?, 7) + } else if !reader.bit()? { + signed(reader.bits(9)?, 9) + } else if !reader.bit()? { + signed(reader.bits(12)?, 12) + } else { + reader.bits(64)? as i64 + }; + delta = delta.wrapping_add(dod); + time = time.wrapping_add(delta); + if reader.bit()? { + if reader.bit()? { + let lead = reader.bits(5)? as u32; + let width = reader.bits(6)? as u32 + 1; + window = (lead, 64u32.checked_sub(lead + width)?); + } + let (lead, trail) = window; + bits ^= reader.bits(64 - lead - trail)? << trail; + } + samples.push((time, f64::from_bits(bits))); + } + Some(samples) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Any timestamps (regular, jittered, far apart, backwards) and any + /// value bits read back exactly; a counter at 1 s takes under a quarter + /// of its plain bytes. + #[test] + fn chunks_read_back_exactly() { + let counter: Vec<(i64, f64)> = (0..3600).map(|s| (s * 1000, (s * 3) as f64)).collect(); + let odd = vec![ + (5, f64::NAN), + (7, -0.0), + (1_000_000, f64::INFINITY), + (999_999, f64::from_bits(0x7ff8_0000_0000_0001)), + (i64::MIN / 2, 1e-300), + (i64::MAX / 2, f64::NEG_INFINITY), + (i64::MAX / 2 + 13, 0.1 + 0.2), + ]; + let jittered: Vec<(i64, f64)> = (0..500) + .map(|i| (i * 1000 + (i * 37 % 11) - 5, (i as f64).sin())) + .collect(); + for samples in [vec![], vec![(42, 1.5)], counter.clone(), odd, jittered] { + let read = decode(&encode(&samples)).unwrap(); + let bits = |s: &[(i64, f64)]| -> Vec<(i64, u64)> { + s.iter().map(|&(t, v)| (t, v.to_bits())).collect() + }; + assert_eq!(bits(&read), bits(&samples)); + } + // Below the 16 bytes a sample takes as a time and a value. + assert!( + encode(&counter).len() < 3600 * 4, + "{}", + encode(&counter).len() + ); + } +} From 60942cff4b434033ca320db8c21200047882856c Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:13:02 +0000 Subject: [PATCH 11/19] perf(storage): raw data keeps running sample and byte totals instead of walking every pane - RawData keeps its samples and bytes held, updated as panes are appended, compacted, compressed, made columnar again and evicted. The ingest coordinator reads them after every flush for the raw-data gauges; it no longer walks every stored pane and chunk each pass. - A compressed pane's bytes are taken once, when it is made. - A chunk's bytes no longer count the series identity column a read builds later: it is a read cache, and a chunk's bytes must be fixed when it is made for a running total. `asap_raw_data_bytes` is lower by those identity columns. - Test: the running totals equal a walk over every pane after appends in and out of order, late samples of sealed and compressed panes, sealing, compressing and evicting. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/storage/src/store.rs | 163 ++++++++++++++++++++++++++++-------- 1 file changed, 126 insertions(+), 37 deletions(-) diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 957091b80..79fa98480 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -130,14 +130,14 @@ impl Chunk { }) } + /// Bytes of its samples. The series identity column a read builds + /// later ([`Self::identities`]) is a read cache and not counted: a + /// chunk's bytes are fixed when it is made, so the raw data can keep + /// their running total. fn bytes(&self) -> usize { self.time.get_array_memory_size() + self.value.get_array_memory_size() + self.codes.get_array_memory_size() - + self - .identities - .get() - .map_or(0, |identities| identities.get_array_memory_size()) + self.series.len() * std::mem::size_of::<&Series>() } @@ -243,6 +243,7 @@ type Pane = Vec>; struct CompressedPane { series: Vec<(&'static Series, Vec)>, samples: usize, + bytes: usize, } impl CompressedPane { @@ -259,15 +260,21 @@ impl CompressedPane { .push((time, value)); samples += 1; } + let series: Vec<(&'static Series, Vec)> = by_series + .into_values() + .map(|(series, mut rows)| { + rows.sort_by_key(|row| row.0); + (series, crate::xor_chunk::encode(&rows)) + }) + .collect(); + let bytes = series + .iter() + .map(|(_, chunk)| chunk.capacity() + std::mem::size_of::<(&Series, Vec)>()) + .sum(); Self { - series: by_series - .into_values() - .map(|(series, mut rows)| { - rows.sort_by_key(|row| row.0); - (series, crate::xor_chunk::encode(&rows)) - }) - .collect(), + series, samples, + bytes, } } @@ -286,13 +293,6 @@ impl CompressedPane { rows.sort_by_key(|row| row.1); Chunk::new(rows.into_iter()).map(Arc::new) } - - fn bytes(&self) -> usize { - self.series - .iter() - .map(|(_, chunk)| chunk.capacity() + std::mem::size_of::<(&Series, Vec)>()) - .sum() - } } /// One metric's samples. @@ -315,6 +315,18 @@ struct MetricPanes { pub struct RawData { pane_width_ms: i64, by_metric: HashMap, + /// Samples held, kept as panes are added, compacted, compressed and + /// evicted, so reading it walks no pane. + samples: usize, + /// Bytes of the samples held, kept the same way. + bytes: usize, +} + +/// Samples and bytes of `pane`'s chunks. +fn pane_totals(pane: &Pane) -> (usize, usize) { + pane.iter().fold((0, 0), |(samples, bytes), chunk| { + (samples + chunk.len(), bytes + chunk.bytes()) + }) } impl RawData { @@ -331,6 +343,8 @@ impl RawData { .into_iter() .map(|metric| (metric.clone(), MetricPanes::default())) .collect(), + samples: 0, + bytes: 0, } } @@ -365,9 +379,11 @@ impl RawData { }; // A late sample of a compressed pane: the pane is columnar again. if let Some(compressed) = metric.compressed.remove(&pane_end) { - metric - .panes - .insert(pane_end, compressed.chunk().into_iter().collect()); + let pane: Pane = compressed.chunk().into_iter().collect(); + let (samples, bytes) = pane_totals(&pane); + self.samples = self.samples - compressed.samples + samples; + self.bytes = self.bytes - compressed.bytes + bytes; + metric.panes.insert(pane_end, pane); } let pane = metric.panes.entry(pane_end).or_default(); let in_order = rows @@ -378,7 +394,11 @@ impl RawData { .is_none_or(|last| last.time_bounds_ms.1 <= rows[0].timestamp_ms); if in_order { let chunk = Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))); - pane.extend(chunk.map(Arc::new)); + if let Some(chunk) = chunk { + self.samples += chunk.len(); + self.bytes += chunk.bytes(); + pane.push(Arc::new(chunk)); + } continue; } let mut all: Vec<(&'static Series, i64, f64)> = pane @@ -387,10 +407,14 @@ impl RawData { .chain(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))) .collect(); all.sort_by_key(|row| row.1); + let (samples, bytes) = pane_totals(pane); *pane = Chunk::new(all.into_iter()) .map(Arc::new) .into_iter() .collect(); + let (new_samples, new_bytes) = pane_totals(pane); + self.samples = self.samples - samples + new_samples; + self.bytes = self.bytes - bytes + new_bytes; } } @@ -401,8 +425,10 @@ impl RawData { for metric in self.by_metric.values_mut() { for (_, pane) in metric.panes.range_mut(..=watermark_ms) { if pane.len() > 1 { + let (_, bytes) = pane_totals(pane); let compacted = Chunk::new(pane.iter().flat_map(|chunk| chunk.rows())); *pane = compacted.map(Arc::new).into_iter().collect(); + self.bytes = self.bytes - bytes + pane_totals(pane).1; } } } @@ -412,10 +438,19 @@ impl RawData { /// returns them, and the panes ending at or before it are dropped. pub fn evict_through(&mut self, metric: &str, oldest_kept_ms: i64) { if let Some(metric) = self.by_metric.get_mut(metric) { - metric.panes = metric.panes.split_off(&oldest_kept_ms.saturating_add(1)); - metric.compressed = metric + let kept = metric.panes.split_off(&oldest_kept_ms.saturating_add(1)); + for pane in std::mem::replace(&mut metric.panes, kept).values() { + let (samples, bytes) = pane_totals(pane); + self.samples -= samples; + self.bytes -= bytes; + } + let kept = metric .compressed .split_off(&oldest_kept_ms.saturating_add(1)); + for pane in std::mem::replace(&mut metric.compressed, kept).values() { + self.samples -= pane.samples; + self.bytes -= pane.bytes; + } metric.evicted_through_ms = metric.evicted_through_ms.max(Some(oldest_kept_ms)); } } @@ -429,14 +464,19 @@ impl RawData { }; let newer = metric.panes.split_off(&through_ms.saturating_add(1)); for (end, pane) in std::mem::replace(&mut metric.panes, newer) { + let (samples, bytes) = pane_totals(&pane); + self.samples -= samples; + self.bytes -= bytes; if !pane.is_empty() { - metric - .compressed - .insert(end, Arc::new(CompressedPane::new(&pane))); + let compressed = CompressedPane::new(&pane); + self.samples += compressed.samples; + self.bytes += compressed.bytes; + metric.compressed.insert(end, Arc::new(compressed)); } } } + #[cfg(test)] fn chunks(&self) -> impl Iterator> { self.by_metric .values() @@ -452,16 +492,9 @@ impl RawData { .sum() } - fn compressed(&self) -> impl Iterator> { - self.by_metric - .values() - .flat_map(|metric| metric.compressed.values()) - } - /// Samples held, over every metric. pub fn len(&self) -> usize { - self.chunks().map(|chunk| chunk.len()).sum::() - + self.compressed().map(|pane| pane.samples).sum::() + self.samples } pub fn is_empty(&self) -> bool { @@ -470,8 +503,7 @@ impl RawData { /// Bytes of the samples held. pub fn bytes(&self) -> usize { - self.chunks().map(|chunk| chunk.bytes()).sum::() - + self.compressed().map(|pane| pane.bytes()).sum::() + self.bytes } /// `metric`'s samples in `time_range_ms` (`(start, end]`, every sample @@ -2163,6 +2195,63 @@ mod tests { assert_eq!(read(&compressed), read(&columnar)); } + /// The samples and bytes held, by walking every pane. + fn walked_totals(raw: &RawData) -> (usize, usize) { + let columnar = raw.chunks().fold((0, 0), |(samples, bytes), chunk| { + (samples + chunk.len(), bytes + chunk.bytes()) + }); + raw.by_metric + .values() + .flat_map(|metric| metric.compressed.values()) + .fold(columnar, |(samples, bytes), pane| { + (samples + pane.samples, bytes + pane.bytes) + }) + } + + /// The running sample and byte totals equal a walk over every pane + /// after each step of appends in and out of order, late samples of a + /// sealed and of a compressed pane, sealing, compressing and evicting. + #[test] + fn running_totals_equal_a_walk_over_the_panes() { + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + let check = |raw: &RawData, step: &str| { + assert_eq!((raw.len(), raw.bytes()), walked_totals(raw), "after {step}"); + }; + let late = |timestamp_ms: i64| RawSample { + timestamp_ms, + value: 7.0, + ..samples()[0][0].clone() + }; + for request in samples() { + raw.append(&request); + check(&raw, "an append"); + } + raw.seal_through(15_000); + check(&raw, "sealing"); + // In order within its sealed pane: a second chunk, then compacted. + raw.append(&[late(14_999)]); + check(&raw, "a late sample after a sealed pane's newest"); + // Older than its sealed pane's newest: the pane is sorted again. + raw.append(&[late(11_000)]); + check(&raw, "a late sample within a sealed pane"); + raw.seal_through(20_000); + check(&raw, "sealing again"); + raw.compress_through("m_store_test", 15_000); + check(&raw, "compressing"); + raw.append(&[late(7_350)]); + check(&raw, "a late sample of a compressed pane"); + raw.compress_through("m_store_test", 20_000); + check(&raw, "compressing again"); + raw.evict_through("m_store_test", 9_000); + check(&raw, "evicting compressed panes"); + raw.evict_through("m_store_test", 22_000); + check(&raw, "evicting columnar panes"); + assert!(!raw.is_empty()); + let emptied = raw.emptied(); + check(&emptied, "emptying"); + assert_eq!((emptied.len(), emptied.bytes()), (0, 0)); + } + #[test] fn evicts_whole_panes() { let schema = schema(); From a760725c5970e5b1e0852941936e0a277942d224 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:14:18 +0000 Subject: [PATCH 12/19] perf(storage): sealing and compressing visit only the panes not done yet - Each metric remembers how far its panes are sealed; a seal visits only the panes after that and the sealed panes a late sample gave another chunk since (kept in a set by the append). Since the shards get a maintenance message after every flush, the seal no longer walks every pane each pass. - Compressing returns at once when no columnar pane ends at or before its cutoff: compressed panes leave the columnar map, so only newly closed panes, or ones a late sample made columnar again, are left there. - Test: a late chunk in a sealed pane is compacted by the next seal; the running totals still equal a walk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/storage/src/store.rs | 68 +++++++++++++++++++++++++++++++++---- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 79fa98480..54717bcb5 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -306,6 +306,13 @@ struct MetricPanes { /// Samples at or before this are evicted: a read never returns them, /// though the oldest pane kept may still hold some. evicted_through_ms: Option, + /// Every pane ending at or before this is compacted + /// ([`RawData::seal_through`]), but those in `unsealed`: a seal starts + /// after it. + sealed_through_ms: Option, + /// Panes ending at or before `sealed_through_ms` that a late sample + /// gave another chunk: the next seal compacts them. + unsealed: BTreeSet, } /// The raw samples of each metric the plan scans, columnar, by pane: the @@ -322,6 +329,14 @@ pub struct RawData { bytes: usize, } +/// Compacts `pane` into one chunk; returns its bytes before and after. +fn compact(pane: &mut Pane) -> (usize, usize) { + let (_, bytes) = pane_totals(pane); + let compacted = Chunk::new(pane.iter().flat_map(|chunk| chunk.rows())); + *pane = compacted.map(Arc::new).into_iter().collect(); + (bytes, pane_totals(pane).1) +} + /// Samples and bytes of `pane`'s chunks. fn pane_totals(pane: &Pane) -> (usize, usize) { pane.iter().fold((0, 0), |(samples, bytes), chunk| { @@ -399,6 +414,9 @@ impl RawData { self.bytes += chunk.bytes(); pane.push(Arc::new(chunk)); } + if pane.len() > 1 && metric.sealed_through_ms.is_some_and(|s| pane_end <= s) { + metric.unsealed.insert(pane_end); + } continue; } let mut all: Vec<(&'static Series, i64, f64)> = pane @@ -420,17 +438,35 @@ impl RawData { /// Compacts each pane ending at or before `watermark_ms` into one chunk: /// no more samples are expected for it (a late one adds a chunk, which - /// the next call compacts). + /// the next call compacts). Only the panes after the last call's + /// watermark, and those late samples changed since, are visited. pub fn seal_through(&mut self, watermark_ms: i64) { for metric in self.by_metric.values_mut() { - for (_, pane) in metric.panes.range_mut(..=watermark_ms) { + let newer = metric.unsealed.split_off(&watermark_ms.saturating_add(1)); + let late = std::mem::replace(&mut metric.unsealed, newer); + let mut changed = |pane: &mut Pane| { if pane.len() > 1 { - let (_, bytes) = pane_totals(pane); - let compacted = Chunk::new(pane.iter().flat_map(|chunk| chunk.rows())); - *pane = compacted.map(Arc::new).into_iter().collect(); - self.bytes = self.bytes - bytes + pane_totals(pane).1; + let (before, after) = compact(pane); + self.bytes = self.bytes - before + after; } + }; + for end in late { + if let Some(pane) = metric.panes.get_mut(&end) { + changed(pane); + } + } + let start = match metric.sealed_through_ms { + Some(sealed) if sealed >= watermark_ms => continue, + Some(sealed) => Bound::Excluded(sealed), + None => Bound::Unbounded, + }; + for (_, pane) in metric + .panes + .range_mut((start, Bound::Included(watermark_ms))) + { + changed(pane); } + metric.sealed_through_ms = Some(watermark_ms); } } @@ -451,17 +487,27 @@ impl RawData { self.samples -= pane.samples; self.bytes -= pane.bytes; } + metric.unsealed = metric.unsealed.split_off(&oldest_kept_ms.saturating_add(1)); metric.evicted_through_ms = metric.evicted_through_ms.max(Some(oldest_kept_ms)); } } /// Compresses `metric`'s panes ending at or before `through_ms` /// ([`CompressedPane`]): only windows computed again from raw samples - /// read them, and reads decode them. + /// read them, and reads decode them. A compressed pane leaves the + /// columnar ones, so only the panes not compressed yet (newly closed, + /// or made columnar again by a late sample) are visited. pub fn compress_through(&mut self, metric: &str, through_ms: i64) { let Some(metric) = self.by_metric.get_mut(metric) else { return; }; + if metric + .panes + .first_key_value() + .is_none_or(|(&end, _)| end > through_ms) + { + return; + } let newer = metric.panes.split_off(&through_ms.saturating_add(1)); for (end, pane) in std::mem::replace(&mut metric.panes, newer) { let (samples, bytes) = pane_totals(&pane); @@ -2234,8 +2280,16 @@ mod tests { // Older than its sealed pane's newest: the pane is sorted again. raw.append(&[late(11_000)]); check(&raw, "a late sample within a sealed pane"); + raw.append(&[late(9_999)]); + check(&raw, "a late sample after another sealed pane's newest"); + assert_eq!(raw.by_metric["m_store_test"].panes[&10_000].len(), 2); raw.seal_through(20_000); check(&raw, "sealing again"); + // Sealing visits only the panes after its last watermark and the + // sealed ones late samples changed: every pane sealed is one chunk. + let panes = &raw.by_metric["m_store_test"].panes; + assert!(panes.range(..=20_000).all(|(_, pane)| pane.len() == 1)); + assert!(panes[&25_000].len() > 1); raw.compress_through("m_store_test", 15_000); check(&raw, "compressing"); raw.append(&[late(7_350)]); From fab39b2da5ff50cabe36cf9ae6bbdcd5a8e7a0a7 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:16:15 +0000 Subject: [PATCH 13/19] perf(storage): appended samples grouped by the interned metric; ahash for chunk building - The series interner keeps one name per metric, shared by its series, so two series' metrics are equal exactly when the pointers are (`Series::metric_key`). - RawData::append groups a request's samples by (metric pointer, pane), checking the last group first, instead of a BTreeMap keyed by the metric name that compared the names byte by byte per sample. The routing finds a sample's metric by pointer too. - Chunk::new maps series ids to codes with ahash instead of SipHash. - Test: series of one metric share its name; other metrics do not. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/ingestion.rs | 5 ++-- crates/storage/src/series_ids.rs | 43 ++++++++++++++++++++++++++++-- crates/storage/src/store.rs | 29 ++++++++++++++------ 3 files changed, 65 insertions(+), 12 deletions(-) diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 7e80d0f55..78fec707f 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -1001,14 +1001,15 @@ impl Routing { ..Routed::default() }; // Samples of one metric usually come together: the last metric is - // checked by pointer first. + // checked first. Metric names are interned, so they compare by + // pointer. let mut metrics: Vec> = Vec::new(); let mut last: Option = None; for sample in samples { let metric = &sample.labels.metric; let known = last .filter(|&i| Arc::ptr_eq(&metrics[i].metric, metric)) - .or_else(|| metrics.iter().position(|m| m.metric == *metric)); + .or_else(|| metrics.iter().position(|m| Arc::ptr_eq(&m.metric, metric))); let index = match known { Some(index) => index, None => { diff --git a/crates/storage/src/series_ids.rs b/crates/storage/src/series_ids.rs index af3e76fb0..cd53be137 100644 --- a/crates/storage/src/series_ids.rs +++ b/crates/storage/src/series_ids.rs @@ -23,7 +23,9 @@ use ahash::RandomState; pub struct Series { /// The series' id, dense from 0 in the order series are first seen. pub id: u32, - /// The `__name__` label (empty without one). + /// The `__name__` label (empty without one), interned: every series of + /// a metric shares this one, so two series' metrics are equal exactly + /// when the pointers are ([`Self::metric_key`]). pub metric: Arc, /// The canonical JSON of every label, `__name__` included: the series /// identity column of a raw-data read, computed once when interned. @@ -33,6 +35,12 @@ pub struct Series { } impl Series { + /// Its metric's identity: equal for two series exactly when their + /// metric names are, compared without reading the names. + pub fn metric_key(&self) -> usize { + Arc::as_ptr(&self.metric) as *const u8 as usize + } + /// The label set, shared: a query result row of this series holds it /// without copying. pub fn labels(&self) -> &Arc> { @@ -85,6 +93,8 @@ struct Interner { /// Series ids by identity text, for reading a query result's series /// back without parsing its JSON. by_identity: ahash::HashMap, u32>, + /// Every metric name, shared by its series. + metrics: ahash::HashSet>, series: Vec<&'static Series>, } @@ -151,10 +161,19 @@ pub fn intern_pairs, V: AsRef>(pairs: &[(N, V)]) -> &'static .map(|(n, v)| (n.to_string(), v.to_string())) .collect(); let id = u32::try_from(interner.series.len()).expect("fewer than 2^32 series"); + let name = labels.get("__name__").map_or("", String::as_str); + let metric = match interner.metrics.get(name) { + Some(metric) => metric.clone(), + None => { + let metric: Arc = name.into(); + interner.metrics.insert(metric.clone()); + metric + } + }; // Never freed: the interner keeps every series. let series: &'static Series = Box::leak(Box::new(Series { id, - metric: labels.get("__name__").map_or("", String::as_str).into(), + metric, identity: serde_json::to_string(&labels) .expect("labels serialize") .into(), @@ -207,3 +226,23 @@ pub(crate) fn labels_of_identity(identity: &str) -> Option result_labels(identity).ok(), } } + +#[cfg(test)] +mod tests { + use super::*; + + /// Series of one metric share its interned name, so metrics compare by + /// pointer; series of different metrics do not. + #[test] + fn series_of_one_metric_share_its_name() { + let a = intern_pairs(&[("__name__", "m_interned"), ("i", "1")]); + let b = intern_pairs(&[("i", "2"), ("__name__", "m_interned")]); + let other = intern_pairs(&[("__name__", "m_interned_other"), ("i", "1")]); + let unnamed = intern_pairs(&[("i", "1")]); + assert!(Arc::ptr_eq(&a.metric, &b.metric)); + assert_eq!(a.metric_key(), b.metric_key()); + assert_ne!(a.metric_key(), other.metric_key()); + assert_ne!(a.metric_key(), unnamed.metric_key()); + assert_eq!(&*unnamed.metric, ""); + } +} diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 54717bcb5..85dbd80b9 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -85,7 +85,7 @@ struct Chunk { impl Chunk { /// `rows` (series, time, value), in order; `None` when there is none. fn new(rows: impl Iterator) -> Option { - let mut code_of: HashMap = HashMap::new(); + let mut code_of: ahash::HashMap = ahash::HashMap::default(); let mut series: Vec<&'static Series> = Vec::new(); let (mut times, mut values, mut codes) = (Vec::new(), Vec::new(), Vec::new()); for (row_series, time, value) in rows { @@ -380,15 +380,28 @@ impl RawData { /// late sample), make the pane one chunk sorted by time, equal times in /// arrival order. pub fn append(&mut self, samples: &[RawSample]) { - let mut by_pane: BTreeMap<(&str, i64), Vec<&RawSample>> = BTreeMap::new(); + // Grouped by the interned metric ([`Series::metric_key`]), not by + // comparing names; a request's samples mostly run in one group. + type Group<'a> = ((usize, i64), &'a str, Vec<&'a RawSample>); + let mut groups: Vec = Vec::new(); + let mut group_of: ahash::HashMap<(usize, i64), usize> = ahash::HashMap::default(); + let mut last: Option = None; for sample in samples { - let pane_end = window_end(sample.timestamp_ms, self.pane_width_ms); - by_pane - .entry((&sample.labels.metric, pane_end)) - .or_default() - .push(sample); + let key = ( + sample.labels.metric_key(), + window_end(sample.timestamp_ms, self.pane_width_ms), + ); + let index = match last { + Some(index) if groups[index].0 == key => index, + _ => *group_of.entry(key).or_insert_with(|| { + groups.push((key, &sample.labels.metric, Vec::new())); + groups.len() - 1 + }), + }; + groups[index].2.push(sample); + last = Some(index); } - for ((metric, pane_end), rows) in by_pane { + for ((_, pane_end), metric, rows) in groups { let Some(metric) = self.by_metric.get_mut(metric) else { continue; }; From 5a60272529a066eac125ae55cb05c8873906511a Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:28:27 +0000 Subject: [PATCH 14/19] perf(storage): counter raw kept for recompute compressed in multi-pane blocks, off the ingest shards - A compressed block takes consecutive closed panes of a metric, enough for 120 samples per series (COMPRESSED_SAMPLES_PER_SERIES), and keeps one XOR chunk per series over all of them: at 1 sample/s a 15 s pane gave each series a chunk of 15 samples, whose header and slack dominated. The newest panes that do not fill a block yet stay columnar. - A late sample within a block's span makes the block's panes columnar again (one chunk per pane), so a window computed again reads exactly the samples it did; the panes are compressed again later. A read decodes the blocks overlapping its range and keeps the rows in it; an eviction drops the blocks ending at or before the cutoff. - Compression runs on one thread of its own (`raw-compress`), not on the ingest shards: a shard's maintenance takes the panes to compress (RawData::panes_to_compress) and sends them; the shard installs the encoded blocks at its next maintenance (RawData::install_compressed), each only if its panes are as they were taken, else the panes are taken again later. One metric has at most one batch in flight. - RawData::compress_through still compresses here and now (tests). - Test: blocks of several panes read back as the columnar panes over ranges inside, across and outside blocks, after late samples in a block's first, middle and last pane and on a block boundary, after compressing again, after a late sample while a block was encoded, and after evicting part of a block; running totals and pane counts equal a walk. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/engine.rs | 37 ++- crates/precompute/src/ingestion.rs | 20 +- crates/storage/src/store.rs | 426 +++++++++++++++++++++++++---- 3 files changed, 418 insertions(+), 65 deletions(-) diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 7dd06c77a..fc059b533 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -38,7 +38,8 @@ use storage::memory_budget::serve_view_cache; use storage::persist::ViewFiles; use storage::persist_pool::{PersistBacklog, PersistOptions, PersistPool}; use storage::store::{ - PublishedStore, RawData, RawSample, RawShards, SeriesPartition, ViewStore, ViewTier, WindowSlot, + CompressedPanes, PanesToCompress, PublishedStore, RawData, RawSample, RawShards, + SeriesPartition, ViewStore, ViewTier, WindowSlot, }; use tokio::sync::oneshot; @@ -483,9 +484,17 @@ impl InstalledPrecompute { let (commands, command_receiver) = channel(); let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); + // Raw panes kept only for windows computed again are compressed on + // one thread of their own, off the ingest shards: each shard sends + // the panes to compress and installs what comes back. + let (to_compress, compress_inbox) = channel::<(usize, Vec)>(); + let mut compressed_outboxes = Vec::new(); let mut shards = Vec::new(); for (index, raw_data) in raw_shards.iter().enumerate() { let (shard, messages) = channel(); + let (compressed_outbox, compressed) = channel::(); + compressed_outboxes.push(compressed_outbox); + let to_compress = to_compress.clone(); let (coordinator, raw_data) = (commands.clone(), raw_data.clone()); let shard_shared = shared.clone(); let guard = RunningGuard(running.clone()); @@ -522,10 +531,22 @@ impl InstalledPrecompute { &shard_shared, delay, push, + (to_compress, compressed), ); })?; shards.push(shard); } + drop(to_compress); + // Ends when every shard has. + std::thread::Builder::new() + .name("raw-compress".into()) + .spawn(move || { + for (shard, panes) in compress_inbox { + for panes in panes { + let _ = compressed_outboxes[shard].send(panes.encode()); + } + } + })?; let ingest_guard = RunningGuard(running.clone()); let ingest_shared = shared.clone(); let coordinator_shards = shards.clone(); @@ -790,6 +811,7 @@ fn flush(shards: &[Sender], shared: &Shared) -> ClockReading { /// An ingest shard: routes and appends the samples of its series to its /// own raw data, seals and evicts it when told, and reports its state to /// the coordinator after each message. +#[allow(clippy::too_many_arguments)] fn serve_shard( index: usize, mut raw_data: Arc, @@ -798,6 +820,10 @@ fn serve_shard( shared: &Shared, delay: std::time::Duration, mut push: Option, + (to_compress, compressed): ( + Sender<(usize, Vec)>, + Receiver, + ), ) { let mut newest_ms: Option = None; // A message taken while draining a batch, to run next. @@ -829,7 +855,14 @@ fn serve_shard( routing, watermark_ms, } => { - routing.maintain(Arc::make_mut(&mut raw_data), watermark_ms); + let raw = Arc::make_mut(&mut raw_data); + for panes in compressed.try_iter() { + raw.install_compressed(panes); + } + let panes = routing.maintain(raw, watermark_ms); + if !panes.is_empty() { + let _ = to_compress.send((index, panes)); + } awaiting_routing = false; if held.is_empty() { continue; diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 78fec707f..6d9f4a13a 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -49,7 +49,8 @@ use asap_executor::runtime::{Limits, RunContext, Scope}; use asap_executor::values::{Batch, SchemaRef}; use futures::executor::block_on; use storage::store::{ - millis, window_end, RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, + millis, window_end, PanesToCompress, RawData, RawSample, RawShards, RunStore, SeriesPartition, + ViewStore, }; use common::MAX_TIME_MS; @@ -1092,19 +1093,26 @@ impl Routing { /// Seals and evicts `raw_data` as the ingestion stands: compacts the /// panes the watermark has passed and drops the panes at or before - /// each metric's cutoff. - pub(crate) fn maintain(&self, raw_data: &mut RawData, watermark_ms: Option) { + /// each metric's cutoff. Returns the panes kept only for windows + /// computed again, to compress off the ingest thread + /// ([`RawData::install_compressed`]). + pub(crate) fn maintain( + &self, + raw_data: &mut RawData, + watermark_ms: Option, + ) -> Vec { if let Some(watermark_ms) = watermark_ms { raw_data.seal_through(watermark_ms); } - for (metric, through) in &self.compress_through { - raw_data.compress_through(metric, *through); - } for (metric, cutoff) in &self.cutoffs { if let Some(cutoff) = cutoff { raw_data.evict_through(metric, *cutoff); } } + self.compress_through + .iter() + .filter_map(|(metric, through)| raw_data.panes_to_compress(metric, *through)) + .collect() } } diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 85dbd80b9..5d84b2ea2 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -236,23 +236,37 @@ impl Chunk { /// The samples of one pane `(end - width, end]` of a metric, as chunks. type Pane = Vec>; -/// A closed pane's samples kept only for windows computed again from raw -/// samples (late samples of an order-sensitive view): one XOR chunk per -/// series ([`crate::xor_chunk`]), decoded when read. +/// How many samples of each series a compressed block takes at least: its +/// panes are consecutive closed panes, enough of them for this many samples +/// per series (an XOR chunk of a few samples costs its header and slack per +/// sample). +pub const COMPRESSED_SAMPLES_PER_SERIES: usize = 120; + +/// Consecutive closed panes' samples kept only for windows computed again +/// from raw samples (late samples of an order-sensitive view): one XOR chunk +/// per series over all its panes ([`crate::xor_chunk`]), decoded when read. +/// No columnar pane ends within its span (its first to its last pane end). #[derive(Debug)] -struct CompressedPane { +struct CompressedBlock { + /// Its panes' ends, oldest first. + pane_ends: Vec, series: Vec<(&'static Series, Vec)>, samples: usize, bytes: usize, } -impl CompressedPane { - /// `pane`'s rows, per series in time order. - fn new(pane: &Pane) -> Self { +impl CompressedBlock { + /// The rows of `panes` (consecutive, oldest first), per series in time + /// order. + fn new(panes: &[(i64, Pane)]) -> Self { type SeriesSamples = (&'static Series, Vec<(i64, f64)>); - let mut by_series: BTreeMap = BTreeMap::new(); + let mut by_series: ahash::HashMap = ahash::HashMap::default(); let mut samples = 0; - for (series, time, value) in pane.iter().flat_map(|chunk| chunk.rows()) { + for (series, time, value) in panes + .iter() + .flat_map(|(_, pane)| pane) + .flat_map(|chunk| chunk.rows()) + { by_series .entry(series.id) .or_insert_with(|| (series, Vec::new())) @@ -260,26 +274,35 @@ impl CompressedPane { .push((time, value)); samples += 1; } + let mut by_series: Vec = by_series.into_values().collect(); + by_series.sort_unstable_by_key(|(series, _)| series.id); let series: Vec<(&'static Series, Vec)> = by_series - .into_values() + .into_iter() .map(|(series, mut rows)| { rows.sort_by_key(|row| row.0); (series, crate::xor_chunk::encode(&rows)) }) .collect(); + let pane_ends: Vec = panes.iter().map(|(end, _)| *end).collect(); let bytes = series .iter() .map(|(_, chunk)| chunk.capacity() + std::mem::size_of::<(&Series, Vec)>()) - .sum(); + .sum::() + + pane_ends.capacity() * std::mem::size_of::(); Self { + pane_ends, series, samples, bytes, } } - /// Its rows as one chunk in time order (equal times by series). - fn chunk(&self) -> Option> { + fn first_end(&self) -> i64 { + self.pane_ends[0] + } + + /// Its rows in time order (equal times by series). + fn rows(&self) -> Vec<(&'static Series, i64, f64)> { let mut rows: Vec<(&'static Series, i64, f64)> = self .series .iter() @@ -291,8 +314,59 @@ impl CompressedPane { }) .collect(); rows.sort_by_key(|row| row.1); - Chunk::new(rows.into_iter()).map(Arc::new) + rows } + + /// Its rows as one chunk in time order. + fn chunk(&self) -> Option> { + Chunk::new(self.rows().into_iter()).map(Arc::new) + } + + /// Its panes, columnar again: one chunk each, in time order. + fn panes(&self, pane_width_ms: i64) -> Vec<(i64, Pane)> { + let mut by_pane: BTreeMap> = BTreeMap::new(); + for row in self.rows() { + by_pane + .entry(window_end(row.1, pane_width_ms)) + .or_default() + .push(row); + } + by_pane + .into_iter() + .filter_map(|(end, rows)| Some((end, vec![Arc::new(Chunk::new(rows.into_iter())?)]))) + .collect() + } +} + +/// A metric's closed panes to compress off the ingest thread +/// ([`RawData::panes_to_compress`]): [`Self::encode`] them anywhere, then +/// [`RawData::install_compressed`] the result into the raw data they came +/// from. +#[derive(Debug)] +pub struct PanesToCompress { + metric: String, + /// Each block's panes, as they were taken. + blocks: Vec>, +} + +impl PanesToCompress { + pub fn encode(self) -> CompressedPanes { + CompressedPanes { + metric: self.metric, + blocks: self + .blocks + .into_iter() + .map(|panes| (CompressedBlock::new(&panes), panes)) + .collect(), + } + } +} + +/// Encoded [`PanesToCompress`], each block with the panes it was made from. +#[derive(Debug)] +pub struct CompressedPanes { + metric: String, + blocks: Vec<(CompressedBlock, Vec<(i64, Pane)>)>, } /// One metric's samples. @@ -300,9 +374,15 @@ impl CompressedPane { struct MetricPanes { /// Panes by end. panes: BTreeMap, - /// Closed panes kept compressed ([`RawData::compress_through`]), by end; - /// never also in `panes`. - compressed: BTreeMap>, + /// Closed panes kept compressed ([`RawData::compress_through`]), as + /// blocks by their last pane end; no columnar pane ends within a + /// block's span. + compressed: BTreeMap>, + /// Panes in `compressed`. + compressed_panes: usize, + /// Some of its panes are being compressed ([`PanesToCompress`]): no + /// more are taken until they are installed. + compressing: bool, /// Samples at or before this are evicted: a read never returns them, /// though the oldest pane kept may still hold some. evicted_through_ms: Option, @@ -405,13 +485,24 @@ impl RawData { let Some(metric) = self.by_metric.get_mut(metric) else { continue; }; - // A late sample of a compressed pane: the pane is columnar again. - if let Some(compressed) = metric.compressed.remove(&pane_end) { - let pane: Pane = compressed.chunk().into_iter().collect(); - let (samples, bytes) = pane_totals(&pane); - self.samples = self.samples - compressed.samples + samples; - self.bytes = self.bytes - compressed.bytes + bytes; - metric.panes.insert(pane_end, pane); + // A late sample within a compressed block: its panes are + // columnar again. + let block = metric + .compressed + .range(pane_end..) + .next() + .filter(|(_, block)| block.first_end() <= pane_end) + .map(|(&last, _)| last); + if let Some(block) = block.and_then(|last| metric.compressed.remove(&last)) { + self.samples -= block.samples; + self.bytes -= block.bytes; + metric.compressed_panes -= block.pane_ends.len(); + for (end, pane) in block.panes(self.pane_width_ms) { + let (samples, bytes) = pane_totals(&pane); + self.samples += samples; + self.bytes += bytes; + metric.panes.insert(end, pane); + } } let pane = metric.panes.entry(pane_end).or_default(); let in_order = rows @@ -496,43 +587,111 @@ impl RawData { let kept = metric .compressed .split_off(&oldest_kept_ms.saturating_add(1)); - for pane in std::mem::replace(&mut metric.compressed, kept).values() { - self.samples -= pane.samples; - self.bytes -= pane.bytes; + for block in std::mem::replace(&mut metric.compressed, kept).values() { + self.samples -= block.samples; + self.bytes -= block.bytes; + metric.compressed_panes -= block.pane_ends.len(); } metric.unsealed = metric.unsealed.split_off(&oldest_kept_ms.saturating_add(1)); metric.evicted_through_ms = metric.evicted_through_ms.max(Some(oldest_kept_ms)); } } - /// Compresses `metric`'s panes ending at or before `through_ms` - /// ([`CompressedPane`]): only windows computed again from raw samples - /// read them, and reads decode them. A compressed pane leaves the - /// columnar ones, so only the panes not compressed yet (newly closed, - /// or made columnar again by a late sample) are visited. + /// Compresses `metric`'s panes ending at or before `through_ms`, here + /// and now: [`Self::panes_to_compress`], encoded and installed. pub fn compress_through(&mut self, metric: &str, through_ms: i64) { - let Some(metric) = self.by_metric.get_mut(metric) else { - return; - }; - if metric - .panes - .first_key_value() - .is_none_or(|(&end, _)| end > through_ms) + if let Some(panes) = self.panes_to_compress(metric, through_ms) { + self.install_compressed(panes.encode()); + } + } + + /// `metric`'s columnar panes ending at or before `through_ms`, in + /// blocks of consecutive panes of [`COMPRESSED_SAMPLES_PER_SERIES`] + /// samples per series at least ([`CompressedBlock`]): only windows + /// computed again from raw samples read them, and reads decode them. + /// The newest panes that do not fill a block yet stay columnar. + /// `None` when there is no block, or while the last ones taken are not + /// installed. Compressed panes leave the columnar ones, so only panes + /// not compressed yet (newly closed, or made columnar again by a late + /// sample) are visited. + pub fn panes_to_compress(&mut self, metric: &str, through_ms: i64) -> Option { + self.panes_to_compress_in_blocks_of(metric, through_ms, COMPRESSED_SAMPLES_PER_SERIES) + } + + fn panes_to_compress_in_blocks_of( + &mut self, + metric: &str, + through_ms: i64, + samples_per_series: usize, + ) -> Option { + let name = metric; + let metric = self.by_metric.get_mut(metric)?; + if metric.compressing + || metric + .panes + .first_key_value() + .is_none_or(|(&end, _)| end > through_ms) { - return; + return None; } - let newer = metric.panes.split_off(&through_ms.saturating_add(1)); - for (end, pane) in std::mem::replace(&mut metric.panes, newer) { - let (samples, bytes) = pane_totals(&pane); - self.samples -= samples; - self.bytes -= bytes; - if !pane.is_empty() { - let compressed = CompressedPane::new(&pane); - self.samples += compressed.samples; - self.bytes += compressed.bytes; - metric.compressed.insert(end, Arc::new(compressed)); + let mut blocks = Vec::new(); + let mut block: Vec<(i64, Pane)> = Vec::new(); + let (mut samples, mut needed) = (0, 0); + for (&end, pane) in metric.panes.range(..=through_ms) { + if block.is_empty() { + let series = pane.iter().map(|chunk| chunk.series.len()).max(); + needed = samples_per_series * series.unwrap_or(1); + } + samples += pane_totals(pane).0; + block.push((end, pane.clone())); + if samples >= needed { + blocks.push(std::mem::take(&mut block)); + samples = 0; } } + if blocks.is_empty() { + return None; + } + metric.compressing = true; + Some(PanesToCompress { + metric: name.to_string(), + blocks, + }) + } + + /// Installs compressed panes ([`Self::panes_to_compress`]): each block + /// whose panes are still as they were taken, with no other columnar + /// pane within its span, replaces them; a block whose panes a late + /// sample or an eviction changed since is dropped, and its panes are + /// taken again later. + pub fn install_compressed(&mut self, compressed: CompressedPanes) { + let Some(metric) = self.by_metric.get_mut(&compressed.metric) else { + return; + }; + metric.compressing = false; + for (block, sources) in compressed.blocks { + let span = block.first_end()..=*block.pane_ends.last().expect("a block has panes"); + let unchanged = metric.panes.range(span.clone()).count() == sources.len() + && sources.iter().all(|(end, taken)| { + metric.panes.get(end).is_some_and(|pane| { + pane.len() == taken.len() + && pane.iter().zip(taken).all(|(a, b)| Arc::ptr_eq(a, b)) + }) + }); + if !unchanged { + continue; + } + for (end, _) in &sources { + let pane = metric.panes.remove(end).expect("checked above"); + let (samples, bytes) = pane_totals(&pane); + self.samples -= samples; + self.bytes -= bytes; + } + self.samples += block.samples; + self.bytes += block.bytes; + metric.compressed_panes += block.pane_ends.len(); + metric.compressed.insert(*span.end(), Arc::new(block)); + } } #[cfg(test)] @@ -547,7 +706,7 @@ impl RawData { pub fn panes(&self) -> usize { self.by_metric .values() - .map(|m| m.panes.len() + m.compressed.len()) + .map(|m| m.panes.len() + m.compressed_panes) .sum() } @@ -599,11 +758,14 @@ impl RawData { Bound::Excluded(start), Bound::Excluded(end.saturating_add(self.pane_width_ms)), ); - // Compressed panes are decoded for this read only. + // Compressed blocks overlapping the range are decoded for this read + // only: those whose last pane is after `start` and whose first is + // before `end + w`. let decoded: Vec> = metric_data .compressed - .range(range) - .filter_map(|(_, pane)| pane.chunk()) + .range((Bound::Excluded(start), Bound::Unbounded)) + .take_while(|(_, block)| block.first_end() < end.saturating_add(self.pane_width_ms)) + .filter_map(|(_, block)| block.chunk()) .collect(); let mut batches = Vec::new(); let stored_chunks = metric_data.panes.range(range).flat_map(|(_, pane)| pane); @@ -2239,7 +2401,8 @@ mod tests { columnar.append(&request); } let mut compressed = columnar.clone(); - compressed.compress_through("m_store_test", 20_000); + // A block per pane. + compress_in_blocks_of(&mut compressed, 20_000, 1); let read = |raw: &RawData| sorted(read_rows(raw, &schema, Some((0, 30_000)), None)); assert_eq!(read(&compressed), read(&columnar)); assert!(compressed.bytes() < columnar.bytes()); @@ -2254,6 +2417,155 @@ mod tests { assert_eq!(read(&compressed), read(&columnar)); } + /// Compresses the test metric's panes through `through_ms`, here and + /// now, in blocks of `samples_per_series`. + fn compress_in_blocks_of(raw: &mut RawData, through_ms: i64, samples_per_series: usize) { + if let Some(panes) = + raw.panes_to_compress_in_blocks_of("m_store_test", through_ms, samples_per_series) + { + raw.install_compressed(panes.encode()); + } + } + + /// The samples and panes held, by walking every pane. + fn walked_panes(raw: &RawData) -> usize { + raw.by_metric + .values() + .map(|metric| { + metric.panes.len() + + metric + .compressed + .values() + .map(|block| block.pane_ends.len()) + .sum::() + }) + .sum() + } + + /// Panes compressed several to a block read back as the columnar ones, + /// row for row, over ranges inside, across and outside blocks: after + /// compressing, after late samples in a block's first, middle and last + /// pane, after compressing + /// again, and after evicting part of a block. A block taken off the + /// thread is installed only if a late sample changed none of its panes. + #[test] + fn multi_pane_blocks_read_as_the_columnar_ones() { + let schema = schema(); + let mut columnar = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in samples() { + columnar.append(&request); + } + columnar.seal_through(30_000); + let mut compressed = columnar.clone(); + let ranges = [ + None, + Some((0, 30_000)), + Some((4_000, 12_000)), + Some((9_999, 10_001)), + Some((10_000, 20_000)), + Some((14_500, 26_000)), + ]; + let same = |columnar: &RawData, compressed: &RawData, step: &str| { + for range in ranges { + let read = |raw: &RawData| sorted(read_rows(raw, &schema, range, None)); + assert_eq!(read(compressed), read(columnar), "{step}, range {range:?}"); + } + assert_eq!( + (compressed.len(), compressed.bytes(), compressed.panes()), + { + let (samples, bytes) = walked_totals(compressed); + (samples, bytes, walked_panes(compressed)) + }, + "{step}" + ); + assert_eq!(compressed.len(), columnar.len(), "{step}"); + assert_eq!(compressed.panes(), columnar.panes(), "{step}"); + }; + // About 7 samples per series per pane: two panes to a block. + compress_in_blocks_of(&mut compressed, 25_000, 14); + let blocks = &compressed.by_metric["m_store_test"].compressed; + assert!(blocks.len() >= 2); + assert!(blocks.values().all(|block| block.pane_ends.len() == 2)); + assert!(compressed.bytes() < columnar.bytes()); + same(&columnar, &compressed, "compressed"); + let late = |timestamp_ms: i64, value: f64| RawSample { + timestamp_ms, + value, + ..samples()[1][2].clone() + }; + let firsts: Vec = blocks.values().map(|block| block.first_end()).collect(); + let lasts: Vec = blocks.keys().copied().collect(); + for (step, sample) in [ + ( + "a late sample in a block's first pane", + late(firsts[0] - 1, 1.5), + ), + ( + "a late sample in a block's last pane", + late(lasts[1] - 4_000, 2.5), + ), + ("a late sample at a block's boundary", late(lasts[0], 3.5)), + ( + "another late sample in a block", + late(firsts[1] - 2_500, 4.5), + ), + ] { + for raw in [&mut columnar, &mut compressed] { + raw.append(std::slice::from_ref(&sample)); + raw.seal_through(30_000); + } + same(&columnar, &compressed, step); + compress_in_blocks_of(&mut compressed, 25_000, 14); + same(&columnar, &compressed, &format!("{step}, compressed again")); + } + // Taken off the thread, then a late sample: that block stays + // columnar; the next take compresses it. + let job = compressed + .panes_to_compress_in_blocks_of("m_store_test", 30_000, 7) + .expect("panes to compress"); + assert!(compressed + .panes_to_compress_in_blocks_of("m_store_test", 30_000, 7) + .is_none()); + let sample = late(26_000, 5.5); + for raw in [&mut columnar, &mut compressed] { + raw.append(std::slice::from_ref(&sample)); + } + compressed.install_compressed(job.encode()); + same( + &columnar, + &compressed, + "a block changed while it was encoded", + ); + assert!(compressed.by_metric["m_store_test"] + .panes + .contains_key(&30_000)); + compressed.seal_through(30_000); + columnar.seal_through(30_000); + compress_in_blocks_of(&mut compressed, 30_000, 7); + assert!(!compressed.by_metric["m_store_test"] + .panes + .contains_key(&30_000)); + same(&columnar, &compressed, "compressed after the change"); + // Evicting through the middle of a block keeps the block; reads + // return no evicted sample. + let cut = firsts[1]; + for raw in [&mut columnar, &mut compressed] { + raw.evict_through("m_store_test", cut); + } + for range in [None, Some((cut, 30_000))] { + let read = |raw: &RawData| sorted(read_rows(raw, &schema, range, None)); + assert_eq!( + read(&compressed), + read(&columnar), + "evicted, range {range:?}" + ); + } + assert_eq!( + walked_totals(&compressed), + (compressed.len(), compressed.bytes()) + ); + } + /// The samples and bytes held, by walking every pane. fn walked_totals(raw: &RawData) -> (usize, usize) { let columnar = raw.chunks().fold((0, 0), |(samples, bytes), chunk| { @@ -2303,11 +2615,11 @@ mod tests { let panes = &raw.by_metric["m_store_test"].panes; assert!(panes.range(..=20_000).all(|(_, pane)| pane.len() == 1)); assert!(panes[&25_000].len() > 1); - raw.compress_through("m_store_test", 15_000); + compress_in_blocks_of(&mut raw, 15_000, 14); check(&raw, "compressing"); raw.append(&[late(7_350)]); check(&raw, "a late sample of a compressed pane"); - raw.compress_through("m_store_test", 20_000); + compress_in_blocks_of(&mut raw, 20_000, 14); check(&raw, "compressing again"); raw.evict_through("m_store_test", 9_000); check(&raw, "evicting compressed panes"); From 2d75ed9c65bbec7ca608676a921944487561ca2a Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 05:17:48 +0000 Subject: [PATCH 15/19] test(storage): out-of-order requests add chunks and read as one sorted pane (failing first) Concurrent senders deliver requests out of time order. Today each such request rebuilds its whole pane (every row so far, sorted again), so a window-mode raw store does work in the pane's size per request. The test swaps each pair of requests, checks no pane is rebuilt, and that reads return exactly the rows, in the order, of one pane sorted by time (equal times in arrival order), before and after sealing and after a late request into sealed panes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/storage/src/store.rs | 82 +++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 5d84b2ea2..2221a3358 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -2417,6 +2417,88 @@ mod tests { assert_eq!(read(&compressed), read(&columnar)); } + /// Requests out of time order (concurrent senders) each add a chunk of + /// their own rather than rebuilding the pane: reads return exactly the + /// rows, in the order, one pane sorted by time (equal times in arrival + /// order) returns, before and after sealing, and after a late request + /// into a sealed pane; sealing leaves one chunk per pane. + #[test] + fn out_of_order_requests_read_as_one_sorted_pane() { + let schema = schema(); + let mut requests = samples(); + // Each pair of requests arrives swapped. + for pair in requests.chunks_mut(2) { + pair.reverse(); + } + let late = vec![ + RawSample { + timestamp_ms: 9_100, + value: 42.0, + ..requests[0][0].clone() + }, + RawSample { + timestamp_ms: 6_000, + value: 43.0, + ..requests[0][1].clone() + }, + ]; + let mut raw = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in &requests { + let before: Vec> = raw.chunks().cloned().collect(); + raw.append(request); + // No pane is rebuilt: every chunk held before is still held. + let after: Vec> = raw.chunks().cloned().collect(); + assert!(before + .iter() + .all(|chunk| after.iter().any(|kept| Arc::ptr_eq(chunk, kept)))); + } + // What the pane held when each request rebuilt it: every row so + // far, stably sorted by time. + let sorted_pane = |requests: &[Vec]| { + let mut all: Vec = requests.iter().flatten().cloned().collect(); + all.sort_by_key(|sample| sample.timestamp_ms); + let mut reference = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + reference.append(&all); + reference + }; + let ranges = [ + None, + Some((5_000, 10_000)), + Some((2_100, 27_001)), + Some((25_000, 40_000)), + ]; + let same = |raw: &RawData, reference: &RawData, step: &str| { + for range in ranges { + let in_order = |raw: &RawData| -> Vec { + read_rows(raw, &schema, range, None) + .iter() + .map(|row| format!("{row:?}")) + .collect() + }; + assert_eq!( + in_order(raw), + in_order(reference), + "{step}, range {range:?}" + ); + } + assert_eq!((raw.len(), raw.bytes()), walked_totals(raw), "{step}"); + }; + same(&raw, &sorted_pane(&requests), "unsealed"); + raw.seal_through(20_000); + let panes = &raw.by_metric["m_store_test"].panes; + assert!(panes.range(..=20_000).all(|(_, pane)| pane.len() == 1)); + same(&raw, &sorted_pane(&requests), "sealed"); + raw.append(&late); + requests.push(late); + same( + &raw, + &sorted_pane(&requests), + "a late request into sealed panes", + ); + raw.seal_through(20_000); + same(&raw, &sorted_pane(&requests), "sealed again"); + } + /// Compresses the test metric's panes through `through_ms`, here and /// now, in blocks of `samples_per_series`. fn compress_in_blocks_of(raw: &mut RawData, through_ms: i64, samples_per_series: usize) { From 0867ce644d62c9f1aa01533533725796eb006edb Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 05:19:40 +0000 Subject: [PATCH 16/19] perf(storage): a request older than its pane's newest sample adds a chunk; the pane is merged in time order when read or sealed - Concurrent senders (an OTLP exporter, a feeder with several requests in flight) deliver requests out of time order. Each such request used to rebuild its whole pane: every row so far collected, sorted and made one chunk again, work in the pane's size per request. With the raw samples kept (window mode), this was most of the ingest shards' CPU over OTLP. - Now the request's rows (sorted among themselves if needed) become a chunk of their own, and the pane is marked unsorted. The first read of an unsorted pane merges its chunks in time order (equal times in arrival order, as the rebuild did) and keeps the merged chunk for later reads and clones; an append replaces it. Sealing compacts the pane in time order, reusing that merged chunk when a read built it. Panes not sealed in time order yet are not compressed. - Reads return the same rows in the same order as before. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/storage/src/store.rs | 141 +++++++++++++++++++++++++----------- 1 file changed, 97 insertions(+), 44 deletions(-) diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 2221a3358..961f7e266 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -393,6 +393,12 @@ struct MetricPanes { /// Panes ending at or before `sealed_through_ms` that a late sample /// gave another chunk: the next seal compacts them. unsealed: BTreeSet, + /// Panes whose chunks are not in time order with each other (a + /// request older than the pane's newest sample added one), each with + /// its chunks merged in time order, built by the first read of the + /// pane as it stands and shared by later reads (and by clones); an + /// append replaces it. Sealing compacts such a pane in time order. + unsorted: BTreeMap>>>>, } /// The raw samples of each metric the plan scans, columnar, by pane: the @@ -409,14 +415,27 @@ pub struct RawData { bytes: usize, } -/// Compacts `pane` into one chunk; returns its bytes before and after. -fn compact(pane: &mut Pane) -> (usize, usize) { +/// Compacts `pane` into one chunk, in time order when `unsorted` (equal +/// times in chunk order); returns its bytes before and after. +fn compact(pane: &mut Pane, unsorted: bool) -> (usize, usize) { let (_, bytes) = pane_totals(pane); - let compacted = Chunk::new(pane.iter().flat_map(|chunk| chunk.rows())); - *pane = compacted.map(Arc::new).into_iter().collect(); + *pane = merged(pane, unsorted).into_iter().collect(); (bytes, pane_totals(pane).1) } +/// `pane`'s rows as one chunk, in time order when `unsorted`. +fn merged(pane: &Pane, unsorted: bool) -> Option> { + let rows = pane.iter().flat_map(|chunk| chunk.rows()); + let compacted = if unsorted { + let mut rows: Vec<(&'static Series, i64, f64)> = rows.collect(); + rows.sort_by_key(|row| row.1); + Chunk::new(rows.into_iter()) + } else { + Chunk::new(rows) + }; + compacted.map(Arc::new) +} + /// Samples and bytes of `pane`'s chunks. fn pane_totals(pane: &Pane) -> (usize, usize) { pane.iter().fold((0, 0), |(samples, bytes), chunk| { @@ -505,38 +524,37 @@ impl RawData { } } let pane = metric.panes.entry(pane_end).or_default(); - let in_order = rows + // Rows out of order among themselves are sorted (equal times in + // arrival order); rows older than the pane's newest make the + // pane unsorted: its chunks are merged in time order when read + // or sealed, not here per request. + let sorted = rows .windows(2) - .all(|pair| pair[0].timestamp_ms <= pair[1].timestamp_ms) - && pane + .all(|pair| pair[0].timestamp_ms <= pair[1].timestamp_ms); + let chunk = if sorted { + Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))) + } else { + let mut rows: Vec<(&'static Series, i64, f64)> = rows + .iter() + .map(|s| (s.labels, s.timestamp_ms, s.value)) + .collect(); + rows.sort_by_key(|row| row.1); + Chunk::new(rows.into_iter()) + }; + let Some(chunk) = chunk else { continue }; + if metric.unsorted.contains_key(&pane_end) + || pane .last() - .is_none_or(|last| last.time_bounds_ms.1 <= rows[0].timestamp_ms); - if in_order { - let chunk = Chunk::new(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))); - if let Some(chunk) = chunk { - self.samples += chunk.len(); - self.bytes += chunk.bytes(); - pane.push(Arc::new(chunk)); - } - if pane.len() > 1 && metric.sealed_through_ms.is_some_and(|s| pane_end <= s) { - metric.unsealed.insert(pane_end); - } - continue; + .is_some_and(|last| last.time_bounds_ms.1 > chunk.time_bounds_ms.0) + { + metric.unsorted.insert(pane_end, Arc::default()); + } + self.samples += chunk.len(); + self.bytes += chunk.bytes(); + pane.push(Arc::new(chunk)); + if pane.len() > 1 && metric.sealed_through_ms.is_some_and(|s| pane_end <= s) { + metric.unsealed.insert(pane_end); } - let mut all: Vec<(&'static Series, i64, f64)> = pane - .iter() - .flat_map(|chunk| chunk.rows()) - .chain(rows.iter().map(|s| (s.labels, s.timestamp_ms, s.value))) - .collect(); - all.sort_by_key(|row| row.1); - let (samples, bytes) = pane_totals(pane); - *pane = Chunk::new(all.into_iter()) - .map(Arc::new) - .into_iter() - .collect(); - let (new_samples, new_bytes) = pane_totals(pane); - self.samples = self.samples - samples + new_samples; - self.bytes = self.bytes - bytes + new_bytes; } } @@ -548,15 +566,24 @@ impl RawData { for metric in self.by_metric.values_mut() { let newer = metric.unsealed.split_off(&watermark_ms.saturating_add(1)); let late = std::mem::replace(&mut metric.unsealed, newer); - let mut changed = |pane: &mut Pane| { + let unsorted = &mut metric.unsorted; + let mut changed = |end: i64, pane: &mut Pane| { if pane.len() > 1 { - let (before, after) = compact(pane); + let (before, after) = match unsorted.remove(&end) { + // A read merged it already. + Some(once) if once.get().is_some_and(Option::is_some) => { + let (_, before) = pane_totals(pane); + *pane = once.get().cloned().flatten().into_iter().collect(); + (before, pane_totals(pane).1) + } + unsorted => compact(pane, unsorted.is_some()), + }; self.bytes = self.bytes - before + after; } }; for end in late { if let Some(pane) = metric.panes.get_mut(&end) { - changed(pane); + changed(end, pane); } } let start = match metric.sealed_through_ms { @@ -564,11 +591,11 @@ impl RawData { Some(sealed) => Bound::Excluded(sealed), None => Bound::Unbounded, }; - for (_, pane) in metric + for (&end, pane) in metric .panes .range_mut((start, Bound::Included(watermark_ms))) { - changed(pane); + changed(end, pane); } metric.sealed_through_ms = Some(watermark_ms); } @@ -593,6 +620,7 @@ impl RawData { metric.compressed_panes -= block.pane_ends.len(); } metric.unsealed = metric.unsealed.split_off(&oldest_kept_ms.saturating_add(1)); + metric.unsorted = metric.unsorted.split_off(&oldest_kept_ms.saturating_add(1)); metric.evicted_through_ms = metric.evicted_through_ms.max(Some(oldest_kept_ms)); } } @@ -638,6 +666,10 @@ impl RawData { let mut block: Vec<(i64, Pane)> = Vec::new(); let (mut samples, mut needed) = (0, 0); for (&end, pane) in metric.panes.range(..=through_ms) { + // Not sealed in time order yet: compressed once it is. + if metric.unsorted.contains_key(&end) { + break; + } if block.is_empty() { let series = pane.iter().map(|chunk| chunk.series.len()).max(); needed = samples_per_series * series.unwrap_or(1); @@ -767,12 +799,20 @@ impl RawData { .take_while(|(_, block)| block.first_end() < end.saturating_add(self.pane_width_ms)) .filter_map(|(_, block)| block.chunk()) .collect(); + // An unsorted pane's chunks are merged in time order for this read. + let mut chunks: Vec<(Arc, bool)> = Vec::new(); + for (end, pane) in metric_data.panes.range(range) { + if let Some(merged_once) = metric_data.unsorted.get(end) { + let chunk = merged_once.get_or_init(|| merged(pane, true)); + chunks.extend(chunk.iter().map(|chunk| (chunk.clone(), true))); + } else { + chunks.extend(pane.iter().map(|chunk| (chunk.clone(), true))); + } + } + chunks.extend(decoded.into_iter().map(|chunk| (chunk, false))); let mut batches = Vec::new(); - let stored_chunks = metric_data.panes.range(range).flat_map(|(_, pane)| pane); - for (stored, cached) in stored_chunks - .map(|chunk| (chunk, true)) - .chain(decoded.iter().map(|chunk| (chunk, false))) - { + for (stored, cached) in &chunks { + let (stored, cached) = (stored, *cached); let Some(chunk) = stored.in_range((start, end)) else { continue; }; @@ -2377,7 +2417,20 @@ mod tests { } } let converted: usize = shared.shards.iter().map(|s| s.lock().unwrap().len()).sum(); - assert_eq!(converted, raw.chunks().count(), "each chunk converted once"); + // An unsorted pane is read as one chunk, its chunks merged. + let metric = &raw.by_metric["m_store_test"]; + let read_chunks: usize = metric + .panes + .iter() + .map(|(end, pane)| { + if metric.unsorted.contains_key(end) { + 1 + } else { + pane.len() + } + }) + .sum(); + assert_eq!(converted, read_chunks, "each chunk converted once"); } // A closed pane is compacted into one chunk; the open ones are not. let panes = &raw.by_metric["m_store_test"].panes; From 38eaecf77ce89409c7f2c95dc23c722dd7de4a34 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 06:25:24 +0000 Subject: [PATCH 17/19] test(precompute): order-sensitive views leave the rest of their group pushed (failing first) A refresh group mixing a counter's rate (computed again from raw samples on late data) with other views is not pushed at all today, so in push mode the whole group falls back to the window path and keeps raw samples for every metric it scans. The test plans sum_over_time(data[30s]) with rate(data_total[30s]) in one group and checks that in push mode the other views are built by push, with every answer equal to the window path's, late samples included. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/data-plane/tests/push_precompute.rs | 58 ++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index 8cd10753a..587c66611 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -1025,6 +1025,64 @@ async fn late_samples_count_in_the_window_paths_windows() { } } +/// A refresh group mixing an order-sensitive view (a counter's `rate`, +/// computed again from raw samples on late data) with other views is run +/// as two: in push mode the other views are built by push, the +/// order-sensitive one on the window path, and every answer equals the +/// window path's, late samples included. +#[tokio::test(flavor = "multi_thread")] +async fn order_sensitive_views_leave_the_rest_of_their_group_pushed() { + let queries: [Query; 2] = [ + ("sum_over_time(data[30s])", 10_000), + ("rate(data_total[30s])", 10_000), + ]; + let metrics = ["data", "data_total"]; + let plan = plan(&queries, &metrics, 16, 1000, false); + assert!( + plan.ingestion_refresh_groups() + .unwrap() + .iter() + .any(|group| group.views.len() >= 2), + "the Planner groups both views' windows together" + ); + let times: Vec = (3..=6).map(|t| t * 10_000).collect(); + let mut results = Vec::new(); + for mode in [WINDOW, PUSH] { + let (app, _) = install( + &plan, + EngineOptions { + ingestion: IngestionOptions { + allowed_lateness_ms: 5_000, + stream_start_ms: Some(0), + ..IngestionOptions::default() + }, + ..options(mode, 4) + }, + ); + write_seconds(&app, &metrics, 16, 0, 61).await; + barrier(&app, 61_000).await; + // Late, into the sealed window (40, 50]. + post(&app, body(&metrics, 0..4, &[40_500])).await; + barrier(&app, 61_000).await; + let text = metrics_text(&app).await; + let pushed = metric_sum( + &text, + "asap_phase_runs_total", + &["phase=\"precompute_push\""], + ) + .unwrap_or(0.0); + results.push((answers(&app, &plan, ×).await, pushed)); + } + assert_eq!( + results[1].0, results[0].0, + "push answers equal the window path's" + ); + assert!( + results[1].1 > 0.0, + "the non-order-sensitive views are built by push" + ); +} + // ── T14, T15: backpressure and memory reservations ────────────────────── /// T14. Backpressure goes from the commit backlog to the shard queues to From c6401d95505fd654d47d6340fef5128e948fdc15 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 06:30:13 +0000 Subject: [PATCH 18/19] feat(precompute): a refresh group's order-sensitive views run apart, so the rest stays pushed A group was pushed only if none of its views was order-sensitive (a counter's or an instant rate's state, computed again from raw samples on late data). One rate(...) in a group therefore sent all its views to the window path, and raw samples of every metric they scan were kept: the collector e2e's W1 plans its five views into one 5 s group, so at the data plane's default push mode W1 lost push entirely. Ingestion::new now runs such a group as two groups of the same window: the order-sensitive views (window path, raw samples kept, recomputed) and the others (pushed when they qualify). The part read by the other comes first; a group whose two parts read each other stays whole. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/ingestion.rs | 76 ++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 6d9f4a13a..1b2d3b6df 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -268,6 +268,7 @@ impl Ingestion { ))); } let index = DagIndex::new(dag); + let groups = split_order_sensitive_views(dag, views, groups)?; let group_of: HashMap = groups .iter() .enumerate() @@ -1746,6 +1747,81 @@ fn with_retention_margin( serde_json::from_value(value).map_err(error) } +/// `groups` with each group that mixes order-sensitive views +/// ([`order_sensitive`]) with others run as two groups of the same window: +/// the order-sensitive views, whose windows are computed again from raw +/// samples kept for them, and the others, which can then be built by push +/// and keep no raw samples. The group read by the other comes first; a +/// group whose two parts read each other stays whole. +fn split_order_sensitive_views( + dag: &PhysicalASAPDAG, + views: &[MaterializedView], + groups: Vec, +) -> Result, IngestionError> { + let mut split = Vec::with_capacity(groups.len()); + for group in groups { + if group.views.len() < 2 { + split.push(group); + continue; + } + let ids: Vec = group.views.iter().map(|v| v.node_id).collect(); + let in_group: HashSet = ids.iter().copied().collect(); + let read: HashSet = group + .views + .iter() + .flat_map(|v| v.inputs.materialized_views.iter().copied()) + .filter(|id| !in_group.contains(id)) + .collect(); + let read_views: Vec = views + .iter() + .filter(|v| read.contains(&v.node_id)) + .cloned() + .collect(); + let roots: Vec = ids.iter().map(|&id| id as u64).collect(); + let compiled = + compile(dag, &read_views, &roots).map_err(|error| IngestionError::Compile { + views: ids.clone(), + error, + })?; + let (sensitive, others): (Vec, Vec) = + group.views.into_iter().partition(|view| { + compiled + .output_schema(view.node_id as u64) + .is_ok_and(|schema| order_sensitive(&schema)) + }); + let reads_from = |readers: &[MaterializedView], read: &[MaterializedView]| { + readers.iter().any(|reader| { + reader + .inputs + .materialized_views + .iter() + .any(|id| read.iter().any(|view| view.node_id == *id)) + }) + }; + let part = |views: Vec| IngestionRefreshGroup { + refresh_window: group.refresh_window, + views, + }; + let sensitive_reads_others = reads_from(&sensitive, &others); + let others_read_sensitive = reads_from(&others, &sensitive); + if sensitive.is_empty() || others.is_empty() { + split.push(part(sensitive.into_iter().chain(others).collect())); + } else if sensitive_reads_others && others_read_sensitive { + // Each part reads the other: kept whole, in the plan's order. + let mut views: Vec = sensitive.into_iter().chain(others).collect(); + views.sort_by_key(|view| ids.iter().position(|id| *id == view.node_id)); + split.push(part(views)); + } else if others_read_sensitive { + split.push(part(sensitive)); + split.push(part(others)); + } else { + split.push(part(others)); + split.push(part(sensitive)); + } + } + Ok(split) +} + fn gcd(a: i64, b: i64) -> i64 { if b == 0 { a.abs() From 5da5b6c91edffbbc8da94d83f79bab595d2e9e6c Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 06:33:23 +0000 Subject: [PATCH 19/19] perf(precompute): the raw-compress queue is bounded; past it, shards encode their panes themselves When ingest outran the one raw-compress thread (an unpaced backfill at 2-4 M samples/s), each metric had one batch in flight and the panes behind it waited columnar until it came back: the dashboard shape's max RSS went from 2.8 to 4.8 GB. - A metric may now have several batches in flight: a take gets only panes newer than every batch in flight (RawData keeps their newest ends), so panes no longer wait for an earlier batch to come back. - The shards count the samples queued for the thread; past 4 M samples (about 64 MiB columnar) a shard encodes and installs its batch itself, which slows its ingest instead of growing memory (backpressure). - Test: two batches in flight, installed in either order, read as the columnar panes; a block a late sample changed in flight is taken again once the newest batch is installed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- crates/precompute/src/engine.rs | 39 +++++++++++-- crates/storage/src/store.rs | 98 +++++++++++++++++++++++++++------ 2 files changed, 117 insertions(+), 20 deletions(-) diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index fc059b533..9e78ae664 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -24,7 +24,7 @@ //! [`Metrics`], exported on `/metrics`. use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, RwLock}; use std::time::Instant; @@ -124,6 +124,10 @@ struct ShardReport { late: Vec<(ClosedWindow, RawSample)>, } +/// Most raw samples queued for the `raw-compress` thread at once +/// ([`Shared::raw_compress_queued`]): about 64 MiB of columnar panes. +const RAW_COMPRESS_QUEUE_SAMPLES: usize = 4_000_000; + /// What an ingest shard does next. enum ShardMessage { Samples(Vec), @@ -214,6 +218,11 @@ struct Shared { clock: WallClock, /// For tests ([`PrecomputeOptions::routing_delay_after_flush_ms`]). routing_delay_after_flush: std::time::Duration, + /// Raw samples sent to the `raw-compress` thread and not yet encoded: + /// past [`RAW_COMPRESS_QUEUE_SAMPLES`], shards encode their panes + /// themselves, so a thread that falls behind bounds the panes waiting + /// columnar instead of letting them grow. + raw_compress_queued: AtomicUsize, } /// Marks the engine stopped when its thread exits, panics included. @@ -477,6 +486,7 @@ impl InstalledPrecompute { precompute_gate: Mutex::new(()), metrics, clock: options.clock.clone(), + raw_compress_queued: AtomicUsize::new(0), routing_delay_after_flush: std::time::Duration::from_millis( options.routing_delay_after_flush_ms, ), @@ -538,12 +548,17 @@ impl InstalledPrecompute { } drop(to_compress); // Ends when every shard has. + let compress_shared = shared.clone(); std::thread::Builder::new() .name("raw-compress".into()) .spawn(move || { for (shard, panes) in compress_inbox { for panes in panes { + let samples = panes.samples(); let _ = compressed_outboxes[shard].send(panes.encode()); + compress_shared + .raw_compress_queued + .fetch_sub(samples, Ordering::Relaxed); } } })?; @@ -859,9 +874,25 @@ fn serve_shard( for panes in compressed.try_iter() { raw.install_compressed(panes); } - let panes = routing.maintain(raw, watermark_ms); - if !panes.is_empty() { - let _ = to_compress.send((index, panes)); + // Sent to the `raw-compress` thread while its queue has + // room; past it, encoded here (backpressure). + let mut queued = Vec::new(); + for panes in routing.maintain(raw, watermark_ms) { + let samples = panes.samples(); + let before = shared + .raw_compress_queued + .fetch_add(samples, Ordering::Relaxed); + if before + samples <= RAW_COMPRESS_QUEUE_SAMPLES { + queued.push(panes); + } else { + shared + .raw_compress_queued + .fetch_sub(samples, Ordering::Relaxed); + raw.install_compressed(panes.encode()); + } + } + if !queued.is_empty() { + let _ = to_compress.send((index, queued)); } awaiting_routing = false; if held.is_empty() { diff --git a/crates/storage/src/store.rs b/crates/storage/src/store.rs index 961f7e266..9c392050d 100644 --- a/crates/storage/src/store.rs +++ b/crates/storage/src/store.rs @@ -350,9 +350,26 @@ pub struct PanesToCompress { } impl PanesToCompress { + /// Samples taken, over every block. + pub fn samples(&self) -> usize { + self.blocks + .iter() + .flatten() + .map(|(_, pane)| pane_totals(pane).0) + .sum() + } + pub fn encode(self) -> CompressedPanes { + let through_ms = self + .blocks + .iter() + .flatten() + .map(|(end, _)| *end) + .max() + .expect("panes to compress"); CompressedPanes { metric: self.metric, + through_ms, blocks: self .blocks .into_iter() @@ -366,6 +383,8 @@ impl PanesToCompress { #[derive(Debug)] pub struct CompressedPanes { metric: String, + /// The newest pane end taken. + through_ms: i64, blocks: Vec<(CompressedBlock, Vec<(i64, Pane)>)>, } @@ -380,9 +399,10 @@ struct MetricPanes { compressed: BTreeMap>, /// Panes in `compressed`. compressed_panes: usize, - /// Some of its panes are being compressed ([`PanesToCompress`]): no - /// more are taken until they are installed. - compressing: bool, + /// The newest pane end of each batch of its panes being compressed + /// ([`PanesToCompress`]): only panes newer than every batch in flight + /// are taken. + compressing_through_ms: BTreeSet, /// Samples at or before this are evicted: a read never returns them, /// though the oldest pane kept may still hold some. evicted_through_ms: Option, @@ -638,8 +658,8 @@ impl RawData { /// samples per series at least ([`CompressedBlock`]): only windows /// computed again from raw samples read them, and reads decode them. /// The newest panes that do not fill a block yet stay columnar. - /// `None` when there is no block, or while the last ones taken are not - /// installed. Compressed panes leave the columnar ones, so only panes + /// `None` when there is no block. Panes taken and not yet installed + /// are not taken again, so several batches can be in flight. Compressed panes leave the columnar ones, so only panes /// not compressed yet (newly closed, or made columnar again by a late /// sample) are visited. pub fn panes_to_compress(&mut self, metric: &str, through_ms: i64) -> Option { @@ -654,18 +674,22 @@ impl RawData { ) -> Option { let name = metric; let metric = self.by_metric.get_mut(metric)?; - if metric.compressing - || metric - .panes - .first_key_value() - .is_none_or(|(&end, _)| end > through_ms) + let after = metric + .compressing_through_ms + .last() + .map_or(Bound::Unbounded, |&end| Bound::Excluded(end)); + if metric + .panes + .range((after, Bound::Unbounded)) + .next() + .is_none_or(|(&end, _)| end > through_ms) { return None; } let mut blocks = Vec::new(); let mut block: Vec<(i64, Pane)> = Vec::new(); let (mut samples, mut needed) = (0, 0); - for (&end, pane) in metric.panes.range(..=through_ms) { + for (&end, pane) in metric.panes.range((after, Bound::Included(through_ms))) { // Not sealed in time order yet: compressed once it is. if metric.unsorted.contains_key(&end) { break; @@ -681,10 +705,8 @@ impl RawData { samples = 0; } } - if blocks.is_empty() { - return None; - } - metric.compressing = true; + let last = blocks.last()?.last()?.0; + metric.compressing_through_ms.insert(last); Some(PanesToCompress { metric: name.to_string(), blocks, @@ -700,7 +722,7 @@ impl RawData { let Some(metric) = self.by_metric.get_mut(&compressed.metric) else { return; }; - metric.compressing = false; + metric.compressing_through_ms.remove(&compressed.through_ms); for (block, sources) in compressed.blocks { let span = block.first_end()..=*block.pane_ends.last().expect("a block has panes"); let unchanged = metric.panes.range(span.clone()).count() == sources.len() @@ -2562,6 +2584,50 @@ mod tests { } } + /// Several batches of one metric can be in flight: a second take gets + /// only panes newer than the first; installed in either order, reads + /// equal the columnar ones, and a block a late sample changed while in + /// flight is taken again once the newest batch is installed. + #[test] + fn batches_in_flight_install_in_any_order() { + let schema = schema(); + let mut columnar = RawData::for_metrics(&["m_store_test".to_string()], 5_000); + for request in samples() { + columnar.append(&request); + } + columnar.seal_through(30_000); + let mut raw = columnar.clone(); + let first = raw + .panes_to_compress_in_blocks_of("m_store_test", 15_000, 7) + .expect("panes through 15 s"); + assert!(raw + .panes_to_compress_in_blocks_of("m_store_test", 15_000, 7) + .is_none()); + let second = raw + .panes_to_compress_in_blocks_of("m_store_test", 25_000, 7) + .expect("panes after 15 s"); + assert!(second.samples() > 0 && first.samples() > 0); + // A late sample changes a pane of the first batch while in flight. + let late = RawSample { + timestamp_ms: 7_400, + value: 5.0, + ..samples()[0][0].clone() + }; + for raw in [&mut raw, &mut columnar] { + raw.append(std::slice::from_ref(&late)); + raw.seal_through(30_000); + } + raw.install_compressed(second.encode()); + raw.install_compressed(first.encode()); + let read = |raw: &RawData| sorted(read_rows(raw, &schema, Some((0, 30_000)), None)); + assert_eq!(read(&raw), read(&columnar)); + assert_eq!(walked_totals(&raw), (raw.len(), raw.bytes())); + assert!(raw.by_metric["m_store_test"].panes.contains_key(&10_000)); + compress_in_blocks_of(&mut raw, 25_000, 7); + assert!(!raw.by_metric["m_store_test"].panes.contains_key(&10_000)); + assert_eq!(read(&raw), read(&columnar)); + } + /// The samples and panes held, by walking every pane. fn walked_panes(raw: &RawData) -> usize { raw.by_metric