diff --git a/data_plane/examples/packets_bench.rs b/data_plane/examples/packets_bench.rs index 2640ee211..323533b08 100644 --- a/data_plane/examples/packets_bench.rs +++ b/data_plane/examples/packets_bench.rs @@ -34,9 +34,10 @@ use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use tower::ServiceExt; -/// Event time of the stream's epoch: 2023-11-14, a multiple of 10 s, in +/// Event time of the stream's epoch: 2023-11-14, a whole hour (windows of +/// every width up to an hour end on it), in /// the past (the data plane drops samples from the future). -const EPOCH_MS: i64 = 1_700_000_000_000; +const EPOCH_MS: i64 = 1_699_999_200_000; const REQUEST_MS: i64 = 250; const ROUND_MS: i64 = 10_000; @@ -154,6 +155,8 @@ async fn main() { no_forward: true, ..EngineOptions::default() }; + // Every row from the epoch on is fed: the first windows are complete. + options.ingestion.stream_start_ms = Some(EPOCH_MS); if let Some(threads) = env_usize("INGEST_THREADS") { options.ingest_threads = threads; } @@ -261,60 +264,105 @@ async fn main() { (rows.len() * std::mem::size_of::()) as f64 / 1048576.0, ); - // Rounds, 10 s apart, the last at the barrier. - let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name) - .unwrap() - .remove(0); - let intent = - IntentLoop::new(schedule, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap(); + // Rounds `ROUND_STEP_MS` apart (10 s by default), the last at the + // barrier; the first clock's queries, or every clock's (`ALL_CLOCKS=1`). + let step_ms = std::env::var("ROUND_STEP_MS").map_or(ROUND_MS, |v| v.parse().unwrap()); + let mut schedules = IntentSchedule::per_clock_from_intent_plan(&plan, intent_name).unwrap(); + if std::env::var("ALL_CLOCKS").is_err() { + schedules.truncate(1); + } + let intents: Vec = schedules + .into_iter() + .map(|s| IntentLoop::new(s, BindMode::ParameterSlot, Duration::from_secs(600)).unwrap()) + .collect(); let mut answers = std::env::var("ANSWERS_OUT") .ok() .map(|path| std::fs::File::create(path).unwrap()); + let mut exact_failures = 0; for round in 0..rounds { - let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * ROUND_MS; - let cpu_before = thread_cpu_seconds(); - let record = intent.run_round(&state.engine, round as u64, time_ms).await; - let cpu_after = thread_cpu_seconds(); - let cpu: f64 = cpu_after - .iter() - .map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0)) - .sum(); - let latencies: Vec = record - .queries - .iter() - .map(|q| { - format!( - "{} {:?} {} rows {}", - q.query_id, - q.status, - q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")), - q.answer.len() - ) - }) - .collect(); - println!( - "round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}", - (time_ms - EPOCH_MS) / 1000, - record.duration_ms, - latencies.join("; ") - ); - if let Some(file) = answers.as_mut() { - for q in &record.queries { - let mut rows: Vec = q + let time_ms = EPOCH_MS + feed_ms - (rounds - 1 - round) * step_ms; + for intent in &intents { + let cpu_before = thread_cpu_seconds(); + let record = intent.run_round(&state.engine, round as u64, time_ms).await; + let cpu_after = thread_cpu_seconds(); + let cpu: f64 = cpu_after + .iter() + .map(|(name, after)| after - cpu_before.get(name).copied().unwrap_or(0.0)) + .sum(); + let latencies: Vec = record + .queries + .iter() + .map(|q| { + format!( + "{} {:?} {} rows {}{}", + q.query_id, + q.status, + q.latency_ms.map_or("-".into(), |l| format!("{l:.1} ms")), + q.answer.len(), + q.error + .as_deref() + .map_or(String::new(), |e| format!(" ERROR {e}")) + ) + }) + .collect(); + println!( + "round {round} at +{} s: {:.1} ms, cpu {cpu:.2} s; {}", + (time_ms - EPOCH_MS) / 1000, + record.duration_ms, + latencies.join("; ") + ); + // Exact check of the per-proto byte sums (`proto_`). + for q in record + .queries + .iter() + .filter(|q| q.query_id.starts_with("proto_")) + { + let window_ms = match q.query_id.rsplit('_').next() { + Some("1m") => 60_000, + Some("5m") => 300_000, + Some("1h") => 3_600_000, + _ => continue, + }; + let (start, end) = (time_ms - EPOCH_MS - window_ms, time_ms - EPOCH_MS); + let mut exact: std::collections::BTreeMap = Default::default(); + for p in rows.iter().filter(|p| start < p.ts_ms && p.ts_ms <= end) { + *exact.entry(p.proto.to_string()).or_default() += p.bytes as f64; + } + let got: std::collections::BTreeMap = q .answer .iter() - .map(|r| format!("{:?} {:?}", r.labels, r.value)) + .map(|r| (r.labels.get("proto").cloned().unwrap_or_default(), r.value)) .collect(); - rows.sort(); - let line = serde_json::json!({ - "round": round, "time_ms": time_ms, "query": q.query_id, - "status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings), - "rows": rows, - }); - writeln!(file, "{line}").unwrap(); + if got != exact { + exact_failures += 1; + println!( + " EXACT MISMATCH {} at +{} s: got {got:?} exact {exact:?}", + q.query_id, + end / 1000 + ); + } else { + println!(" exact ok {} at +{} s", q.query_id, end / 1000); + } + } + if let Some(file) = answers.as_mut() { + for q in &record.queries { + let mut rows: Vec = q + .answer + .iter() + .map(|r| format!("{:?} {:?}", r.labels, r.value)) + .collect(); + rows.sort(); + let line = serde_json::json!({ + "round": round, "time_ms": time_ms, "query": q.query_id, + "status": format!("{:?}", q.status), "bindings": format!("{:?}", q.bindings), + "rows": rows, + }); + writeln!(file, "{line}").unwrap(); + } } } } + println!("exact mismatches: {exact_failures}"); let (peak_mib, _) = rss_mib(); println!("RSS peak after rounds {peak_mib:.0} MiB"); state.engine.stop(); diff --git a/data_plane/src/engine.rs b/data_plane/src/engine.rs index eaddf5049..d9a27e136 100644 --- a/data_plane/src/engine.rs +++ b/data_plane/src/engine.rs @@ -721,7 +721,7 @@ impl EngineHandle { pub async fn evaluate(&self, query: String, time_ms: i64) -> Result { let started = std::time::Instant::now(); let metrics = self.shared.metrics.query(&query); - let answer = self.run_on_worker(query, time_ms, None, None).await; + let answer = self.run_on_worker(query, time_ms, None, false, None).await; if let Some(metrics) = metrics { metrics.latency.observe(started.elapsed().as_secs_f64()); } @@ -737,7 +737,55 @@ impl EngineHandle { time_ms: i64, slots: Vec, ) -> Result { - self.run_on_worker(query, time_ms, None, Some(slots)).await + self.run_on_worker(query, time_ms, None, false, Some(slots)) + .await + } + + /// [`Self::evaluate`] (with `slots`: [`Self::evaluate_bound`]) over + /// `snapshot`, which every query of an intent round reads. + pub async fn evaluate_in( + &self, + query: String, + time_ms: i64, + snapshot: Arc, + slots: Option>, + ) -> Result { + self.run_on_worker(query, time_ms, Some(snapshot), false, slots) + .await + } + + /// The store an intent round at `time_ms` reads, pinned once for all + /// its queries: a query that runs late in a slow round reads the + /// samples and windows that were kept when the round started, not a + /// store already evicted past its window's start. With `max_wait`, + /// first waits (at most that long) until every sample at or before + /// `time_ms` has arrived (the watermark has passed it) and every window + /// ending by then is refreshed, so a round never answers from data its + /// producer has not delivered yet. Returns the snapshot and how long it + /// waited. + pub async fn pin_round_snapshot( + &self, + time_ms: i64, + max_wait: std::time::Duration, + ) -> (Arc, std::time::Duration) { + let started = std::time::Instant::now(); + if !max_wait.is_zero() { + let deadline = tokio::time::Instant::now() + max_wait; + let mut arrived = false; + while tokio::time::Instant::now() < deadline { + if self.shared.published.watermark_ms() >= Some(time_ms) { + arrived = true; + break; + } + tokio::time::sleep(std::time::Duration::from_millis(20)).await; + } + // The watermark has closed every window ending by `time_ms`; + // the barrier only waits for their refreshes to commit. + if arrived { + let _ = tokio::time::timeout_at(deadline, self.advance_watermark(time_ms)).await; + } + } + (self.snapshot(), started.elapsed()) } /// Evaluates one step of a range query over `snapshot`, which every @@ -751,7 +799,7 @@ impl EngineHandle { time_ms: i64, snapshot: Arc, ) -> Result { - self.run_on_worker(query, time_ms, Some(snapshot), None) + self.run_on_worker(query, time_ms, Some(snapshot), true, None) .await } @@ -770,7 +818,8 @@ impl EngineHandle { &self, query: String, time_ms: i64, - range_step: Option>, + snapshot: Option>, + range_step: bool, bound: Option>, ) -> Result { let stopped = || Unanswered::Execution("the query workers have stopped".into()); @@ -779,6 +828,7 @@ impl EngineHandle { .send(QueryJob { query, time_ms, + snapshot, range_step, bound, reply, @@ -935,8 +985,11 @@ fn admit(queued: u64, count: u64, max_queued: u64) -> Result { struct QueryJob { query: String, time_ms: i64, - /// One step of a range query, and the snapshot every step reads. - range_step: Option>, + /// The snapshot the run reads (every step of a range query, every + /// query of an intent round); `None`: the newest when the run starts. + snapshot: Option>, + /// One step of a range query (for the metrics). + range_step: bool, /// An intent query's holes bound to these values /// ([`QueryEngine::evaluate_bound`]); `None`: as planned. bound: Option>, @@ -986,7 +1039,7 @@ fn spawn_query_workers( // A bug in one run must not take the worker down: it // answers that run with the error and keeps serving. let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - let snapshot = match &job.range_step { + let snapshot = match &job.snapshot { Some(snapshot) => snapshot.clone(), None => Arc::new(query.snapshot(&shared.published)), }; @@ -1008,8 +1061,8 @@ fn spawn_query_workers( }); if let Some(metrics) = shared.metrics.query(&job.query) { match job.range_step { - None => metrics.run.record(timer), - Some(_) => metrics.range_step_run.record(timer), + false => metrics.run.record(timer), + true => metrics.range_step_run.record(timer), }; } let _ = job.reply.send(answer); diff --git a/data_plane/src/intent.rs b/data_plane/src/intent.rs index 73cc98da3..87dc03872 100644 --- a/data_plane/src/intent.rs +++ b/data_plane/src/intent.rs @@ -152,8 +152,43 @@ pub trait QueryRunner: Sync { time_ms: i64, slots: &[SlotBinding], ) -> impl Future> + Send; + + /// The store every query of a round at `time_ms` reads, pinned when the + /// round starts (after waiting at most `max_wait` for its data), and how + /// long it waited; `None`: each query reads the newest store. + fn pin_round( + &self, + _time_ms: i64, + _max_wait: Duration, + ) -> impl Future, Duration)> + Send { + async { (None, Duration::ZERO) } + } + + /// [`Self::answer`] over the round's pinned store. + fn answer_in( + &self, + _pinned: Option<&RoundSnapshot>, + query: &str, + time_ms: i64, + ) -> impl Future> + Send { + self.answer(query, time_ms) + } + + /// [`Self::answer_bound`] over the round's pinned store. + fn answer_bound_in( + &self, + _pinned: Option<&RoundSnapshot>, + query: &str, + time_ms: i64, + slots: &[SlotBinding], + ) -> impl Future> + Send { + self.answer_bound(query, time_ms, slots) + } } +/// The store snapshot every query of one round reads. +pub type RoundSnapshot = std::sync::Arc; + /// A variable's values in one round, deduplicated and sorted. pub type Bindings = BTreeMap>; @@ -165,6 +200,9 @@ pub struct IntentLoop { order: Vec, mode: BindMode, query_timeout: Duration, + /// How long a round waits for its data before its queries run + /// ([`QueryRunner::pin_round`]). + data_wait: Duration, } /// What happened to one query in one round. @@ -237,6 +275,10 @@ pub struct RoundRecord { /// How long after its scheduled start it started. pub start_lag_ms: f64, pub duration_ms: f64, + /// How long the round waited for its data before its queries ran + /// (included in `duration_ms`). + #[serde(default)] + pub data_wait_ms: f64, /// It ended after the next round's scheduled start. pub overrun: bool, pub queries: Vec, @@ -545,6 +587,7 @@ impl IntentLoop { order, mode, query_timeout, + data_wait: Duration::ZERO, }) } @@ -556,7 +599,21 @@ impl IntentLoop { .collect() } - /// Runs round `round` at evaluation time `time_ms`. + /// A round first waits at most `data_wait` until every sample at or + /// before its evaluation time has arrived and the windows ending by + /// then are refreshed (0: it does not wait). + pub fn with_data_wait(mut self, data_wait: Duration) -> Self { + self.data_wait = data_wait; + self + } + + /// The round interval of this loop's clock. + pub fn round_interval_ms(&self) -> u64 { + self.schedule.round_interval_ms + } + + /// Runs round `round` at evaluation time `time_ms`: every query reads + /// one store pinned when the round starts. pub async fn run_round( &self, runner: &R, @@ -564,6 +621,7 @@ impl IntentLoop { time_ms: i64, ) -> RoundRecord { let round_start = Instant::now(); + let (pinned, waited) = runner.pin_round(time_ms, self.data_wait).await; let queries = &self.schedule.queries; // Per query: its answer when it was answered, and when its run // ended (group latency runs from the round's start to it). @@ -613,7 +671,14 @@ impl IntentLoop { let started = Instant::now(); let result = tokio::time::timeout( self.query_timeout, - bind_and_run(self.mode, runner, query, &record.bindings, time_ms), + bind_and_run( + self.mode, + runner, + pinned.as_ref(), + query, + &record.bindings, + time_ms, + ), ) .await; let ended = Instant::now(); @@ -688,6 +753,7 @@ impl IntentLoop { status: RoundStatus::Ran, start_lag_ms: 0.0, duration_ms: millis(round_start.elapsed()), + data_wait_ms: millis(waited), overrun: false, queries: records.into_iter().flatten().collect(), groups, @@ -707,6 +773,13 @@ impl IntentLoop { mut emit: impl FnMut(RoundRecord), ) { let interval_ms = self.schedule.round_interval_ms; + // Each clock evaluates on multiples of its interval, as the plan's + // windows are cut (a 5-minute clock's 1-minute chain windows tile + // only ranges ending on a minute): the first such time at or after + // `first_evaluation_ms`, started that much later. + let aligned_ms = aligned_evaluation_ms(first_evaluation_ms, interval_ms); + let start = start + Duration::from_millis((aligned_ms - first_evaluation_ms) as u64); + let first_evaluation_ms = aligned_ms; let scheduled = |round: u64| start + Duration::from_millis(interval_ms * round); let mut round = 0; while round < rounds { @@ -728,6 +801,7 @@ impl IntentLoop { status: RoundStatus::Missed, start_lag_ms: 0.0, duration_ms: 0.0, + data_wait_ms: 0.0, overrun: false, queries: vec![], groups: vec![], @@ -739,23 +813,35 @@ impl IntentLoop { } } +/// The first multiple of `interval_ms` at or after `time_ms`. +pub fn aligned_evaluation_ms(time_ms: i64, interval_ms: u64) -> i64 { + let interval = interval_ms.max(1) as i64; + time_ms.div_euclid(interval) * interval + + if time_ms.rem_euclid(interval) == 0 { + 0 + } else { + interval + } +} + /// The binding step: `query`'s answer at `time_ms` for `bindings`, in /// `mode`. A query that reads no variable runs as planned in either mode. async fn bind_and_run( mode: BindMode, runner: &R, + pinned: Option<&RoundSnapshot>, query: &IntentQuery, bindings: &Bindings, time_ms: i64, ) -> Result, String> { if query.bind_slots.is_empty() { - let answer = runner.answer(&query.query, time_ms).await; + let answer = runner.answer_in(pinned, &query.query, time_ms).await; return answer.map(|a| a.to_vec()).map_err(|e| e.to_string()); } match mode { BindMode::FilterGroupedResult => { let grouped = runner - .answer(&query.query, time_ms) + .answer_in(pinned, &query.query, time_ms) .await .map_err(|e| e.to_string())?; Ok(filter_by_bindings(&grouped, &query.bind_slots, bindings)) @@ -778,7 +864,9 @@ async fn bind_and_run( }) }) .collect::, String>>()?; - let answer = runner.answer_bound(&query.query, time_ms, &slots).await; + let answer = runner + .answer_bound_in(pinned, &query.query, time_ms, &slots) + .await; answer.map(|a| a.to_vec()).map_err(|e| e.to_string()) } } @@ -805,6 +893,57 @@ impl QueryRunner for crate::engine::EngineHandle { self.evaluate_bound(query.to_string(), time_ms, slots.to_vec()) .await } + + async fn pin_round( + &self, + time_ms: i64, + max_wait: Duration, + ) -> (Option, Duration) { + let (snapshot, waited) = self.pin_round_snapshot(time_ms, max_wait).await; + (Some(snapshot), waited) + } + + async fn answer_in( + &self, + pinned: Option<&RoundSnapshot>, + query: &str, + time_ms: i64, + ) -> Result { + if let Some(answer) = self.cached(query, time_ms) { + return Ok(answer); + } + match pinned { + Some(snapshot) => { + self.evaluate_in(query.to_string(), time_ms, snapshot.clone(), None) + .await + } + None => self.evaluate(query.to_string(), time_ms).await, + } + } + + async fn answer_bound_in( + &self, + pinned: Option<&RoundSnapshot>, + query: &str, + time_ms: i64, + slots: &[SlotBinding], + ) -> Result { + match pinned { + Some(snapshot) => { + self.evaluate_in( + query.to_string(), + time_ms, + snapshot.clone(), + Some(slots.to_vec()), + ) + .await + } + None => { + self.evaluate_bound(query.to_string(), time_ms, slots.to_vec()) + .await + } + } + } } /// The name of the column at `position` of query `query_index`'s root @@ -1538,6 +1677,45 @@ mod tests { assert_eq!(round.round_interval_ms, 1_000); } + /// A clock evaluates on multiples of its interval (the plan's windows + /// are cut on them): the first at or after the first evaluation time, + /// started that much later; an aligned first time is kept. + #[tokio::test(start_paused = true)] + async fn each_clock_evaluates_on_multiples_of_its_interval() { + assert_eq!( + aligned_evaluation_ms(1_796_337_270_000, 300_000), + 1_796_337_300_000 + ); + assert_eq!( + aligned_evaluation_ms(1_796_337_300_000, 300_000), + 1_796_337_300_000 + ); + assert_eq!(aligned_evaluation_ms(-5, 10), 0); + let runner = FakeRunner::default().with("q1", &[(&[("host", "a")], 1.0)]); + let mut five_minutes = schedule(vec![query("q1", &[], &[])]); + five_minutes.round_interval_ms = 300_000; + let intent = IntentLoop::new( + five_minutes, + BindMode::FilterGroupedResult, + Duration::from_secs(1), + ) + .unwrap(); + let start = Instant::now(); + let mut rounds = Vec::new(); + intent + .run_rounds(&runner, 3_670_000, 2, start, |r| { + rounds.push((r.evaluation_ms, Instant::now() - start)) + }) + .await; + assert_eq!( + rounds, + vec![ + (3_900_000, Duration::from_secs(230)), + (4_200_000, Duration::from_secs(530)), + ] + ); + } + /// B7: every clock covers the span of the fastest clock's rounds. #[test] fn rounds_per_clock_cover_the_same_span() { @@ -1578,8 +1756,9 @@ mod tests { let mut expected: Vec<(u64, u64, i64, String)> = (0..6) .map(|r| (1_000, r, 10_000 + 1_000 * r as i64, "q1".to_string())) .collect(); - expected.push((3_000, 0, 10_000, "q3".into())); - expected.push((3_000, 1, 13_000, "q3".into())); + // The 3 s clock evaluates on multiples of 3 s. + expected.push((3_000, 0, 12_000, "q3".into())); + expected.push((3_000, 1, 15_000, "q3".into())); expected.sort(); assert_eq!(seen, expected); } diff --git a/data_plane/src/main.rs b/data_plane/src/main.rs index 73e3f40a6..29a28f3bf 100644 --- a/data_plane/src/main.rs +++ b/data_plane/src/main.rs @@ -210,6 +210,11 @@ struct Args { /// The longest one intent query may run before it fails as timed out. #[arg(long, default_value_t = 30_000)] intent_query_timeout_ms: u64, + /// The longest a round waits, before its queries run, for every sample + /// at or before its evaluation time to arrive (the watermark to pass + /// it) and the windows ending by then to be refreshed; 0: no wait. + #[arg(long, default_value_t = 30_000)] + intent_data_wait_ms: u64, /// How bound values reach a downstream query: `parameter-slot` (the /// planner's placeholders replaced in the plan) or the fallback /// `filter-grouped-result` (a grouped answer filtered by the values). @@ -302,6 +307,9 @@ async fn main() -> anyhow::Result<()> { args.intent_bind_mode, Duration::from_millis(args.intent_query_timeout_ms), ) + .map(|intent| { + intent.with_data_wait(Duration::from_millis(args.intent_data_wait_ms)) + }) }) .collect::>>()?; let first_evaluation_ms = args diff --git a/data_plane/tests/intent_sil_modes.rs b/data_plane/tests/intent_sil_modes.rs index bbbba0166..1bed6e197 100644 --- a/data_plane/tests/intent_sil_modes.rs +++ b/data_plane/tests/intent_sil_modes.rs @@ -239,6 +239,15 @@ async fn install_options( .unwrap(), ); let app = router(state.clone()); + write_rows(&state, &app, tables).await; + common::barrier(&app, EVALUATION_MS).await; + state +} + +/// Writes `tables`' rows by Remote Write (each row a sample of the series +/// `{__name__=table, host, user}`), in time order, and waits until the +/// ingest shards have taken them. +async fn write_rows(state: &DataPlane, app: &axum::Router, tables: &BTreeMap<&str, Vec>) { let mut by_time: BTreeMap> = BTreeMap::new(); for (table, rows) in tables { for row in rows { @@ -263,7 +272,7 @@ async fn install_options( } } for timeseries in by_time.into_values() { - common::remote_write(&app, timeseries).await; + common::remote_write(app, timeseries).await; } for _ in 0..1000 { if state.engine.queued_samples() == 0 { @@ -271,8 +280,6 @@ async fn install_options( } tokio::time::sleep(Duration::from_millis(10)).await; } - common::barrier(&app, EVALUATION_MS).await; - state } /// In each planning mode: two rounds, each query's answer exact, q2's and @@ -611,3 +618,141 @@ async fn keyed_table_answers_equal_the_label_layout_and_exact() { } } } + +/// A data plane installing `plan` with nothing written yet. +fn empty_install(plan: &IntentPlan) -> (Arc, axum::Router) { + let state = Arc::new( + DataPlane::with_options( + serde_json::to_string(&plan.plan).unwrap(), + "http://127.0.0.1:1".into(), + EngineOptions { + no_forward: true, + ..EngineOptions::default() + }, + ) + .unwrap(), + ); + let app = router(state.clone()); + (state, app) +} + +/// Late data: a round at T whose last 30 s of rows arrive after the round +/// started. Without waiting, q1 answers from the rows delivered so far +/// (a partial window: not the exact answer); with a data wait, the round +/// waits until the watermark passes T and the windows ending by then are +/// refreshed, then answers exactly (and records the wait). +#[tokio::test(flavor = "multi_thread")] +async fn a_round_waits_for_its_late_data_and_answers_exactly() { + let all = tables(); + let exact = exact_q1(&all, EVALUATION_MS); + let (early, late): (Vec, Vec) = all["flows"] + .iter() + .cloned() + .partition(|r| r.ts <= EVALUATION_MS - 30_000); + let q1_of = |round: &RoundRecord| -> BTreeMap { + rows_of(round, "q1") + .into_iter() + .map(|(labels, value)| (labels["host"].clone(), value)) + .collect() + }; + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentFull, + ] { + let plan = planned(mode).await; + let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, "triage") + .unwrap() + .remove(0); + for wait in [false, true] { + let what = format!("{mode:?}, wait {wait}"); + let (state, app) = empty_install(&plan); + write_rows(&state, &app, &BTreeMap::from([("flows", early.clone())])).await; + let intent = IntentLoop::new( + schedule.clone(), + BindMode::ParameterSlot, + Duration::from_secs(30), + ) + .unwrap() + .with_data_wait(Duration::from_secs(if wait { 20 } else { 0 })); + let engine = state.clone(); + let round = + tokio::spawn( + async move { intent.run_round(&engine.engine, 0, EVALUATION_MS).await }, + ); + tokio::time::sleep(Duration::from_millis(300)).await; + write_rows(&state, &app, &BTreeMap::from([("flows", late.clone())])).await; + common::barrier(&app, EVALUATION_MS).await; + let round = round.await.unwrap(); + if wait { + assert_eq!(q1_of(&round), exact, "{what}"); + assert!( + round.data_wait_ms >= 250.0, + "{what}: waited {}", + round.data_wait_ms + ); + } else { + let answered = round.queries[0].status == QueryStatus::Answered; + assert!( + !answered || q1_of(&round) != exact, + "{what}: answered exactly from data not yet delivered?" + ); + } + state.engine.stop(); + } + } +} + +/// A round's queries read the store pinned when the round started: after +/// ingestion moved three hours ahead (evicting the raw samples and +/// windows of T's window), q1 at T no longer answers from the newest store, +/// but does, exactly, from the snapshot pinned before. +#[tokio::test(flavor = "multi_thread")] +async fn a_round_reads_the_store_pinned_when_it_started() { + let all = tables(); + let exact = exact_q1(&all, EVALUATION_MS); + for mode in [ + IntentPlanningMode::QueryAtATime, + IntentPlanningMode::IntentFull, + ] { + let what = format!("{mode:?}"); + let plan = planned(mode).await; + let schedule = IntentSchedule::per_clock_from_intent_plan(&plan, "triage") + .unwrap() + .remove(0); + let q1_text = schedule.queries[0].query.clone(); + let state = install(&plan, &all).await; + let app = router(state.clone()); + let (pinned, _) = state + .engine + .pin_round_snapshot(EVALUATION_MS, Duration::ZERO) + .await; + // Three hours later: rows of one host, then the barrier. + let later = EVALUATION_MS + 3 * 3_600_000; + let ahead: Vec = (0..30) + .map(|i| Row { + host: "h0".into(), + user: "u0".into(), + ts: later - 290_000 + i * 10_000, + value: 1.0, + }) + .collect(); + write_rows(&state, &app, &BTreeMap::from([("flows", ahead)])).await; + common::barrier(&app, later).await; + let newest = state.engine.evaluate(q1_text.clone(), EVALUATION_MS).await; + assert!( + newest.is_err(), + "{what}: the newest store still holds T's window: {newest:?}" + ); + let answer = state + .engine + .evaluate_in(q1_text, EVALUATION_MS, pinned, None) + .await + .unwrap_or_else(|e| panic!("{what}: {e}")); + let got: BTreeMap = answer + .iter() + .map(|s| (s.labels["host"].clone(), s.value)) + .collect(); + assert_eq!(got, exact, "{what}"); + state.engine.stop(); + } +}