Skip to content

refactor: split precompute and query crates out of data-plane (layout step 5a) - #879

Draft
zzylol wants to merge 5 commits into
refactor/layout-commonfrom
refactor/layout-engines
Draft

zzylol wants to merge 5 commits into
refactor/layout-commonfrom
refactor/layout-engines

Conversation

@zzylol

@zzylol zzylol commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: crates/data-plane still holds the ingest side, the query side and engine.rs (about 2,700 lines), which runs both. Nothing stops the query code from reaching into the ingest threads, and the next step (the common traits wired at the seams) has no crate boundary to put them on.
  • Change: step 5, first half, of docs/design/repo-layout.md (docs(design): repository layout and engine boundaries #874). Two new crates, precompute and query, take ingestion.rs/push.rs and query.rs/result_cache.rs. engine.rs splits: the ingest shards, the ingest coordinator, the precompute pool and the committer go to precompute::engine; the query-N workers to query::workers; the persist-N threads to storage::persist_pool. data-plane keeps EngineOptions, install and EngineHandle, which wires the two engines to one published store.
  • Effect: behavior is unchanged. A small fixture (3 series, 60 s, the plan of sum by (job) (sum_over_time(data[10s]))) gives byte-identical HTTP responses and the same /metrics lines before and after (see Verification). For example, cargo run --release -p data_plane --example ingest_bench -- 10000 120 views 1 persist still works; IngestionOptions now comes from precompute::ingestion.

Review guide

  • Base: refactor/layout-common (feat(common): engine boundary types and the fallback trait (layout step 4) #878). This is a stacked draft; feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) #880 (traits, PlanInstaller, QueryDispatcher) is stacked on it.
  • Commits:
    1. git mv only (ingestion.rs, push.rs → crates/precompute/src/, query.rs → crates/query/src/lib.rs, result_cache.rs → crates/query/src/), so history follows each file.
    2. The split of engine.rs and the crates' manifests. Import paths in tests and benchmarks.
    3. Review fixes (listed under Verification).
  • Read first: crates/precompute/src/engine.rs from pub struct Shared to the end of InstalledPrecompute::start (named PrecomputeEngine::start here), crates/storage/src/persist_pool.rs, crates/query/src/workers.rs, and crates/data-plane/src/engine.rs.
  • Mechanical: everything in precompute::engine from fn flush to the end of WindowTasks is moved unchanged except the two persist call sites (persist.queue(…) without shared, persist.barrier(closure)). serve_persist is moved unchanged except that it takes the backlog and Metrics instead of Shared. Import paths in crates/data-plane/tests/ and benchmarks/micro/.

Old → new

Old (crates/data-plane/src/…) New
ingestion.rs, push.rs crates/precompute/src/ (package precompute), modules ingestion and push
query.rs crates/query/src/lib.rs (package query)
result_cache.rs crates/query/src/result_cache.rs
engine.rs: PrecomputeMode, SlowRefresh, IngestError, Command, ShardMessage, PrecomputeJob, Shared, RunningGuard, try_ingest, advance_watermark, stop, hold_precompute, the stats getters, admit_shards, admit, flush, serve_shard, serve_ingest, queue_refreshes, the precompute pool (spawn_precompute, Slots, compute_window, TaskInputs, serve_precompute, commit_window, WindowTasks) and the spawning half of EngineHandle::spawn crates/precompute/src/engine.rs: PrecomputeEngine::start and its methods
engine.rs: QueryJob, spawn_query_workers, EngineHandle::{evaluate, evaluate_range_step, snapshot, cached, run_on_worker} crates/query/src/workers.rs: QueryWorkers
engine.rs: PersistJob, PersistBarrier, PersistPool, release_persist_queue, serve_persist; Shared::{persist_backlog, persist_queue} crates/storage/src/persist_pool.rs: PersistPool, PersistBacklog, PersistOptions
engine.rs: EngineOptions, DEFAULT_VIEW_CACHE_IDLE_MS, install, view_tier, EngineHandle stay in crates/data-plane/src/engine.rs
prometheus::MAX_TIME_MS common::MAX_TIME_MS
engine.rs tests (admission, windows_commit_in_window_order…, running_guard_clears_on_panic, …) crates/precompute/src/engine.rs tests, same module path engine::tests::…

Dependency graph

data_plane ──► precompute ──► storage ──► internal_metrics
     │    └──► query ───────► storage      (and common, asap-executor)
     │           └──────────► common
     ├──► precompute, query, storage, common, internal_metrics
     └──► asap-planner, asap-executor
precompute ──► common, internal_metrics, asap-executor
query      ──► common, internal_metrics, asap-executor
(dev) precompute ──► control_plane

precompute and query do not depend on each other. Both depend on storage: see Decisions.

Behavior: before → after

No change. The threads are the same (ingest-N, ingest, precompute-partials, precompute-queue, precompute-N, precompute, persist-N, view-cache, query-N), spawned in the same order. The CLI flags, defaults, /metrics lines, HTTP responses and view-file names are the same.

Interfaces

crates/precompute/src/engine.rs (new; former parts of data_plane::engine)

+/// How the views of a closed refresh window are built (`--precompute-mode`).
+pub enum PrecomputeMode { Window, Push }
+/// For tests: refresh windows that wait before they are computed.
+pub struct SlowRefresh { pub group: Option<usize>, pub end_ms: Option<i64>, pub part: Option<u32>, pub delay_ms: u64, pub per_series: bool }
+/// Why the engine did not take samples.
+pub enum IngestError { Busy, Stopped }
+/// How the precompute engine ingests samples and builds the views (the precompute subset of `EngineOptions`).
+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<SlowRefresh>,
+    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<u64>,
+    pub panic_in_combine_of_window_end_ms: Option<i64>,
+}
+/// Where the views are persisted: directory, the plan file's hash, sync interval, segment width, persist threads, cold tier.
+pub struct PersistedViews { pub dir: PathBuf, pub plan_hash: u64, pub sync_interval: Duration, pub segment_ms: i64, pub persist: PersistOptions, pub tier: Arc<ViewTier> }
+/// The ingest shards, the ingest coordinator, the precompute pool and committer, and (persisted) the persist threads and the view-cache monitor.
+pub struct PrecomputeEngine { /* commands, shards, shared, max_queued_samples */ }
+impl PrecomputeEngine {
+    /// Starts the threads; publishes what query runs read to `published`.
+    pub fn start(ingestion: Ingestion, precompute: Precompute, query_texts: &[String], options: &PrecomputeOptions, persisted: Option<PersistedViews>, published: Arc<PublishedStore>) -> anyhow::Result<Self>;
+    pub fn try_ingest(&self, samples: Vec<RawSample>) -> Result<(), IngestError>;
+    pub async fn advance_watermark(&self, barrier_ms: i64) -> Result<i64, IngestError>;
+    pub fn is_running(&self) -> bool;
+    pub fn queued_samples(&self) -> u64;
+    pub fn precompute_backlog(&self) -> u64;
+    pub fn stats(&self) -> IngestionStats;
+    pub fn metrics(&self) -> &Arc<Metrics>;
+    pub fn persist_backlog(&self) -> &PersistBacklog;
+    pub fn stop(&self);                                  // doc(hidden), for tests
+    pub fn hold_precompute(&self) -> MutexGuard<'_, ()>; // doc(hidden), for tests
+}

crates/storage/src/persist_pool.rs (new; former PersistPool/serve_persist of data_plane::engine)

+/// Refreshed windows queued for the persist threads and not yet written, and their bytes (for `/metrics`).
+pub struct PersistBacklog { /* windows: AtomicU64, bytes: Mutex<u64> */ }
+impl PersistBacklog { pub fn windows(&self) -> u64; pub fn bytes(&self) -> u64; }
+/// Persist thread count, backlog bound, and the test hooks (`delay`, `unpersistable_views`).
+pub struct PersistOptions { pub threads: usize, pub max_backlog_bytes: u64, pub delay: Duration, pub unpersistable_views: BTreeSet<PhysicalASAPNodeId> }
+/// The persist threads as the committer sees them.
+pub struct PersistPool { /* shards, max_bytes, backlog, metrics */ }
+impl PersistPool {
+    /// Starts `persist-0`, `persist-1`, … over `files` split by refresh group.
+    pub fn spawn(files: ViewFiles, options: PersistOptions, backlog: Arc<PersistBacklog>, metrics: Arc<Metrics>) -> io::Result<Self>;
+    pub fn queue(&self, group: usize, range_ms: (i64, i64), views: Vec<(PhysicalASAPNodeId, Vec<Batch>)>, slots: Vec<Option<Arc<WindowSlot>>>);
+    /// Runs `reached` once every persist thread has written the windows queued before.
+    pub fn barrier(&self, reached: impl FnOnce() + Send + 'static);
+}

crates/query/src/workers.rs (new; former query half of data_plane::engine)

+/// The query-N workers and the compiled queries they run.
+pub struct QueryWorkers { /* queries, query, threads, published, metrics */ }
+impl QueryWorkers {
+    pub fn start(query: QueryEngine, published: Arc<PublishedStore>, metrics: Arc<Metrics>, threads: usize) -> io::Result<Self>;
+    pub async fn evaluate(&self, query: String, time_ms: i64) -> Result<Answer, Unanswered>;
+    pub async fn evaluate_range_step(&self, query: String, time_ms: i64, snapshot: Arc<Snapshot>) -> Result<Answer, Unanswered>;
+    pub fn snapshot(&self) -> Arc<Snapshot>;
+    pub fn cached(&self, query: &str, time_ms: i64) -> Option<Answer>;
+    pub fn threads(&self) -> usize;
+    pub fn engine(&self) -> &QueryEngine;
+}

crates/data-plane/src/engine.rs, crates/data-plane/src/lib.rs

 // data_plane
-pub mod ingestion; pub mod push; pub mod query; pub mod result_cache;
 pub mod engine;
 pub struct EngineHandle {
-    commands: Sender<Command>, shards: Vec<Sender<ShardMessage>>, queries: Sender<QueryJob>,
-    query: Arc<QueryEngine>, query_threads: usize, shared: Arc<Shared>, max_queued_samples: u64,
+    precompute: PrecomputeEngine,
+    query: QueryWorkers,
+    view_tier: Option<Arc<ViewTier>>,
 }
-pub enum PrecomputeMode { … }      // now precompute::engine::PrecomputeMode
-pub struct SlowRefresh { … }       // now precompute::engine::SlowRefresh
-pub enum IngestError { … }         // now precompute::engine::IngestError
 // EngineOptions, its fields and defaults, and every EngineHandle method keep their signatures.

 // precompute::ingestion
-pub(crate) fn new(dag, views, groups, options, limits) -> Result<(Self, Precompute), IngestionError>   // Ingestion::new
+pub fn new(dag, views, groups, options, limits) -> Result<(Self, Precompute), IngestionError>
-pub(crate) enum IngestionError
+pub enum IngestionError
-pub fn newest_sample_ms(&self) -> Option<i64>                                                       // Ingestion; no callers
-pub fn refresh(&self, window, raw_data, views) -> Result<Refreshed, asap_executor::Error>            // Precompute; no callers

 // common
+pub const MAX_TIME_MS: i64 = i64::MAX / 4;   // was data_plane::prometheus::MAX_TIME_MS (pub(crate))

Ingestion::new is pub because data_plane::engine::install compiles the ingestion and the queries together (as before), and calls it from another crate now.

Usage (unchanged for callers): DataPlane::with_options(plan_json, prometheus_url, EngineOptions { ingest_threads: 4, ..EngineOptions::default() }) runs install (query compile, --no-forward check, Ingestion::new), then PrecomputeEngine::start (shards, coordinator, persist threads, view-cache monitor, precompute pool; it publishes the initial raw data and views) and QueryWorkers::start (query-N), both on one Arc<PublishedStore>. POST /api/v1/write → EngineHandle::try_ingest → PrecomputeEngine::try_ingest; GET /api/v1/query → EngineHandle::{cached, evaluate} → QueryWorkers.

Algorithm changes

None.

Decisions and open questions

Needs reviewer decision: none.

Decided (judgment calls in this PR):

  • precompute → storage and query → storage. The design says the three crates do not depend on each other and meet in common's traits. Both engines need storage's concrete stores: queries read one copy-on-write snapshot of the raw data and views (PublishedStore), and runs read the executor's batches through RunStore, its DataStore. By the design's rule ("concrete types they must share go in common or in the lower crate"), they stay in storage, the lower crate; common has no store trait (repo-layout decision 4). There is no edge between precompute and query, and no cycle.
  • The persist threads move to storage with a small interface for the backlog accounting (refactor: split internal-metrics and storage crates out of data-plane (layout step 3) #877 deferred them): PersistBacklog (windows and bytes queued, read by /metrics) is shared by the pool and the engine; PersistPool::barrier takes a closure instead of the committer's oneshot::Sender, so storage needs no tokio. One boxed closure per event-time barrier.
  • view_tier() stays in data-plane. It reads EngineOptions (the result cache's and query-time results' bytes, the view cache options). data-plane builds the tier and passes it in PersistedViews.
  • PrecomputeOptions is a subset of EngineOptions, built by EngineOptions::precompute(). EngineOptions stays flat, so the tests that set options (EngineOptions { ingest_threads: 4, ..EngineOptions::default() }) and the CLI do not change.
  • MAX_TIME_MS moves to common. Ingestion drops samples beyond it, and the Prometheus parameter parser refuses times beyond it; the parser becomes an adapter in step 6, which depends on common only.
  • Metrics is an Arc, shared by the precompute engine, the persist threads and the query workers. One more pointer hop per recorded phase (per batch or window, never per sample).

Verification

One remote host per tree, one target directory each, ulimit -n raised (as in #876).

Scope #878 head this PR Newly failing
cargo fmt --all -- --check pass pass —
cargo build --workspace --all-targets --locked (all 8 micro benchmarks included) pass pass —
cargo clippy --workspace --all-targets --locked -- -D warnings pass pass —
cargo test --workspace --locked 191 passed, 0 failed, 3 ignored (38 suites; forward_mode::bodies_wait_for_a_raw_store_that_is_down and planner_executor_parity::push_precompute_stores_the_window_paths_view_rows failed once under load, timing-dependent, and passed alone, 3/3 and 1/1) 191 passed, 0 failed, 3 ignored (42 suites) none

The four new suites are precompute's and query's unit tests and doc tests. The sorted lists of passing test names (test … ok) are identical to #878's head (no new test): the engine::tests::… tests keep their names in precompute, and the moved modules keep theirs (result_cache::tests::…).

End to end, an uncommitted test (tests/zz_parity_dump.rs, run on both trees) writes 60 s of 3 series to a data plane planned for sum by (job) (sum_over_time(data[10s])), sets the barrier at 60 s, and records the status, headers and body of: two instant queries (one with surrounding spaces), a range query twice (the second from the result cache), a query at a window not yet stored, a range reaching one, and an unplanned query, each with --no-forward and with forwarding; then every /metrics family, metric name and label set. The two outputs are byte-identical (547 lines).

Micro benchmarks on the same quiet host (16 cores pinned), three runs each:

Benchmark (3 runs each; median, [min–max]) #878 head #879 head #880 head
ingest_bench 10000 120 views 1 persist: every write acknowledged 0.19 s 0.19 s 0.19 s [0.18–0.19]
… every window refreshed 8.69 s [8.64–11.13] 8.52 s [8.49–10.93] 8.76 s [8.67–11.34]
… CPU, all threads 20.73 s [20.57–20.76] 20.85 s [20.27–21.06] 20.78 s [20.73–20.91]
view_read_bench 10000 40 15 (KLL): pread cold / warm, ns per row 282 / 241 284 / 241 280 / 240
… mmap cold / warm, ns per row 294 / 236 305 / 237 284 / 235

All within run-to-run noise (one run in three of each tree refreshes about 2.5 s later, the same on all three).

An independent review covered correctness and behavior parity, over-abstraction and dependency direction, dead code and duplication, and hot-path efficiency. Its findings for this PR are fixed in the third commit:

  • MAX_TIME_MS moved to common (above).
  • PrecomputeOptions documents its own fields instead of pointing at EngineOptions, which is in a crate above it.
  • 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.

Whole-stack review fixes

  • pub(crate) for items used only inside their crate since the split: precompute's push pipeline types (Morsel, Feed, PushStore, PushGroup, Partial, PushShard, probe), RefreshTaskGraph, and the Ingestion/Precompute methods only the engine calls (set_push_groups, group_windows, group_metrics, refreshed_through, queries_read_raw_data, advance_clock, advance_newest_sample, close, advance_watermark_at, maintain, push_run, missing_only, tasks); storage's ViewFiles::{sync_if_due, delete_expired}, now that the persist threads are storage's.
  • README: the crates/common/ row says "types and the FallbackClient trait".
  • Re-verified on the restacked head (02d480a): the gate above.

Follow-ups

@zzylol zzylol added area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior labels Nov 26, 2026
@zzylol zzylol added the enhancement New feature or request label Nov 27, 2026
@zzylol zzylol changed the title refactor: split precompute and query crates out of data-plane refactor: split precompute and query crates out of data-plane (layout step 5a) Nov 27, 2026
git mv only, so history follows each file; the next commit makes the
crates build.
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.
- 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.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant