From 47525c6c22c6bcb475afd6b847d2e72db95c81a7 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 10:35:16 +0000 Subject: [PATCH 1/5] refactor: move ingestion, push, query and result_cache into their crates git mv only, so history follows each file; the next commit makes the crates build. --- crates/{data-plane => precompute}/src/ingestion.rs | 0 crates/{data-plane => precompute}/src/push.rs | 0 crates/{data-plane/src/query.rs => query/src/lib.rs} | 0 crates/{data-plane => query}/src/result_cache.rs | 0 4 files changed, 0 insertions(+), 0 deletions(-) rename crates/{data-plane => precompute}/src/ingestion.rs (100%) rename crates/{data-plane => precompute}/src/push.rs (100%) rename crates/{data-plane/src/query.rs => query/src/lib.rs} (100%) rename crates/{data-plane => query}/src/result_cache.rs (100%) diff --git a/crates/data-plane/src/ingestion.rs b/crates/precompute/src/ingestion.rs similarity index 100% rename from crates/data-plane/src/ingestion.rs rename to crates/precompute/src/ingestion.rs diff --git a/crates/data-plane/src/push.rs b/crates/precompute/src/push.rs similarity index 100% rename from crates/data-plane/src/push.rs rename to crates/precompute/src/push.rs diff --git a/crates/data-plane/src/query.rs b/crates/query/src/lib.rs similarity index 100% rename from crates/data-plane/src/query.rs rename to crates/query/src/lib.rs diff --git a/crates/data-plane/src/result_cache.rs b/crates/query/src/result_cache.rs similarity index 100% rename from crates/data-plane/src/result_cache.rs rename to crates/query/src/result_cache.rs From 867661f37afc1fb9b1d4c6910eadefbc03f896f1 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 10:44:43 +0000 Subject: [PATCH 2/5] refactor: split engine.rs into the precompute and query crates The ingest shards, the ingest coordinator, the precompute pool and the committer move to precompute::engine; the query-N workers to query::workers; the persist-N threads to storage::persist_pool. The data plane's engine keeps EngineOptions, install and EngineHandle, which wires the two engines to one published store. --- Cargo.lock | 36 + Cargo.toml | 5 + benchmarks/micro/ingest_bench.rs | 11 +- benchmarks/micro/matrix_bench.rs | 2 +- benchmarks/micro/offset_bench.rs | 2 +- benchmarks/micro/range_bench.rs | 2 +- benchmarks/micro/tier_bench.rs | 2 +- crates/data-plane/Cargo.toml | 2 + crates/data-plane/src/engine.rs | 2444 +---------------- crates/data-plane/src/lib.rs | 11 +- crates/data-plane/src/main.rs | 11 +- crates/data-plane/src/metrics_endpoint.rs | 6 +- crates/data-plane/src/prometheus.rs | 10 +- crates/data-plane/tests/common/mod.rs | 2 +- crates/data-plane/tests/forward_mode.rs | 2 +- crates/data-plane/tests/ingest_shards.rs | 12 +- crates/data-plane/tests/pipelines/mod.rs | 2 +- .../tests/planner_executor_parity.rs | 5 +- crates/data-plane/tests/precompute_pool.rs | 5 +- crates/data-plane/tests/push_precompute.rs | 9 +- crates/data-plane/tests/range_isolation.rs | 2 +- crates/data-plane/tests/range_queries.rs | 2 +- crates/data-plane/tests/time_params.rs | 2 +- .../data-plane/tests/view_cold_allocations.rs | 2 +- crates/data-plane/tests/view_tiering.rs | 2 +- crates/precompute/Cargo.toml | 24 + crates/precompute/src/engine.rs | 2058 ++++++++++++++ crates/precompute/src/ingestion.rs | 10 +- crates/precompute/src/lib.rs | 7 + crates/query/Cargo.toml | 18 + crates/query/src/lib.rs | 14 +- crates/query/src/result_cache.rs | 4 +- crates/query/src/workers.rs | 195 ++ crates/storage/src/lib.rs | 6 +- crates/storage/src/persist_pool.rs | 308 +++ 35 files changed, 2835 insertions(+), 2400 deletions(-) create mode 100644 crates/precompute/Cargo.toml create mode 100644 crates/precompute/src/engine.rs create mode 100644 crates/precompute/src/lib.rs create mode 100644 crates/query/Cargo.toml create mode 100644 crates/query/src/workers.rs create mode 100644 crates/storage/src/persist_pool.rs diff --git a/Cargo.lock b/Cargo.lock index 4db60f4ce..73f96f7a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -975,7 +975,9 @@ dependencies = [ "http-body-util", "internal_metrics", "libc", + "precompute", "prost", + "query", "reqwest", "ryu", "serde", @@ -2830,6 +2832,24 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "precompute" +version = "0.1.0" +dependencies = [ + "anyhow", + "asap-executor", + "clap", + "control_plane", + "futures", + "internal_metrics", + "serde", + "serde_json", + "storage", + "thiserror 1.0.69", + "tokio", + "tracing", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -2895,6 +2915,22 @@ dependencies = [ "cc", ] +[[package]] +name = "query" +version = "0.1.0" +dependencies = [ + "anyhow", + "asap-executor", + "common", + "futures", + "internal_metrics", + "serde_json", + "storage", + "thiserror 1.0.69", + "tokio", + "tracing", +] + [[package]] name = "quinn" version = "0.11.11" diff --git a/Cargo.toml b/Cargo.toml index daff37847..b4abd52a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,6 +5,8 @@ members = [ "crates/control-plane", "crates/data-plane", "crates/internal-metrics", + "crates/precompute", + "crates/query", "crates/storage", ] @@ -39,7 +41,10 @@ tokio = { version = "1.0", features = ["full"] } axum = "0.7" reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } control_plane = { path = "crates/control-plane" } +common = { path = "crates/common" } internal_metrics = { path = "crates/internal-metrics" } +precompute = { path = "crates/precompute" } +query = { path = "crates/query" } storage = { path = "crates/storage" } # asap_sketchlib#271's head, ahead of the Planner's pin (389530c): DDSketch diff --git a/benchmarks/micro/ingest_bench.rs b/benchmarks/micro/ingest_bench.rs index 18f07e66e..9a7021f0f 100644 --- a/benchmarks/micro/ingest_bench.rs +++ b/benchmarks/micro/ingest_bench.rs @@ -42,11 +42,12 @@ use std::time::Instant; use axum::body::Body; use axum::http::{Request, StatusCode}; use control_plane::{plan_workload, DeploymentInputs}; -use data_plane::engine::{EngineOptions, PrecomputeMode}; -use data_plane::ingestion::IngestionOptions; +use data_plane::engine::EngineOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use internal_metrics::thread_cpu_seconds; +use precompute::engine::PrecomputeMode; +use precompute::ingestion::IngestionOptions; use tower::ServiceExt; #[tokio::main(flavor = "multi_thread")] @@ -125,13 +126,13 @@ async fn main() { .map_or(EngineOptions::default().ingest_threads, |n| { n.parse().unwrap() }), - push_batching: data_plane::push::MorselBatching { + push_batching: precompute::push::MorselBatching { max_samples: std::env::var("PUSH_BATCH_SAMPLES").map_or( - data_plane::push::MorselBatching::default().max_samples, + precompute::push::MorselBatching::default().max_samples, |n| n.parse().unwrap(), ), max_age_ms: std::env::var("PUSH_BATCH_MAX_MS").map_or( - data_plane::push::MorselBatching::default().max_age_ms, + precompute::push::MorselBatching::default().max_age_ms, |n| n.parse().unwrap(), ), }, diff --git a/benchmarks/micro/matrix_bench.rs b/benchmarks/micro/matrix_bench.rs index 239009a5d..5bac5e637 100644 --- a/benchmarks/micro/matrix_bench.rs +++ b/benchmarks/micro/matrix_bench.rs @@ -9,7 +9,7 @@ use std::sync::Arc; use std::time::Instant; use data_plane::prometheus::range_response_body; -use data_plane::query::ResultSample; +use query::ResultSample; fn main() { let args: Vec = std::env::args() diff --git a/benchmarks/micro/offset_bench.rs b/benchmarks/micro/offset_bench.rs index 422ac6845..91ea7924a 100644 --- a/benchmarks/micro/offset_bench.rs +++ b/benchmarks/micro/offset_bench.rs @@ -17,10 +17,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::json; use tower::ServiceExt; diff --git a/benchmarks/micro/range_bench.rs b/benchmarks/micro/range_bench.rs index d8bb74da7..03a137ba1 100644 --- a/benchmarks/micro/range_bench.rs +++ b/benchmarks/micro/range_bench.rs @@ -25,11 +25,11 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; use internal_metrics::thread_cpu_seconds; +use precompute::ingestion::IngestionOptions; use tower::ServiceExt; const STEP_MS: i64 = 15_000; diff --git a/benchmarks/micro/tier_bench.rs b/benchmarks/micro/tier_bench.rs index c5711a45d..0d974e0ba 100644 --- a/benchmarks/micro/tier_bench.rs +++ b/benchmarks/micro/tier_bench.rs @@ -38,10 +38,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use storage::persist::ViewRead; use tower::ServiceExt; diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 5f78c885b..6bd90015c 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -7,6 +7,8 @@ edition.workspace = true asap-planner.workspace = true asap-executor.workspace = true internal_metrics.workspace = true +precompute.workspace = true +query.workspace = true storage.workspace = true ahash = "0.8" # The per-thread series cache of the Remote Write decoder (a table of diff --git a/crates/data-plane/src/engine.rs b/crates/data-plane/src/engine.rs index 113137131..bf8c5b25f 100644 --- a/crates/data-plane/src/engine.rs +++ b/crates/data-plane/src/engine.rs @@ -1,78 +1,27 @@ //! The engine: the installed plan, compiled once when it is installed, -//! and the threads that execute it: -//! -//! - `ingest-N` shards each route the samples of the series hashed to them -//! (Remote Write is decoded on the HTTP side) and append them to their -//! own copy of the raw data, and seal and evict it when told; -//! - the `ingest` coordinator keeps the watermark over the shards, closes -//! the windows it passes, publishes the raw data and hands each closed -//! refresh window, with the raw data as it was when the window closed, -//! to the precompute pool; -//! - the precompute pool: `precompute-N` workers compute closed windows in -//! parallel (a group starts a window only after the windows of the -//! groups it reads are committed, [`RefreshTaskGraph`]), and the -//! `precompute` committer appends each group's windows' rows in window -//! order to its copy of the views and publishes them; -//! - `persist-N` threads write each refreshed window to the view files, -//! after it is published; -//! - `query-N` workers each run one query to completion over the newest -//! published snapshot, so a query never waits for ingestion. A run's -//! output stream is not `Send`, so a run never moves between threads. -//! -//! Windows closed and not yet refreshed (the precompute backlog) are -//! bounded by `max_precompute_backlog`: when it is full, the ingest -//! coordinator waits, the shards' queues fill and Remote Write gets 503 -//! (`max_queued_samples`). -//! -//! Each thread records the thread CPU and wall time of its phases in -//! [`Metrics`], exported on `/metrics`. +//! and the precompute and query engines that execute it +//! ([`precompute::engine`], [`query::workers`]), wired to one published +//! store. -use std::collections::{BTreeMap, BTreeSet, VecDeque}; -use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; -use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; -use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock}; -use std::time::Instant; +use std::sync::Arc; use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; use asap_executor::runtime::Limits; -use asap_executor::values::Batch; use asap_planner::InstallablePlan; -use internal_metrics::{Metrics, PushMetrics, Timer}; -use storage::memory_budget::serve_view_cache; -use storage::persist::{plan_hash, ViewFiles, ViewRead}; -use storage::store::{ - PublishedStore, QueryTimeResults, RawData, RawSample, RawShards, RunStore, SeriesPartition, - ViewStore, ViewTier, WindowSlot, +use internal_metrics::Metrics; +use precompute::engine::{ + IngestError, PersistedViews, PrecomputeEngine, PrecomputeMode, PrecomputeOptions, SlowRefresh, }; +use precompute::ingestion::{Ingestion, IngestionOptions, IngestionStats, Precompute}; +use query::result_cache::{Answer, ResultCache}; +use query::workers::QueryWorkers; +use query::{QueryEngine, Snapshot, Unanswered}; +use storage::persist::{plan_hash, ViewRead}; +use storage::persist_pool::PersistOptions; +use storage::store::{PublishedStore, QueryTimeResults, RawSample, ViewTier}; use storage::window_cache::WindowCache; -use tokio::sync::oneshot; -use crate::ingestion::{ - ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, - RefreshTaskGraph, Refreshed, Routing, -}; use crate::metrics_endpoint::Gauges; -use crate::push::{Partial, PushGroup, PushShard}; -use crate::query::{QueryEngine, Snapshot, Unanswered}; -use crate::result_cache::{Answer, ResultCache}; - -/// How the views of a closed refresh window are built -/// (docs/design/parallel-precompute.md). The `data_plane` binary defaults -/// to `Push`, the faster mode for a running server. The library default -/// stays `Window`: it is the reference path every push test compares -/// against, so tests and other callers get it unless they ask for push. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)] -pub enum PrecomputeMode { - /// One ingestion run per closed window, over the raw samples the - /// shards buffered for it (`--precompute-mode=window`). - #[default] - Window, - /// Each ingest shard folds its samples into its own instance of each - /// window's pipelines as they arrive; at close the shards' partials are - /// combined and committed. Groups that cannot be pushed keep the - /// window path. - Push, -} /// How the engine ingests samples and runs queries. #[derive(Debug, Clone, PartialEq, Eq)] @@ -138,7 +87,7 @@ pub struct EngineOptions { /// first. pub query_time_results_max_bytes: usize, /// Keep each planned query's final answer at each evaluation time - /// ([`crate::result_cache`]), so a range request recomputes only the + /// ([`query::result_cache`]), so a range request recomputes only the /// steps not answered before. pub result_cache: bool, /// The most bytes of answers the result cache keeps; the least @@ -176,7 +125,7 @@ pub struct EngineOptions { pub precompute_mode: PrecomputeMode, /// Push mode: how each shard coalesces samples into morsels before /// folding them. - pub push_batching: crate::push::MorselBatching, + pub push_batching: precompute::push::MorselBatching, /// Push mode: bytes of open-window state all shards may hold together. /// Over it, nothing waits: while some group has an older window open /// (whose seal will free memory) the state is kept; otherwise a shard @@ -229,510 +178,98 @@ impl Default for EngineOptions { unpersistable_views: Vec::new(), precompute_mode: PrecomputeMode::Window, precompute_memory_budget_bytes: None, - push_batching: crate::push::MorselBatching::default(), + push_batching: precompute::push::MorselBatching::default(), panic_in_combine_of_window_end_ms: None, } } } -/// For tests: the windows of refresh group `group` (any group if -/// `None`) ending at `end_ms` (any end if `None`) wait `delay_ms` before -/// they are computed; of a window split by series, only part `part` (every -/// part if `None`). With `per_series`, the delay is a run's over every -/// series, and a run over a part of the series waits that share of it, as -/// work proportional to the samples read would. -#[doc(hidden)] -#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] -pub struct SlowRefresh { - pub group: Option, - pub end_ms: Option, - pub part: Option, - pub delay_ms: u64, - pub per_series: bool, -} - -impl SlowRefresh { - /// Whether it delays `window` (any part of it). - fn matches(&self, window: ClosedWindow) -> bool { - self.group.is_none_or(|g| g == window.group) - && self.end_ms.is_none_or(|e| e == window.end_ms) - } -} - -type Reply = oneshot::Sender>; - -/// What the ingest coordinator does next. -enum Command { - /// A shard routed and appended a batch, or sealed and evicted. - Report(ShardReport), - /// The shard numbered here has run every message sent to it before a - /// flush. - /// With the shard's raw data as of then: what windows closing behind - /// the flush read. - Flushed(usize, Arc), - AdvanceWatermark { - barrier_ms: i64, - reply: oneshot::Sender, - }, - Stop, -} - -/// A shard's state after its last message. -struct ShardReport { - shard: usize, - /// The newest sample the shard holds. - newest_ms: Option, - /// Each metric's first sample, while a group waits for one. - first_seen: Vec<(Arc, i64)>, - /// Samples of the batch reported, counted out of the queues when the - /// coordinator applies the report. - samples: u64, -} - -/// What an ingest shard does next. -enum ShardMessage { - Samples(Vec), - /// Seal the panes through the watermark and evict by the routing's - /// cutoffs. - Maintain { - routing: Arc, - watermark_ms: Option, - }, - /// Report `Flushed` once every message before is run. - Flush, - /// Push mode: seal these windows of groups built by push and send - /// their partials; each group's windows through `through` are closed - /// or skipped. - Seal { - windows: Vec, - through: Vec>, - }, -} - -/// What the precompute committer does next, in the order the windows -/// closed. -enum PrecomputeJob { - Refresh { - window: ClosedWindow, - raw_data: RawShards, - closed_at: Instant, - }, - /// A window of a group built by push: the shards send its partials. - Push { - window: ClosedWindow, - closed_at: Instant, - }, - /// Answers `barrier_ms` once every window queued before is refreshed. - Barrier { - barrier_ms: i64, - reply: oneshot::Sender, - }, -} - -/// Why the engine did not take samples. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -pub enum IngestError { - /// More samples are queued than `max_queued_samples`; retry later. - #[error("the engine is busy: too many samples queued")] - Busy, - /// The ingest thread has stopped; no sample will be ingested again. - #[error("the engine has stopped")] - Stopped, -} - /// The HTTP side of the engine. #[derive(Clone)] pub struct EngineHandle { - commands: Sender, - /// Each ingest shard's queue; a sample goes to the shard of its series. - shards: Vec>, - /// Queries for the worker threads. - queries: Sender, - query: Arc, - query_threads: usize, - shared: Arc, - max_queued_samples: u64, -} - -/// What the engine's threads publish to the HTTP side and to each other. -struct Shared { - /// Samples sent to the ingest shards and not yet ingested. - queued_samples: AtomicU64, - /// The same, per shard. - shard_queued: Vec, - /// What the shards route samples by, as the coordinator last published. - routing: RwLock>, - /// Held (shared) while a request is sent to its shards, and - /// exclusively while a flush is sent, so no flush splits a request. - admission: RwLock<()>, - /// Windows closed and not yet refreshed. - precompute_backlog: AtomicU64, - /// Refreshed windows not yet written to the view files. - persist_backlog: AtomicU64, - /// Bytes of the refreshed windows queued for the persist threads. - persist_queue: Mutex, - /// Signalled when the persist threads release queued bytes. - - /// False once the ingest or precompute thread has exited, for any - /// reason. - running: Arc, - /// The ingestion counters: samples and skipped windows as of the last - /// command the ingest thread ran, refreshed and failed windows as the - /// precompute thread counts them. - stats: Mutex, - published: PublishedStore, - /// Held by the precompute thread during each refresh; tests hold it to - /// keep a refresh from finishing. - precompute_gate: Mutex<()>, - metrics: Metrics, + precompute: PrecomputeEngine, + query: QueryWorkers, /// The views' cold tier, when they are persisted. view_tier: Option>, } -/// Marks the engine stopped when its thread exits, panics included. -struct RunningGuard(Arc); - -impl Drop for RunningGuard { - fn drop(&mut self) { - self.0.store(false, Ordering::SeqCst); - } -} - impl EngineHandle { /// Starts the engine for the plan file `plan_json`, read, checked and /// compiled once, and returns the plan's queries. Fails if the plan is /// invalid or the data plane cannot execute it. pub fn spawn(plan_json: String, options: EngineOptions) -> anyhow::Result<(Self, Vec)> { - let (mut ingestion, precompute, query, query_texts) = install(&plan_json, &options)?; - let precompute = Arc::new(precompute); - // Push mode: the groups the shards build by push. - let push_groups: Vec> = match options.precompute_mode { - PrecomputeMode::Window => vec![None; precompute.groups().len()], - PrecomputeMode::Push => { - 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() - }) - .collect(); - crate::push::probe( - &precompute, - &candidates, - &ingestion.group_windows(), - &ingestion.group_metrics(), - ) - } - }; - ingestion.set_push_groups(push_groups.iter().map(Option::is_some).collect()); - let mut views = ViewStore::default().with_stream_start(options.ingestion.stream_start_ms); - let mut tier = None; - let files = match &options.view_dir { - Some(dir) => { - let new_tier = Arc::new(view_tier(&options)); - views = ViewStore::tiered(new_tier.clone()) - .with_stream_start(options.ingestion.stream_start_ms); - tier = Some(new_tier); - let sync_interval = std::time::Duration::from_millis(options.view_sync_interval_ms); - let mut files = - ViewFiles::open(dir, plan_hash(plan_json.as_bytes()), sync_interval)? - .with_segment_ms(options.view_segment_ms); - // Indexed, not decoded: the first reads decode what they read. - let mut index = files.index(&precompute.views())?; - let mut loaded = 0; - for (view, schema) in precompute.views().into_iter().flatten() { - for (range, location) in index.remove(&view.node_id).unwrap_or_default() { - if views - .append_stored(&view, range, location, schema.clone()) - .is_ok() - { - loaded += 1; - } - } - } - tracing::info!(dir = %dir.display(), windows = loaded, "indexed persisted views"); - if loaded > 0 { - ingestion.restarted(); - views.restarted(); - } - Some((files, loaded)) - } - None => None, - }; - let shard_count = options.ingest_threads.max(1); - let raw_shards: Vec> = (0..shard_count) - .map(|_| Arc::new(ingestion.raw_data())) - .collect(); - let groups: Vec<(i64, Vec)> = precompute - .groups() - .into_iter() - .map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect())) - .collect(); - let mut metrics = Metrics::new(&groups, &query_texts); - if options.precompute_mode == PrecomputeMode::Push { - metrics.push = Some(PushMetrics::new(groups.len(), shard_count)); - } - let pushed: Arc> = Arc::new(push_groups.iter().map(Option::is_some).collect()); - // The committer's inbox; the shards' partials reach it through a - // forwarder. - let (events, inbox) = channel::(); - let (partials, partial_inbox) = channel::(); - { - let events = events.clone(); - std::thread::Builder::new() - .name("precompute-partials".into()) - .spawn(move || { - for partial in partial_inbox { - if events.send(PoolEvent::Partial(partial)).is_err() { - break; - } - } - })?; - } - let running = Arc::new(AtomicBool::new(true)); - let shared = Arc::new(Shared { - queued_samples: AtomicU64::new(0), - shard_queued: (0..shard_count).map(|_| AtomicU64::new(0)).collect(), - routing: RwLock::new(Arc::new(ingestion.routing())), - admission: RwLock::new(()), - precompute_backlog: AtomicU64::new(0), - persist_backlog: AtomicU64::new(0), - persist_queue: Mutex::new(0), - - running: running.clone(), - stats: Mutex::new(IngestionStats::default()), - published: PublishedStore::new(Arc::new(raw_shards.clone())), - precompute_gate: Mutex::new(()), - metrics, - view_tier: tier.clone(), - }); - let (commands, command_receiver) = channel(); - let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); - let (queries, query_receiver) = channel::(); - - let mut shards = Vec::new(); - for (index, raw_data) in raw_shards.iter().enumerate() { - let (shard, messages) = channel(); - let (coordinator, raw_data) = (commands.clone(), raw_data.clone()); - let shard_shared = shared.clone(); - let guard = RunningGuard(running.clone()); - let delay = std::time::Duration::from_millis(if index == 0 { - 0 - } else { - options.shard_delay_ms - }); - let push_init = (options.precompute_mode == PrecomputeMode::Push).then(|| { - ( - precompute.clone(), - push_groups.clone(), - ingestion.pane_width_ms(), - options.precompute_memory_budget_bytes, - partials.clone(), - options.push_batching, - ) + let (ingestion, precompute, query, query_texts) = install(&plan_json, &options)?; + let view_tier = options + .view_dir + .is_some() + .then(|| Arc::new(view_tier(&options))); + let persisted = options + .view_dir + .clone() + .zip(view_tier.clone()) + .map(|(dir, tier)| PersistedViews { + dir, + plan_hash: plan_hash(plan_json.as_bytes()), + sync_interval: std::time::Duration::from_millis(options.view_sync_interval_ms), + segment_ms: options.view_segment_ms, + persist: PersistOptions { + threads: options.persist_threads, + max_backlog_bytes: options.max_persist_backlog_bytes, + delay: std::time::Duration::from_millis(options.persist_delay_ms), + unpersistable_views: options.unpersistable_views.iter().copied().collect(), + }, + tier, }); - std::thread::Builder::new() - .name(format!("ingest-{index}")) - .spawn(move || { - let _guard = guard; - let push = - push_init.map(|(precompute, groups, pane, budget, partials, batching)| { - PushShard::new( - index, precompute, groups, pane, budget, partials, batching, - ) - }); - serve_shard( - index, - raw_data, - messages, - coordinator, - &shard_shared, - delay, - push, - ); - })?; - shards.push(shard); - } - let ingest_guard = RunningGuard(running.clone()); - let ingest_shared = shared.clone(); - let coordinator_shards = shards.clone(); - std::thread::Builder::new() - .name("ingest".into()) - .spawn(move || { - let _guard = ingest_guard; - serve_ingest( - ingestion, - raw_shards, - coordinator_shards, - command_receiver, - jobs, - &ingest_shared, - &pushed, - ); - })?; - let views = Arc::new(views); - shared.published.publish_views(views.clone()); - shared - .metrics - .view_bytes - .store(views.bytes() as u64, Ordering::Relaxed); - let persist = match files { - Some((files, loaded)) => { - shared - .metrics - .view_windows_loaded - .store(loaded, Ordering::Relaxed); - shared - .metrics - .view_file_bytes - .store(files.bytes(), Ordering::Relaxed); - let unpersistable: Arc> = - Arc::new(options.unpersistable_views.iter().copied().collect()); - let mut shards = Vec::new(); - for (index, files) in files.split(options.persist_threads).into_iter().enumerate() { - let (shard, jobs) = channel(); - let persist_shared = shared.clone(); - let delay = std::time::Duration::from_millis(options.persist_delay_ms); - let unpersistable = unpersistable.clone(); - std::thread::Builder::new() - .name(format!("persist-{index}")) - .spawn(move || { - serve_persist(files, jobs, &persist_shared, delay, &unpersistable) - })?; - shards.push(shard); - } - Some(PersistPool { - shards, - max_bytes: options.max_persist_backlog_bytes, - }) - } - None => None, - }; - if let Some(tier) = &tier { - let (tier, monitor_running) = (tier.clone(), running.clone()); - let budget = tier.cache.max_bytes(); - std::thread::Builder::new() - .name("view-cache".into()) - .spawn(move || serve_view_cache(tier, budget, monitor_running))?; - } - spawn_precompute( + let published = Arc::new(PublishedStore::new(Arc::default())); + let precompute = PrecomputeEngine::start( + ingestion, precompute, - views, - persist, - job_receiver, - (events, inbox), - PoolOptions { - threads: options.precompute_threads.max(1), - slow_refreshes: options.slow_refreshes.clone(), - check_task_inputs: options.check_task_inputs, - push_parts: shard_count as u32, - panic_in_combine_of_window_end_ms: options.panic_in_combine_of_window_end_ms, - }, - RunningGuard(running), - &shared, + &query_texts, + &options.precompute(), + persisted, + published.clone(), )?; - let query = Arc::new(query); - spawn_query_workers( - query.clone(), - shared.clone(), - query_receiver, - options.query_threads.max(1), + let query = QueryWorkers::start( + query, + published, + precompute.metrics().clone(), + options.query_threads, )?; let handle = Self { - commands, - shards, - queries, + precompute, query, - query_threads: options.query_threads.max(1), - shared, - max_queued_samples: options.max_queued_samples, + view_tier, }; Ok((handle, query_texts)) } - /// Queues `samples` for ingestion. `Busy` when the queue would hold - /// more than `max_queued_samples`; `Stopped` when the engine has exited. + /// Queues `samples` for ingestion; see [`PrecomputeEngine::try_ingest`]. pub fn try_ingest(&self, samples: Vec) -> Result<(), IngestError> { - if !self.is_running() { - return Err(IngestError::Stopped); - } - // Each series' samples go to one shard, in order. - let mut by_shard: Vec> = Vec::new(); - if self.shards.len() == 1 { - by_shard.push(samples); - } else { - // Room for a fair share and a quarter more, so a request rarely - // grows a shard's vector. - let room = samples.len() / self.shards.len() * 5 / 4 + 1; - by_shard.resize_with(self.shards.len(), || Vec::with_capacity(room)); - for sample in samples { - by_shard[sample.labels.id as usize % self.shards.len()].push(sample); - } - } - let counts: Vec = by_shard.iter().map(|s| s.len() as u64).collect(); - // A request reaches its shards whole between two flushes, never - // split by one: a flush covers all of it or none. - let _sending = self - .shared - .admission - .read() - .unwrap_or_else(|e| e.into_inner()); - admit_shards(&self.shared.shard_queued, &counts, self.max_queued_samples)?; - let shared = &self.shared; - for (shard, samples) in by_shard.into_iter().enumerate() { - let count = samples.len() as u64; - if count == 0 { - continue; - } - shared.queued_samples.fetch_add(count, Ordering::SeqCst); - if self.shards[shard] - .send(ShardMessage::Samples(samples)) - .is_err() - { - // This shard and the ones not sent to yet were admitted - // but get nothing. - shared.queued_samples.fetch_sub(count, Ordering::SeqCst); - for (queued, &later) in shared.shard_queued[shard..].iter().zip(&counts[shard..]) { - queued.fetch_sub(later, Ordering::SeqCst); - } - return Err(IngestError::Stopped); - } - } - Ok(()) + self.precompute.try_ingest(samples) } - /// Answers the planned `query` at `time_ms` on a query worker, from - /// the newest snapshot published when the run starts; see - /// [`QueryEngine::evaluate`]. Two queries at one evaluation time may - /// read different snapshots. A query does not wait for writes - /// acknowledged before it; an event-time barrier does - /// ([`Self::advance_watermark`]). + /// Answers the planned `query` at `time_ms` on a query worker; see + /// [`QueryWorkers::evaluate`]. 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).await; - if let Some(metrics) = metrics { - metrics.latency.observe(started.elapsed().as_secs_f64()); - } - answer + self.query.evaluate(query, time_ms).await } - /// Evaluates one step of a range query over `snapshot`, which every - /// step of the request reads ([`Self::snapshot`]): as - /// [`Self::evaluate`], counted as a range step rather than an instant - /// query. A step whose future is dropped before a worker takes it (the - /// range failed or its client went away) is not run. + /// Evaluates one step of a range query over `snapshot`; see + /// [`QueryWorkers::evaluate_range_step`]. pub async fn evaluate_range_step( &self, query: String, time_ms: i64, snapshot: Arc, ) -> Result { - self.run_on_worker(query, time_ms, Some(snapshot)).await + self.query + .evaluate_range_step(query, time_ms, snapshot) + .await } /// The newest published store, for the steps of one range request. pub fn snapshot(&self) -> Arc { - Arc::new(self.query.snapshot(&self.shared.published)) + self.query.snapshot() } /// The result cache's answer to the planned `query` at `time_ms`, if @@ -741,247 +278,103 @@ impl EngineHandle { self.query.cached(query, time_ms) } - async fn run_on_worker( - &self, - query: String, - time_ms: i64, - range_step: Option>, - ) -> Result { - let stopped = || Unanswered::Execution("the query workers have stopped".into()); - let (reply, answer) = oneshot::channel(); - self.queries - .send(QueryJob { - query, - time_ms, - range_step, - reply, - }) - .map_err(|_| stopped())?; - answer.await.map_err(|_| stopped())? - } - /// The query worker threads: the most query runs at once. pub fn query_threads(&self) -> usize { - self.query_threads + self.query.threads() } /// How many query-time `OneEvaluation` nodes several queries share. pub fn shared_nodes(&self) -> usize { - self.query.shared_nodes().len() + self.query.engine().shared_nodes().len() } /// The query-time partition of the view store. pub fn query_time_results(&self) -> &QueryTimeResults { - self.query.query_time_results() + self.query.engine().query_time_results() } /// The engine's measurements. pub fn metrics(&self) -> &Metrics { - &self.shared.metrics + self.precompute.metrics() } /// The engine's measurements and counters in the Prometheus text /// format. pub fn render_metrics(&self) -> String { + let persist_backlog = self.precompute.persist_backlog(); crate::metrics_endpoint::render( - &self.shared.metrics, + self.metrics(), &Gauges { stats: self.stats(), samples_queued: self.queued_samples(), precompute_backlog: self.precompute_backlog(), - persist_backlog: self.shared.persist_backlog.load(Ordering::SeqCst), - persist_backlog_bytes: *self - .shared - .persist_queue - .lock() - .unwrap_or_else(|e| e.into_inner()), - now_ms: crate::ingestion::wall_clock_ms(), - query_time_results: self.query.query_time_results(), - result_cache: self.query.result_cache(), - view_tier: self.shared.view_tier.as_deref(), + persist_backlog: persist_backlog.windows(), + persist_backlog_bytes: persist_backlog.bytes(), + now_ms: precompute::ingestion::wall_clock_ms(), + query_time_results: self.query_time_results(), + result_cache: self.query.engine().result_cache(), + view_tier: self.view_tier.as_deref(), }, ) } /// Whether the ingest and precompute threads are still running. pub fn is_running(&self) -> bool { - self.shared.running.load(Ordering::SeqCst) + self.precompute.is_running() } /// Samples queued and not yet ingested. pub fn queued_samples(&self) -> u64 { - self.shared.queued_samples.load(Ordering::SeqCst) + self.precompute.queued_samples() } /// Refresh windows closed and not yet refreshed. pub fn precompute_backlog(&self) -> u64 { - self.shared.precompute_backlog.load(Ordering::SeqCst) + self.precompute.precompute_backlog() } /// The ingestion counters. pub fn stats(&self) -> IngestionStats { - *self.shared.stats.lock().unwrap_or_else(|e| e.into_inner()) + self.precompute.stats() } - /// Queues an event-time barrier behind every write already acknowledged - /// and waits until it has run and every window it closed is refreshed: - /// every window ending at or before `barrier_ms` (capped at the wall - /// clock) is then answered from. Returns the barrier in force; see - /// [`Ingestion::advance_watermark_at`]. + /// Queues an event-time barrier and waits for it; see + /// [`PrecomputeEngine::advance_watermark`]. pub async fn advance_watermark(&self, barrier_ms: i64) -> Result { - if !self.is_running() { - return Err(IngestError::Stopped); - } - let (reply, done) = oneshot::channel(); - self.commands - .send(Command::AdvanceWatermark { barrier_ms, reply }) - .map_err(|_| IngestError::Stopped)?; - done.await.map_err(|_| IngestError::Stopped) + self.precompute.advance_watermark(barrier_ms).await } - /// For tests: stops the ingest thread after the commands queued before, - /// and the precompute thread once it has refreshed the windows queued - /// before. Samples queued between this call and the stop are - /// acknowledged and then lost; ingestion after the stop fails with - /// [`IngestError::Stopped`]. + /// For tests: stops ingestion; see [`PrecomputeEngine::stop`]. #[doc(hidden)] pub fn stop(&self) { - let _ = self.commands.send(Command::Stop); + self.precompute.stop() } /// For tests: no refresh finishes while the guard is held. #[doc(hidden)] - pub fn hold_precompute(&self) -> MutexGuard<'_, ()> { - self.shared - .precompute_gate - .lock() - .unwrap_or_else(|e| e.into_inner()) + pub fn hold_precompute(&self) -> std::sync::MutexGuard<'_, ()> { + self.precompute.hold_precompute() } } -/// Admits `counts[i]` samples to shard `i`'s queue `queued[i]` for every -/// shard, or none: `Busy` if any shard's queue would pass `max_queued` -/// ([`admit`]), and then no queue changes, so a request is taken whole or -/// not at all. -fn admit_shards(queued: &[AtomicU64], counts: &[u64], max_queued: u64) -> Result<(), IngestError> { - let mut admitted: Vec = Vec::new(); - for (shard, &count) in counts.iter().enumerate() { - if count == 0 { - continue; - } - let queue = &queued[shard]; - let mut current = queue.load(Ordering::SeqCst); - let result = loop { - let total = match admit(current, count, max_queued) { - Ok(total) => total, - Err(error) => break Err(error), - }; - match queue.compare_exchange(current, total, Ordering::SeqCst, Ordering::SeqCst) { - Ok(_) => break Ok(()), - Err(now) => current = now, - } - }; - if let Err(error) = result { - for shard in admitted { - queued[shard].fetch_sub(counts[shard], Ordering::SeqCst); - } - return Err(error); +impl EngineOptions { + /// The options of the precompute engine. + fn precompute(&self) -> PrecomputeOptions { + PrecomputeOptions { + ingestion: self.ingestion, + max_queued_samples: self.max_queued_samples, + max_precompute_backlog: self.max_precompute_backlog, + ingest_threads: self.ingest_threads, + precompute_threads: self.precompute_threads, + slow_refreshes: self.slow_refreshes.clone(), + check_task_inputs: self.check_task_inputs, + shard_delay_ms: self.shard_delay_ms, + precompute_mode: self.precompute_mode, + 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, } - admitted.push(shard); } - Ok(()) -} - -/// The queue length after admitting `count` samples to a queue of -/// `queued`: admitted while the total stays within `max_queued`, and always -/// into an empty queue, so a bound smaller than one request cannot refuse -/// that request forever. -fn admit(queued: u64, count: u64, max_queued: u64) -> Result { - let total = queued.checked_add(count).ok_or(IngestError::Busy)?; - if queued == 0 || total <= max_queued { - Ok(total) - } else { - Err(IngestError::Busy) - } -} - -/// One query for a worker thread. -struct QueryJob { - query: String, - time_ms: i64, - /// One step of a range query, and the snapshot every step reads. - range_step: Option>, - reply: Reply, -} - -/// What crosses threads: the compiled queries and refresh runs, the store -/// snapshots runs read, and what the threads share. -#[allow(dead_code)] -fn assert_send_sync() {} -#[allow(dead_code)] -fn assert_send() {} -const _: fn() = || { - assert_send_sync::(); - assert_send_sync::(); - assert_send_sync::(); - assert_send_sync::(); - assert_send_sync::(); - assert_send_sync::(); - assert_send::(); -}; - -/// Starts `threads` workers `query-0`, `query-1`, …, each running one query -/// at a time to completion from `jobs`; more queries wait in `jobs`. -fn spawn_query_workers( - query: Arc, - shared: Arc, - jobs: Receiver, - threads: usize, -) -> std::io::Result<()> { - let jobs = Arc::new(Mutex::new(jobs)); - for index in 0..threads { - let (query, shared, jobs) = (query.clone(), shared.clone(), jobs.clone()); - std::thread::Builder::new() - .name(format!("query-{index}")) - .spawn(move || loop { - let job = match jobs.lock().unwrap_or_else(|e| e.into_inner()).recv() { - Ok(job) => job, - Err(_) => break, - }; - // Nobody waits for it any more (a failed range, a client - // that went away). - if job.reply.is_closed() { - continue; - } - let timer = Timer::start(); - // 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 { - Some(snapshot) => snapshot.clone(), - None => Arc::new(query.snapshot(&shared.published)), - }; - query.evaluate(&job.query, job.time_ms, &snapshot) - })) - .unwrap_or_else(|panic| { - let reason = panic - .downcast_ref::<&str>() - .map(ToString::to_string) - .or_else(|| panic.downcast_ref::().cloned()) - .unwrap_or_default(); - tracing::error!(query = %job.query, time_ms = job.time_ms, %reason, "query run panicked"); - Err(Unanswered::Execution(format!("the query run panicked: {reason}"))) - }); - 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), - }; - } - let _ = job.reply.send(answer); - })?; - } - Ok(()) } /// Reads, checks and compiles the plan file `plan_json`: its ingestion, @@ -1040,1403 +433,6 @@ fn install( Ok((ingestion, precompute, query, plan.query_texts.clone())) } -/// 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 { - let _admission = shared.admission.write().unwrap_or_else(|e| e.into_inner()); - let sent_ms = crate::ingestion::wall_clock_ms(); - for shard in shards { - let _ = shard.send(ShardMessage::Flush); - } - sent_ms -} - -/// 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. -fn serve_shard( - index: usize, - mut raw_data: Arc, - messages: Receiver, - coordinator: Sender, - shared: &Shared, - delay: std::time::Duration, - mut push: Option, -) { - let mut newest_ms: Option = None; - // A message taken while draining a batch, to run next. - let mut next: Option = None; - loop { - let message = match next.take() { - Some(message) => message, - None => match messages.recv() { - Ok(message) => message, - Err(_) => break, - }, - }; - let mut samples = match message { - ShardMessage::Samples(samples) => samples, - // Eviction changes no sample time: no report (each would start - // another coordinator pass). - ShardMessage::Maintain { - routing, - watermark_ms, - } => { - routing.maintain(Arc::make_mut(&mut raw_data), watermark_ms); - continue; - } - ShardMessage::Flush => { - // The raw data travels only with a flush, which a window - // closing reads; the coordinator lets it go after its pass, - // so appending rarely copies the pane lists it shares. - if coordinator - .send(Command::Flushed(index, raw_data.clone())) - .is_err() - { - break; - } - continue; - } - ShardMessage::Seal { windows, through } => { - if let Some(push) = &mut push { - push.seal(&windows, &through, &shared.metrics); - } - continue; - } - }; - // Every batch already queued, appended and reported at once: one - // report (and so at most one coordinator pass) per drained queue, - // not per request. - let mut count = 0; - let mut first_seen = Vec::new(); - loop { - if !delay.is_zero() { - std::thread::sleep(delay); - } - let timer = Timer::start(); - count += samples.len() as u64; - let routing = shared - .routing - .read() - .unwrap_or_else(|e| e.into_inner()) - .clone(); - let routed = routing.route(samples, crate::ingestion::wall_clock_ms()); - Arc::make_mut(&mut raw_data).append(&routed.accepted); - newest_ms = newest_ms.max(routed.newest_ms); - if let Some(push) = &mut push { - push.push(&routed.accepted, &shared.metrics); - } - { - let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); - 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); - match messages.try_recv() { - Ok(ShardMessage::Samples(more)) => samples = more, - Ok(other) => { - next = Some(other); - break; - } - Err(_) => break, - } - } - let report = ShardReport { - shard: index, - newest_ms, - first_seen, - samples: count, - }; - // The coordinator counts the samples out of the queues when it - // applies the report, so samples stay counted while it cannot keep - // up (waiting for the precompute workers): the queues fill and - // Remote Write gets 503, and reports waiting for it stay bounded. - if coordinator.send(Command::Report(report)).is_err() { - break; - } - } -} - -/// The ingest coordinator: keeps the watermark over the shards, closes the -/// windows it passes and queues their refreshes over every shard's raw data -/// as it was then, publishes the raw data and the routing, and has the -/// shards seal and evict as the watermark moves. The watermark follows the -/// newest sample of any shard, capped at the wall clock; it moves only -/// behind a flush, which every pass that took a report or a barrier -/// sends: every shard runs the samples queued to it, so a window closes -/// over every sample admitted before. The clock cap is the time that flush -/// 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. -fn serve_ingest( - mut ingestion: Ingestion, - mut raw_shards: Vec>, - shards: Vec>, - commands: Receiver, - jobs: SyncSender, - shared: &Shared, - pushed: &[bool], -) { - 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; - 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); - shared - .queued_samples - .fetch_sub(report.samples, Ordering::SeqCst); - newest[report.shard] = report.newest_ms; - }; - // Barriers that came while a flush was waited for: written after it, - // so they take the next pass, behind its own flush. - let mut deferred: VecDeque<(i64, oneshot::Sender)> = VecDeque::new(); - // Reports a shard sent after answering a flush, of samples admitted - // after it: held for the next pass, so they move neither this pass's - // watermark nor its raw data. Without this, a shard that ran ahead - // would move the watermark past samples other shards have yet to - // append, and windows would close without them. - let mut held: Vec = Vec::new(); - let queries_read_raw_data = ingestion.queries_read_raw_data(); - // Published in place of the raw data when no query reads it. - let no_raw_data: RawShards = Arc::new( - (0..shards.len()) - .map(|_| Arc::new(ingestion.raw_data())) - .collect(), - ); - 'serve: loop { - let mut barriers: Vec<_> = deferred.drain(..).collect(); - // Whether anything this pass may move the watermark: a newer - // 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(); - for report in held.drain(..) { - apply(report, &mut ingestion, &mut newest); - } - if !moved { - match commands.recv_timeout(TICK) { - Ok(Command::Report(report)) => { - apply(report, &mut ingestion, &mut newest); - moved = true; - } - Ok(Command::Flushed(..)) => {} - Ok(Command::AdvanceWatermark { barrier_ms, reply }) => { - barriers.push((barrier_ms, reply)); - moved = true; - } - Ok(Command::Stop) => break, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, - } - } - // Drain what was already sent, so one pass takes it all. A barrier - // taken here is behind every write acknowledged before it, as the - // flush below is sent after it. - while let Ok(command) = commands.try_recv() { - match command { - Command::Report(report) => { - apply(report, &mut ingestion, &mut newest); - moved = true; - } - Command::Flushed(..) => {} - Command::AdvanceWatermark { barrier_ms, reply } => { - barriers.push((barrier_ms, reply)); - moved = true; - } - Command::Stop => break 'serve, - } - } - // 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; - if moved { - let flushed_ms = flush(&shards, shared); - let mut flushed = vec![false; shards.len()]; - while !flushed.iter().all(|&f| f) { - match commands.recv_timeout(TICK) { - Ok(Command::Report(report)) - if flushed[report.shard] - || held.iter().any(|r| r.shard == report.shard) => - { - held.push(report) - } - Ok(Command::Report(report)) => apply(report, &mut ingestion, &mut newest), - Ok(Command::Flushed(shard, raw_data)) => { - flushed[shard] = true; - raw_shards[shard] = raw_data; - } - Ok(Command::AdvanceWatermark { barrier_ms, reply }) => { - deferred.push_back((barrier_ms, reply)) - } - Ok(Command::Stop) => break 'serve, - // A shard that died never answers: stop, failing the - // barriers waiting. - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { - if !shared.running.load(Ordering::SeqCst) { - break 'serve; - } - } - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break 'serve, - } - } - ingestion.advance_clock(flushed_ms); - } - let newest_ms = newest.iter().flatten().copied().max(); - ingestion.advance_newest_sample(newest_ms); - let mut closed = ingestion.close(); - let mut answered = Vec::new(); - for (barrier_ms, reply) in barriers { - let (barrier_ms, more) = ingestion.advance_watermark(barrier_ms); - closed.extend(more); - answered.push((barrier_ms, reply)); - } - let snapshot: RawShards = Arc::new(raw_shards.clone()); - let sealed: Vec = closed - .iter() - .copied() - .filter(|w| pushed.get(w.group).copied().unwrap_or(false)) - .collect(); - if !sealed.is_empty() { - let through = ingestion.refreshed_through(); - for shard in &shards { - let _ = shard.send(ShardMessage::Seal { - windows: sealed.clone(), - through: through.clone(), - }); - } - } - if !queue_refreshes(&closed, &snapshot, &jobs, shared, pushed) { - break; - } - 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() { - sealed_through = watermark_ms; - for shard in &shards { - let _ = shard.send(ShardMessage::Maintain { - routing: routing.clone(), - watermark_ms, - }); - } - } - let metrics = &shared.metrics; - if let Some(watermark_ms) = watermark_ms { - metrics.watermark_ms.store(watermark_ms, Ordering::Relaxed); - } - if flushed { - let sum = |f: fn(&RawData) -> usize| snapshot.iter().map(|r| f(r) as u64).sum::(); - metrics - .raw_data_bytes - .store(sum(RawData::bytes), Ordering::Relaxed); - metrics - .raw_data_samples - .store(sum(RawData::len), Ordering::Relaxed); - metrics - .raw_data_panes - .store(sum(RawData::panes), Ordering::Relaxed); - } - if queries_read_raw_data { - shared - .published - .publish_raw_data(snapshot.clone(), watermark_ms); - } else { - // No query reads the raw data, and the next windows to close - // read it as of their own flush: let the shards' raw data go, - // so their next appends own it again instead of copying the - // pane lists this snapshot shares (only the queued refreshes - // still hold it, until they run). - shared - .published - .publish_raw_data(no_raw_data.clone(), watermark_ms); - drop(snapshot); - for raw_data in raw_shards.iter_mut() { - *raw_data = no_raw_data[0].clone(); - } - } - { - 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; - } - for (barrier_ms, reply) in answered { - if jobs - .send(PrecomputeJob::Barrier { barrier_ms, reply }) - .is_err() - { - break 'serve; - } - } - } - tracing::warn!("ingest stopped"); -} - -/// Queues a refresh of each of `closed` over `raw_data`, waiting while the -/// backlog is full; `false` once the precompute thread has exited. -fn queue_refreshes( - closed: &[ClosedWindow], - raw_data: &RawShards, - jobs: &SyncSender, - shared: &Shared, - pushed: &[bool], -) -> bool { - for &window in closed { - shared.precompute_backlog.fetch_add(1, Ordering::SeqCst); - let job = if pushed.get(window.group).copied().unwrap_or(false) { - PrecomputeJob::Push { - window, - closed_at: Instant::now(), - } - } else { - PrecomputeJob::Refresh { - window, - raw_data: raw_data.clone(), - closed_at: Instant::now(), - } - }; - if jobs.send(job).is_err() { - return false; - } - } - true -} - -/// How the precompute task pool runs. -#[derive(Clone)] -struct PoolOptions { - threads: usize, - slow_refreshes: Vec, - check_task_inputs: bool, - /// The partials a pushed window combines: one per ingest shard. - push_parts: u32, - panic_in_combine_of_window_end_ms: Option, -} - -/// What the precompute committer waits for. -enum PoolEvent { - /// The next job, in the order the windows closed. - Job(PrecomputeJob), - /// A worker computed window `seq`, or its part `part` of a window split - /// by series. - Computed { - seq: u64, - part: u32, - result: Result, - times: TaskTimes, - }, - /// A shard's partial of a pushed window. - Partial(Partial), - /// No job will come any more. - Closed, -} - -/// When a window's computation started and ended. -#[derive(Debug, Clone, Copy)] -struct TaskTimes { - started: Instant, - computed: Instant, -} - -/// A window for a worker to compute. -struct WindowRun { - seq: u64, - window: ClosedWindow, - raw_data: RawShards, - /// The views as committed when the run was started: every window of - /// the groups it reads that closed before it. - views: Arc, - /// The series the run reads, when the window is split by series. - partition: Option, -} - -/// Starts the precompute task pool: the committer (`precompute`, today's -/// precompute thread), which takes the closed windows in order, starts -/// them, and stores and publishes their rows in window order, so the view -/// store keeps one writer; and, with more than one thread, the workers -/// `precompute-N` that compute the windows, and `precompute-queue`, which -/// takes jobs from the bounded backlog for the committer as room frees. -#[allow(clippy::too_many_arguments)] -fn spawn_precompute( - precompute: Arc, - views: Arc, - persist: Option, - jobs: Receiver, - (events, inbox): (Sender, Receiver), - options: PoolOptions, - guard: RunningGuard, - shared: &Arc, -) -> std::io::Result<()> { - shared - .metrics - .precompute_threads - .store(options.threads as u64, Ordering::Relaxed); - for (group, &split) in precompute.tasks().split_by_series.iter().enumerate() { - let parts = if split { options.threads } else { 1 }; - shared.metrics.precompute_windows[group] - .parts - .store(parts as u64, Ordering::Relaxed); - } - // Windows taken from the backlog and not yet committed: one at a time - // when the committer computes them itself; with workers, two per - // worker, so a slow window does not leave the others idle while the - // windows after it wait to be committed. - let slots = Arc::new(Slots::new(if options.threads == 1 { - 1 - } else { - 2 * options.threads - })); - let workers = if options.threads == 1 { - None - } else { - let (runs, run_receiver) = channel::(); - let run_receiver = Arc::new(Mutex::new(run_receiver)); - for index in 0..options.threads { - let (precompute, shared, runs, events) = ( - precompute.clone(), - shared.clone(), - run_receiver.clone(), - events.clone(), - ); - let checks = options.clone(); - std::thread::Builder::new() - .name(format!("precompute-{index}")) - .spawn(move || loop { - let run = match runs.lock().unwrap_or_else(|e| e.into_inner()).recv() { - Ok(run) => run, - Err(_) => break, - }; - let (result, times) = compute_window( - &precompute, - run.window, - run.raw_data, - run.views, - run.partition, - &checks, - &shared, - ); - let event = PoolEvent::Computed { - seq: run.seq, - part: run.partition.map_or(0, |p| p.index), - result, - times, - }; - if events.send(event).is_err() { - break; - } - })?; - } - Some(runs) - }; - { - let (slots, shared) = (slots.clone(), shared.clone()); - std::thread::Builder::new() - .name("precompute-queue".into()) - .spawn(move || { - for job in jobs { - if matches!( - job, - PrecomputeJob::Refresh { .. } | PrecomputeJob::Push { .. } - ) && !slots.acquire(&shared.running) - { - break; - } - if events.send(PoolEvent::Job(job)).is_err() { - break; - } - } - let _ = events.send(PoolEvent::Closed); - })?; - } - let shared = shared.clone(); - std::thread::Builder::new() - .name("precompute".into()) - .spawn(move || { - let _guard = guard; - serve_precompute( - &precompute, - views, - persist, - inbox, - workers, - &slots, - &options, - &shared, - ); - })?; - Ok(()) -} - -/// A counting semaphore: the windows taken from the backlog and not yet -/// committed. -struct Slots { - free: Mutex, - freed: Condvar, -} - -impl Slots { - fn new(count: usize) -> Self { - Self { - free: Mutex::new(count), - freed: Condvar::new(), - } - } - - /// Takes a slot, waiting for one; `false` once the engine has stopped. - fn acquire(&self, running: &AtomicBool) -> bool { - let mut free = self.free.lock().unwrap_or_else(|e| e.into_inner()); - while *free == 0 { - if !running.load(Ordering::SeqCst) { - return false; - } - free = self - .freed - .wait_timeout(free, std::time::Duration::from_millis(100)) - .unwrap_or_else(|e| e.into_inner()) - .0; - } - *free -= 1; - true - } - - fn release(&self) { - *self.free.lock().unwrap_or_else(|e| e.into_inner()) += 1; - self.freed.notify_one(); - } -} - -/// Computes `window` on this thread, after its test delay; a panic in the -/// run fails the window, not the thread. -fn compute_window( - precompute: &Precompute, - window: ClosedWindow, - raw_data: RawShards, - views: Arc, - partition: Option, - options: &PoolOptions, - shared: &Shared, -) -> (Result, TaskTimes) { - let started = Instant::now(); - let inputs = options - .check_task_inputs - .then(|| TaskInputs::read(precompute, window, &raw_data, &views)); - let delay_ms: u64 = options - .slow_refreshes - .iter() - .filter(|s| s.matches(window)) - .filter(|s| { - s.part - .is_none_or(|part| partition.is_none_or(|p| p.index == part)) - }) - .map(|s| match (s.per_series, partition) { - (true, Some(partition)) => s.delay_ms / u64::from(partition.count), - _ => s.delay_ms, - }) - .sum(); - if delay_ms > 0 { - std::thread::sleep(std::time::Duration::from_millis(delay_ms)); - } - let timer = Timer::start(); - let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - precompute - .compute(window, raw_data, views, partition) - .map_err(|e| e.to_string()) - })) - .unwrap_or_else(|panic| { - let reason = panic - .downcast_ref::<&str>() - .map(ToString::to_string) - .or_else(|| panic.downcast_ref::().cloned()) - .unwrap_or_default(); - Err(format!("the ingestion run panicked: {reason}")) - }); - if !matches!(result, Ok(Computed::AlreadyStored)) { - shared.metrics.precompute[window.group].1.record(timer); - } - let result = match inputs { - Some((before, raw_data, views)) => result.and_then(|computed| { - before.check(window)?; - if TaskInputs::read(precompute, window, &raw_data, &views).0 != before { - return Err("a run's inputs changed while it ran".into()); - } - Ok(computed) - }), - None => result, - }; - let computed = Instant::now(); - shared - .metrics - .precompute_busy_ns - .fetch_add((computed - started).as_nanos() as u64, Ordering::Relaxed); - (result, TaskTimes { started, computed }) -} - -/// What a window's run reads, for tests: each raw shard's identity, -/// samples and panes, the view store's identity, and how far each view of the groups -/// it reads is stored. -#[derive(Debug, PartialEq, Eq)] -struct TaskInputs { - raw_shards: Vec<(usize, usize, usize)>, - views: usize, - read_views_stored_through: Vec>, -} - -impl TaskInputs { - /// The inputs as of now, and the snapshots to read them again from. - fn read( - precompute: &Precompute, - window: ClosedWindow, - raw_data: &RawShards, - views: &Arc, - ) -> (Self, RawShards, Arc) { - let groups = precompute.groups(); - let inputs = Self { - raw_shards: raw_data - .iter() - // Samples and panes, not bytes: a chunk builds its series - // identity column once, on first read, and counts it. - .map(|shard| (Arc::as_ptr(shard) as usize, shard.len(), shard.panes())) - .collect(), - views: Arc::as_ptr(views) as usize, - read_views_stored_through: precompute.tasks().reads[window.group] - .iter() - .flat_map(|&group| &groups[group].1) - .map(|&view| views.stored_through(view)) - .collect(), - }; - (inputs, raw_data.clone(), views.clone()) - } - - /// Every view of the groups the window reads is committed through the - /// window's end. - fn check(&self, window: ClosedWindow) -> Result<(), String> { - if self - .read_views_stored_through - .iter() - .all(|stored| stored.is_some_and(|end| end >= window.end_ms)) - { - Ok(()) - } else { - Err(format!( - "window {window:?} ran before the views it reads were committed: {:?}", - self.read_views_stored_through - )) - } - } -} - -/// The precompute committer: takes the jobs in the order the windows -/// closed, starts each window once the windows it reads are committed, -/// commits computed windows in window order per group, publishes the views -/// once per pass and then queues the windows for the persist threads, and -/// answers a barrier once every window before it is committed. Without -/// `workers` it computes each window itself. -#[allow(clippy::too_many_arguments)] -fn serve_precompute( - precompute: &Precompute, - mut views: Arc, - persist: Option, - inbox: Receiver, - workers: Option>, - slots: &Slots, - options: &PoolOptions, - shared: &Shared, -) { - // A window of a group split by series runs as one part per worker. - let parts = if workers.is_some() { - options.threads - } else { - 1 - }; - let mut tasks = WindowTasks::new(precompute.tasks().clone(), parts as u32); - let mut closed = false; - while !(closed && tasks.is_empty()) { - let Ok(event) = inbox.recv() else { - break; - }; - // Take every event already sent, so one pass commits and publishes - // them together (as an ASAPQuery worker emits the windows one - // flush closed as one batch: `precompute_engine/worker.rs`, - // `flush_all`). - let mut next = Some(event); - while let Some(event) = next.take().or_else(|| inbox.try_recv().ok()) { - match event { - PoolEvent::Job(PrecomputeJob::Refresh { - window, - raw_data, - closed_at, - }) => tasks.push(window, raw_data, closed_at), - PoolEvent::Job(PrecomputeJob::Push { window, closed_at }) => { - tasks.push_window(window, closed_at, options.push_parts) - } - PoolEvent::Partial(partial) => tasks.partial(partial), - PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { - tasks.barrier(barrier_ms, reply) - } - PoolEvent::Computed { - seq, - part, - result, - times, - } => tasks.computed(seq, part, result, times), - PoolEvent::Closed => closed = true, - } - } - let mut to_persist = Vec::new(); - let mut committed = false; - loop { - // Started after every commit, so a window that reads another - // group's views sees exactly the windows that closed before it. - for (seq, window, raw_data, partition) in tasks.start() { - match &workers { - Some(workers) => { - let run = WindowRun { - seq, - window, - raw_data, - views: views.clone(), - partition, - }; - if workers.send(run).is_err() { - tracing::error!("the precompute workers have stopped"); - return; - } - } - None => { - let (result, times) = compute_window( - precompute, - window, - raw_data, - views.clone(), - partition, - options, - shared, - ); - tasks.computed(seq, 0, result, times); - } - } - } - let Some(task) = tasks.next_commit() else { - break; - }; - commit_window( - precompute, - task, - &mut views, - &mut to_persist, - options, - shared, - ); - committed = true; - slots.release(); - } - if committed { - shared.published.publish_views(views.clone()); - shared - .metrics - .view_bytes - .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, shared); - } - } - for (barrier_ms, reply) in tasks.passed_barriers() { - match &persist { - // The barrier answers once the windows before it are also - // written (not necessarily synced), without the committer - // waiting for that. - Some(persist) => persist.barrier(barrier_ms, reply), - None => { - let _ = reply.send(barrier_ms); - } - } - } - } - 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)>); - -/// Stores a computed window's rows in `views` and counts it. -fn commit_window( - precompute: &Precompute, - task: CommitTask, - views: &mut Arc, - to_persist: &mut Vec, - options: &PoolOptions, - shared: &Shared, -) { - let window = task.window; - let result = { - let _gate = shared - .precompute_gate - .lock() - .unwrap_or_else(|e| e.into_inner()); - let combine = |parts: Vec| -> Result { - if task.pushed { - let delay_ms: u64 = options - .slow_refreshes - .iter() - .filter(|s| s.matches(window)) - .map(|s| s.delay_ms) - .sum(); - if delay_ms > 0 { - std::thread::sleep(std::time::Duration::from_millis(delay_ms)); - } - } - let timer = Timer::start(); - let combined = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - if task.pushed && options.panic_in_combine_of_window_end_ms == Some(window.end_ms) { - panic!( - "combine of the window ending at {} panicked (test hook)", - window.end_ms - ); - } - let mut parts = parts; - match parts.len() { - 1 => Ok(parts.remove(0)), - _ => precompute.merge(parts).map_err(|e| e.to_string()), - } - })) - .unwrap_or_else(|_| Err("the combine panicked".to_string()))?; - if let (true, Some(push)) = (task.pushed, &shared.metrics.push) { - push.combine[window.group].record(timer); - } - Ok(if task.pushed { - precompute.missing_only(window, combined, views) - } else { - combined - }) - }; - let timer = Timer::start(); - let result = task.result.and_then(combine).and_then(|computed| { - precompute - .commit(window, computed, views) - .map_err(|e| e.to_string()) - }); - 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), - Ordering::Relaxed, - ); - } - result - }; - let now = Instant::now(); - let latency = &shared.metrics.precompute_windows[window.group]; - 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), - ); - { - let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); - match result { - 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)); - } - Ok(Refreshed::AlreadyStored) => stats.windows_already_stored += 1, - Err(error) => { - tracing::error!(group = window.group, end = window.end_ms, %error, "ingestion run failed"); - stats.windows_failed += 1; - } - } - } - shared.precompute_backlog.fetch_sub(1, Ordering::SeqCst); -} - -/// A computed window ready to commit: its run, or its parts' runs by -/// part. -struct CommitTask { - window: ClosedWindow, - /// Built by push: its parts are the shards' partials. - pushed: bool, - result: Result, String>, - closed_at: Instant, - times: TaskTimes, -} - -/// Where a window taken from the backlog is. -enum TaskState { - /// Waiting for the windows it reads to be committed. - Waiting(RawShards), - /// Computing: `parts` runs, those done so far by part, and when the - /// first started and the last ended. - Running { - parts: u32, - done: BTreeMap>, - times: Option, - }, - Computed { - result: Result, String>, - times: TaskTimes, - }, -} - -struct WindowTask { - window: ClosedWindow, - pushed: bool, - closed_at: Instant, - state: TaskState, -} - -/// The windows taken from the backlog and not yet committed, by the order -/// they closed (`seq`), and the barriers between them, scheduled by the -/// plan's [`RefreshTaskGraph`]. A window starts once every earlier window -/// of the groups it reads is committed (a superset of the windows covering -/// it, since a group is listed after the groups it reads and its windows -/// close no earlier than theirs), and, in a serial group, once the group's -/// earlier windows are committed; otherwise windows of different groups, -/// and of one group, compute at once. A group's windows commit in window -/// order (a reorder buffer per group). -struct WindowTasks { - graph: RefreshTaskGraph, - /// The parts a window of a group split by series runs as. - parts: u32, - tasks: BTreeMap, - next_seq: u64, - /// Each barrier, after the windows before `seq`. - barriers: VecDeque<(u64, i64, oneshot::Sender)>, - /// Partials of pushed windows whose job has not come yet. - early: Vec, -} - -impl WindowTasks { - fn new(graph: RefreshTaskGraph, parts: u32) -> Self { - Self { - graph, - parts, - tasks: BTreeMap::new(), - next_seq: 0, - barriers: VecDeque::new(), - early: Vec::new(), - } - } - - fn is_empty(&self) -> bool { - self.tasks.is_empty() && self.barriers.is_empty() - } - - fn push(&mut self, window: ClosedWindow, raw_data: RawShards, closed_at: Instant) { - self.tasks.insert( - self.next_seq, - WindowTask { - window, - pushed: false, - closed_at, - state: TaskState::Waiting(raw_data), - }, - ); - self.next_seq += 1; - } - - /// A pushed window: computing on the shards, one partial per shard. - fn push_window(&mut self, window: ClosedWindow, closed_at: Instant, parts: u32) { - let seq = self.next_seq; - self.tasks.insert( - seq, - WindowTask { - window, - pushed: true, - closed_at, - state: TaskState::Running { - parts, - done: BTreeMap::new(), - times: None, - }, - }, - ); - self.next_seq += 1; - let early: Vec = std::mem::take(&mut self.early); - for partial in early { - self.partial(partial); - } - } - - /// A shard's partial of a pushed window. - fn partial(&mut self, partial: Partial) { - let seq = self - .tasks - .iter() - .find_map(|(&seq, task)| (task.pushed && task.window == partial.window).then_some(seq)); - match seq { - Some(seq) => self.computed( - seq, - partial.shard, - partial.result, - TaskTimes { - started: partial.started, - computed: partial.sealed_at, - }, - ), - None => self.early.push(partial), - } - } - - fn barrier(&mut self, barrier_ms: i64, reply: oneshot::Sender) { - self.barriers.push_back((self.next_seq, barrier_ms, reply)); - } - - /// The waiting windows that may start now: no earlier window of a - /// group they read is still uncommitted. They are marked running; a - /// window of a group split by series starts as one run per part. - fn start(&mut self) -> Vec<(u64, ClosedWindow, RawShards, Option)> { - let mut uncommitted = BTreeSet::new(); - let mut started = Vec::new(); - for (&seq, task) in &mut self.tasks { - let group = task.window.group; - let waits_for = |g: &usize| uncommitted.contains(g); - if matches!(task.state, TaskState::Waiting(_)) - && !self.graph.reads[group].iter().any(waits_for) - && !(self.graph.serial[group] && waits_for(&group)) - { - let parts = if self.graph.split_by_series[group] { - self.parts - } else { - 1 - }; - let running = TaskState::Running { - parts, - done: BTreeMap::new(), - times: None, - }; - let TaskState::Waiting(raw_data) = std::mem::replace(&mut task.state, running) - else { - unreachable!() - }; - if parts == 1 { - started.push((seq, task.window, raw_data, None)); - } else { - for index in 0..parts { - let partition = SeriesPartition { - index, - count: parts, - }; - started.push((seq, task.window, raw_data.clone(), Some(partition))); - } - } - } - uncommitted.insert(group); - } - started - } - - /// Part `part` of window `seq` is computed; the window is, once every - /// part is. - fn computed( - &mut self, - seq: u64, - part: u32, - result: Result, - times: TaskTimes, - ) { - let Some(task) = self.tasks.get_mut(&seq) else { - return; - }; - let TaskState::Running { - parts, - done, - times: all, - } = &mut task.state - else { - return; - }; - done.insert(part, result); - let all = all.get_or_insert(times); - all.started = all.started.min(times.started); - all.computed = all.computed.max(times.computed); - if done.len() as u32 == *parts { - let times = *all; - let result = std::mem::take(done).into_values().collect(); - task.state = TaskState::Computed { result, times }; - } - } - - /// The earliest computed window with no earlier window of its group - /// still uncommitted, removed. - fn next_commit(&mut self) -> Option { - let mut uncommitted = BTreeSet::new(); - let seq = self.tasks.iter().find_map(|(&seq, task)| { - let ready = matches!(task.state, TaskState::Computed { .. }) - && !uncommitted.contains(&task.window.group); - uncommitted.insert(task.window.group); - ready.then_some(seq) - })?; - let task = self.tasks.remove(&seq)?; - let TaskState::Computed { result, times } = task.state else { - unreachable!() - }; - Some(CommitTask { - window: task.window, - pushed: task.pushed, - result, - closed_at: task.closed_at, - times, - }) - } - - /// The barriers every window before which is committed, removed. - fn passed_barriers(&mut self) -> Vec<(i64, oneshot::Sender)> { - let first_uncommitted = self.tasks.keys().next().copied().unwrap_or(self.next_seq); - let mut passed = Vec::new(); - while self - .barriers - .front() - .is_some_and(|(seq, _, _)| *seq <= first_uncommitted) - { - let (_, barrier_ms, reply) = self.barriers.pop_front().unwrap(); - passed.push((barrier_ms, reply)); - } - passed - } -} - -/// What a persist thread does next. -enum PersistJob { - /// Write the rows each view got for its group's window `range_ms`; - /// `bytes` of the queue it releases once written. - Window { - group: usize, - range_ms: (i64, i64), - views: Vec<(PhysicalASAPNodeId, Vec)>, - /// Each view's stored window, told where it was written. - slots: Vec>>, - bytes: u64, - }, - /// Done once every window queued to this thread before is written. - Barrier(Arc), -} - -/// An event-time barrier waiting for every persist thread. -struct PersistBarrier { - barrier_ms: i64, - remaining: AtomicU64, - reply: Mutex>>, -} - -impl PersistBarrier { - /// One persist thread reached it; the last one answers. - fn reached(&self) { - if self.remaining.fetch_sub(1, Ordering::SeqCst) == 1 { - if let Some(reply) = self.reply.lock().unwrap_or_else(|e| e.into_inner()).take() { - let _ = reply.send(self.barrier_ms); - } - } - } -} - -/// The persist threads, as the precompute thread sees them: refresh group -/// `g`'s windows go to thread `g % threads`, so each file has one writer -/// and its records stay in window order. The queue between precompute and -/// the threads is bounded by bytes. -struct PersistPool { - shards: Vec>, - max_bytes: u64, -} - -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). - fn queue( - &self, - group: usize, - range_ms: (i64, i64), - views: Vec<(PhysicalASAPNodeId, Vec)>, - slots: Vec>>, - shared: &Shared, - ) { - let bytes: u64 = views - .iter() - .flat_map(|(_, batches)| batches) - .map(|batch| batch.memory_bytes() as u64) - .sum(); - // The committer never waits for the disk: a slow disk leaves more - // windows `Pending` (in memory, as without tiering) instead of - // holding refreshes, the watermark and ingest. Windows queued past - // the bound are counted. - { - let mut queued = shared - .persist_queue - .lock() - .unwrap_or_else(|e| e.into_inner()); - if *queued > 0 && *queued + bytes > self.max_bytes { - shared - .metrics - .view_persist_over_bound - .fetch_add(1, Ordering::Relaxed); - } - *queued += bytes; - } - shared.persist_backlog.fetch_add(1, Ordering::SeqCst); - let job = PersistJob::Window { - group, - range_ms, - views, - slots, - bytes, - }; - if self.shards[group % self.shards.len()].send(job).is_err() { - tracing::error!(group, "the persist thread has stopped"); - release_persist_queue(shared, bytes); - } - } - - /// Answers `reply` once every persist thread has written the windows - /// queued before. - fn barrier(&self, barrier_ms: i64, reply: oneshot::Sender) { - let barrier = Arc::new(PersistBarrier { - barrier_ms, - remaining: AtomicU64::new(self.shards.len() as u64), - reply: Mutex::new(Some(reply)), - }); - for shard in &self.shards { - if shard.send(PersistJob::Barrier(barrier.clone())).is_err() { - barrier.reached(); - } - } - } -} - -/// Releases `bytes` of the persist queue for a window written (or lost). -fn release_persist_queue(shared: &Shared, bytes: u64) { - let mut queued = shared - .persist_queue - .lock() - .unwrap_or_else(|e| e.into_inner()); - *queued = queued.saturating_sub(bytes); - shared.persist_backlog.fetch_sub(1, Ordering::SeqCst); -} - -/// The persist thread: writes each refreshed window's records to the view -/// files, in order, and syncs them every sync interval, also when no window -/// arrives; syncs everything when the precompute thread stops. -fn serve_persist( - mut files: ViewFiles, - jobs: Receiver, - shared: &Shared, - delay: std::time::Duration, - unpersistable: &BTreeSet, -) { - let metrics = &shared.metrics; - let wait = files.sync_interval().clamp( - std::time::Duration::from_millis(1), - std::time::Duration::from_secs(3600), - ); - loop { - let job = match jobs.recv_timeout(wait) { - Ok(job) => job, - Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { - match files.sync_if_due() { - Ok(ns) => metrics.view_sync_ns.fetch_add(ns, Ordering::Relaxed), - Err(error) => { - tracing::error!(%error, "syncing the view files failed"); - 0 - } - }; - continue; - } - Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, - }; - match job { - PersistJob::Window { - group, - range_ms, - views, - slots, - bytes, - } => { - // A slow disk, for tests. - if !delay.is_zero() { - std::thread::sleep(delay); - } - let records: Vec<(PhysicalASAPNodeId, &[Batch])> = views - .iter() - .filter(|(view, _)| !unpersistable.contains(view)) - .map(|(view, batches)| (*view, batches.as_slice())) - .collect(); - let skipped = (views.len() - records.len()) as u64; - let files_before = files.bytes(); - let locations = match files.append(group, range_ms, &records) { - Ok(written) => { - metrics - .view_persisted_bytes - .fetch_add(written.bytes, Ordering::Relaxed); - metrics - .view_sync_ns - .fetch_add(written.sync_ns, Ordering::Relaxed); - metrics - .view_windows_not_persisted - .fetch_add(written.not_persisted + skipped, Ordering::Relaxed); - metrics - .view_segments_marked_cold - .fetch_add(written.segments_marked_cold, Ordering::Relaxed); - written.locations - } - Err(error) => { - tracing::error!(group, ?range_ms, %error, "persisting a window failed"); - metrics - .view_windows_not_persisted - .fetch_add(views.len() as u64, Ordering::Relaxed); - Vec::new() - } - }; - // Each written window leaves memory (unless the cache keeps - // it); one that was not written stays. - for ((view, _), slot) in views.iter().zip(&slots) { - let Some(slot) = slot else { continue }; - match locations.iter().find(|(v, _)| v == view) { - Some((_, location)) => slot.stored(location.clone()), - None => slot.pin(), - } - } - // Each view's windows expire at its own retention (the - // files recorded it when indexing). - if let Err(error) = files.delete_expired(group, range_ms.1) { - tracing::error!(group, %error, "deleting expired view segments failed"); - } - let files_after = files.bytes(); - if files_after >= files_before { - metrics - .view_file_bytes - .fetch_add(files_after - files_before, Ordering::Relaxed); - } else { - metrics - .view_file_bytes - .fetch_sub(files_before - files_after, Ordering::Relaxed); - } - release_persist_queue(shared, bytes); - } - PersistJob::Barrier(barrier) => barrier.reached(), - } - } - match files.sync() { - Ok(ns) => { - metrics.view_sync_ns.fetch_add(ns, Ordering::Relaxed); - } - Err(error) => tracing::error!(%error, "syncing the view files failed"), - } - tracing::info!("persist stopped"); -} - /// The cold tier of a data plane persisting its views: the window cache /// with its budget (the option, else from the cgroup's `memory.max`, else /// none) and idle time. @@ -2464,235 +460,3 @@ fn view_tier(options: &EngineOptions) -> ViewTier { std::time::Duration::from_millis(options.cold_decode_delay_ms), ) } - -#[cfg(test)] -mod tests { - use super::*; - - /// A request is admitted while the queue stays within its bound, and - /// always into an empty queue; otherwise it is `Busy`. - #[test] - fn admission() { - assert_eq!(admit(0, 3, 2), Ok(3)); - assert_eq!(admit(1, 1, 2), Ok(2)); - assert_eq!(admit(1, 2, 2), Err(IngestError::Busy)); - assert_eq!(admit(u64::MAX, 1, u64::MAX), Err(IngestError::Busy)); - } - - /// A request reaching a full shard is refused whole: no other shard's - /// queue takes its samples. - #[test] - fn a_full_shard_refuses_the_whole_request() { - let queued: Vec = [0, 5, 0].into_iter().map(AtomicU64::new).collect(); - assert_eq!(admit_shards(&queued, &[2, 3, 1], 6), Err(IngestError::Busy)); - let now: Vec = queued.iter().map(|q| q.load(Ordering::SeqCst)).collect(); - assert_eq!(now, [0, 5, 0]); - assert_eq!(admit_shards(&queued, &[2, 1, 1], 6), Ok(())); - let now: Vec = queued.iter().map(|q| q.load(Ordering::SeqCst)).collect(); - assert_eq!(now, [2, 6, 1]); - } - - fn window(group: usize, end_ms: i64) -> ClosedWindow { - ClosedWindow { group, end_ms } - } - - fn times() -> TaskTimes { - TaskTimes { - started: Instant::now(), - computed: Instant::now(), - } - } - - /// The tasks of `graph` with `windows` pushed in order. - fn tasks(graph: RefreshTaskGraph, windows: &[ClosedWindow]) -> WindowTasks { - let mut tasks = WindowTasks::new(graph, 1); - for &w in windows { - tasks.push(w, Arc::new(Vec::new()), Instant::now()); - } - tasks - } - - fn started(tasks: &mut WindowTasks) -> Vec { - tasks - .start() - .into_iter() - .map(|(seq, _, _, _)| seq) - .collect() - } - - /// A group's windows all start at once; one finishing before an - /// earlier one waits for it and the two commit in window order. - #[test] - fn windows_commit_in_window_order_when_computed_out_of_order() { - let graph = RefreshTaskGraph { - reads: vec![vec![]], - serial: vec![false], - split_by_series: vec![false], - }; - let mut tasks = tasks(graph, &[window(0, 10), window(0, 20)]); - assert_eq!(started(&mut tasks), [0, 1]); - tasks.computed(1, 0, Ok(Computed::AlreadyStored), times()); - assert!(tasks.next_commit().is_none()); - tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); - let ends: Vec = std::iter::from_fn(|| tasks.next_commit()) - .map(|t| t.window.end_ms) - .collect(); - assert_eq!(ends, [10, 20]); - } - - /// A window of a group reading another group's views starts once the - /// earlier windows of that group are committed; an unrelated group's - /// window starts at once. - #[test] - fn a_window_waits_for_the_groups_it_reads() { - let graph = RefreshTaskGraph { - reads: vec![vec![], vec![0], vec![]], - serial: vec![false; 3], - split_by_series: vec![false; 3], - }; - let mut tasks = tasks(graph, &[window(0, 10), window(1, 10), window(2, 10)]); - assert_eq!(started(&mut tasks), [0, 2]); - tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); - assert!(started(&mut tasks).is_empty()); - assert_eq!(tasks.next_commit().unwrap().window, window(0, 10)); - assert_eq!(started(&mut tasks), [1]); - } - - /// A serial group's windows start one at a time. - #[test] - fn a_serial_group_computes_one_window_at_a_time() { - let graph = RefreshTaskGraph { - reads: vec![vec![]], - serial: vec![true], - split_by_series: vec![false], - }; - let mut tasks = tasks(graph, &[window(0, 10), window(0, 20)]); - assert_eq!(started(&mut tasks), [0]); - tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); - assert!(started(&mut tasks).is_empty()); - tasks.next_commit().unwrap(); - assert_eq!(started(&mut tasks), [1]); - } - - /// A barrier passes once every window queued before it is committed, - /// not waiting for windows queued after it. - #[test] - fn a_barrier_passes_once_the_windows_before_it_are_committed() { - let graph = RefreshTaskGraph { - reads: vec![vec![], vec![]], - serial: vec![false; 2], - split_by_series: vec![false; 2], - }; - let mut tasks = tasks(graph, &[window(0, 10)]); - let (reply, _answer) = oneshot::channel(); - tasks.barrier(10, reply); - tasks.push(window(1, 20), Arc::new(Vec::new()), Instant::now()); - assert_eq!(started(&mut tasks), [0, 1]); - assert!(tasks.passed_barriers().is_empty()); - tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); - tasks.next_commit().unwrap(); - assert_eq!(tasks.passed_barriers().len(), 1); - assert!(!tasks.is_empty()); - } - - /// A window of a group split by series starts as one run per part and - /// is committed once every part is computed, with the parts in order. - #[test] - fn a_split_window_commits_once_every_part_is_computed() { - let graph = RefreshTaskGraph { - reads: vec![vec![]], - serial: vec![false], - split_by_series: vec![true], - }; - let mut tasks = WindowTasks::new(graph, 3); - tasks.push(window(0, 10), Arc::new(Vec::new()), Instant::now()); - let parts: Vec> = - tasks.start().into_iter().map(|(_, _, _, p)| p).collect(); - assert_eq!( - parts, - (0..3) - .map(|index| Some(SeriesPartition { index, count: 3 })) - .collect::>() - ); - for part in [2, 0] { - tasks.computed(0, part, Ok(Computed::AlreadyStored), times()); - assert!(tasks.next_commit().is_none()); - } - tasks.computed(0, 1, Ok(Computed::AlreadyStored), times()); - assert_eq!(tasks.next_commit().unwrap().result.unwrap().len(), 3); - } - - /// The running flag clears when an engine thread panics. - #[test] - fn running_guard_clears_on_panic() { - let running = Arc::new(AtomicBool::new(true)); - let guard = RunningGuard(running.clone()); - let thread = std::thread::spawn(move || { - let _guard = guard; - panic!("engine bug"); - }); - assert!(thread.join().is_err()); - assert!(!running.load(Ordering::SeqCst)); - } - /// A metric read by a pushed 60 s group and a window-path 10 s group: - /// once the 10 s group closed (10, 20], a sample at 15 s is still in - /// the pushed group's open window (0, 60], so it is not late. - #[test] - fn a_pushed_groups_open_window_keeps_samples_another_group_closed() { - let workload = serde_json::from_value(serde_json::json!({ - "query_workload": {"language": "promql", "repeating_queries": [ - { - "query": "sum_over_time(m_engine_push_late[60s])", - "demand": {"fixed_interval_at": {"interval": 60000, "evaluation_phase": 0}}, - "requirements": {"accuracy": {"max_error": 0.05, "failure_probability": 0.01, - "accuracy_scope": "whole_result"}}, - "predictability": {"predictable": {"known_at": null}}, - }, - { - "query": "sum by (job) (sum_over_time(m_engine_push_late[10s]))", - "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": {"m_engine_push_late": {"series_count": 1, "sample_interval": 1000, - "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, - })) - .unwrap(); - let mut inputs = control_plane::DeploymentInputs::default(); - inputs.deployment_capabilities.raw_data_retained = false; - let plan = control_plane::plan_workload(&workload, &inputs).unwrap().0; - let options = EngineOptions { - no_forward: true, - ingestion: crate::ingestion::IngestionOptions { - allowed_lateness_ms: 0, - stream_start_ms: Some(0), - ..Default::default() - }, - ..EngineOptions::default() - }; - let (mut ingestion, ..) = - install(&serde_json::to_string(&plan).unwrap(), &options).unwrap(); - let widths: Vec = ingestion.group_windows().iter().map(|w| w.0).collect(); - assert_eq!(widths, [60_000, 10_000]); - ingestion.set_push_groups(vec![true, false]); - let series = storage::series_ids::intern_pairs(&[("__name__", "m_engine_push_late")]); - ingestion.observe(&[(series.metric.clone(), 1_000)]); - ingestion.advance_newest_sample(Some(25_000)); - ingestion.advance_clock(25_000); - let closed: Vec<(usize, i64)> = ingestion - .close() - .iter() - .map(|w| (w.group, w.end_ms)) - .collect(); - assert_eq!(closed, [(0, 0), (1, 0), (1, 10_000), (1, 20_000)]); - let sample = RawSample { - labels: series, - timestamp_ms: 15_000, - value: 1.0, - }; - let routed = ingestion.routing().route(vec![sample], 25_000); - assert_eq!(routed.accepted.len(), 1, "{:?}", routed.stats); - } -} diff --git a/crates/data-plane/src/lib.rs b/crates/data-plane/src/lib.rs index a2fc42183..4fa052255 100644 --- a/crates/data-plane/src/lib.rs +++ b/crates/data-plane/src/lib.rs @@ -15,14 +15,10 @@ //! (labels, series, metadata), proxied with `x-asap-execution: forwarded`. pub mod engine; -pub mod ingestion; mod metrics_endpoint; pub mod prometheus; -pub mod push; -pub mod query; pub mod raw_forward; pub mod remote_write; -pub mod result_cache; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -34,7 +30,8 @@ use axum::http::{header, HeaderMap, HeaderValue, Method, StatusCode}; use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use axum::Router; -use engine::{EngineHandle, EngineOptions, IngestError}; +use engine::{EngineHandle, EngineOptions}; +use precompute::engine::IngestError; use prometheus::{InstantQuery, RangeQuery}; use query::Unanswered; @@ -372,7 +369,9 @@ async fn answer( state: &DataPlane, query: InstantQuery, ) -> Result { - let time_ms = query.time_ms.unwrap_or_else(ingestion::wall_clock_ms); + let time_ms = query + .time_ms + .unwrap_or_else(precompute::ingestion::wall_clock_ms); let samples = match state.engine.cached(&query.query, time_ms) { Some(samples) => samples, None => state.engine.evaluate(query.query, time_ms).await?, diff --git a/crates/data-plane/src/main.rs b/crates/data-plane/src/main.rs index 43359a450..66eac7976 100644 --- a/crates/data-plane/src/main.rs +++ b/crates/data-plane/src/main.rs @@ -19,9 +19,10 @@ static ALLOCATOR: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc; #[export_name = "_rjem_malloc_conf"] static malloc_conf: &[u8] = b"background_thread:true,dirty_decay_ms:1000,muzzy_decay_ms:0,narenas:8\0"; -use data_plane::engine::{EngineOptions, PrecomputeMode}; -use data_plane::ingestion::IngestionOptions; +use data_plane::engine::EngineOptions; use data_plane::{router, DataPlane, DEFAULT_FORWARD_TIMEOUT}; +use precompute::engine::PrecomputeMode; +use precompute::ingestion::IngestionOptions; use storage::persist::ViewRead; /// Serve Remote Write ingestion and the Prometheus query API for a plan. @@ -78,10 +79,10 @@ struct Args { precompute_memory_budget_bytes: Option, /// Push mode: a shard folds its pending samples once this many are /// pending (0: fold every request's samples at once). - #[arg(long, default_value_t = data_plane::push::MorselBatching::default().max_samples)] + #[arg(long, default_value_t = precompute::push::MorselBatching::default().max_samples)] push_batch_samples: usize, /// Push mode: ... or once the oldest pending sample is this old. - #[arg(long, default_value_t = data_plane::push::MorselBatching::default().max_age_ms)] + #[arg(long, default_value_t = precompute::push::MorselBatching::default().max_age_ms)] push_batch_max_ms: u64, /// Threads computing closed refresh windows at once: windows of /// different refresh groups, and of one group, run in parallel and are @@ -212,7 +213,7 @@ async fn main() -> anyhow::Result<()> { view_read: args.view_read, precompute_mode: args.precompute_mode, precompute_memory_budget_bytes: args.precompute_memory_budget_bytes, - push_batching: data_plane::push::MorselBatching { + push_batching: precompute::push::MorselBatching { max_samples: args.push_batch_samples, max_age_ms: args.push_batch_max_ms, }, diff --git a/crates/data-plane/src/metrics_endpoint.rs b/crates/data-plane/src/metrics_endpoint.rs index 0af0e7b17..a6b5a9889 100644 --- a/crates/data-plane/src/metrics_endpoint.rs +++ b/crates/data-plane/src/metrics_endpoint.rs @@ -8,9 +8,9 @@ use std::sync::atomic::{AtomicU64, Ordering}; use internal_metrics::{thread_cpu_seconds, Metrics, QueryMetrics, WindowLatency}; use storage::store::{QueryTimeResults, ViewTier}; -use crate::ingestion::IngestionStats; -use crate::query::Unanswered; -use crate::result_cache::ResultCache; +use precompute::ingestion::IngestionStats; +use query::result_cache::ResultCache; +use query::Unanswered; /// What `/metrics` reports beside [`Metrics`]. pub(crate) struct Gauges<'a> { diff --git a/crates/data-plane/src/prometheus.rs b/crates/data-plane/src/prometheus.rs index 3cc788d7d..4377a3bb1 100644 --- a/crates/data-plane/src/prometheus.rs +++ b/crates/data-plane/src/prometheus.rs @@ -6,8 +6,9 @@ use std::collections::BTreeMap; use serde::{Serialize, Serializer}; use serde_json::{json, Value}; -use crate::query::ResultSample; -use crate::result_cache::Answer; +use precompute::ingestion::MAX_TIME_MS; +use query::result_cache::Answer; +use query::ResultSample; /// Parameters of an instant query, from its URL query and form body. pub struct InstantQuery { @@ -16,11 +17,6 @@ pub struct InstantQuery { pub time_ms: Option, } -/// The largest evaluation time, in milliseconds either side of the epoch, the -/// data plane answers; beyond it a request is refused as Prometheus refuses -/// a time it cannot represent. Leaves room for any window offset. -pub(crate) const MAX_TIME_MS: i64 = i64::MAX / 4; - /// Why a query's parameters are refused (400, `bad_data`): the error text. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[error("{0}")] diff --git a/crates/data-plane/tests/common/mod.rs b/crates/data-plane/tests/common/mod.rs index eb1ff9820..ae43ff871 100644 --- a/crates/data-plane/tests/common/mod.rs +++ b/crates/data-plane/tests/common/mod.rs @@ -7,10 +7,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, TimeSeries, WriteRequest}; use data_plane::{DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::Value; use tower::ServiceExt; diff --git a/crates/data-plane/tests/forward_mode.rs b/crates/data-plane/tests/forward_mode.rs index 5ec1d0209..43fef4954 100644 --- a/crates/data-plane/tests/forward_mode.rs +++ b/crates/data-plane/tests/forward_mode.rs @@ -19,11 +19,11 @@ use axum::response::IntoResponse; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::raw_forward::RawForwardOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::{json, Value}; use tokio::sync::Notify; use tower::ServiceExt; diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index f731bf932..1a7e5964a 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -11,9 +11,9 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; +use precompute::ingestion::IngestionOptions; use serde_json::{json, Value}; use tower::ServiceExt; @@ -321,16 +321,16 @@ fn clock_data_plane( /// still hold every sample: the watermark moves only behind a flush. #[tokio::test(flavor = "multi_thread")] async fn a_watermark_capped_at_the_clock_moves_only_behind_a_flush() { - let start_ms = (data_plane::ingestion::wall_clock_ms() / 1000 + 1) * 1000; + let start_ms = (precompute::ingestion::wall_clock_ms() / 1000 + 1) * 1000; let (app, state) = clock_data_plane(4, 250, start_ms); - while data_plane::ingestion::wall_clock_ms() < start_ms { + while precompute::ingestion::wall_clock_ms() < start_ms { tokio::time::sleep(std::time::Duration::from_millis(5)).await; } // Every 100 ms for 3 s: each series one sample, series i stamped // (i + 1) / 64 s after the send time. let mut sent: Vec<(usize, i64)> = Vec::new(); for _ in 0..30 { - let now_ms = data_plane::ingestion::wall_clock_ms(); + let now_ms = precompute::ingestion::wall_clock_ms(); let timeseries = (0..64usize) .map(|i| { let timestamp = now_ms + (i as i64 + 1) * 1000 / 64; @@ -358,7 +358,7 @@ async fn a_watermark_capped_at_the_clock_moves_only_behind_a_flush() { tokio::time::sleep(std::time::Duration::from_millis(100)).await; } let last_ms = sent.iter().map(|(_, t)| *t).max().unwrap(); - while data_plane::ingestion::wall_clock_ms() <= last_ms { + while precompute::ingestion::wall_clock_ms() <= last_ms { tokio::time::sleep(std::time::Duration::from_millis(20)).await; } common::barrier(&app, last_ms).await; @@ -412,7 +412,7 @@ async fn a_precompute_that_cannot_keep_up_reaches_remote_write() { max_queued_samples: 2_000, max_precompute_backlog: 1, view_dir: Some(dir.clone()), - slow_refreshes: vec![data_plane::engine::SlowRefresh { + slow_refreshes: vec![precompute::engine::SlowRefresh { group: None, end_ms: None, part: None, diff --git a/crates/data-plane/tests/pipelines/mod.rs b/crates/data-plane/tests/pipelines/mod.rs index 3b30d9ef3..1dae1cb0a 100644 --- a/crates/data-plane/tests/pipelines/mod.rs +++ b/crates/data-plane/tests/pipelines/mod.rs @@ -1,7 +1,7 @@ //! Push precompute's combine rules (docs/design/parallel-precompute.md, //! "Combine rules"): each ingestion-time breaker's rule, from the plan node //! alone. The tests check the design's table here; the data plane decides -//! which groups are pushed by its install probe (`data_plane::push::probe`). +//! which groups are pushed by its install probe (`precompute::push::probe`). use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAGNode, PhysicalASAPNodeId}; use asap_planner::InstallablePlan; diff --git a/crates/data-plane/tests/planner_executor_parity.rs b/crates/data-plane/tests/planner_executor_parity.rs index d588e1a67..1efccc3c5 100644 --- a/crates/data-plane/tests/planner_executor_parity.rs +++ b/crates/data-plane/tests/planner_executor_parity.rs @@ -44,12 +44,13 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::{plan_workload, DeploymentInputs}; -use data_plane::engine::{EngineOptions, PrecomputeMode}; -use data_plane::ingestion::IngestionOptions; +use data_plane::engine::EngineOptions; use data_plane::remote_write::{Label, Sample, TimeSeries}; 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 serde_json::Value as Json; use tower::ServiceExt; diff --git a/crates/data-plane/tests/precompute_pool.rs b/crates/data-plane/tests/precompute_pool.rs index 5e6b6bd5a..f79ee0fd4 100644 --- a/crates/data-plane/tests/precompute_pool.rs +++ b/crates/data-plane/tests/precompute_pool.rs @@ -22,10 +22,11 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; -use data_plane::engine::{EngineOptions, SlowRefresh}; -use data_plane::ingestion::IngestionOptions; +use data_plane::engine::EngineOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; +use precompute::engine::SlowRefresh; +use precompute::ingestion::IngestionOptions; use tower::ServiceExt; /// Series per metric. diff --git a/crates/data-plane/tests/push_precompute.rs b/crates/data-plane/tests/push_precompute.rs index 6ac99092a..9cbc2e857 100644 --- a/crates/data-plane/tests/push_precompute.rs +++ b/crates/data-plane/tests/push_precompute.rs @@ -23,12 +23,13 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; -use data_plane::engine::{EngineOptions, PrecomputeMode, SlowRefresh}; -use data_plane::ingestion::IngestionOptions; +use data_plane::engine::EngineOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; 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 serde_json::{json, Value}; use tower::ServiceExt; @@ -1088,8 +1089,8 @@ async fn peak_state_bytes(app: &Router, requests: Vec>) -> f64 { /// Push folding every request's samples as they come, so open state grows /// request by request (the default batches them into larger morsels). -fn per_request() -> data_plane::push::MorselBatching { - data_plane::push::MorselBatching { +fn per_request() -> precompute::push::MorselBatching { + precompute::push::MorselBatching { max_samples: 0, max_age_ms: 0, } diff --git a/crates/data-plane/tests/range_isolation.rs b/crates/data-plane/tests/range_isolation.rs index b733d6303..b7f5c102f 100644 --- a/crates/data-plane/tests/range_isolation.rs +++ b/crates/data-plane/tests/range_isolation.rs @@ -12,10 +12,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::json; use tower::ServiceExt; diff --git a/crates/data-plane/tests/range_queries.rs b/crates/data-plane/tests/range_queries.rs index d6f2b6230..202a5698a 100644 --- a/crates/data-plane/tests/range_queries.rs +++ b/crates/data-plane/tests/range_queries.rs @@ -9,9 +9,9 @@ use axum::http::StatusCode; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{Label, Sample, TimeSeries}; use data_plane::{router, DataPlane}; +use precompute::ingestion::IngestionOptions; use serde_json::json; const QUERY: &str = "sum by (job) (sum_over_time(data[10s]))"; diff --git a/crates/data-plane/tests/time_params.rs b/crates/data-plane/tests/time_params.rs index 8d4fb2455..8f19d2f78 100644 --- a/crates/data-plane/tests/time_params.rs +++ b/crates/data-plane/tests/time_params.rs @@ -13,10 +13,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane, EXECUTION_HEADER}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::{json, Value}; use tower::ServiceExt; diff --git a/crates/data-plane/tests/view_cold_allocations.rs b/crates/data-plane/tests/view_cold_allocations.rs index 90137b96d..5367f297d 100644 --- a/crates/data-plane/tests/view_cold_allocations.rs +++ b/crates/data-plane/tests/view_cold_allocations.rs @@ -16,10 +16,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::{json, Value}; use tower::ServiceExt; diff --git a/crates/data-plane/tests/view_tiering.rs b/crates/data-plane/tests/view_tiering.rs index a2ca1e6f4..3d86b7b36 100644 --- a/crates/data-plane/tests/view_tiering.rs +++ b/crates/data-plane/tests/view_tiering.rs @@ -17,10 +17,10 @@ use axum::http::{Request, StatusCode}; use axum::Router; use control_plane::plan_workload; use data_plane::engine::EngineOptions; -use data_plane::ingestion::IngestionOptions; use data_plane::remote_write::{encode, Label, Sample, TimeSeries, WriteRequest}; use data_plane::{router, DataPlane}; use http_body_util::BodyExt; +use precompute::ingestion::IngestionOptions; use serde_json::{json, Value}; use tower::ServiceExt; diff --git a/crates/precompute/Cargo.toml b/crates/precompute/Cargo.toml new file mode 100644 index 000000000..48a5642b0 --- /dev/null +++ b/crates/precompute/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "precompute" +version.workspace = true +edition.workspace = true + +# The ingest side of the data plane: ingest shards, the ingest coordinator, +# push pipelines and the precompute pool over the Planner's executor. +[dependencies] +asap-executor.workspace = true +internal_metrics.workspace = true +storage.workspace = true +anyhow.workspace = true +# `PrecomputeMode` is a command-line value of the data plane +# (`--precompute-mode`). +clap.workspace = true +futures = "0.3" +serde.workspace = true +serde_json.workspace = true +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true + +[dev-dependencies] +control_plane.workspace = true diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs new file mode 100644 index 000000000..57090cc92 --- /dev/null +++ b/crates/precompute/src/engine.rs @@ -0,0 +1,2058 @@ +//! The precompute engine: the installed plan's ingestion, compiled once +//! when it is installed, and the threads that execute it: +//! +//! - `ingest-N` shards each route the samples of the series hashed to them +//! (Remote Write is decoded on the HTTP side) and append them to their +//! own copy of the raw data, and seal and evict it when told; +//! - the `ingest` coordinator keeps the watermark over the shards, closes +//! the windows it passes, publishes the raw data and hands each closed +//! refresh window, with the raw data as it was when the window closed, +//! to the precompute pool; +//! - the precompute pool: `precompute-N` workers compute closed windows in +//! parallel (a group starts a window only after the windows of the +//! groups it reads are committed, [`RefreshTaskGraph`]), and the +//! `precompute` committer appends each group's windows' rows in window +//! order to its copy of the views and publishes them, then queues them +//! for the `persist-N` threads ([`storage::persist_pool`]). +//! +//! Windows closed and not yet refreshed (the precompute backlog) are +//! bounded by `max_precompute_backlog`: when it is full, the ingest +//! coordinator waits, the shards' queues fill and Remote Write gets 503 +//! (`max_queued_samples`). +//! +//! Each thread records the thread CPU and wall time of its phases in +//! [`Metrics`], exported on `/metrics`. + +use std::collections::{BTreeMap, BTreeSet, VecDeque}; +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::mpsc::{channel, sync_channel, Receiver, Sender, SyncSender}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, RwLock}; +use std::time::Instant; + +use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; +use asap_executor::values::Batch; +use internal_metrics::{Metrics, PushMetrics, Timer}; +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, +}; +use tokio::sync::oneshot; + +use crate::ingestion::{ + ClosedWindow, Computed, Ingestion, IngestionOptions, IngestionStats, Precompute, + RefreshTaskGraph, Refreshed, Routing, +}; +use crate::push::{Partial, PushGroup, PushShard}; + +/// How the views of a closed refresh window are built +/// (docs/design/parallel-precompute.md). The `data_plane` binary defaults +/// to `Push`, the faster mode for a running server. The library default +/// stays `Window`: it is the reference path every push test compares +/// against, so tests and other callers get it unless they ask for push. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)] +pub enum PrecomputeMode { + /// One ingestion run per closed window, over the raw samples the + /// shards buffered for it (`--precompute-mode=window`). + #[default] + Window, + /// Each ingest shard folds its samples into its own instance of each + /// window's pipelines as they arrive; at close the shards' partials are + /// combined and committed. Groups that cannot be pushed keep the + /// window path. + Push, +} + +/// For tests: the windows of refresh group `group` (any group if +/// `None`) ending at `end_ms` (any end if `None`) wait `delay_ms` before +/// they are computed; of a window split by series, only part `part` (every +/// part if `None`). With `per_series`, the delay is a run's over every +/// series, and a run over a part of the series waits that share of it, as +/// work proportional to the samples read would. +#[doc(hidden)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SlowRefresh { + pub group: Option, + pub end_ms: Option, + pub part: Option, + pub delay_ms: u64, + pub per_series: bool, +} + +impl SlowRefresh { + /// Whether it delays `window` (any part of it). + fn matches(&self, window: ClosedWindow) -> bool { + self.group.is_none_or(|g| g == window.group) + && self.end_ms.is_none_or(|e| e == window.end_ms) + } +} + +/// What the ingest coordinator does next. +enum Command { + /// A shard routed and appended a batch, or sealed and evicted. + Report(ShardReport), + /// The shard numbered here has run every message sent to it before a + /// flush. + /// With the shard's raw data as of then: what windows closing behind + /// the flush read. + Flushed(usize, Arc), + AdvanceWatermark { + barrier_ms: i64, + reply: oneshot::Sender, + }, + Stop, +} + +/// A shard's state after its last message. +struct ShardReport { + shard: usize, + /// The newest sample the shard holds. + newest_ms: Option, + /// Each metric's first sample, while a group waits for one. + first_seen: Vec<(Arc, i64)>, + /// Samples of the batch reported, counted out of the queues when the + /// coordinator applies the report. + samples: u64, +} + +/// What an ingest shard does next. +enum ShardMessage { + Samples(Vec), + /// Seal the panes through the watermark and evict by the routing's + /// cutoffs. + Maintain { + routing: Arc, + watermark_ms: Option, + }, + /// Report `Flushed` once every message before is run. + Flush, + /// Push mode: seal these windows of groups built by push and send + /// their partials; each group's windows through `through` are closed + /// or skipped. + Seal { + windows: Vec, + through: Vec>, + }, +} + +/// What the precompute committer does next, in the order the windows +/// closed. +enum PrecomputeJob { + Refresh { + window: ClosedWindow, + raw_data: RawShards, + closed_at: Instant, + }, + /// A window of a group built by push: the shards send its partials. + Push { + window: ClosedWindow, + closed_at: Instant, + }, + /// Answers `barrier_ms` once every window queued before is refreshed. + Barrier { + barrier_ms: i64, + reply: oneshot::Sender, + }, +} + +/// Why the engine did not take samples. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum IngestError { + /// More samples are queued than `max_queued_samples`; retry later. + #[error("the engine is busy: too many samples queued")] + Busy, + /// The ingest thread has stopped; no sample will be ingested again. + #[error("the engine has stopped")] + Stopped, +} + +/// What the engine's threads publish to the HTTP side and to each other. +struct Shared { + /// Samples sent to the ingest shards and not yet ingested. + queued_samples: AtomicU64, + /// The same, per shard. + shard_queued: Vec, + /// What the shards route samples by, as the coordinator last published. + routing: RwLock>, + /// Held (shared) while a request is sent to its shards, and + /// exclusively while a flush is sent, so no flush splits a request. + admission: RwLock<()>, + /// Windows closed and not yet refreshed. + precompute_backlog: AtomicU64, + /// Refreshed windows queued for the persist threads and not yet + /// written (none when the views are not persisted). + persist_backlog: Arc, + /// False once the ingest or precompute thread has exited, for any + /// reason. + running: Arc, + /// The ingestion counters: samples and skipped windows as of the last + /// command the ingest thread ran, refreshed and failed windows as the + /// precompute thread counts them. + stats: Mutex, + /// What query runs read: the raw data and views as last published. + published: Arc, + /// Held by the precompute thread during each refresh; tests hold it to + /// keep a refresh from finishing. + precompute_gate: Mutex<()>, + metrics: Arc, +} + +/// Marks the engine stopped when its thread exits, panics included. +struct RunningGuard(Arc); + +impl Drop for RunningGuard { + fn drop(&mut self) { + self.0.store(false, Ordering::SeqCst); + } +} + +/// How the precompute engine ingests samples and builds the views; the +/// data plane's `EngineOptions` describes each field. +#[derive(Debug, Clone)] +pub struct PrecomputeOptions { + pub ingestion: IngestionOptions, + pub max_queued_samples: u64, + pub max_precompute_backlog: usize, + pub ingest_threads: usize, + pub precompute_threads: usize, + pub slow_refreshes: Vec, + pub check_task_inputs: bool, + pub shard_delay_ms: u64, + pub precompute_mode: PrecomputeMode, + pub push_batching: crate::push::MorselBatching, + pub precompute_memory_budget_bytes: Option, + pub panic_in_combine_of_window_end_ms: Option, +} + +/// Where the views are persisted, when they are: the view files' +/// directory, what names them, how they are synced and rolled, the +/// persist threads, and the cold tier windows are read back through. +pub struct PersistedViews { + pub dir: std::path::PathBuf, + /// The installed plan file's hash ([`storage::persist::plan_hash`]): + /// files of another plan are set aside, not loaded. + pub plan_hash: u64, + pub sync_interval: std::time::Duration, + pub segment_ms: i64, + pub persist: PersistOptions, + pub tier: Arc, +} + +/// The precompute engine: the `ingest-N` shards, the `ingest` +/// coordinator, the precompute pool and committer, and (with persisted +/// views) the `persist-N` threads and the `view-cache` monitor. +#[derive(Clone)] +pub struct PrecomputeEngine { + commands: Sender, + /// Each ingest shard's queue; a sample goes to the shard of its series. + shards: Vec>, + shared: Arc, + max_queued_samples: u64, +} + +impl PrecomputeEngine { + /// Starts the threads that run `ingestion` and `precompute`, compiled + /// from the installed plan, whose queries are `query_texts`; they + /// publish what query runs read to `published`. With `persisted`, the + /// views stored in its files are indexed first. + pub fn start( + mut ingestion: Ingestion, + precompute: Precompute, + query_texts: &[String], + options: &PrecomputeOptions, + persisted: Option, + published: Arc, + ) -> anyhow::Result { + let precompute = Arc::new(precompute); + // Push mode: the groups the shards build by push. + let push_groups: Vec> = match options.precompute_mode { + PrecomputeMode::Window => vec![None; precompute.groups().len()], + PrecomputeMode::Push => { + 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() + }) + .collect(); + crate::push::probe( + &precompute, + &candidates, + &ingestion.group_windows(), + &ingestion.group_metrics(), + ) + } + }; + ingestion.set_push_groups(push_groups.iter().map(Option::is_some).collect()); + let mut views = ViewStore::default().with_stream_start(options.ingestion.stream_start_ms); + let files = match persisted { + Some(persisted) => { + views = ViewStore::tiered(persisted.tier.clone()) + .with_stream_start(options.ingestion.stream_start_ms); + let dir = &persisted.dir; + let mut files = ViewFiles::open(dir, persisted.plan_hash, persisted.sync_interval)? + .with_segment_ms(persisted.segment_ms); + // Indexed, not decoded: the first reads decode what they read. + let mut index = files.index(&precompute.views())?; + let mut loaded = 0; + for (view, schema) in precompute.views().into_iter().flatten() { + for (range, location) in index.remove(&view.node_id).unwrap_or_default() { + if views + .append_stored(&view, range, location, schema.clone()) + .is_ok() + { + loaded += 1; + } + } + } + tracing::info!(dir = %dir.display(), windows = loaded, "indexed persisted views"); + if loaded > 0 { + ingestion.restarted(); + views.restarted(); + } + Some((files, loaded, persisted.persist, persisted.tier)) + } + None => None, + }; + let shard_count = options.ingest_threads.max(1); + let raw_shards: Vec> = (0..shard_count) + .map(|_| Arc::new(ingestion.raw_data())) + .collect(); + let groups: Vec<(i64, Vec)> = precompute + .groups() + .into_iter() + .map(|(width_ms, views)| (width_ms, views.iter().map(ToString::to_string).collect())) + .collect(); + let mut metrics = Metrics::new(&groups, query_texts); + if options.precompute_mode == PrecomputeMode::Push { + metrics.push = Some(PushMetrics::new(groups.len(), shard_count)); + } + let metrics = Arc::new(metrics); + let pushed: Arc> = Arc::new(push_groups.iter().map(Option::is_some).collect()); + // The committer's inbox; the shards' partials reach it through a + // forwarder. + let (events, inbox) = channel::(); + let (partials, partial_inbox) = channel::(); + { + let events = events.clone(); + std::thread::Builder::new() + .name("precompute-partials".into()) + .spawn(move || { + for partial in partial_inbox { + if events.send(PoolEvent::Partial(partial)).is_err() { + break; + } + } + })?; + } + let running = Arc::new(AtomicBool::new(true)); + published.publish_raw_data(Arc::new(raw_shards.clone()), None); + let shared = Arc::new(Shared { + queued_samples: AtomicU64::new(0), + shard_queued: (0..shard_count).map(|_| AtomicU64::new(0)).collect(), + routing: RwLock::new(Arc::new(ingestion.routing())), + admission: RwLock::new(()), + precompute_backlog: AtomicU64::new(0), + persist_backlog: Arc::default(), + running: running.clone(), + stats: Mutex::new(IngestionStats::default()), + published, + precompute_gate: Mutex::new(()), + metrics, + }); + let (commands, command_receiver) = channel(); + let (jobs, job_receiver) = sync_channel(options.max_precompute_backlog.max(1)); + + let mut shards = Vec::new(); + for (index, raw_data) in raw_shards.iter().enumerate() { + let (shard, messages) = channel(); + let (coordinator, raw_data) = (commands.clone(), raw_data.clone()); + let shard_shared = shared.clone(); + let guard = RunningGuard(running.clone()); + let delay = std::time::Duration::from_millis(if index == 0 { + 0 + } else { + options.shard_delay_ms + }); + let push_init = (options.precompute_mode == PrecomputeMode::Push).then(|| { + ( + precompute.clone(), + push_groups.clone(), + ingestion.pane_width_ms(), + options.precompute_memory_budget_bytes, + partials.clone(), + options.push_batching, + ) + }); + std::thread::Builder::new() + .name(format!("ingest-{index}")) + .spawn(move || { + let _guard = guard; + let push = + push_init.map(|(precompute, groups, pane, budget, partials, batching)| { + PushShard::new( + index, precompute, groups, pane, budget, partials, batching, + ) + }); + serve_shard( + index, + raw_data, + messages, + coordinator, + &shard_shared, + delay, + push, + ); + })?; + shards.push(shard); + } + let ingest_guard = RunningGuard(running.clone()); + let ingest_shared = shared.clone(); + let coordinator_shards = shards.clone(); + std::thread::Builder::new() + .name("ingest".into()) + .spawn(move || { + let _guard = ingest_guard; + serve_ingest( + ingestion, + raw_shards, + coordinator_shards, + command_receiver, + jobs, + &ingest_shared, + &pushed, + ); + })?; + let views = Arc::new(views); + shared.published.publish_views(views.clone()); + shared + .metrics + .view_bytes + .store(views.bytes() as u64, Ordering::Relaxed); + let persist = match files { + Some((files, loaded, persist, tier)) => { + shared + .metrics + .view_windows_loaded + .store(loaded, Ordering::Relaxed); + shared + .metrics + .view_file_bytes + .store(files.bytes(), Ordering::Relaxed); + let pool = PersistPool::spawn( + files, + persist, + shared.persist_backlog.clone(), + shared.metrics.clone(), + )?; + let (monitor_running, budget) = (running.clone(), tier.cache.max_bytes()); + std::thread::Builder::new() + .name("view-cache".into()) + .spawn(move || serve_view_cache(tier, budget, monitor_running))?; + Some(pool) + } + None => None, + }; + spawn_precompute( + precompute, + views, + persist, + job_receiver, + (events, inbox), + PoolOptions { + threads: options.precompute_threads.max(1), + slow_refreshes: options.slow_refreshes.clone(), + check_task_inputs: options.check_task_inputs, + push_parts: shard_count as u32, + panic_in_combine_of_window_end_ms: options.panic_in_combine_of_window_end_ms, + }, + RunningGuard(running), + &shared, + )?; + Ok(Self { + commands, + shards, + shared, + max_queued_samples: options.max_queued_samples, + }) + } + + /// Queues `samples` for ingestion. `Busy` when the queue would hold + /// more than `max_queued_samples`; `Stopped` when the engine has exited. + pub fn try_ingest(&self, samples: Vec) -> Result<(), IngestError> { + if !self.is_running() { + return Err(IngestError::Stopped); + } + // Each series' samples go to one shard, in order. + let mut by_shard: Vec> = Vec::new(); + if self.shards.len() == 1 { + by_shard.push(samples); + } else { + // Room for a fair share and a quarter more, so a request rarely + // grows a shard's vector. + let room = samples.len() / self.shards.len() * 5 / 4 + 1; + by_shard.resize_with(self.shards.len(), || Vec::with_capacity(room)); + for sample in samples { + by_shard[sample.labels.id as usize % self.shards.len()].push(sample); + } + } + let counts: Vec = by_shard.iter().map(|s| s.len() as u64).collect(); + // A request reaches its shards whole between two flushes, never + // split by one: a flush covers all of it or none. + let _sending = self + .shared + .admission + .read() + .unwrap_or_else(|e| e.into_inner()); + admit_shards(&self.shared.shard_queued, &counts, self.max_queued_samples)?; + let shared = &self.shared; + for (shard, samples) in by_shard.into_iter().enumerate() { + let count = samples.len() as u64; + if count == 0 { + continue; + } + shared.queued_samples.fetch_add(count, Ordering::SeqCst); + if self.shards[shard] + .send(ShardMessage::Samples(samples)) + .is_err() + { + // This shard and the ones not sent to yet were admitted + // but get nothing. + shared.queued_samples.fetch_sub(count, Ordering::SeqCst); + for (queued, &later) in shared.shard_queued[shard..].iter().zip(&counts[shard..]) { + queued.fetch_sub(later, Ordering::SeqCst); + } + return Err(IngestError::Stopped); + } + } + Ok(()) + } + + /// Whether the ingest and precompute threads are still running. + pub fn is_running(&self) -> bool { + self.shared.running.load(Ordering::SeqCst) + } + + /// Samples queued and not yet ingested. + pub fn queued_samples(&self) -> u64 { + self.shared.queued_samples.load(Ordering::SeqCst) + } + + /// Refresh windows closed and not yet refreshed. + pub fn precompute_backlog(&self) -> u64 { + self.shared.precompute_backlog.load(Ordering::SeqCst) + } + + /// The ingestion counters. + pub fn stats(&self) -> IngestionStats { + *self.shared.stats.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Queues an event-time barrier behind every write already acknowledged + /// and waits until it has run and every window it closed is refreshed: + /// every window ending at or before `barrier_ms` (capped at the wall + /// clock) is then answered from. Returns the barrier in force; see + /// [`Ingestion::advance_watermark_at`]. + pub async fn advance_watermark(&self, barrier_ms: i64) -> Result { + if !self.is_running() { + return Err(IngestError::Stopped); + } + let (reply, done) = oneshot::channel(); + self.commands + .send(Command::AdvanceWatermark { barrier_ms, reply }) + .map_err(|_| IngestError::Stopped)?; + done.await.map_err(|_| IngestError::Stopped) + } + + /// For tests: stops the ingest thread after the commands queued before, + /// and the precompute thread once it has refreshed the windows queued + /// before. Samples queued between this call and the stop are + /// acknowledged and then lost; ingestion after the stop fails with + /// [`IngestError::Stopped`]. + #[doc(hidden)] + pub fn stop(&self) { + let _ = self.commands.send(Command::Stop); + } + + /// For tests: no refresh finishes while the guard is held. + #[doc(hidden)] + pub fn hold_precompute(&self) -> MutexGuard<'_, ()> { + self.shared + .precompute_gate + .lock() + .unwrap_or_else(|e| e.into_inner()) + } + + /// The engine's measurements. + pub fn metrics(&self) -> &Arc { + &self.shared.metrics + } + + /// Refreshed windows queued for the persist threads and their bytes. + pub fn persist_backlog(&self) -> &PersistBacklog { + &self.shared.persist_backlog + } +} + +/// Admits `counts[i]` samples to shard `i`'s queue `queued[i]` for every +/// shard, or none: `Busy` if any shard's queue would pass `max_queued` +/// ([`admit`]), and then no queue changes, so a request is taken whole or +/// not at all. +fn admit_shards(queued: &[AtomicU64], counts: &[u64], max_queued: u64) -> Result<(), IngestError> { + let mut admitted: Vec = Vec::new(); + for (shard, &count) in counts.iter().enumerate() { + if count == 0 { + continue; + } + let queue = &queued[shard]; + let mut current = queue.load(Ordering::SeqCst); + let result = loop { + let total = match admit(current, count, max_queued) { + Ok(total) => total, + Err(error) => break Err(error), + }; + match queue.compare_exchange(current, total, Ordering::SeqCst, Ordering::SeqCst) { + Ok(_) => break Ok(()), + Err(now) => current = now, + } + }; + if let Err(error) = result { + for shard in admitted { + queued[shard].fetch_sub(counts[shard], Ordering::SeqCst); + } + return Err(error); + } + admitted.push(shard); + } + Ok(()) +} + +/// The queue length after admitting `count` samples to a queue of +/// `queued`: admitted while the total stays within `max_queued`, and always +/// into an empty queue, so a bound smaller than one request cannot refuse +/// that request forever. +fn admit(queued: u64, count: u64, max_queued: u64) -> Result { + let total = queued.checked_add(count).ok_or(IngestError::Busy)?; + if queued == 0 || total <= max_queued { + Ok(total) + } else { + Err(IngestError::Busy) + } +} + +/// What crosses threads: the compiled refresh runs, the store snapshots +/// runs read, and what the threads share. +#[allow(dead_code)] +fn assert_send_sync() {} +#[allow(dead_code)] +fn assert_send() {} +const _: fn() = || { + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send_sync::(); + assert_send::(); +}; + +/// 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 { + let _admission = shared.admission.write().unwrap_or_else(|e| e.into_inner()); + let sent_ms = crate::ingestion::wall_clock_ms(); + for shard in shards { + let _ = shard.send(ShardMessage::Flush); + } + sent_ms +} + +/// 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. +fn serve_shard( + index: usize, + mut raw_data: Arc, + messages: Receiver, + coordinator: Sender, + shared: &Shared, + delay: std::time::Duration, + mut push: Option, +) { + let mut newest_ms: Option = None; + // A message taken while draining a batch, to run next. + let mut next: Option = None; + loop { + let message = match next.take() { + Some(message) => message, + None => match messages.recv() { + Ok(message) => message, + Err(_) => break, + }, + }; + let mut samples = match message { + ShardMessage::Samples(samples) => samples, + // Eviction changes no sample time: no report (each would start + // another coordinator pass). + ShardMessage::Maintain { + routing, + watermark_ms, + } => { + routing.maintain(Arc::make_mut(&mut raw_data), watermark_ms); + continue; + } + ShardMessage::Flush => { + // The raw data travels only with a flush, which a window + // closing reads; the coordinator lets it go after its pass, + // so appending rarely copies the pane lists it shares. + if coordinator + .send(Command::Flushed(index, raw_data.clone())) + .is_err() + { + break; + } + continue; + } + ShardMessage::Seal { windows, through } => { + if let Some(push) = &mut push { + push.seal(&windows, &through, &shared.metrics); + } + continue; + } + }; + // Every batch already queued, appended and reported at once: one + // report (and so at most one coordinator pass) per drained queue, + // not per request. + let mut count = 0; + let mut first_seen = Vec::new(); + loop { + if !delay.is_zero() { + std::thread::sleep(delay); + } + let timer = Timer::start(); + count += samples.len() as u64; + let routing = shared + .routing + .read() + .unwrap_or_else(|e| e.into_inner()) + .clone(); + let routed = routing.route(samples, crate::ingestion::wall_clock_ms()); + Arc::make_mut(&mut raw_data).append(&routed.accepted); + newest_ms = newest_ms.max(routed.newest_ms); + if let Some(push) = &mut push { + push.push(&routed.accepted, &shared.metrics); + } + { + let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); + 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); + match messages.try_recv() { + Ok(ShardMessage::Samples(more)) => samples = more, + Ok(other) => { + next = Some(other); + break; + } + Err(_) => break, + } + } + let report = ShardReport { + shard: index, + newest_ms, + first_seen, + samples: count, + }; + // The coordinator counts the samples out of the queues when it + // applies the report, so samples stay counted while it cannot keep + // up (waiting for the precompute workers): the queues fill and + // Remote Write gets 503, and reports waiting for it stay bounded. + if coordinator.send(Command::Report(report)).is_err() { + break; + } + } +} + +/// The ingest coordinator: keeps the watermark over the shards, closes the +/// windows it passes and queues their refreshes over every shard's raw data +/// as it was then, publishes the raw data and the routing, and has the +/// shards seal and evict as the watermark moves. The watermark follows the +/// newest sample of any shard, capped at the wall clock; it moves only +/// behind a flush, which every pass that took a report or a barrier +/// sends: every shard runs the samples queued to it, so a window closes +/// over every sample admitted before. The clock cap is the time that flush +/// 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. +fn serve_ingest( + mut ingestion: Ingestion, + mut raw_shards: Vec>, + shards: Vec>, + commands: Receiver, + jobs: SyncSender, + shared: &Shared, + pushed: &[bool], +) { + 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; + 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); + shared + .queued_samples + .fetch_sub(report.samples, Ordering::SeqCst); + newest[report.shard] = report.newest_ms; + }; + // Barriers that came while a flush was waited for: written after it, + // so they take the next pass, behind its own flush. + let mut deferred: VecDeque<(i64, oneshot::Sender)> = VecDeque::new(); + // Reports a shard sent after answering a flush, of samples admitted + // after it: held for the next pass, so they move neither this pass's + // watermark nor its raw data. Without this, a shard that ran ahead + // would move the watermark past samples other shards have yet to + // append, and windows would close without them. + let mut held: Vec = Vec::new(); + let queries_read_raw_data = ingestion.queries_read_raw_data(); + // Published in place of the raw data when no query reads it. + let no_raw_data: RawShards = Arc::new( + (0..shards.len()) + .map(|_| Arc::new(ingestion.raw_data())) + .collect(), + ); + 'serve: loop { + let mut barriers: Vec<_> = deferred.drain(..).collect(); + // Whether anything this pass may move the watermark: a newer + // 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(); + for report in held.drain(..) { + apply(report, &mut ingestion, &mut newest); + } + if !moved { + match commands.recv_timeout(TICK) { + Ok(Command::Report(report)) => { + apply(report, &mut ingestion, &mut newest); + moved = true; + } + Ok(Command::Flushed(..)) => {} + Ok(Command::AdvanceWatermark { barrier_ms, reply }) => { + barriers.push((barrier_ms, reply)); + moved = true; + } + Ok(Command::Stop) => break, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {} + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + } + } + // Drain what was already sent, so one pass takes it all. A barrier + // taken here is behind every write acknowledged before it, as the + // flush below is sent after it. + while let Ok(command) = commands.try_recv() { + match command { + Command::Report(report) => { + apply(report, &mut ingestion, &mut newest); + moved = true; + } + Command::Flushed(..) => {} + Command::AdvanceWatermark { barrier_ms, reply } => { + barriers.push((barrier_ms, reply)); + moved = true; + } + Command::Stop => break 'serve, + } + } + // 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; + if moved { + let flushed_ms = flush(&shards, shared); + let mut flushed = vec![false; shards.len()]; + while !flushed.iter().all(|&f| f) { + match commands.recv_timeout(TICK) { + Ok(Command::Report(report)) + if flushed[report.shard] + || held.iter().any(|r| r.shard == report.shard) => + { + held.push(report) + } + Ok(Command::Report(report)) => apply(report, &mut ingestion, &mut newest), + Ok(Command::Flushed(shard, raw_data)) => { + flushed[shard] = true; + raw_shards[shard] = raw_data; + } + Ok(Command::AdvanceWatermark { barrier_ms, reply }) => { + deferred.push_back((barrier_ms, reply)) + } + Ok(Command::Stop) => break 'serve, + // A shard that died never answers: stop, failing the + // barriers waiting. + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + if !shared.running.load(Ordering::SeqCst) { + break 'serve; + } + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break 'serve, + } + } + ingestion.advance_clock(flushed_ms); + } + let newest_ms = newest.iter().flatten().copied().max(); + ingestion.advance_newest_sample(newest_ms); + let mut closed = ingestion.close(); + let mut answered = Vec::new(); + for (barrier_ms, reply) in barriers { + let (barrier_ms, more) = ingestion.advance_watermark(barrier_ms); + closed.extend(more); + answered.push((barrier_ms, reply)); + } + let snapshot: RawShards = Arc::new(raw_shards.clone()); + let sealed: Vec = closed + .iter() + .copied() + .filter(|w| pushed.get(w.group).copied().unwrap_or(false)) + .collect(); + if !sealed.is_empty() { + let through = ingestion.refreshed_through(); + for shard in &shards { + let _ = shard.send(ShardMessage::Seal { + windows: sealed.clone(), + through: through.clone(), + }); + } + } + if !queue_refreshes(&closed, &snapshot, &jobs, shared, pushed) { + break; + } + 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() { + sealed_through = watermark_ms; + for shard in &shards { + let _ = shard.send(ShardMessage::Maintain { + routing: routing.clone(), + watermark_ms, + }); + } + } + let metrics = &shared.metrics; + if let Some(watermark_ms) = watermark_ms { + metrics.watermark_ms.store(watermark_ms, Ordering::Relaxed); + } + if flushed { + let sum = |f: fn(&RawData) -> usize| snapshot.iter().map(|r| f(r) as u64).sum::(); + metrics + .raw_data_bytes + .store(sum(RawData::bytes), Ordering::Relaxed); + metrics + .raw_data_samples + .store(sum(RawData::len), Ordering::Relaxed); + metrics + .raw_data_panes + .store(sum(RawData::panes), Ordering::Relaxed); + } + if queries_read_raw_data { + shared + .published + .publish_raw_data(snapshot.clone(), watermark_ms); + } else { + // No query reads the raw data, and the next windows to close + // read it as of their own flush: let the shards' raw data go, + // so their next appends own it again instead of copying the + // pane lists this snapshot shares (only the queued refreshes + // still hold it, until they run). + shared + .published + .publish_raw_data(no_raw_data.clone(), watermark_ms); + drop(snapshot); + for raw_data in raw_shards.iter_mut() { + *raw_data = no_raw_data[0].clone(); + } + } + { + 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; + } + for (barrier_ms, reply) in answered { + if jobs + .send(PrecomputeJob::Barrier { barrier_ms, reply }) + .is_err() + { + break 'serve; + } + } + } + tracing::warn!("ingest stopped"); +} + +/// Queues a refresh of each of `closed` over `raw_data`, waiting while the +/// backlog is full; `false` once the precompute thread has exited. +fn queue_refreshes( + closed: &[ClosedWindow], + raw_data: &RawShards, + jobs: &SyncSender, + shared: &Shared, + pushed: &[bool], +) -> bool { + for &window in closed { + shared.precompute_backlog.fetch_add(1, Ordering::SeqCst); + let job = if pushed.get(window.group).copied().unwrap_or(false) { + PrecomputeJob::Push { + window, + closed_at: Instant::now(), + } + } else { + PrecomputeJob::Refresh { + window, + raw_data: raw_data.clone(), + closed_at: Instant::now(), + } + }; + if jobs.send(job).is_err() { + return false; + } + } + true +} + +/// How the precompute task pool runs. +#[derive(Clone)] +struct PoolOptions { + threads: usize, + slow_refreshes: Vec, + check_task_inputs: bool, + /// The partials a pushed window combines: one per ingest shard. + push_parts: u32, + panic_in_combine_of_window_end_ms: Option, +} + +/// What the precompute committer waits for. +enum PoolEvent { + /// The next job, in the order the windows closed. + Job(PrecomputeJob), + /// A worker computed window `seq`, or its part `part` of a window split + /// by series. + Computed { + seq: u64, + part: u32, + result: Result, + times: TaskTimes, + }, + /// A shard's partial of a pushed window. + Partial(Partial), + /// No job will come any more. + Closed, +} + +/// When a window's computation started and ended. +#[derive(Debug, Clone, Copy)] +struct TaskTimes { + started: Instant, + computed: Instant, +} + +/// A window for a worker to compute. +struct WindowRun { + seq: u64, + window: ClosedWindow, + raw_data: RawShards, + /// The views as committed when the run was started: every window of + /// the groups it reads that closed before it. + views: Arc, + /// The series the run reads, when the window is split by series. + partition: Option, +} + +/// Starts the precompute task pool: the committer (`precompute`, today's +/// precompute thread), which takes the closed windows in order, starts +/// them, and stores and publishes their rows in window order, so the view +/// store keeps one writer; and, with more than one thread, the workers +/// `precompute-N` that compute the windows, and `precompute-queue`, which +/// takes jobs from the bounded backlog for the committer as room frees. +#[allow(clippy::too_many_arguments)] +fn spawn_precompute( + precompute: Arc, + views: Arc, + persist: Option, + jobs: Receiver, + (events, inbox): (Sender, Receiver), + options: PoolOptions, + guard: RunningGuard, + shared: &Arc, +) -> std::io::Result<()> { + shared + .metrics + .precompute_threads + .store(options.threads as u64, Ordering::Relaxed); + for (group, &split) in precompute.tasks().split_by_series.iter().enumerate() { + let parts = if split { options.threads } else { 1 }; + shared.metrics.precompute_windows[group] + .parts + .store(parts as u64, Ordering::Relaxed); + } + // Windows taken from the backlog and not yet committed: one at a time + // when the committer computes them itself; with workers, two per + // worker, so a slow window does not leave the others idle while the + // windows after it wait to be committed. + let slots = Arc::new(Slots::new(if options.threads == 1 { + 1 + } else { + 2 * options.threads + })); + let workers = if options.threads == 1 { + None + } else { + let (runs, run_receiver) = channel::(); + let run_receiver = Arc::new(Mutex::new(run_receiver)); + for index in 0..options.threads { + let (precompute, shared, runs, events) = ( + precompute.clone(), + shared.clone(), + run_receiver.clone(), + events.clone(), + ); + let checks = options.clone(); + std::thread::Builder::new() + .name(format!("precompute-{index}")) + .spawn(move || loop { + let run = match runs.lock().unwrap_or_else(|e| e.into_inner()).recv() { + Ok(run) => run, + Err(_) => break, + }; + let (result, times) = compute_window( + &precompute, + run.window, + run.raw_data, + run.views, + run.partition, + &checks, + &shared, + ); + let event = PoolEvent::Computed { + seq: run.seq, + part: run.partition.map_or(0, |p| p.index), + result, + times, + }; + if events.send(event).is_err() { + break; + } + })?; + } + Some(runs) + }; + { + let (slots, shared) = (slots.clone(), shared.clone()); + std::thread::Builder::new() + .name("precompute-queue".into()) + .spawn(move || { + for job in jobs { + if matches!( + job, + PrecomputeJob::Refresh { .. } | PrecomputeJob::Push { .. } + ) && !slots.acquire(&shared.running) + { + break; + } + if events.send(PoolEvent::Job(job)).is_err() { + break; + } + } + let _ = events.send(PoolEvent::Closed); + })?; + } + let shared = shared.clone(); + std::thread::Builder::new() + .name("precompute".into()) + .spawn(move || { + let _guard = guard; + serve_precompute( + &precompute, + views, + persist, + inbox, + workers, + &slots, + &options, + &shared, + ); + })?; + Ok(()) +} + +/// A counting semaphore: the windows taken from the backlog and not yet +/// committed. +struct Slots { + free: Mutex, + freed: Condvar, +} + +impl Slots { + fn new(count: usize) -> Self { + Self { + free: Mutex::new(count), + freed: Condvar::new(), + } + } + + /// Takes a slot, waiting for one; `false` once the engine has stopped. + fn acquire(&self, running: &AtomicBool) -> bool { + let mut free = self.free.lock().unwrap_or_else(|e| e.into_inner()); + while *free == 0 { + if !running.load(Ordering::SeqCst) { + return false; + } + free = self + .freed + .wait_timeout(free, std::time::Duration::from_millis(100)) + .unwrap_or_else(|e| e.into_inner()) + .0; + } + *free -= 1; + true + } + + fn release(&self) { + *self.free.lock().unwrap_or_else(|e| e.into_inner()) += 1; + self.freed.notify_one(); + } +} + +/// Computes `window` on this thread, after its test delay; a panic in the +/// run fails the window, not the thread. +fn compute_window( + precompute: &Precompute, + window: ClosedWindow, + raw_data: RawShards, + views: Arc, + partition: Option, + options: &PoolOptions, + shared: &Shared, +) -> (Result, TaskTimes) { + let started = Instant::now(); + let inputs = options + .check_task_inputs + .then(|| TaskInputs::read(precompute, window, &raw_data, &views)); + let delay_ms: u64 = options + .slow_refreshes + .iter() + .filter(|s| s.matches(window)) + .filter(|s| { + s.part + .is_none_or(|part| partition.is_none_or(|p| p.index == part)) + }) + .map(|s| match (s.per_series, partition) { + (true, Some(partition)) => s.delay_ms / u64::from(partition.count), + _ => s.delay_ms, + }) + .sum(); + if delay_ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(delay_ms)); + } + let timer = Timer::start(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + precompute + .compute(window, raw_data, views, partition) + .map_err(|e| e.to_string()) + })) + .unwrap_or_else(|panic| { + let reason = panic + .downcast_ref::<&str>() + .map(ToString::to_string) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_default(); + Err(format!("the ingestion run panicked: {reason}")) + }); + if !matches!(result, Ok(Computed::AlreadyStored)) { + shared.metrics.precompute[window.group].1.record(timer); + } + let result = match inputs { + Some((before, raw_data, views)) => result.and_then(|computed| { + before.check(window)?; + if TaskInputs::read(precompute, window, &raw_data, &views).0 != before { + return Err("a run's inputs changed while it ran".into()); + } + Ok(computed) + }), + None => result, + }; + let computed = Instant::now(); + shared + .metrics + .precompute_busy_ns + .fetch_add((computed - started).as_nanos() as u64, Ordering::Relaxed); + (result, TaskTimes { started, computed }) +} + +/// What a window's run reads, for tests: each raw shard's identity, +/// samples and panes, the view store's identity, and how far each view of the groups +/// it reads is stored. +#[derive(Debug, PartialEq, Eq)] +struct TaskInputs { + raw_shards: Vec<(usize, usize, usize)>, + views: usize, + read_views_stored_through: Vec>, +} + +impl TaskInputs { + /// The inputs as of now, and the snapshots to read them again from. + fn read( + precompute: &Precompute, + window: ClosedWindow, + raw_data: &RawShards, + views: &Arc, + ) -> (Self, RawShards, Arc) { + let groups = precompute.groups(); + let inputs = Self { + raw_shards: raw_data + .iter() + // Samples and panes, not bytes: a chunk builds its series + // identity column once, on first read, and counts it. + .map(|shard| (Arc::as_ptr(shard) as usize, shard.len(), shard.panes())) + .collect(), + views: Arc::as_ptr(views) as usize, + read_views_stored_through: precompute.tasks().reads[window.group] + .iter() + .flat_map(|&group| &groups[group].1) + .map(|&view| views.stored_through(view)) + .collect(), + }; + (inputs, raw_data.clone(), views.clone()) + } + + /// Every view of the groups the window reads is committed through the + /// window's end. + fn check(&self, window: ClosedWindow) -> Result<(), String> { + if self + .read_views_stored_through + .iter() + .all(|stored| stored.is_some_and(|end| end >= window.end_ms)) + { + Ok(()) + } else { + Err(format!( + "window {window:?} ran before the views it reads were committed: {:?}", + self.read_views_stored_through + )) + } + } +} + +/// The precompute committer: takes the jobs in the order the windows +/// closed, starts each window once the windows it reads are committed, +/// commits computed windows in window order per group, publishes the views +/// once per pass and then queues the windows for the persist threads, and +/// answers a barrier once every window before it is committed. Without +/// `workers` it computes each window itself. +#[allow(clippy::too_many_arguments)] +fn serve_precompute( + precompute: &Precompute, + mut views: Arc, + persist: Option, + inbox: Receiver, + workers: Option>, + slots: &Slots, + options: &PoolOptions, + shared: &Shared, +) { + // A window of a group split by series runs as one part per worker. + let parts = if workers.is_some() { + options.threads + } else { + 1 + }; + let mut tasks = WindowTasks::new(precompute.tasks().clone(), parts as u32); + let mut closed = false; + while !(closed && tasks.is_empty()) { + let Ok(event) = inbox.recv() else { + break; + }; + // Take every event already sent, so one pass commits and publishes + // them together (as an ASAPQuery worker emits the windows one + // flush closed as one batch: `precompute_engine/worker.rs`, + // `flush_all`). + let mut next = Some(event); + while let Some(event) = next.take().or_else(|| inbox.try_recv().ok()) { + match event { + PoolEvent::Job(PrecomputeJob::Refresh { + window, + raw_data, + closed_at, + }) => tasks.push(window, raw_data, closed_at), + PoolEvent::Job(PrecomputeJob::Push { window, closed_at }) => { + tasks.push_window(window, closed_at, options.push_parts) + } + PoolEvent::Partial(partial) => tasks.partial(partial), + PoolEvent::Job(PrecomputeJob::Barrier { barrier_ms, reply }) => { + tasks.barrier(barrier_ms, reply) + } + PoolEvent::Computed { + seq, + part, + result, + times, + } => tasks.computed(seq, part, result, times), + PoolEvent::Closed => closed = true, + } + } + let mut to_persist = Vec::new(); + let mut committed = false; + loop { + // Started after every commit, so a window that reads another + // group's views sees exactly the windows that closed before it. + for (seq, window, raw_data, partition) in tasks.start() { + match &workers { + Some(workers) => { + let run = WindowRun { + seq, + window, + raw_data, + views: views.clone(), + partition, + }; + if workers.send(run).is_err() { + tracing::error!("the precompute workers have stopped"); + return; + } + } + None => { + let (result, times) = compute_window( + precompute, + window, + raw_data, + views.clone(), + partition, + options, + shared, + ); + tasks.computed(seq, 0, result, times); + } + } + } + let Some(task) = tasks.next_commit() else { + break; + }; + commit_window( + precompute, + task, + &mut views, + &mut to_persist, + options, + shared, + ); + committed = true; + slots.release(); + } + if committed { + shared.published.publish_views(views.clone()); + shared + .metrics + .view_bytes + .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 (barrier_ms, reply) in tasks.passed_barriers() { + match &persist { + // The barrier answers once the windows before it are also + // written (not necessarily synced), without the committer + // waiting for that. + Some(persist) => persist.barrier(move || { + let _ = reply.send(barrier_ms); + }), + None => { + let _ = reply.send(barrier_ms); + } + } + } + } + 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)>); + +/// Stores a computed window's rows in `views` and counts it. +fn commit_window( + precompute: &Precompute, + task: CommitTask, + views: &mut Arc, + to_persist: &mut Vec, + options: &PoolOptions, + shared: &Shared, +) { + let window = task.window; + let result = { + let _gate = shared + .precompute_gate + .lock() + .unwrap_or_else(|e| e.into_inner()); + let combine = |parts: Vec| -> Result { + if task.pushed { + let delay_ms: u64 = options + .slow_refreshes + .iter() + .filter(|s| s.matches(window)) + .map(|s| s.delay_ms) + .sum(); + if delay_ms > 0 { + std::thread::sleep(std::time::Duration::from_millis(delay_ms)); + } + } + let timer = Timer::start(); + let combined = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + if task.pushed && options.panic_in_combine_of_window_end_ms == Some(window.end_ms) { + panic!( + "combine of the window ending at {} panicked (test hook)", + window.end_ms + ); + } + let mut parts = parts; + match parts.len() { + 1 => Ok(parts.remove(0)), + _ => precompute.merge(parts).map_err(|e| e.to_string()), + } + })) + .unwrap_or_else(|_| Err("the combine panicked".to_string()))?; + if let (true, Some(push)) = (task.pushed, &shared.metrics.push) { + push.combine[window.group].record(timer); + } + Ok(if task.pushed { + precompute.missing_only(window, combined, views) + } else { + combined + }) + }; + let timer = Timer::start(); + let result = task.result.and_then(combine).and_then(|computed| { + precompute + .commit(window, computed, views) + .map_err(|e| e.to_string()) + }); + 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), + Ordering::Relaxed, + ); + } + result + }; + let now = Instant::now(); + let latency = &shared.metrics.precompute_windows[window.group]; + 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), + ); + { + let mut stats = shared.stats.lock().unwrap_or_else(|e| e.into_inner()); + match result { + 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)); + } + Ok(Refreshed::AlreadyStored) => stats.windows_already_stored += 1, + Err(error) => { + tracing::error!(group = window.group, end = window.end_ms, %error, "ingestion run failed"); + stats.windows_failed += 1; + } + } + } + shared.precompute_backlog.fetch_sub(1, Ordering::SeqCst); +} + +/// A computed window ready to commit: its run, or its parts' runs by +/// part. +struct CommitTask { + window: ClosedWindow, + /// Built by push: its parts are the shards' partials. + pushed: bool, + result: Result, String>, + closed_at: Instant, + times: TaskTimes, +} + +/// Where a window taken from the backlog is. +enum TaskState { + /// Waiting for the windows it reads to be committed. + Waiting(RawShards), + /// Computing: `parts` runs, those done so far by part, and when the + /// first started and the last ended. + Running { + parts: u32, + done: BTreeMap>, + times: Option, + }, + Computed { + result: Result, String>, + times: TaskTimes, + }, +} + +struct WindowTask { + window: ClosedWindow, + pushed: bool, + closed_at: Instant, + state: TaskState, +} + +/// The windows taken from the backlog and not yet committed, by the order +/// they closed (`seq`), and the barriers between them, scheduled by the +/// plan's [`RefreshTaskGraph`]. A window starts once every earlier window +/// of the groups it reads is committed (a superset of the windows covering +/// it, since a group is listed after the groups it reads and its windows +/// close no earlier than theirs), and, in a serial group, once the group's +/// earlier windows are committed; otherwise windows of different groups, +/// and of one group, compute at once. A group's windows commit in window +/// order (a reorder buffer per group). +struct WindowTasks { + graph: RefreshTaskGraph, + /// The parts a window of a group split by series runs as. + parts: u32, + tasks: BTreeMap, + next_seq: u64, + /// Each barrier, after the windows before `seq`. + barriers: VecDeque<(u64, i64, oneshot::Sender)>, + /// Partials of pushed windows whose job has not come yet. + early: Vec, +} + +impl WindowTasks { + fn new(graph: RefreshTaskGraph, parts: u32) -> Self { + Self { + graph, + parts, + tasks: BTreeMap::new(), + next_seq: 0, + barriers: VecDeque::new(), + early: Vec::new(), + } + } + + fn is_empty(&self) -> bool { + self.tasks.is_empty() && self.barriers.is_empty() + } + + fn push(&mut self, window: ClosedWindow, raw_data: RawShards, closed_at: Instant) { + self.tasks.insert( + self.next_seq, + WindowTask { + window, + pushed: false, + closed_at, + state: TaskState::Waiting(raw_data), + }, + ); + self.next_seq += 1; + } + + /// A pushed window: computing on the shards, one partial per shard. + fn push_window(&mut self, window: ClosedWindow, closed_at: Instant, parts: u32) { + let seq = self.next_seq; + self.tasks.insert( + seq, + WindowTask { + window, + pushed: true, + closed_at, + state: TaskState::Running { + parts, + done: BTreeMap::new(), + times: None, + }, + }, + ); + self.next_seq += 1; + let early: Vec = std::mem::take(&mut self.early); + for partial in early { + self.partial(partial); + } + } + + /// A shard's partial of a pushed window. + fn partial(&mut self, partial: Partial) { + let seq = self + .tasks + .iter() + .find_map(|(&seq, task)| (task.pushed && task.window == partial.window).then_some(seq)); + match seq { + Some(seq) => self.computed( + seq, + partial.shard, + partial.result, + TaskTimes { + started: partial.started, + computed: partial.sealed_at, + }, + ), + None => self.early.push(partial), + } + } + + fn barrier(&mut self, barrier_ms: i64, reply: oneshot::Sender) { + self.barriers.push_back((self.next_seq, barrier_ms, reply)); + } + + /// The waiting windows that may start now: no earlier window of a + /// group they read is still uncommitted. They are marked running; a + /// window of a group split by series starts as one run per part. + fn start(&mut self) -> Vec<(u64, ClosedWindow, RawShards, Option)> { + let mut uncommitted = BTreeSet::new(); + let mut started = Vec::new(); + for (&seq, task) in &mut self.tasks { + let group = task.window.group; + let waits_for = |g: &usize| uncommitted.contains(g); + if matches!(task.state, TaskState::Waiting(_)) + && !self.graph.reads[group].iter().any(waits_for) + && !(self.graph.serial[group] && waits_for(&group)) + { + let parts = if self.graph.split_by_series[group] { + self.parts + } else { + 1 + }; + let running = TaskState::Running { + parts, + done: BTreeMap::new(), + times: None, + }; + let TaskState::Waiting(raw_data) = std::mem::replace(&mut task.state, running) + else { + unreachable!() + }; + if parts == 1 { + started.push((seq, task.window, raw_data, None)); + } else { + for index in 0..parts { + let partition = SeriesPartition { + index, + count: parts, + }; + started.push((seq, task.window, raw_data.clone(), Some(partition))); + } + } + } + uncommitted.insert(group); + } + started + } + + /// Part `part` of window `seq` is computed; the window is, once every + /// part is. + fn computed( + &mut self, + seq: u64, + part: u32, + result: Result, + times: TaskTimes, + ) { + let Some(task) = self.tasks.get_mut(&seq) else { + return; + }; + let TaskState::Running { + parts, + done, + times: all, + } = &mut task.state + else { + return; + }; + done.insert(part, result); + let all = all.get_or_insert(times); + all.started = all.started.min(times.started); + all.computed = all.computed.max(times.computed); + if done.len() as u32 == *parts { + let times = *all; + let result = std::mem::take(done).into_values().collect(); + task.state = TaskState::Computed { result, times }; + } + } + + /// The earliest computed window with no earlier window of its group + /// still uncommitted, removed. + fn next_commit(&mut self) -> Option { + let mut uncommitted = BTreeSet::new(); + let seq = self.tasks.iter().find_map(|(&seq, task)| { + let ready = matches!(task.state, TaskState::Computed { .. }) + && !uncommitted.contains(&task.window.group); + uncommitted.insert(task.window.group); + ready.then_some(seq) + })?; + let task = self.tasks.remove(&seq)?; + let TaskState::Computed { result, times } = task.state else { + unreachable!() + }; + Some(CommitTask { + window: task.window, + pushed: task.pushed, + result, + closed_at: task.closed_at, + times, + }) + } + + /// The barriers every window before which is committed, removed. + fn passed_barriers(&mut self) -> Vec<(i64, oneshot::Sender)> { + let first_uncommitted = self.tasks.keys().next().copied().unwrap_or(self.next_seq); + let mut passed = Vec::new(); + while self + .barriers + .front() + .is_some_and(|(seq, _, _)| *seq <= first_uncommitted) + { + let (_, barrier_ms, reply) = self.barriers.pop_front().unwrap(); + passed.push((barrier_ms, reply)); + } + passed + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A request is admitted while the queue stays within its bound, and + /// always into an empty queue; otherwise it is `Busy`. + #[test] + fn admission() { + assert_eq!(admit(0, 3, 2), Ok(3)); + assert_eq!(admit(1, 1, 2), Ok(2)); + assert_eq!(admit(1, 2, 2), Err(IngestError::Busy)); + assert_eq!(admit(u64::MAX, 1, u64::MAX), Err(IngestError::Busy)); + } + + /// A request reaching a full shard is refused whole: no other shard's + /// queue takes its samples. + #[test] + fn a_full_shard_refuses_the_whole_request() { + let queued: Vec = [0, 5, 0].into_iter().map(AtomicU64::new).collect(); + assert_eq!(admit_shards(&queued, &[2, 3, 1], 6), Err(IngestError::Busy)); + let now: Vec = queued.iter().map(|q| q.load(Ordering::SeqCst)).collect(); + assert_eq!(now, [0, 5, 0]); + assert_eq!(admit_shards(&queued, &[2, 1, 1], 6), Ok(())); + let now: Vec = queued.iter().map(|q| q.load(Ordering::SeqCst)).collect(); + assert_eq!(now, [2, 6, 1]); + } + + fn window(group: usize, end_ms: i64) -> ClosedWindow { + ClosedWindow { group, end_ms } + } + + fn times() -> TaskTimes { + TaskTimes { + started: Instant::now(), + computed: Instant::now(), + } + } + + /// The tasks of `graph` with `windows` pushed in order. + fn tasks(graph: RefreshTaskGraph, windows: &[ClosedWindow]) -> WindowTasks { + let mut tasks = WindowTasks::new(graph, 1); + for &w in windows { + tasks.push(w, Arc::new(Vec::new()), Instant::now()); + } + tasks + } + + fn started(tasks: &mut WindowTasks) -> Vec { + tasks + .start() + .into_iter() + .map(|(seq, _, _, _)| seq) + .collect() + } + + /// A group's windows all start at once; one finishing before an + /// earlier one waits for it and the two commit in window order. + #[test] + fn windows_commit_in_window_order_when_computed_out_of_order() { + let graph = RefreshTaskGraph { + reads: vec![vec![]], + serial: vec![false], + split_by_series: vec![false], + }; + let mut tasks = tasks(graph, &[window(0, 10), window(0, 20)]); + assert_eq!(started(&mut tasks), [0, 1]); + tasks.computed(1, 0, Ok(Computed::AlreadyStored), times()); + assert!(tasks.next_commit().is_none()); + tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); + let ends: Vec = std::iter::from_fn(|| tasks.next_commit()) + .map(|t| t.window.end_ms) + .collect(); + assert_eq!(ends, [10, 20]); + } + + /// A window of a group reading another group's views starts once the + /// earlier windows of that group are committed; an unrelated group's + /// window starts at once. + #[test] + fn a_window_waits_for_the_groups_it_reads() { + let graph = RefreshTaskGraph { + reads: vec![vec![], vec![0], vec![]], + serial: vec![false; 3], + split_by_series: vec![false; 3], + }; + let mut tasks = tasks(graph, &[window(0, 10), window(1, 10), window(2, 10)]); + assert_eq!(started(&mut tasks), [0, 2]); + tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); + assert!(started(&mut tasks).is_empty()); + assert_eq!(tasks.next_commit().unwrap().window, window(0, 10)); + assert_eq!(started(&mut tasks), [1]); + } + + /// A serial group's windows start one at a time. + #[test] + fn a_serial_group_computes_one_window_at_a_time() { + let graph = RefreshTaskGraph { + reads: vec![vec![]], + serial: vec![true], + split_by_series: vec![false], + }; + let mut tasks = tasks(graph, &[window(0, 10), window(0, 20)]); + assert_eq!(started(&mut tasks), [0]); + tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); + assert!(started(&mut tasks).is_empty()); + tasks.next_commit().unwrap(); + assert_eq!(started(&mut tasks), [1]); + } + + /// A barrier passes once every window queued before it is committed, + /// not waiting for windows queued after it. + #[test] + fn a_barrier_passes_once_the_windows_before_it_are_committed() { + let graph = RefreshTaskGraph { + reads: vec![vec![], vec![]], + serial: vec![false; 2], + split_by_series: vec![false; 2], + }; + let mut tasks = tasks(graph, &[window(0, 10)]); + let (reply, _answer) = oneshot::channel(); + tasks.barrier(10, reply); + tasks.push(window(1, 20), Arc::new(Vec::new()), Instant::now()); + assert_eq!(started(&mut tasks), [0, 1]); + assert!(tasks.passed_barriers().is_empty()); + tasks.computed(0, 0, Ok(Computed::AlreadyStored), times()); + tasks.next_commit().unwrap(); + assert_eq!(tasks.passed_barriers().len(), 1); + assert!(!tasks.is_empty()); + } + + /// A window of a group split by series starts as one run per part and + /// is committed once every part is computed, with the parts in order. + #[test] + fn a_split_window_commits_once_every_part_is_computed() { + let graph = RefreshTaskGraph { + reads: vec![vec![]], + serial: vec![false], + split_by_series: vec![true], + }; + let mut tasks = WindowTasks::new(graph, 3); + tasks.push(window(0, 10), Arc::new(Vec::new()), Instant::now()); + let parts: Vec> = + tasks.start().into_iter().map(|(_, _, _, p)| p).collect(); + assert_eq!( + parts, + (0..3) + .map(|index| Some(SeriesPartition { index, count: 3 })) + .collect::>() + ); + for part in [2, 0] { + tasks.computed(0, part, Ok(Computed::AlreadyStored), times()); + assert!(tasks.next_commit().is_none()); + } + tasks.computed(0, 1, Ok(Computed::AlreadyStored), times()); + assert_eq!(tasks.next_commit().unwrap().result.unwrap().len(), 3); + } + + /// The running flag clears when an engine thread panics. + #[test] + fn running_guard_clears_on_panic() { + let running = Arc::new(AtomicBool::new(true)); + let guard = RunningGuard(running.clone()); + let thread = std::thread::spawn(move || { + let _guard = guard; + panic!("engine bug"); + }); + assert!(thread.join().is_err()); + assert!(!running.load(Ordering::SeqCst)); + } + /// A metric read by a pushed 60 s group and a window-path 10 s group: + /// once the 10 s group closed (10, 20], a sample at 15 s is still in + /// the pushed group's open window (0, 60], so it is not late. + #[test] + fn a_pushed_groups_open_window_keeps_samples_another_group_closed() { + let workload = serde_json::from_value(serde_json::json!({ + "query_workload": {"language": "promql", "repeating_queries": [ + { + "query": "sum_over_time(m_engine_push_late[60s])", + "demand": {"fixed_interval_at": {"interval": 60000, "evaluation_phase": 0}}, + "requirements": {"accuracy": {"max_error": 0.05, "failure_probability": 0.01, + "accuracy_scope": "whole_result"}}, + "predictability": {"predictable": {"known_at": null}}, + }, + { + "query": "sum by (job) (sum_over_time(m_engine_push_late[10s]))", + "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": {"m_engine_push_late": {"series_count": 1, "sample_interval": 1000, + "metric_type": "gauge", "column_signs": {"value": "non_negative"}}}}, + })) + .unwrap(); + let mut inputs = control_plane::DeploymentInputs::default(); + inputs.deployment_capabilities.raw_data_retained = false; + let plan = control_plane::plan_workload(&workload, &inputs).unwrap().0; + let options = IngestionOptions { + allowed_lateness_ms: 0, + stream_start_ms: Some(0), + ..Default::default() + }; + plan.validate().unwrap(); + let views = plan.materialized_views().unwrap(); + let groups = plan.ingestion_refresh_groups().unwrap(); + let limits = asap_executor::runtime::Limits { max_bytes: 4 << 30 }; + let (mut ingestion, _) = + Ingestion::new(&plan.dag, &views, groups, options, limits).unwrap(); + let widths: Vec = ingestion.group_windows().iter().map(|w| w.0).collect(); + assert_eq!(widths, [60_000, 10_000]); + ingestion.set_push_groups(vec![true, false]); + let series = storage::series_ids::intern_pairs(&[("__name__", "m_engine_push_late")]); + ingestion.observe(&[(series.metric.clone(), 1_000)]); + ingestion.advance_newest_sample(Some(25_000)); + ingestion.advance_clock(25_000); + let closed: Vec<(usize, i64)> = ingestion + .close() + .iter() + .map(|w| (w.group, w.end_ms)) + .collect(); + assert_eq!(closed, [(0, 0), (1, 0), (1, 10_000), (1, 20_000)]); + let sample = RawSample { + labels: series, + timestamp_ms: 15_000, + value: 1.0, + }; + let routed = ingestion.routing().route(vec![sample], 25_000); + assert_eq!(routed.accepted.len(), 1, "{:?}", routed.stats); + } +} diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 783afc437..860d16238 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -45,7 +45,11 @@ use storage::store::{ millis, window_end, RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, }; -use crate::prometheus::MAX_TIME_MS; +/// The largest time, in milliseconds either side of the epoch, the data +/// plane takes a sample at or answers a query at; beyond it a sample is +/// dropped and a query refused, as Prometheus refuses a time it cannot +/// represent. Leaves room for any window offset. +pub const MAX_TIME_MS: i64 = i64::MAX / 4; /// How ingestion treats sample times. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -112,7 +116,7 @@ pub struct IngestionStats { /// Why a plan cannot be ingested. #[derive(Debug, thiserror::Error)] -pub(crate) enum IngestionError { +pub enum IngestionError { #[error("{0}")] Unsupported(String), #[error("refresh group of views {views:?}: {error}")] @@ -203,7 +207,7 @@ impl Ingestion { /// for the [`Precompute`] returned with the ingestion. Refuses views /// refreshed on first read, which the data plane does not refresh yet, /// and groups without a bounded window. - pub(crate) fn new( + pub fn new( dag: &PhysicalASAPDAG, views: &[MaterializedView], groups: Vec, diff --git a/crates/precompute/src/lib.rs b/crates/precompute/src/lib.rs new file mode 100644 index 000000000..9d647e05c --- /dev/null +++ b/crates/precompute/src/lib.rs @@ -0,0 +1,7 @@ +//! The data plane's ingest side: routing samples to the plan's raw data and +//! closing windows ([`ingestion`]), building views by push pipelines +//! ([`push`]), and the threads that run them ([`engine`]). + +pub mod engine; +pub mod ingestion; +pub mod push; diff --git a/crates/query/Cargo.toml b/crates/query/Cargo.toml new file mode 100644 index 000000000..ab0eff9fa --- /dev/null +++ b/crates/query/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "query" +version.workspace = true +edition.workspace = true + +# The query side of the data plane: planned queries over the published +# store, on the query workers, and the result cache. +[dependencies] +asap-executor.workspace = true +common.workspace = true +internal_metrics.workspace = true +storage.workspace = true +anyhow.workspace = true +futures = "0.3" +serde_json.workspace = true +thiserror.workspace = true +tokio.workspace = true +tracing.workspace = true diff --git a/crates/query/src/lib.rs b/crates/query/src/lib.rs index 924673b3f..4ed4579a4 100644 --- a/crates/query/src/lib.rs +++ b/crates/query/src/lib.rs @@ -30,13 +30,16 @@ use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalA use asap_executor::planner::stages::Lifetime; use asap_executor::runtime::{Limits, RunContext, Scope}; use asap_executor::values::{Batch, Value}; -use asap_planner::InstallablePlan; +use common::InstallablePlan; use futures::executor::block_on; use futures::StreamExt; use storage::store::{PublishedStore, QueryTimeResults, RawReads, RawShards, RunStore, ViewStore}; use crate::result_cache::{Answer, ResultCache}; +pub mod result_cache; +pub mod workers; + /// One series of an instant-query result. #[derive(Debug, Clone, PartialEq)] pub struct ResultSample { @@ -302,6 +305,15 @@ impl QueryEngine { } } +/// What crosses threads: the compiled queries and the store each run +/// reads. +#[allow(dead_code)] +fn assert_send_sync() {} +const _: fn() = || { + assert_send_sync::(); + assert_send_sync::(); +}; + /// What evaluations read: the raw data and views published when they /// started, the watermark then, and the raw chunks they converted so far. pub struct Snapshot { diff --git a/crates/query/src/result_cache.rs b/crates/query/src/result_cache.rs index 5b3af07df..e8f2f260c 100644 --- a/crates/query/src/result_cache.rs +++ b/crates/query/src/result_cache.rs @@ -4,7 +4,7 @@ //! An instant query at `T` and a range step at `T` share one entry. //! //! Only a final answer is kept: one whose inputs can no longer change -//! ([`crate::query::QueryEngine`] decides). Entries are dropped once `T` +//! ([`crate::QueryEngine`] 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. @@ -16,7 +16,7 @@ use std::sync::{Arc, Mutex}; use asap_executor::planner::ir::{NonASAPOp, Operator}; use asap_executor::planner::plan::physical_asap_dag::{PhysicalASAPDAG, PhysicalASAPNodeId}; -use crate::query::ResultSample; +use crate::ResultSample; /// One evaluation's answer, shared by every request that reads it. pub type Answer = Arc>; diff --git a/crates/query/src/workers.rs b/crates/query/src/workers.rs new file mode 100644 index 000000000..bdf2a8678 --- /dev/null +++ b/crates/query/src/workers.rs @@ -0,0 +1,195 @@ +//! The `query-N` workers: each runs one query to completion over the +//! newest published snapshot, so a query never waits for ingestion. A +//! run's output stream is not `Send`, so a run never moves between +//! threads. + +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{Arc, Mutex}; + +use internal_metrics::{Metrics, Timer}; +use storage::store::PublishedStore; +use tokio::sync::oneshot; + +use crate::result_cache::Answer; +use crate::{QueryEngine, Snapshot, Unanswered}; + +type Reply = oneshot::Sender>; + +/// The query workers and the compiled queries they run. +#[derive(Clone)] +pub struct QueryWorkers { + /// Queries for the worker threads. + queries: Sender, + query: Arc, + threads: usize, + published: Arc, + metrics: Arc, +} + +impl QueryWorkers { + /// Starts `threads` workers running `query`'s queries over the + /// snapshots `published` holds, recording into `metrics`. + pub fn start( + query: QueryEngine, + published: Arc, + metrics: Arc, + threads: usize, + ) -> std::io::Result { + let threads = threads.max(1); + let query = Arc::new(query); + let (queries, jobs) = channel::(); + spawn_query_workers( + query.clone(), + published.clone(), + metrics.clone(), + jobs, + threads, + )?; + Ok(Self { + queries, + query, + threads, + published, + metrics, + }) + } + + /// Answers the planned `query` at `time_ms` on a query worker, from + /// the newest snapshot published when the run starts; see + /// [`QueryEngine::evaluate`]. Two queries at one evaluation time may + /// read different snapshots. A query does not wait for writes + /// acknowledged before it; an event-time barrier does + /// (`advance_watermark` of the precompute engine). + pub async fn evaluate(&self, query: String, time_ms: i64) -> Result { + let started = std::time::Instant::now(); + let metrics = self.metrics.query(&query); + let answer = self.run_on_worker(query, time_ms, None).await; + if let Some(metrics) = metrics { + metrics.latency.observe(started.elapsed().as_secs_f64()); + } + answer + } + + /// Evaluates one step of a range query over `snapshot`, which every + /// step of the request reads ([`Self::snapshot`]): as + /// [`Self::evaluate`], counted as a range step rather than an instant + /// query. A step whose future is dropped before a worker takes it (the + /// range failed or its client went away) is not run. + pub async fn evaluate_range_step( + &self, + query: String, + time_ms: i64, + snapshot: Arc, + ) -> Result { + self.run_on_worker(query, time_ms, Some(snapshot)).await + } + + /// The newest published store, for the steps of one range request. + pub fn snapshot(&self) -> Arc { + Arc::new(self.query.snapshot(&self.published)) + } + + /// The result cache's answer to the planned `query` at `time_ms`, if + /// it keeps one ([`QueryEngine::cached`]). + pub fn cached(&self, query: &str, time_ms: i64) -> Option { + self.query.cached(query, time_ms) + } + + async fn run_on_worker( + &self, + query: String, + time_ms: i64, + range_step: Option>, + ) -> Result { + let stopped = || Unanswered::Execution("the query workers have stopped".into()); + let (reply, answer) = oneshot::channel(); + self.queries + .send(QueryJob { + query, + time_ms, + range_step, + reply, + }) + .map_err(|_| stopped())?; + answer.await.map_err(|_| stopped())? + } + + /// The query worker threads: the most query runs at once. + pub fn threads(&self) -> usize { + self.threads + } + + /// The compiled queries. + pub fn engine(&self) -> &QueryEngine { + &self.query + } +} + +/// One query for a worker thread. +struct QueryJob { + query: String, + time_ms: i64, + /// One step of a range query, and the snapshot every step reads. + range_step: Option>, + reply: Reply, +} + +/// Starts `threads` workers `query-0`, `query-1`, …, each running one query +/// at a time to completion from `jobs`; more queries wait in `jobs`. +fn spawn_query_workers( + query: Arc, + published: Arc, + metrics: Arc, + jobs: Receiver, + threads: usize, +) -> std::io::Result<()> { + let jobs = Arc::new(Mutex::new(jobs)); + for index in 0..threads { + let (query, published, metrics, jobs) = ( + query.clone(), + published.clone(), + metrics.clone(), + jobs.clone(), + ); + std::thread::Builder::new() + .name(format!("query-{index}")) + .spawn(move || loop { + let job = match jobs.lock().unwrap_or_else(|e| e.into_inner()).recv() { + Ok(job) => job, + Err(_) => break, + }; + // Nobody waits for it any more (a failed range, a client + // that went away). + if job.reply.is_closed() { + continue; + } + let timer = Timer::start(); + // 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 { + Some(snapshot) => snapshot.clone(), + None => Arc::new(query.snapshot(&published)), + }; + query.evaluate(&job.query, job.time_ms, &snapshot) + })) + .unwrap_or_else(|panic| { + let reason = panic + .downcast_ref::<&str>() + .map(ToString::to_string) + .or_else(|| panic.downcast_ref::().cloned()) + .unwrap_or_default(); + tracing::error!(query = %job.query, time_ms = job.time_ms, %reason, "query run panicked"); + Err(Unanswered::Execution(format!("the query run panicked: {reason}"))) + }); + if let Some(metrics) = metrics.query(&job.query) { + match job.range_step { + None => metrics.run.record(timer), + Some(_) => metrics.range_step_run.record(timer), + }; + } + let _ = job.reply.send(answer); + })?; + } + Ok(()) +} diff --git a/crates/storage/src/lib.rs b/crates/storage/src/lib.rs index f4c3e9772..fc40e80cb 100644 --- a/crates/storage/src/lib.rs +++ b/crates/storage/src/lib.rs @@ -1,10 +1,12 @@ //! The data plane's stores: the raw samples the plan's `Scan`s read and the //! materialized views its precompute writes ([`store`]), the views' window -//! cache and memory budget, their on-disk segments and persistence, the -//! state codecs, and the process-wide series interner. +//! cache and memory budget, their on-disk segments and persistence (and +//! the `persist-N` threads that write them, [`persist_pool`]), the state +//! codecs, and the process-wide series interner. pub mod memory_budget; pub mod persist; +pub mod persist_pool; pub mod segment; pub mod series_ids; mod state_codec; diff --git a/crates/storage/src/persist_pool.rs b/crates/storage/src/persist_pool.rs new file mode 100644 index 000000000..7cacf83c8 --- /dev/null +++ b/crates/storage/src/persist_pool.rs @@ -0,0 +1,308 @@ +//! The `persist-N` threads: each writes the refreshed windows of its +//! refresh groups to the view files after they are published, and syncs +//! the files every sync interval. The precompute committer queues windows +//! through [`PersistPool`] and never waits for the disk; the queue's +//! length and bytes are the [`PersistBacklog`], exported on `/metrics`. + +use std::collections::BTreeSet; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::mpsc::{channel, Receiver, Sender}; +use std::sync::{Arc, Mutex}; + +use asap_executor::planner::plan::physical_asap_dag::PhysicalASAPNodeId; +use asap_executor::values::Batch; +use internal_metrics::Metrics; + +use crate::persist::ViewFiles; +use crate::store::WindowSlot; + +/// What a persist thread does next. +enum PersistJob { + /// Write the rows each view got for its group's window `range_ms`; + /// `bytes` of the queue it releases once written. + Window { + group: usize, + range_ms: (i64, i64), + views: Vec<(PhysicalASAPNodeId, Vec)>, + /// Each view's stored window, told where it was written. + slots: Vec>>, + bytes: u64, + }, + /// Done once every window queued to this thread before is written. + Barrier(Arc), +} + +/// An event-time barrier waiting for every persist thread. +struct PersistBarrier { + remaining: AtomicU64, + /// Answers the barrier; run by the last persist thread to reach it. + reached: Mutex>>, +} + +impl PersistBarrier { + /// One persist thread reached it; the last one answers. + fn reached(&self) { + if self.remaining.fetch_sub(1, Ordering::SeqCst) == 1 { + if let Some(reached) = self + .reached + .lock() + .unwrap_or_else(|e| e.into_inner()) + .take() + { + reached(); + } + } + } +} + +/// The persist queue: refreshed windows queued for the persist threads and +/// not yet written, and their bytes. +#[derive(Debug, Default)] +pub struct PersistBacklog { + windows: AtomicU64, + bytes: Mutex, +} + +impl PersistBacklog { + /// Refreshed windows not yet written to the view files. + pub fn windows(&self) -> u64 { + self.windows.load(Ordering::SeqCst) + } + + /// Bytes of the refreshed windows queued for the persist threads. + pub fn bytes(&self) -> u64 { + *self.bytes.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Releases `bytes` of the queue for a window written (or lost). + fn release(&self, bytes: u64) { + let mut queued = self.bytes.lock().unwrap_or_else(|e| e.into_inner()); + *queued = queued.saturating_sub(bytes); + self.windows.fetch_sub(1, Ordering::SeqCst); + } +} + +/// How the persist threads run. +#[derive(Debug, Clone, Default)] +pub struct PersistOptions { + /// Persist threads, each writing the view files of every + /// `threads`-th refresh group. + pub threads: usize, + /// Bytes queued beyond which further windows are counted + /// (`asap_view_persist_over_bound_total`). + pub max_backlog_bytes: u64, + /// For tests: how long a thread waits before writing each window, as a + /// slow disk would. + pub delay: std::time::Duration, + /// For tests: these views' windows are never written. + pub unpersistable_views: BTreeSet, +} + +/// The persist threads, as the precompute thread sees them: refresh group +/// `g`'s windows go to thread `g % threads`, so each file has one writer +/// and its records stay in window order. The queue between precompute and +/// the threads is bounded by bytes. +pub struct PersistPool { + shards: Vec>, + max_bytes: u64, + backlog: Arc, + metrics: Arc, +} + +impl PersistPool { + /// Starts `options.threads` threads `persist-0`, `persist-1`, …, over + /// `files` split by refresh group, counting their queue in `backlog`. + pub fn spawn( + files: ViewFiles, + options: PersistOptions, + backlog: Arc, + metrics: Arc, + ) -> std::io::Result { + let unpersistable = Arc::new(options.unpersistable_views); + let mut shards = Vec::new(); + for (index, files) in files.split(options.threads).into_iter().enumerate() { + let (shard, jobs) = channel(); + let (backlog, metrics) = (backlog.clone(), metrics.clone()); + let (delay, unpersistable) = (options.delay, unpersistable.clone()); + std::thread::Builder::new() + .name(format!("persist-{index}")) + .spawn(move || { + serve_persist(files, jobs, &backlog, &metrics, delay, &unpersistable) + })?; + shards.push(shard); + } + Ok(Self { + shards, + max_bytes: options.max_backlog_bytes, + backlog, + metrics, + }) + } + + /// 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). + pub fn queue( + &self, + group: usize, + range_ms: (i64, i64), + views: Vec<(PhysicalASAPNodeId, Vec)>, + slots: Vec>>, + ) { + let bytes: u64 = views + .iter() + .flat_map(|(_, batches)| batches) + .map(|batch| batch.memory_bytes() as u64) + .sum(); + // The committer never waits for the disk: a slow disk leaves more + // windows `Pending` (in memory, as without tiering) instead of + // holding refreshes, the watermark and ingest. Windows queued past + // the bound are counted. + { + let mut queued = self.backlog.bytes.lock().unwrap_or_else(|e| e.into_inner()); + if *queued > 0 && *queued + bytes > self.max_bytes { + self.metrics + .view_persist_over_bound + .fetch_add(1, Ordering::Relaxed); + } + *queued += bytes; + } + self.backlog.windows.fetch_add(1, Ordering::SeqCst); + let job = PersistJob::Window { + group, + range_ms, + views, + slots, + bytes, + }; + if self.shards[group % self.shards.len()].send(job).is_err() { + tracing::error!(group, "the persist thread has stopped"); + self.backlog.release(bytes); + } + } + + /// Runs `reached` once every persist thread has written the windows + /// queued before. + pub fn barrier(&self, reached: impl FnOnce() + Send + 'static) { + let barrier = Arc::new(PersistBarrier { + remaining: AtomicU64::new(self.shards.len() as u64), + reached: Mutex::new(Some(Box::new(reached))), + }); + for shard in &self.shards { + if shard.send(PersistJob::Barrier(barrier.clone())).is_err() { + barrier.reached(); + } + } + } +} + +/// The persist thread: writes each refreshed window's records to the view +/// files, in order, and syncs them every sync interval, also when no window +/// arrives; syncs everything when the precompute thread stops. +fn serve_persist( + mut files: ViewFiles, + jobs: Receiver, + backlog: &PersistBacklog, + metrics: &Metrics, + delay: std::time::Duration, + unpersistable: &BTreeSet, +) { + let wait = files.sync_interval().clamp( + std::time::Duration::from_millis(1), + std::time::Duration::from_secs(3600), + ); + loop { + let job = match jobs.recv_timeout(wait) { + Ok(job) => job, + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => { + match files.sync_if_due() { + Ok(ns) => metrics.view_sync_ns.fetch_add(ns, Ordering::Relaxed), + Err(error) => { + tracing::error!(%error, "syncing the view files failed"); + 0 + } + }; + continue; + } + Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break, + }; + match job { + PersistJob::Window { + group, + range_ms, + views, + slots, + bytes, + } => { + // A slow disk, for tests. + if !delay.is_zero() { + std::thread::sleep(delay); + } + let records: Vec<(PhysicalASAPNodeId, &[Batch])> = views + .iter() + .filter(|(view, _)| !unpersistable.contains(view)) + .map(|(view, batches)| (*view, batches.as_slice())) + .collect(); + let skipped = (views.len() - records.len()) as u64; + let files_before = files.bytes(); + let locations = match files.append(group, range_ms, &records) { + Ok(written) => { + metrics + .view_persisted_bytes + .fetch_add(written.bytes, Ordering::Relaxed); + metrics + .view_sync_ns + .fetch_add(written.sync_ns, Ordering::Relaxed); + metrics + .view_windows_not_persisted + .fetch_add(written.not_persisted + skipped, Ordering::Relaxed); + metrics + .view_segments_marked_cold + .fetch_add(written.segments_marked_cold, Ordering::Relaxed); + written.locations + } + Err(error) => { + tracing::error!(group, ?range_ms, %error, "persisting a window failed"); + metrics + .view_windows_not_persisted + .fetch_add(views.len() as u64, Ordering::Relaxed); + Vec::new() + } + }; + // Each written window leaves memory (unless the cache keeps + // it); one that was not written stays. + for ((view, _), slot) in views.iter().zip(&slots) { + let Some(slot) = slot else { continue }; + match locations.iter().find(|(v, _)| v == view) { + Some((_, location)) => slot.stored(location.clone()), + None => slot.pin(), + } + } + // Each view's windows expire at its own retention (the + // files recorded it when indexing). + if let Err(error) = files.delete_expired(group, range_ms.1) { + tracing::error!(group, %error, "deleting expired view segments failed"); + } + let files_after = files.bytes(); + if files_after >= files_before { + metrics + .view_file_bytes + .fetch_add(files_after - files_before, Ordering::Relaxed); + } else { + metrics + .view_file_bytes + .fetch_sub(files_before - files_after, Ordering::Relaxed); + } + backlog.release(bytes); + } + PersistJob::Barrier(barrier) => barrier.reached(), + } + } + match files.sync() { + Ok(ns) => { + metrics.view_sync_ns.fetch_add(ns, Ordering::Relaxed); + } + Err(error) => tracing::error!(%error, "syncing the view files failed"), + } + tracing::info!("persist stopped"); +} From 97631bb1fd27ac5ffbdf9f30fc267764d1f69c8d Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 11:24:20 +0000 Subject: [PATCH 3/5] refactor: review fixes for the precompute and query split - MAX_TIME_MS moves to common: ingestion and the Prometheus parameter parser (an adapter from step 6) both bound times by it. - PrecomputeOptions documents its fields instead of pointing at the data plane's EngineOptions. - Ingestion::newest_sample_ms and Precompute::refresh had no callers and are deleted. - README's layout table and the design documents' path notes name the new crates; two comments name the moved files. --- Cargo.lock | 2 ++ README.md | 7 ++++-- crates/common/src/lib.rs | 6 +++++ crates/data-plane/Cargo.toml | 1 + crates/data-plane/src/prometheus.rs | 2 +- crates/data-plane/tests/ingest_shards.rs | 2 +- crates/data-plane/tests/precompute_pool.rs | 2 +- crates/precompute/Cargo.toml | 1 + crates/precompute/src/engine.rs | 17 +++++++++++-- crates/precompute/src/ingestion.rs | 29 +++------------------- docs/design/data-plane-demo.md | 8 ++++-- docs/design/demo-plan.md | 6 ++++- docs/design/parallel-precompute.md | 6 ++++- docs/design/tiered-view-storage.md | 6 ++++- 14 files changed, 57 insertions(+), 38 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 73f96f7a2..17fdac859 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -968,6 +968,7 @@ dependencies = [ "asap_sketchlib", "axum", "clap", + "common", "control_plane", "form_urlencoded", "futures", @@ -2839,6 +2840,7 @@ dependencies = [ "anyhow", "asap-executor", "clap", + "common", "control_plane", "futures", "internal_metrics", diff --git a/README.md b/README.md index 5de55a0b6..7ccdaf677 100644 --- a/README.md +++ b/README.md @@ -230,8 +230,11 @@ not stored) with a Prometheus `execution` error (422, | Path | Holds | |---|---| | `crates/control-plane/` | package `control_plane`: workload → `asap-planner` → plan file | -| `crates/data-plane/` | package `data_plane`: the data plane and its binary | -| `crates/storage/` | package `storage`: raw samples and views in memory, the view cache, segments and persistence | +| `crates/common/` | package `common`: the engine boundary's types and traits | +| `crates/data-plane/` | package `data_plane`: the binary, its CLI and HTTP routes, and the engine that wires the crates below | +| `crates/precompute/` | package `precompute`: ingest shards, the ingest coordinator, push pipelines and the precompute pool | +| `crates/query/` | package `query`: planned queries on the query workers, and the result cache | +| `crates/storage/` | package `storage`: raw samples and views in memory, the view cache, segments, persistence and the persist threads | | `crates/internal-metrics/` | package `internal_metrics`: the backend's measurements of itself, exported on `/metrics` | | `benchmarks/` | the backend alone: `micro/` benchmarks (examples of `data_plane`) and `scripts/` | | `eval/` | comparisons with other systems and the live demo; see [eval/README.md](eval/README.md) | diff --git a/crates/common/src/lib.rs b/crates/common/src/lib.rs index bd8e1ec3f..479624b66 100644 --- a/crates/common/src/lib.rs +++ b/crates/common/src/lib.rs @@ -23,6 +23,12 @@ pub use query_result::{ Table, TableValue, }; +/// The largest time, in milliseconds either side of the epoch, the data +/// plane takes a sample at or answers a query at; beyond it a sample is +/// dropped and a query refused, as Prometheus refuses a time it cannot +/// represent. Leaves room for any window offset. +pub const MAX_TIME_MS: i64 = i64::MAX / 4; + /// One series' labels, name to value, `__name__` included, as query results /// carry them. pub type LabelSet = std::collections::BTreeMap; diff --git a/crates/data-plane/Cargo.toml b/crates/data-plane/Cargo.toml index 6bd90015c..83f8d7989 100644 --- a/crates/data-plane/Cargo.toml +++ b/crates/data-plane/Cargo.toml @@ -6,6 +6,7 @@ edition.workspace = true [dependencies] asap-planner.workspace = true asap-executor.workspace = true +common.workspace = true internal_metrics.workspace = true precompute.workspace = true query.workspace = true diff --git a/crates/data-plane/src/prometheus.rs b/crates/data-plane/src/prometheus.rs index 4377a3bb1..5055eb1fd 100644 --- a/crates/data-plane/src/prometheus.rs +++ b/crates/data-plane/src/prometheus.rs @@ -6,7 +6,7 @@ use std::collections::BTreeMap; use serde::{Serialize, Serializer}; use serde_json::{json, Value}; -use precompute::ingestion::MAX_TIME_MS; +use common::MAX_TIME_MS; use query::result_cache::Answer; use query::ResultSample; diff --git a/crates/data-plane/tests/ingest_shards.rs b/crates/data-plane/tests/ingest_shards.rs index 1a7e5964a..ee54c8663 100644 --- a/crates/data-plane/tests/ingest_shards.rs +++ b/crates/data-plane/tests/ingest_shards.rs @@ -504,7 +504,7 @@ async fn barriers_during_one_flush_all_answer() { } /// A sample stamped further from the epoch than the data plane evaluates -/// (`prometheus::MAX_TIME_MS`) is dropped and counted, so window +/// (`common::MAX_TIME_MS`) is dropped and counted, so window /// arithmetic over it cannot overflow; later samples are ingested as /// usual. #[tokio::test(flavor = "multi_thread")] diff --git a/crates/data-plane/tests/precompute_pool.rs b/crates/data-plane/tests/precompute_pool.rs index f79ee0fd4..1371387dc 100644 --- a/crates/data-plane/tests/precompute_pool.rs +++ b/crates/data-plane/tests/precompute_pool.rs @@ -6,7 +6,7 @@ //! the precompute backlog still holds Remote Write back. No public //! workload's plan has a group reading another group's views at //! ingestion, so that order is covered by the scheduler's unit tests -//! (`engine.rs`). +//! (`crates/precompute/src/engine.rs`). mod common; diff --git a/crates/precompute/Cargo.toml b/crates/precompute/Cargo.toml index 48a5642b0..38da74d04 100644 --- a/crates/precompute/Cargo.toml +++ b/crates/precompute/Cargo.toml @@ -7,6 +7,7 @@ edition.workspace = true # push pipelines and the precompute pool over the Planner's executor. [dependencies] asap-executor.workspace = true +common.workspace = true internal_metrics.workspace = true storage.workspace = true anyhow.workspace = true diff --git a/crates/precompute/src/engine.rs b/crates/precompute/src/engine.rs index 57090cc92..6fb252ecc 100644 --- a/crates/precompute/src/engine.rs +++ b/crates/precompute/src/engine.rs @@ -207,21 +207,34 @@ impl Drop for RunningGuard { } } -/// How the precompute engine ingests samples and builds the views; the -/// data plane's `EngineOptions` describes each field. +/// How the precompute engine ingests samples and builds the views. #[derive(Debug, Clone)] pub struct PrecomputeOptions { + /// Lateness, future bound and first-window checks of ingestion. pub ingestion: IngestionOptions, + /// Samples queued for the ingest shards beyond which `try_ingest` is + /// `Busy`. pub max_queued_samples: u64, + /// Refresh windows closed and not yet refreshed beyond which the + /// ingest coordinator waits. pub max_precompute_backlog: usize, + /// Ingest shard threads. pub ingest_threads: usize, + /// Threads computing closed refresh windows at once. pub precompute_threads: usize, + /// For tests: refresh windows whose computation waits first. pub slow_refreshes: Vec, + /// For tests: fail a window whose inputs are not committed or change. pub check_task_inputs: bool, + /// For tests: how long every shard but the first waits per batch. pub shard_delay_ms: u64, + /// How the views of a closed window are built. pub precompute_mode: PrecomputeMode, + /// Push mode: how each shard coalesces samples into morsels. pub push_batching: crate::push::MorselBatching, + /// Push mode: bytes of open-window state all shards may hold together. 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, } diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index 860d16238..e5fbe16d3 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -45,11 +45,7 @@ use storage::store::{ millis, window_end, RawData, RawSample, RawShards, RunStore, SeriesPartition, ViewStore, }; -/// The largest time, in milliseconds either side of the epoch, the data -/// plane takes a sample at or answers a query at; beyond it a sample is -/// dropped and a query refused, as Prometheus refuses a time it cannot -/// represent. Leaves room for any window offset. -pub const MAX_TIME_MS: i64 = i64::MAX / 4; +use common::MAX_TIME_MS; /// How ingestion treats sample times. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -541,11 +537,6 @@ impl Ingestion { self.newest_clock_ms = self.newest_clock_ms.max(Some(now_ms)); } - /// The newest sample time the watermark follows. - pub fn newest_sample_ms(&self) -> Option { - self.newest_sample_ms - } - /// Sets the newest sample time the watermark follows (it never goes /// back): the newest sample any shard ran by the last flush. pub fn advance_newest_sample(&mut self, newest_ms: Option) { @@ -937,22 +928,8 @@ pub struct Precompute { impl Precompute { /// Runs `window`'s group's views in one ingestion run over /// `(end - W, end]`, reading `raw_data` (as it was when the window - /// closed) and `views`, and appends each view's rows to `views`. A view - /// that already stores the window (loaded from files at startup) is not - /// appended to again; a window every view of the group stores is not - /// run. - pub fn refresh( - &self, - window: ClosedWindow, - raw_data: RawShards, - views: &mut Arc, - ) -> Result { - let computed = self.compute(window, raw_data, views.clone(), None)?; - self.commit(window, computed, views) - } - - /// The first half of [`Self::refresh`]: runs the window over - /// `raw_data` and `views` without storing its rows. Windows of one + /// closed) and `views`, without storing its rows ([`Self::commit`] + /// stores them). Windows of one /// group may be computed at once on several threads ([`RefreshTaskGraph`]); /// their rows must be committed in window order, and a window must be /// computed over views that store the windows it reads. diff --git a/docs/design/data-plane-demo.md b/docs/design/data-plane-demo.md index 116e849fc..6dc7a45c5 100644 --- a/docs/design/data-plane-demo.md +++ b/docs/design/data-plane-demo.md @@ -7,7 +7,11 @@ > stays in `crates/data-plane/examples/`), the workloads in `examples/` are in > `docs/examples/`, `scripts/profile.sh` and `scripts/tiered_views_cgroup.sh` > are in `benchmarks/scripts/`, and `bench/demo/` is split into `eval/`, -> `eval/demo/` and `deployment/monitoring/`. +> `eval/demo/` and `deployment/monitoring/`. The data plane's sources are +> split into crates: `src/{ingestion,push}.rs` and the ingest and +> precompute threads of `src/engine.rs` are in `crates/precompute/`, +> `src/{query,result_cache}.rs` and the query workers in `crates/query/`, +> and the stores, persistence and the persist threads in `crates/storage/`. ## Audience and context @@ -623,7 +627,7 @@ requests' shape, so the plan delivers every step time. A Grafana range panel refreshed every 15 s asks for the same range shifted by one step; without a cache every step is computed again. VictoriaMetrics keeps a rollup result cache for this; the data plane keeps one too -(`data_plane/src/result_cache.rs`). +(`crates/query/src/result_cache.rs`). - Key and value: (planned query root, evaluation time T) → the answer vector (`Arc`). An instant query at T and a range step at T share the diff --git a/docs/design/demo-plan.md b/docs/design/demo-plan.md index 38c19be31..8aadd6955 100644 --- a/docs/design/demo-plan.md +++ b/docs/design/demo-plan.md @@ -7,7 +7,11 @@ > stays in `crates/data-plane/examples/`), the workloads in `examples/` are in > `docs/examples/`, `scripts/profile.sh` and `scripts/tiered_views_cgroup.sh` > are in `benchmarks/scripts/`, and `bench/demo/` is split into `eval/`, -> `eval/demo/` and `deployment/monitoring/`. +> `eval/demo/` and `deployment/monitoring/`. The data plane's sources are +> split into crates: `src/{ingestion,push}.rs` and the ingest and +> precompute threads of `src/engine.rs` are in `crates/precompute/`, +> `src/{query,result_cache}.rs` and the query workers in `crates/query/`, +> and the stores, persistence and the persist threads in `crates/storage/`. This document describes the data plane as it stands on `main` and the plan for the single-server demo against VictoriaMetrics. The component diff --git a/docs/design/parallel-precompute.md b/docs/design/parallel-precompute.md index 28af46909..a2867f7d3 100644 --- a/docs/design/parallel-precompute.md +++ b/docs/design/parallel-precompute.md @@ -7,7 +7,11 @@ > stays in `crates/data-plane/examples/`), the workloads in `examples/` are in > `docs/examples/`, `scripts/profile.sh` and `scripts/tiered_views_cgroup.sh` > are in `benchmarks/scripts/`, and `bench/demo/` is split into `eval/`, -> `eval/demo/` and `deployment/monitoring/`. +> `eval/demo/` and `deployment/monitoring/`. The data plane's sources are +> split into crates: `src/{ingestion,push}.rs` and the ingest and +> precompute threads of `src/engine.rs` are in `crates/precompute/`, +> `src/{query,result_cache}.rs` and the query workers in `crates/query/`, +> and the stores, persistence and the persist threads in `crates/storage/`. ## Audience and context diff --git a/docs/design/tiered-view-storage.md b/docs/design/tiered-view-storage.md index efc17dd37..095796b7d 100644 --- a/docs/design/tiered-view-storage.md +++ b/docs/design/tiered-view-storage.md @@ -7,7 +7,11 @@ > stays in `crates/data-plane/examples/`), the workloads in `examples/` are in > `docs/examples/`, `scripts/profile.sh` and `scripts/tiered_views_cgroup.sh` > are in `benchmarks/scripts/`, and `bench/demo/` is split into `eval/`, -> `eval/demo/` and `deployment/monitoring/`. +> `eval/demo/` and `deployment/monitoring/`. The data plane's sources are +> split into crates: `src/{ingestion,push}.rs` and the ingest and +> precompute threads of `src/engine.rs` are in `crates/precompute/`, +> `src/{query,result_cache}.rs` and the query workers in `crates/query/`, +> and the stores, persistence and the persist threads in `crates/storage/`. ## Audience and context From dd0bf7d0d73eaa472b2c78be1c8ce7222de69a8a Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 22:39:40 +0000 Subject: [PATCH 4/5] refactor: whole-stack review fixes for the precompute and query split Items used only inside their crate since the split are pub(crate), so the compiler keeps the boundary the split set up: - precompute: the push pipeline's types (Morsel, Feed, PushStore, PushGroup, Partial, PushShard, probe), the refresh task graph, and the Ingestion and Precompute methods only the engine calls (clock, watermark, close, maintain, push_run, missing_only, tasks, the group accessors). - storage: ViewFiles::sync_if_due and delete_expired, now that the persist-N threads are storage's. --- crates/precompute/src/ingestion.rs | 28 ++++++++++++++-------------- crates/precompute/src/push.rs | 14 +++++++------- crates/storage/src/persist.rs | 8 ++++++-- 3 files changed, 27 insertions(+), 23 deletions(-) diff --git a/crates/precompute/src/ingestion.rs b/crates/precompute/src/ingestion.rs index e5fbe16d3..a0e00946e 100644 --- a/crates/precompute/src/ingestion.rs +++ b/crates/precompute/src/ingestion.rs @@ -402,7 +402,7 @@ impl Ingestion { /// Builds groups `push` (by index) by push: their windows read no raw /// data. Call before [`Self::raw_data`]. - pub fn set_push_groups(&mut self, push: Vec) { + pub(crate) fn set_push_groups(&mut self, push: Vec) { self.push_groups = push; } @@ -411,7 +411,7 @@ impl Ingestion { } /// Each group's window width and phase. - pub fn group_windows(&self) -> Vec<(i64, i64)> { + pub(crate) fn group_windows(&self) -> Vec<(i64, i64)> { self.groups .iter() .map(|g| (g.width_ms, g.phase_ms)) @@ -419,18 +419,18 @@ impl Ingestion { } /// Each group's metrics. - pub fn group_metrics(&self) -> Vec> { + pub(crate) fn group_metrics(&self) -> Vec> { self.groups.iter().map(|g| g.metrics.clone()).collect() } /// Each group's newest window closed or skipped. - pub fn refreshed_through(&self) -> Vec> { + pub(crate) fn refreshed_through(&self) -> Vec> { self.groups.iter().map(|g| g.refreshed_through).collect() } /// Whether a query run reads raw samples (a query-time `Scan`); if not, /// only the refresh windows read them. - pub fn queries_read_raw_data(&self) -> bool { + pub(crate) fn queries_read_raw_data(&self) -> bool { !self.query_time_lookback_ms.is_empty() } @@ -533,20 +533,20 @@ impl Ingestion { /// back): the time every shard was last flushed. A request admitted /// after that time holds samples stamped after it, and a request /// admitted before it was run by every shard. - pub fn advance_clock(&mut self, now_ms: i64) { + pub(crate) fn advance_clock(&mut self, now_ms: i64) { self.newest_clock_ms = self.newest_clock_ms.max(Some(now_ms)); } /// Sets the newest sample time the watermark follows (it never goes /// back): the newest sample any shard ran by the last flush. - pub fn advance_newest_sample(&mut self, newest_ms: Option) { + pub(crate) fn advance_newest_sample(&mut self, newest_ms: Option) { self.newest_sample_ms = self.newest_sample_ms.max(newest_ms); } /// Closes and returns every window the watermark has passed, oldest /// first within each group, groups in plan order (a group may read the /// views of an earlier one). - pub fn close(&mut self) -> Vec { + pub(crate) fn close(&mut self) -> Vec { self.close_windows() } @@ -560,7 +560,7 @@ impl Ingestion { /// before it closes without a later sample. Capped at `now_ms`; a /// repeated or lower barrier does nothing. Returns the barrier in force /// and the windows it closed, as [`Self::close`] does. - pub fn advance_watermark_at( + pub(crate) fn advance_watermark_at( &mut self, barrier_ms: i64, now_ms: i64, @@ -804,7 +804,7 @@ 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 fn maintain(&self, raw_data: &mut RawData, watermark_ms: Option) { + pub(crate) fn maintain(&self, raw_data: &mut RawData, watermark_ms: Option) { if let Some(watermark_ms) = watermark_ms { raw_data.seal_through(watermark_ms); } @@ -857,7 +857,7 @@ pub enum Computed { /// window to the next (`serial`) computes one window at a time, in order; /// other groups stay parallel. #[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct RefreshTaskGraph { +pub(crate) struct RefreshTaskGraph { /// For each refresh group, the other groups whose views its runs read. pub reads: Vec>, /// For each refresh group, whether its windows must be computed one at @@ -1007,7 +1007,7 @@ impl Precompute { /// whose raw data slots are fed as samples arrive: it finishes once /// every slot's stream ends (the window is sealed), with the rows of /// every view of the group. - pub fn push_run( + pub(crate) fn push_run( self: &Arc, group: usize, store: Arc, @@ -1026,7 +1026,7 @@ impl Precompute { /// A pushed window's rows less those of views that already store the /// window (loaded from files at startup). - pub fn missing_only( + pub(crate) fn missing_only( &self, window: ClosedWindow, computed: Computed, @@ -1124,7 +1124,7 @@ impl Precompute { } /// Which windows may be computed at once. - pub fn tasks(&self) -> &RefreshTaskGraph { + pub(crate) fn tasks(&self) -> &RefreshTaskGraph { &self.tasks } diff --git a/crates/precompute/src/push.rs b/crates/precompute/src/push.rs index 1eb6a3544..ed7e87e3f 100644 --- a/crates/precompute/src/push.rs +++ b/crates/precompute/src/push.rs @@ -57,7 +57,7 @@ use crate::ingestion::{ClosedWindow, Computed, Precompute}; /// every open window reading that metric in that schema gets the same /// batches (the executor re-applies each slot's time range and /// predicates, so the conversion ignores them). -pub struct Morsel { +pub(crate) struct Morsel { raw: RawData, converted: RefCell>>, } @@ -114,7 +114,7 @@ impl Reader { /// The raw data slots of one instance, fed by its shard. #[derive(Default)] -pub struct Feed { +pub(crate) struct Feed { readers: RefCell>, /// `Scan`s per metric the run opens (from the install probe); while /// fewer are open, morsels are kept to replay to the late ones. @@ -153,7 +153,7 @@ impl Feed { /// The data store of a push instance: raw data slots are the shard's /// streams; it reads no view (a group built by push reads none). -pub struct PushStore { +pub(crate) struct PushStore { feed: Rc, } @@ -202,7 +202,7 @@ impl DataStore for PushStore { /// What a group built by push needs on every shard, decided at install. #[derive(Debug, Clone)] -pub struct PushGroup { +pub(crate) struct PushGroup { pub width_ms: i64, pub phase_ms: i64, pub metrics: BTreeSet, @@ -217,7 +217,7 @@ impl PushGroup { } /// A shard's partial of one sealed window, for the committer. -pub struct Partial { +pub(crate) struct Partial { pub window: ClosedWindow, pub shard: u32, pub result: Result, @@ -230,7 +230,7 @@ pub struct Partial { /// `(phase, phase + W]` opens only `Scan`s reading exactly that window, all /// before its first stall, and finishes once they end. `None` for a group /// kept on the window path. -pub fn probe( +pub(crate) fn probe( precompute: &Arc, candidates: &[bool], windows: &[(i64, i64)], @@ -306,7 +306,7 @@ struct Instance { /// A shard's push state: its open instances and how far each group is /// sealed. -pub struct PushShard { +pub(crate) struct PushShard { shard: u32, precompute: Arc, groups: Vec>, diff --git a/crates/storage/src/persist.rs b/crates/storage/src/persist.rs index 9ea8cee93..1a9037826 100644 --- a/crates/storage/src/persist.rs +++ b/crates/storage/src/persist.rs @@ -288,7 +288,7 @@ impl ViewFiles { /// Syncs every file written since the last sync when the sync interval /// has passed; returns the nanoseconds spent syncing. - pub fn sync_if_due(&mut self) -> std::io::Result { + pub(crate) fn sync_if_due(&mut self) -> std::io::Result { if self.last_sync.elapsed() < self.sync_interval { return Ok(0); } @@ -333,7 +333,11 @@ impl ViewFiles { /// views' retention of `newest_end_ms` (ends at or before /// `newest_end_ms - retention`); returns how many. A reader still /// holding one keeps reading it (the file stays open until it is done). - pub fn delete_expired(&mut self, group: usize, newest_end_ms: i64) -> std::io::Result { + pub(crate) fn delete_expired( + &mut self, + group: usize, + newest_end_ms: i64, + ) -> std::io::Result { let mut deleted = 0; for (&(_, retention_ms), files) in self.files.range_mut((group, i64::MIN)..=(group, i64::MAX)) From 02d480abbe7974985da901b8a37c33e1d729d177 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 22:57:17 +0000 Subject: [PATCH 5/5] docs(readme): common holds the boundary types and the fallback trait --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ccdaf677..12090e55a 100644 --- a/README.md +++ b/README.md @@ -230,7 +230,7 @@ not stored) with a Prometheus `execution` error (422, | Path | Holds | |---|---| | `crates/control-plane/` | package `control_plane`: workload → `asap-planner` → plan file | -| `crates/common/` | package `common`: the engine boundary's types and traits | +| `crates/common/` | package `common`: the engine boundary's types and the `FallbackClient` trait | | `crates/data-plane/` | package `data_plane`: the binary, its CLI and HTTP routes, and the engine that wires the crates below | | `crates/precompute/` | package `precompute`: ingest shards, the ingest coordinator, push pipelines and the precompute pool | | `crates/query/` | package `query`: planned queries on the query workers, and the result cache |