From 5be28eb19c191c34ee62ed37dfe4d8a5317d464d Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 06:00:39 +0000 Subject: [PATCH 1/2] feat(precompute): close an idle stream's last windows by wall-clock time When no sample arrives, the watermark stops, and the last windows of a stream that stopped sending stay open until a sample or a barrier comes. The ingest coordinator now keeps an idle watermark: the newest sample time plus the wall-clock time since a sample last arrived, less the allowed lateness and a 1 s grace. Because it counts from the newest sample, not from the wall clock, a stream behind the wall clock (a replay) closes no window earlier than if it kept sending. Only samples ingestion keeps reset the time a sample last arrived. The coordinator checks the idle watermark every tick and, when it would close a window, flushes every shard first, so queued samples count before it. Barriers are applied before the idle close, so a window a barrier closes is not counted as closed by wall clock. The others are counted (asap_windows_closed_by_wall_clock_total); a later sample for them is late. The engine reads the wall clock through precompute::ingestion::WallClock, which tests set (manual) or stop (tests replaying past event times). --- README.md | 8 ++ crates/data-plane/src/engine.rs | 7 +- crates/data-plane/src/main.rs | 3 + crates/data-plane/src/metrics_endpoint.rs | 11 ++ crates/data-plane/src/test_support.rs | 7 +- crates/data-plane/tests/common/mod.rs | 7 +- crates/data-plane/tests/forward_mode.rs | 3 +- crates/data-plane/tests/ingest_shards.rs | 96 ++++++++++++- .../tests/planner_executor_parity.rs | 3 +- crates/data-plane/tests/precompute_pool.rs | 3 +- crates/data-plane/tests/push_precompute.rs | 6 +- crates/data-plane/tests/query_protocols.rs | 3 +- crates/data-plane/tests/range_isolation.rs | 3 +- crates/data-plane/tests/range_queries.rs | 3 +- crates/data-plane/tests/time_params.rs | 3 +- .../data-plane/tests/view_cold_allocations.rs | 3 +- crates/data-plane/tests/view_tiering.rs | 3 +- crates/precompute/src/engine.rs | 64 +++++++-- crates/precompute/src/ingestion.rs | 130 +++++++++++++++++- 19 files changed, 328 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index e7179afc1..3c9dda019 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,14 @@ wall clock) is refreshed. A repeated or lower `T` does nothing. The response is `{"barrier_ms": B}`, the barrier in force. With several producers, send the barrier only after all of them have written through `T`. +When no sample arrives at all, the last windows still close by wall-clock +time: event time is taken to advance with the wall clock from the newest +sample, so a window closes once no sample has come for `e - t` plus +`--allowed-lateness-ms` plus 1 s, `e` the window's end and `t` the newest +sample time. A stream behind the wall clock (a replay) waits as long as a +live one. A later sample for such a window is late. These windows are +counted in `asap_windows_closed_by_wall_clock_total`. + **Queries.** An instant query whose text is one of the plan's queries is answered by one query run of its root at its evaluation time `T` (`x-asap-execution: plan`). The run reads the views the root reaches, diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 68daa08f4..d9c6456f0 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -11,7 +11,7 @@ use precompute::engine::{ IngestError, InstalledPrecompute, PersistedViews, PrecomputeEngine, PrecomputeMode, PrecomputeOptions, SlowRefresh, }; -use precompute::ingestion::{IngestionOptions, IngestionStats}; +use precompute::ingestion::{IngestionOptions, IngestionStats, WallClock}; use query::workers::InstalledQueries; use query::{ExecutorQueryEngine, QueryOptions, Unanswered}; use storage::persist::{plan_hash, ViewRead}; @@ -135,6 +135,9 @@ pub struct EngineOptions { /// (ms) panics. #[doc(hidden)] pub panic_in_combine_of_window_end_ms: Option, + /// For tests: the wall clock ingestion reads, set by the test. + #[doc(hidden)] + pub clock: WallClock, } /// The default `view_cache_idle_ms`: a minute, four 15 s dashboard @@ -180,6 +183,7 @@ impl Default for EngineOptions { precompute_memory_budget_bytes: None, push_batching: precompute::push::MorselBatching::default(), panic_in_combine_of_window_end_ms: None, + clock: WallClock::default(), } } } @@ -356,6 +360,7 @@ impl EngineOptions { push_batching: self.push_batching, precompute_memory_budget_bytes: self.precompute_memory_budget_bytes, panic_in_combine_of_window_end_ms: self.panic_in_combine_of_window_end_ms, + clock: self.clock.clone(), } } diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index b9fde7b4c..da8ce63f7 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -40,6 +40,9 @@ struct Args { #[arg(long, default_value = "0.0.0.0:8088")] listen: String, /// How long after the newest sample passes a window's end it is refreshed. + /// While no sample arrives, event time is taken to advance with the wall + /// clock: a window closes once no sample has come for its end less the + /// newest sample time, plus this, plus 1 s. #[arg(long, default_value_t = IngestionOptions::default().allowed_lateness_ms)] allowed_lateness_ms: u64, /// Samples further ahead of the wall clock than this are dropped. diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index 65f67bdf7..d9d3ea6b8 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -159,6 +159,17 @@ pub(crate) fn render(metrics: &Metrics, gauges: &Gauges) -> String { ] { let _ = writeln!(out, "asap_windows_total{{outcome=\"{outcome}\"}} {count}"); } + family( + &mut out, + "asap_windows_closed_by_wall_clock_total", + "counter", + "Refresh windows closed by wall-clock time while no sample arrived, ahead of the samples and barriers.", + ); + let _ = writeln!( + out, + "asap_windows_closed_by_wall_clock_total {}", + stats.windows_closed_by_wall_clock + ); let gauge = |out: &mut String, name: &str, help: &str, value: f64| { let _ = writeln!( diff --git a/crates/data-plane/src/test_support.rs b/crates/data-plane/src/test_support.rs index 79cf6275d..5e30acb3a 100644 --- a/crates/data-plane/src/test_support.rs +++ b/crates/data-plane/src/test_support.rs @@ -1,14 +1,15 @@ //! Options and samples for the unit tests. -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use storage::store::RawSample; use crate::engine::EngineOptions; -/// Options that refresh every window: no allowed lateness, and the stream -/// starting at 0. +/// Options that refresh every window: no allowed lateness, the stream +/// starting at 0, and the clock stopped ([`WallClock::stopped`]). pub(crate) fn options() -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), ingestion: IngestionOptions { allowed_lateness_ms: 0, stream_start_ms: Some(0), diff --git a/crates/data-plane/tests/common/mod.rs b/crates/data-plane/tests/common/mod.rs index f4d0de07c..b4bf0f7fb 100644 --- a/crates/data-plane/tests/common/mod.rs +++ b/crates/data-plane/tests/common/mod.rs @@ -9,7 +9,7 @@ use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; use data_plane::{DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, TimeSeries, WriteRequest}; use serde_json::Value; use tower::ServiceExt; @@ -210,11 +210,12 @@ pub fn one_query_plan_json(query: &str, series: usize, extra: Value) -> String { } /// The engine options of a data plane that never forwards a query and -/// refreshes every window: no allowed lateness, and the producers' stream -/// starting at 0. +/// refreshes every window: no allowed lateness, the producers' stream +/// starting at 0, and the clock stopped (`WallClock::stopped`). #[allow(dead_code)] pub fn no_forward_options() -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), no_forward: true, ingestion: IngestionOptions { allowed_lateness_ms: 0, diff --git a/crates/data-plane/tests/forward_mode.rs b/crates/data-plane/tests/forward_mode.rs index 7a970024d..e1eef8006 100644 --- a/crates/data-plane/tests/forward_mode.rs +++ b/crates/data-plane/tests/forward_mode.rs @@ -22,7 +22,7 @@ use data_plane::engine::EngineOptions; use data_plane::raw_forward::RawForwardOptions; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tokio::sync::Notify; @@ -48,6 +48,7 @@ fn plan_json() -> String { fn options() -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), ingest_threads: 2, ingestion: IngestionOptions { allowed_lateness_ms: 0, diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index 4252b6476..1c6090989 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -12,7 +12,7 @@ use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -533,3 +533,97 @@ async fn a_sample_beyond_the_time_range_is_dropped() { assert_eq!(state.engine.stats().samples_dropped_late, 2); answer(&app, 600).await; } + +/// A data plane of `QUERY` over two shards whose ingestion reads `clock`: +/// no allowed lateness, the stream starting at 0. +fn idle_data_plane(clock: &WallClock) -> (Router, Arc) { + let options = EngineOptions { + ingest_threads: 2, + clock: clock.clone(), + ..common::no_forward_options() + }; + let state = Arc::new( + DataPlane::with_options(plan_json(), "http://127.0.0.1:1".into(), options).unwrap(), + ); + (router(state.clone()), state) +} + +/// One coordinator pass at the clock's time, flushing every shard, with +/// every window it closes committed when it returns: a barrier at 0, which +/// closes nothing itself. +async fn pass(app: &Router) { + common::barrier(app, 0).await; +} + +/// Writes series `0..64` at 1..=40 s while the clock reads `written_ms`, and +/// runs them: the window `(30, 40]` is still open, as its end is the newest +/// sample. +async fn write_through_40s(app: &Router, clock: &WallClock, written_ms: i64) { + clock.set(written_ms); + write_seconds(app, 0..64, 1..=40).await; + pass(app).await; + assert_ne!(status_and_answer(app, 40).await.0, StatusCode::OK); +} + +/// The window `(30, 40]` closed: answered from every sample at 1..=40 s. +/// Then one more pass, so the counters and the routing of the pass that +/// closed it are published (its refresh may commit before they are). +async fn wait_for_answer_at_40s(app: &Router, state: &DataPlane) { + 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() + ); + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + assert_eq!(common::per_job(&answer(app, 40).await), expected(40)); + pass(app).await; +} + +/// A stream that stops: once no sample has come for the allowed lateness +/// (0) and the 1 s grace past the last window's end, that window closes +/// without a sample or a barrier, and is answered. +#[tokio::test(flavor = "multi_thread")] +async fn the_last_window_of_a_stopped_stream_closes_by_wall_clock_time() { + 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; + assert!(state.engine.stats().windows_closed_by_wall_clock > 0); +} + +/// A replayed stream an hour behind the wall clock: its windows close by +/// wall-clock time counted from its newest sample, never by the wall clock +/// itself, so the window `(30, 40]` waits as long as for a live stream. +#[tokio::test(flavor = "multi_thread")] +async fn a_lagging_stream_closes_no_window_early() { + let hour_ms = 3_600_000; + let clock = WallClock::manual(0); + let (app, state) = idle_data_plane(&clock); + write_through_40s(&app, &clock, hour_ms + 40_000).await; + clock.set(hour_ms + 40_999); + pass(&app).await; + assert_ne!(status_and_answer(&app, 40).await.0, StatusCode::OK); + assert_eq!(state.engine.stats().windows_closed_by_wall_clock, 0); + clock.set(hour_ms + 41_000); + 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. +#[tokio::test(flavor = "multi_thread")] +async fn a_sample_after_a_wall_clock_close_is_late() { + 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; + pass(&app).await; + assert_eq!(state.engine.stats().samples_dropped_late, dropped + 1); + assert_eq!(common::per_job(&answer(&app, 40).await), expected(40)); +} diff --git a/crates/data-plane/tests/planner_executor_parity.rs b/crates/data-plane/tests/planner_executor_parity.rs index cc3778454..02e03cbd1 100644 --- a/crates/data-plane/tests/planner_executor_parity.rs +++ b/crates/data-plane/tests/planner_executor_parity.rs @@ -49,7 +49,7 @@ use data_plane::{router, DataPlane, EXECUTION_HEADER}; use futures::{executor::block_on, StreamExt}; use http_body_util::BodyExt; use precompute::engine::PrecomputeMode; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{Label, Sample, TimeSeries}; use serde_json::Value as Json; use tower::ServiceExt; @@ -243,6 +243,7 @@ async fn data_plane_over( Views::EveryReadCold => (Some(fresh_view_dir()), Some(0)), }; let options = EngineOptions { + clock: WallClock::stopped(), view_dir, view_cache_max_bytes, no_forward: true, diff --git a/crates/data-plane/tests/precompute_pool.rs b/crates/data-plane/tests/precompute_pool.rs index be2c484c0..f3a441ea6 100644 --- a/crates/data-plane/tests/precompute_pool.rs +++ b/crates/data-plane/tests/precompute_pool.rs @@ -25,7 +25,7 @@ use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; use precompute::engine::SlowRefresh; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use tower::ServiceExt; @@ -144,6 +144,7 @@ fn requests(plan: &InstallablePlan, series: usize, from_ms: i64, to_ms: i64) -> fn options(threads: usize, view_dir: Option) -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), no_forward: true, precompute_threads: threads, view_dir, diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index e0d9ad661..0f1d53d23 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -28,7 +28,7 @@ use data_plane::{router, DataPlane}; use http_body_util::BodyExt; use pipelines::{combine_rules, CombineRule}; use precompute::engine::{PrecomputeMode, SlowRefresh}; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -117,6 +117,7 @@ fn workload_file(name: &str, series: usize) -> asap_planner::PlanningWorkload { /// windows from 0, no lateness unless a test sets it. fn options(mode: PrecomputeMode, shards: usize) -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), no_forward: true, ingest_threads: shards, precompute_mode: mode, @@ -834,6 +835,7 @@ async fn seal_is_exact_under_shard_skew() { let (skewed, state) = install( &plan, EngineOptions { + clock: WallClock::stopped(), shard_delay_ms: 20, ingestion: IngestionOptions { allowed_lateness_ms: 0, @@ -953,6 +955,7 @@ async fn late_samples_count_in_the_window_paths_windows() { let (app, _) = install( &plan, EngineOptions { + clock: WallClock::stopped(), ingestion: IngestionOptions { allowed_lateness_ms: 5_000, stream_start_ms: Some(0), @@ -1132,6 +1135,7 @@ async fn memory_reservations_wait_then_fail_only_a_lone_window() { let (app, state) = install( &plan, EngineOptions { + clock: WallClock::stopped(), precompute_memory_budget_bytes: Some((one_small * 1.5) as u64), push_batching: per_request(), ingestion: IngestionOptions { diff --git a/crates/data-plane/tests/query_protocols.rs b/crates/data-plane/tests/query_protocols.rs index 0285b1887..1dbd1680d 100644 --- a/crates/data-plane/tests/query_protocols.rs +++ b/crates/data-plane/tests/query_protocols.rs @@ -20,7 +20,7 @@ use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use elastic_http::fallback::ElasticHttpFallback; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{Label, Sample, TimeSeries}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -82,6 +82,7 @@ async fn upstream(received: Received) -> String { /// Forwarding allowed, every window refreshed. fn options() -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), ingestion: IngestionOptions { allowed_lateness_ms: 0, stream_start_ms: Some(0), diff --git a/crates/data-plane/tests/range_isolation.rs b/crates/data-plane/tests/range_isolation.rs index d61d43f32..36fd31ce6 100644 --- a/crates/data-plane/tests/range_isolation.rs +++ b/crates/data-plane/tests/range_isolation.rs @@ -14,7 +14,7 @@ use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::json; use tower::ServiceExt; @@ -147,6 +147,7 @@ async fn range_requests_do_not_hold_up_instant_queries_or_writes() { let dir = std::env::temp_dir().join(format!("range-isolation-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); let options = EngineOptions { + clock: WallClock::stopped(), no_forward: true, query_threads: std::env::var("RANGE_ISOLATION_QUERY_THREADS") .map_or(8, |n| n.parse().unwrap()), diff --git a/crates/data-plane/tests/range_queries.rs b/crates/data-plane/tests/range_queries.rs index 8f87da359..13e1172c7 100644 --- a/crates/data-plane/tests/range_queries.rs +++ b/crates/data-plane/tests/range_queries.rs @@ -10,7 +10,7 @@ use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{Label, Sample, TimeSeries}; use serde_json::json; @@ -189,6 +189,7 @@ async fn a_refreshed_range_reads_its_older_steps_from_the_result_cache() { let plan = serde_json::to_string(&plan_workload(&workload, &inputs).unwrap().0).unwrap(); let start = || { let options = EngineOptions { + clock: WallClock::stopped(), no_forward: true, ingestion: IngestionOptions { allowed_lateness_ms: 0, diff --git a/crates/data-plane/tests/time_params.rs b/crates/data-plane/tests/time_params.rs index 04d0a4ff9..9c3c36f6c 100644 --- a/crates/data-plane/tests/time_params.rs +++ b/crates/data-plane/tests/time_params.rs @@ -15,7 +15,7 @@ use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -41,6 +41,7 @@ fn data_plane() -> Router { .unwrap(); let plan = plan_workload(&workload, &common::inputs(false)).unwrap().0; let options = EngineOptions { + clock: WallClock::stopped(), no_forward: true, view_dir: None, ingestion: IngestionOptions { diff --git a/crates/data-plane/tests/view_cold_allocations.rs b/crates/data-plane/tests/view_cold_allocations.rs index d68e7dbec..009926f1b 100644 --- a/crates/data-plane/tests/view_cold_allocations.rs +++ b/crates/data-plane/tests/view_cold_allocations.rs @@ -18,7 +18,7 @@ use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -89,6 +89,7 @@ fn data_plane( tiered: bool, ) -> (Router, Arc) { let options = EngineOptions { + clock: WallClock::stopped(), no_forward: true, result_cache: false, view_dir, diff --git a/crates/data-plane/tests/view_tiering.rs b/crates/data-plane/tests/view_tiering.rs index 17494cc0e..6c9007904 100644 --- a/crates/data-plane/tests/view_tiering.rs +++ b/crates/data-plane/tests/view_tiering.rs @@ -19,7 +19,7 @@ use control_plane::plan_workload; use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; -use precompute::ingestion::IngestionOptions; +use precompute::ingestion::{IngestionOptions, WallClock}; use prometheus_remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use serde_json::{json, Value}; use tower::ServiceExt; @@ -66,6 +66,7 @@ fn view_dir(test: &str) -> PathBuf { /// (`None`: no budget) and idle time `idle_ms` (`Some(0)`: never). fn options(dir: &Path, max_bytes: Option, idle_ms: Option) -> EngineOptions { EngineOptions { + clock: WallClock::stopped(), no_forward: true, view_dir: Some(dir.to_path_buf()), view_cache_max_bytes: max_bytes, diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 5dfd8e230..395280433 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -44,7 +44,7 @@ use tokio::sync::oneshot; use crate::ingestion::{ ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, - RefreshTaskGraph, Refreshed, Routing, + RefreshTaskGraph, Refreshed, Routing, WallClock, }; use crate::push::{Partial, PushGroup, PushShard}; @@ -116,6 +116,9 @@ struct ShardReport { /// Samples of the batch reported, counted out of the queues when the /// coordinator applies the report. samples: u64, + /// 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, } /// What an ingest shard does next. @@ -198,6 +201,7 @@ struct Shared { /// keep a refresh from finishing. precompute_gate: Mutex<()>, metrics: Arc, + clock: WallClock, } /// Marks the engine stopped when its thread exits, panics included. @@ -240,6 +244,9 @@ pub struct PrecomputeOptions { pub precompute_memory_budget_bytes: Option, /// For tests, push mode: the combine of the window ending here panics. pub panic_in_combine_of_window_end_ms: Option, + /// The wall clock the precompute engine reads (the system clock but in + /// tests). + pub clock: WallClock, } /// Where the views are persisted, when they are: the view files' @@ -451,6 +458,7 @@ impl InstalledPrecompute { published, precompute_gate: Mutex::new(()), metrics, + clock: options.clock.clone(), }); let (commands, command_receiver) = channel(); let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); @@ -752,7 +760,7 @@ const _: fn() = || { /// samples stamped later (a sender stamps before it sends). fn flush(shards: &[Sender], shared: &Shared) -> i64 { let _admission = shared.admission.write().unwrap_or_else(|e| e.into_inner()); - let sent_ms = crate::ingestion::wall_clock_ms(); + let sent_ms = shared.clock.now_ms(); for shard in shards { let _ = shard.send(ShardMessage::Flush); } @@ -816,6 +824,7 @@ fn serve_shard( // report (and so at most one coordinator pass) per drained queue, // not per request. let mut count = 0; + let mut accepted_any = false; let mut first_seen = Vec::new(); loop { if !delay.is_zero() { @@ -828,8 +837,9 @@ fn serve_shard( .read() .unwrap_or_else(|e| e.into_inner()) .clone(); - let routed = routing.route(samples, crate::ingestion::wall_clock_ms()); + let routed = routing.route(samples, shared.clock.now_ms()); Arc::make_mut(&mut raw_data).append(&routed.accepted); + accepted_any |= !routed.accepted.is_empty(); newest_ms = newest_ms.max(routed.newest_ms); if let Some(push) = &mut push { push.push(&routed.accepted, &shared.metrics); @@ -858,6 +868,7 @@ fn serve_shard( newest_ms, first_seen, samples: count, + accepted_any, }; // The coordinator counts the samples out of the queues when it // applies the report, so samples stay counted while it cannot keep @@ -880,7 +891,9 @@ fn serve_shard( /// was sent (a request admitted later holds samples stamped later), never /// a report's time. Barriers that come during a flush take the next pass. /// Shards with nothing queued answer the flush at once, so idle shards -/// never hold the watermark; the coordinator also wakes every tick. +/// never hold the watermark; the coordinator also wakes every tick, and +/// flushes when the idle watermark would close a window +/// ([`Ingestion::idle_closes_at`]). fn serve_ingest( mut ingestion: Ingestion, mut raw_shards: Vec>, @@ -893,6 +906,7 @@ 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; + // Takes in a report; whether it ran a sample ingestion kept. let apply = |report: ShardReport, ingestion: &mut Ingestion, newest: &mut Vec>| { ingestion.observe(&report.first_seen); shared.shard_queued[report.shard].fetch_sub(report.samples, Ordering::SeqCst); @@ -900,6 +914,7 @@ fn serve_ingest( .queued_samples .fetch_sub(report.samples, Ordering::SeqCst); newest[report.shard] = report.newest_ms; + report.accepted_any }; // Barriers that came while a flush was waited for: written after it, // so they take the next pass, behind its own flush. @@ -923,13 +938,15 @@ fn serve_ingest( // sample, the wall clock a report carries (the watermark is capped // at it), a metric's first sample, or a barrier. let mut moved = !barriers.is_empty() || !held.is_empty(); + // Whether a report taken this pass ran a sample. + let mut arrived = false; for report in held.drain(..) { - apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest); } if !moved { match commands.recv_timeout(TICK) { Ok(Command::Report(report)) => { - apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest); moved = true; } Ok(Command::Flushed(..)) => {} @@ -948,7 +965,7 @@ fn serve_ingest( while let Ok(command) = commands.try_recv() { match command { Command::Report(report) => { - apply(report, &mut ingestion, &mut newest); + arrived |= apply(report, &mut ingestion, &mut newest); moved = true; } Command::Flushed(..) => {} @@ -959,10 +976,14 @@ fn serve_ingest( Command::Stop => break 'serve, } } + // An idle stream: when the idle watermark would close a window, the + // shards are flushed first and it is taken at that flush, so + // samples still queued count before it. + moved = moved || ingestion.idle_closes_at(shared.clock.now_ms()); // Before the watermark moves, every shard runs the samples queued to // it, so the windows it closes hold every sample admitted so far // and the raw data they read is every shard's as of then. - let flushed = moved; + let mut flushed_at = None; if moved { let flushed_ms = flush(&shards, shared); let mut flushed = vec![false; shards.len()]; @@ -974,7 +995,9 @@ fn serve_ingest( { held.push(report) } - Ok(Command::Report(report)) => apply(report, &mut ingestion, &mut newest), + Ok(Command::Report(report)) => { + arrived |= apply(report, &mut ingestion, &mut newest) + } Ok(Command::Flushed(shard, raw_data)) => { flushed[shard] = true; raw_shards[shard] = raw_data; @@ -994,16 +1017,27 @@ fn serve_ingest( } } ingestion.advance_clock(flushed_ms); + if arrived { + ingestion.sample_arrived(flushed_ms); + } + flushed_at = Some(flushed_ms); } let newest_ms = newest.iter().flatten().copied().max(); ingestion.advance_newest_sample(newest_ms); - let mut closed = ingestion.close(); + if let Some(flushed_ms) = flushed_at { + ingestion.advance_idle(flushed_ms); + } + // The barriers first, so a window one of them closes is not + // counted as closed by wall-clock time. + let mut closed = Vec::new(); let mut answered = Vec::new(); for (barrier_ms, reply) in barriers { - let (barrier_ms, more) = ingestion.advance_watermark(barrier_ms); + let (barrier_ms, more) = + ingestion.advance_watermark_at(barrier_ms, shared.clock.now_ms()); closed.extend(more); answered.push((barrier_ms, reply)); } + closed.extend(ingestion.close()); let snapshot: RawShards = Arc::new(raw_shards.clone()); let sealed: Vec = closed .iter() @@ -1038,7 +1072,7 @@ fn serve_ingest( if let Some(watermark_ms) = watermark_ms { metrics.watermark_ms.store(watermark_ms, Ordering::Relaxed); } - if flushed { + if flushed_at.is_some() { let sum = |f: fn(&RawData) -> usize| snapshot.iter().map(|r| f(r) as u64).sum::(); metrics .raw_data_bytes @@ -1072,6 +1106,7 @@ fn serve_ingest( let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); stats.windows_skipped_first = ingestion.stats.windows_skipped_first; stats.windows_skipped_expired = ingestion.stats.windows_skipped_expired; + stats.windows_closed_by_wall_clock = ingestion.stats.windows_closed_by_wall_clock; } for (barrier_ms, reply) in answered { if jobs @@ -1640,7 +1675,7 @@ fn commit_window( if let (true, Some(push)) = (task.pushed, &shared.metrics.push) { push.commit.record(timer); push.commit_lag_ms.store( - (crate::ingestion::wall_clock_ms() - window.end_ms).max(0), + (shared.clock.now_ms() - window.end_ms).max(0), Ordering::Relaxed, ); } @@ -1651,7 +1686,7 @@ fn commit_window( latency.record( task.times.started.saturating_duration_since(task.closed_at), now.saturating_duration_since(task.times.computed), - (crate::ingestion::wall_clock_ms() - window.end_ms).max(0), + (shared.clock.now_ms() - window.end_ms).max(0), ); { let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); @@ -2169,6 +2204,7 @@ mod tests { push_batching: crate::push::MorselBatching::default(), precompute_memory_budget_bytes: None, panic_in_combine_of_window_end_ms: None, + clock: WallClock::stopped(), }; PrecomputeEngine::new(options, None, Arc::new(PublishedStore::new(Arc::default()))) } diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index cc2d76e14..5426a3cdd 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -19,6 +19,10 @@ //! When the watermark jumps past a view's retention, the windows that would //! already be dropped are skipped. //! +//! When no sample arrives, the watermark also follows the idle watermark: +//! event time taken to advance with the wall clock from the newest sample, +//! so the last windows of a stream that stopped close without a barrier. +//! //! Raw samples are kept while a window still to be closed or a query-time //! `Scan` (back to its `retention_ms`) reads them. //! @@ -29,6 +33,7 @@ //! are those a serial engine would read. use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::sync::atomic::{AtomicI64, Ordering}; use std::sync::Arc; use asap_executor::physical_planner::{compile, CompiledPhysicalDAG}; @@ -105,6 +110,9 @@ pub struct IngestionStats { pub windows_skipped_first: u64, /// Windows not refreshed because they would already be dropped. pub windows_skipped_expired: u64, + /// Windows closed by wall-clock time while no sample arrived, ahead of + /// the samples and barriers. + pub windows_closed_by_wall_clock: u64, /// Windows not refreshed because every view of the group already /// stores them (loaded from the view files at startup). pub windows_already_stored: u64, @@ -126,6 +134,10 @@ pub(crate) enum IngestionError { /// least this often. const MAX_PANE_WIDTH_MS: i64 = 60_000; +/// How much longer than the allowed lateness past a window's end the idle +/// watermark waits before closing it ([`Ingestion::idle_watermark_at`]). +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)] @@ -192,6 +204,11 @@ pub(crate) struct Ingestion { newest_clock_ms: Option, /// The newest event-time barrier a producer declared. barrier_ms: Option, + /// The wall-clock time of the newest flush that ran a sample: a sample + /// last arrived at or before it. + arrived_ms: Option, + /// The newest idle watermark ([`Self::advance_idle`]). + idle_watermark_ms: Option, /// Groups whose windows the ingest shards build by push: they read no /// raw data, so they keep none. push_groups: Vec, @@ -347,6 +364,8 @@ impl Ingestion { newest_sample_ms: None, newest_clock_ms: None, barrier_ms: None, + arrived_ms: None, + idle_watermark_ms: None, push_groups: Vec::new(), stats: IngestionStats::default(), }; @@ -448,8 +467,14 @@ impl Ingestion { /// for them. A barrier states every sample at or before it was written, /// so it counts whole when later. (Closing a window only once event /// time is past its end follows the ASAPQuery precompute engine's - /// window manager, `closed_windows`.) + /// window manager, `closed_windows`.) The idle watermark counts when + /// later. pub fn watermark_ms(&self) -> Option { + self.event_watermark_ms().max(self.idle_watermark_ms) + } + + /// The watermark from the samples and barriers alone. + fn event_watermark_ms(&self) -> Option { let newest = match self.newest_clock_ms { Some(clock) => self.newest_sample_ms.map(|newest| newest.min(clock)), None => self.newest_sample_ms, @@ -459,6 +484,52 @@ impl Ingestion { from_samples.max(self.barrier_ms) } + /// The idle watermark at wall-clock `now_ms`: while no sample arrives, + /// event time is taken to advance with the wall clock, so it is the + /// newest sample time (capped at the flush that ran it) plus the time + /// since a sample last arrived, less the allowed lateness and + /// [`IDLE_GRACE_MS`]. Counted from the newest sample, not from + /// `now_ms`, a stream behind the wall clock (a replay) closes no window + /// earlier than if it kept sending. `None` before the first sample. + fn idle_watermark_at(&self, now_ms: i64) -> Option { + let arrived = self.arrived_ms?; + let newest = self.newest_sample_ms?.min(arrived); + let lateness = millis(self.options.allowed_lateness_ms); + Some( + newest + .saturating_add(now_ms.saturating_sub(arrived)) + .saturating_sub(lateness) + .saturating_sub(IDLE_GRACE_MS), + ) + } + + /// Whether the idle watermark at `now_ms` would close a window: the + /// coordinator then flushes every shard and moves it at that flush + /// ([`Self::advance_idle`]), so samples still queued count first. + pub(crate) fn idle_closes_at(&self, now_ms: i64) -> bool { + let Some(idle) = self.idle_watermark_at(now_ms) else { + return false; + }; + self.groups.iter().any(|group| { + group + .refreshed_through + .is_some_and(|through| through.saturating_add(group.width_ms) <= idle) + }) + } + + /// Notes that the flush at wall-clock `flushed_ms` ran a sample. + pub(crate) fn sample_arrived(&mut self, flushed_ms: i64) { + self.arrived_ms = self.arrived_ms.max(Some(flushed_ms)); + } + + /// Moves the idle watermark to the flush at wall-clock `flushed_ms` + /// (it never goes back); call after the flush's samples are taken in. + pub(crate) fn advance_idle(&mut self, flushed_ms: i64) { + self.idle_watermark_ms = self + .idle_watermark_ms + .max(self.idle_watermark_at(flushed_ms)); + } + /// What the ingest shards need to route samples now: the metrics a /// `Scan` reads, each one's eviction cutoff and the time at or before /// which its samples are late, and whether a group still waits for its @@ -550,11 +621,6 @@ impl Ingestion { self.close_windows() } - /// [`Self::advance_watermark_at`] the current wall-clock time. - pub fn advance_watermark(&mut self, barrier_ms: i64) -> (i64, Vec) { - self.advance_watermark_at(barrier_ms, wall_clock_ms()) - } - /// An event-time barrier: the producer states that every sample at or /// before `barrier_ms` has been written, so every window ending at or /// before it closes without a later sample. Capped at `now_ms`; a @@ -639,6 +705,8 @@ impl Ingestion { let Some(watermark) = self.watermark_ms() else { return Vec::new(); }; + // Windows ending after this close only by the idle watermark. + let event_watermark = self.event_watermark_ms(); // Per group, the windows ending at or before this would already be // dropped (they are past its retention). A group whose views // another group reads (a narrower level of a window chain) keeps @@ -687,6 +755,9 @@ impl Ingestion { .checked_add(group.width_ms) .filter(|e| *e <= watermark) { + if event_watermark.is_none_or(|w| end > w) { + self.stats.windows_closed_by_wall_clock += 1; + } closed.push(ClosedWindow { group: index, end_ms: end, @@ -1233,6 +1304,53 @@ fn gcd(a: i64, b: i64) -> i64 { } } +/// The wall clock the precompute engine reads: the system clock, or for +/// tests one they set. +#[derive(Debug, Clone, Default)] +pub struct WallClock(Option>); + +/// Two clocks are equal when both are the system clock or one manual clock. +impl PartialEq for WallClock { + fn eq(&self, other: &Self) -> bool { + match (&self.0, &other.0) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + } + } +} + +impl Eq for WallClock {} + +impl WallClock { + /// For tests: a clock at `now_ms` that moves only by [`Self::set`]. + pub fn manual(now_ms: i64) -> Self { + Self(Some(Arc::new(AtomicI64::new(now_ms)))) + } + + /// For tests that replay past event times as fast as they can: the + /// time now, stopped, so a pause under load between their writes is + /// never taken for an idle stream. + pub fn stopped() -> Self { + Self::manual(wall_clock_ms()) + } + + /// Moves a manual clock to `now_ms`; the system clock ignores it. + pub fn set(&self, now_ms: i64) { + if let Some(manual) = &self.0 { + manual.store(now_ms, Ordering::SeqCst); + } + } + + /// Milliseconds since the Unix epoch. + pub fn now_ms(&self) -> i64 { + match &self.0 { + Some(manual) => manual.load(Ordering::SeqCst), + None => wall_clock_ms(), + } + } +} + /// Milliseconds since the Unix epoch. pub fn wall_clock_ms() -> i64 { std::time::SystemTime::now() From e6c41e30dcb1581d4343593bfd9b8d718fe5ddbc Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 15:35:22 +0000 Subject: [PATCH 2/2] fix(precompute): measure the idle time on the monotonic clock The idle watermark measured the time since a sample last arrived as the difference of two wall-clock readings, so a forward step of the system clock (NTP, a resumed VM) advanced it on a live stream and closed windows early. Each flush now reads both clocks (ClockReading): the wall-clock time still caps the watermark and the newest sample time, and the idle time is measured on WallClock::monotonic_ms (an Instant since process start, or the test's manual value). WallClock::step_wall_clock moves a test's wall clock alone. --- README.md | 5 +- crates/data-plane/tests/ingest_shards.rs | 17 +++ crates/precompute/src/engine.rs | 26 ++--- crates/precompute/src/ingestion.rs | 128 ++++++++++++++++------- 4 files changed, 125 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 3c9dda019..a2a519c97 100644 --- a/README.md +++ b/README.md @@ -96,8 +96,9 @@ When no sample arrives at all, the last windows still close by wall-clock time: event time is taken to advance with the wall clock from the newest sample, so a window closes once no sample has come for `e - t` plus `--allowed-lateness-ms` plus 1 s, `e` the window's end and `t` the newest -sample time. A stream behind the wall clock (a replay) waits as long as a -live one. A later sample for such a window is late. These windows are +sample time; that time is measured on a monotonic clock, so a step of the +system clock does not shorten it. A stream behind the wall clock (a +replay) waits as long as a live one. A later sample for such a window is late. These windows are counted in `asap_windows_closed_by_wall_clock_total`. **Queries.** An instant query whose text is one of the plan's queries is diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index 1c6090989..b52dba129 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -612,6 +612,23 @@ async fn a_lagging_stream_closes_no_window_early() { wait_for_answer_at_40s(&app, &state).await; } +/// The system clock steps 15 min forward (NTP, a resumed VM) while real +/// time does not move: the idle time is measured on the monotonic clock, +/// so the window `(30, 40]` does not close early; it closes once 1 s of +/// real time has passed. +#[tokio::test(flavor = "multi_thread")] +async fn a_wall_clock_step_closes_no_window_early() { + let clock = WallClock::manual(0); + let (app, state) = idle_data_plane(&clock); + write_through_40s(&app, &clock, 40_000).await; + clock.step_wall_clock(40_000 + 15 * 60_000); + pass(&app).await; + assert_ne!(status_and_answer(&app, 40).await.0, StatusCode::OK); + assert_eq!(state.engine.stats().windows_closed_by_wall_clock, 0); + clock.set(41_000 + 15 * 60_000); + 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. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 395280433..3e8aa4f9a 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -43,7 +43,7 @@ use storage::store::{ use tokio::sync::oneshot; use crate::ingestion::{ - ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, + ClockReading, ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, RefreshTaskGraph, Refreshed, Routing, WallClock, }; use crate::push::{Partial, PushGroup, PushShard}; @@ -756,15 +756,15 @@ const _: fn() = || { /// Sends every shard a flush, with no request half sent: each request /// already admitted is wholly before it in its shards' queues. Returns -/// the wall-clock time it was sent: every request admitted later holds -/// samples stamped later (a sender stamps before it sends). -fn flush(shards: &[Sender], shared: &Shared) -> i64 { +/// when it was sent: every request admitted later holds samples stamped +/// later than its wall-clock time (a sender stamps before it sends). +fn flush(shards: &[Sender], shared: &Shared) -> ClockReading { let _admission = shared.admission.write().unwrap_or_else(|e| e.into_inner()); - let sent_ms = shared.clock.now_ms(); + let sent = shared.clock.read(); for shard in shards { let _ = shard.send(ShardMessage::Flush); } - sent_ms + sent } /// An ingest shard: routes and appends the samples of its series to its @@ -979,13 +979,13 @@ fn serve_ingest( // An idle stream: when the idle watermark would close a window, the // shards are flushed first and it is taken at that flush, so // samples still queued count before it. - moved = moved || ingestion.idle_closes_at(shared.clock.now_ms()); + moved = moved || ingestion.idle_closes_at(shared.clock.monotonic_ms()); // Before the watermark moves, every shard runs the samples queued to // it, so the windows it closes hold every sample admitted so far // and the raw data they read is every shard's as of then. let mut flushed_at = None; if moved { - let flushed_ms = flush(&shards, shared); + let flush_sent = flush(&shards, shared); let mut flushed = vec![false; shards.len()]; while !flushed.iter().all(|&f| f) { match commands.recv_timeout(TICK) { @@ -1016,16 +1016,16 @@ fn serve_ingest( Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break 'serve, } } - ingestion.advance_clock(flushed_ms); + ingestion.advance_clock(flush_sent.wall_ms); if arrived { - ingestion.sample_arrived(flushed_ms); + ingestion.sample_arrived(flush_sent); } - flushed_at = Some(flushed_ms); + flushed_at = Some(flush_sent); } let newest_ms = newest.iter().flatten().copied().max(); ingestion.advance_newest_sample(newest_ms); - if let Some(flushed_ms) = flushed_at { - ingestion.advance_idle(flushed_ms); + if let Some(flushed) = flushed_at { + ingestion.advance_idle(flushed.monotonic_ms); } // The barriers first, so a window one of them closes is not // counted as closed by wall-clock time. diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 5426a3cdd..52bcd9f8d 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -204,9 +204,9 @@ pub(crate) struct Ingestion { newest_clock_ms: Option, /// The newest event-time barrier a producer declared. barrier_ms: Option, - /// The wall-clock time of the newest flush that ran a sample: a sample - /// last arrived at or before it. - arrived_ms: Option, + /// When the newest flush that ran a sample was sent: a sample last + /// arrived at or before it. + arrived: Option, /// The newest idle watermark ([`Self::advance_idle`]). idle_watermark_ms: Option, /// Groups whose windows the ingest shards build by push: they read no @@ -364,7 +364,7 @@ impl Ingestion { newest_sample_ms: None, newest_clock_ms: None, barrier_ms: None, - arrived_ms: None, + arrived: None, idle_watermark_ms: None, push_groups: Vec::new(), stats: IngestionStats::default(), @@ -484,30 +484,33 @@ impl Ingestion { from_samples.max(self.barrier_ms) } - /// The idle watermark at wall-clock `now_ms`: while no sample arrives, - /// event time is taken to advance with the wall clock, so it is the - /// newest sample time (capped at the flush that ran it) plus the time - /// since a sample last arrived, less the allowed lateness and - /// [`IDLE_GRACE_MS`]. Counted from the newest sample, not from - /// `now_ms`, a stream behind the wall clock (a replay) closes no window - /// earlier than if it kept sending. `None` before the first sample. - fn idle_watermark_at(&self, now_ms: i64) -> Option { - let arrived = self.arrived_ms?; - let newest = self.newest_sample_ms?.min(arrived); + /// The idle watermark at monotonic `now_monotonic_ms`: while no sample + /// arrives, event time is taken to advance with real time, so it is + /// the newest sample time (capped at the wall-clock time of the flush + /// that ran it) plus the time since a sample last arrived, less the + /// allowed lateness and [`IDLE_GRACE_MS`]. That time is measured on the + /// monotonic clock, so a step of the wall clock does not move it. + /// Counted from the newest sample, not from the wall clock, a stream + /// behind the wall clock (a replay) closes no window earlier than if it + /// kept sending. `None` before the first sample. + fn idle_watermark_at(&self, now_monotonic_ms: i64) -> Option { + let arrived = self.arrived?; + let newest = self.newest_sample_ms?.min(arrived.wall_ms); let lateness = millis(self.options.allowed_lateness_ms); Some( newest - .saturating_add(now_ms.saturating_sub(arrived)) + .saturating_add(now_monotonic_ms.saturating_sub(arrived.monotonic_ms)) .saturating_sub(lateness) .saturating_sub(IDLE_GRACE_MS), ) } - /// Whether the idle watermark at `now_ms` would close a window: the - /// coordinator then flushes every shard and moves it at that flush - /// ([`Self::advance_idle`]), so samples still queued count first. - pub(crate) fn idle_closes_at(&self, now_ms: i64) -> bool { - let Some(idle) = self.idle_watermark_at(now_ms) else { + /// Whether the idle watermark at monotonic `now_monotonic_ms` would + /// close a window: the coordinator then flushes every shard and moves it + /// at that flush ([`Self::advance_idle`]), so samples still queued + /// count first. + pub(crate) fn idle_closes_at(&self, now_monotonic_ms: i64) -> bool { + let Some(idle) = self.idle_watermark_at(now_monotonic_ms) else { return false; }; self.groups.iter().any(|group| { @@ -517,17 +520,18 @@ impl Ingestion { }) } - /// Notes that the flush at wall-clock `flushed_ms` ran a sample. - pub(crate) fn sample_arrived(&mut self, flushed_ms: i64) { - self.arrived_ms = self.arrived_ms.max(Some(flushed_ms)); + /// Notes that the flush sent at `flushed` ran a sample. + pub(crate) fn sample_arrived(&mut self, flushed: ClockReading) { + self.arrived = Some(flushed); } - /// Moves the idle watermark to the flush at wall-clock `flushed_ms` - /// (it never goes back); call after the flush's samples are taken in. - pub(crate) fn advance_idle(&mut self, flushed_ms: i64) { + /// Moves the idle watermark to the flush sent at monotonic + /// `flushed_monotonic_ms` (it never goes back); call after the flush's + /// samples are taken in. + pub(crate) fn advance_idle(&mut self, flushed_monotonic_ms: i64) { self.idle_watermark_ms = self .idle_watermark_ms - .max(self.idle_watermark_at(flushed_ms)); + .max(self.idle_watermark_at(flushed_monotonic_ms)); } /// What the ingest shards need to route samples now: the metrics a @@ -1304,12 +1308,26 @@ fn gcd(a: i64, b: i64) -> i64 { } } -/// The wall clock the precompute engine reads: the system clock, or for -/// tests one they set. +/// One reading of both clocks of a [`WallClock`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct ClockReading { + pub wall_ms: i64, + pub monotonic_ms: i64, +} + +/// The clocks the precompute engine reads: the system's wall clock and a +/// monotonic clock (`Instant`), or for tests ones they set. #[derive(Debug, Clone, Default)] -pub struct WallClock(Option>); +pub struct WallClock(Option>); -/// Two clocks are equal when both are the system clock or one manual clock. +/// A test's clocks, in milliseconds. +#[derive(Debug)] +struct ManualClock { + wall_ms: AtomicI64, + monotonic_ms: AtomicI64, +} + +/// Two clocks are equal when both are the system's or one manual clock. impl PartialEq for WallClock { fn eq(&self, other: &Self) -> bool { match (&self.0, &other.0) { @@ -1323,9 +1341,13 @@ impl PartialEq for WallClock { impl Eq for WallClock {} impl WallClock { - /// For tests: a clock at `now_ms` that moves only by [`Self::set`]. + /// For tests: clocks at `now_ms` that move only by [`Self::set`] and + /// [`Self::step_wall_clock`]. pub fn manual(now_ms: i64) -> Self { - Self(Some(Arc::new(AtomicI64::new(now_ms)))) + Self(Some(Arc::new(ManualClock { + wall_ms: AtomicI64::new(now_ms), + monotonic_ms: AtomicI64::new(now_ms), + }))) } /// For tests that replay past event times as fast as they can: the @@ -1335,20 +1357,54 @@ impl WallClock { Self::manual(wall_clock_ms()) } - /// Moves a manual clock to `now_ms`; the system clock ignores it. + /// Moves a manual wall clock to `now_ms`, and its monotonic clock by + /// as much; the system clocks ignore it. pub fn set(&self, now_ms: i64) { if let Some(manual) = &self.0 { - manual.store(now_ms, Ordering::SeqCst); + let before = manual.wall_ms.swap(now_ms, Ordering::SeqCst); + manual + .monotonic_ms + .fetch_add(now_ms - before, Ordering::SeqCst); + } + } + + /// Moves a manual wall clock alone to `now_ms`, as a step of the system + /// clock (NTP, a resumed VM) does; the system clocks ignore it. + pub fn step_wall_clock(&self, now_ms: i64) { + if let Some(manual) = &self.0 { + manual.wall_ms.store(now_ms, Ordering::SeqCst); + } + } + + /// Both clocks now. + pub(crate) fn read(&self) -> ClockReading { + ClockReading { + wall_ms: self.now_ms(), + monotonic_ms: self.monotonic_ms(), } } /// Milliseconds since the Unix epoch. pub fn now_ms(&self) -> i64 { match &self.0 { - Some(manual) => manual.load(Ordering::SeqCst), + Some(manual) => manual.wall_ms.load(Ordering::SeqCst), None => wall_clock_ms(), } } + + /// Milliseconds on a clock that only moves forward, at the rate of real + /// time, whatever steps the wall clock takes: only differences of two + /// readings mean anything. + pub fn monotonic_ms(&self) -> i64 { + match &self.0 { + Some(manual) => manual.monotonic_ms.load(Ordering::SeqCst), + None => { + static START: std::sync::OnceLock = std::sync::OnceLock::new(); + let start = *START.get_or_init(std::time::Instant::now); + i64::try_from(start.elapsed().as_millis()).unwrap_or(i64::MAX) + } + } + } } /// Milliseconds since the Unix epoch.