Skip to content

feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) - #880

Draft
zzylol wants to merge 4 commits into
refactor/layout-enginesfrom
refactor/layout-engines-traits
Draft

zzylol wants to merge 4 commits into
refactor/layout-enginesfrom
refactor/layout-engines-traits

Conversation

@zzylol

@zzylol zzylol commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: after refactor: split precompute and query crates out of data-plane (layout step 5a) #879 the engines are separate crates, but the plan is compiled and the threads started in one EngineHandle::spawn, and the HTTP handlers match query texts, read the result cache and pick the fallback themselves. Steps 6–8 (adapters) have no installer or dispatcher to call.
  • Change: step 5, second half, of docs/design/repo-layout.md (docs(design): repository layout and engine boundaries #874). precompute::engine::PrecomputeEngine and query::ExecutorQueryEngine are created before any plan, and their inherent install(InstalledPlan) compiles the plan and starts their threads (v1: once); ExecutorQueryEngine::execute answers one QueryRequest with common::EngineQueryResult. They are concrete types, not trait objects: each has one implementation. data-plane adds PlanInstaller (validate, then query engine, ingest engine, dispatcher, stopping at the first failure; v1 installs once) and QueryDispatcher (exact query-text match, run, fallback decision), and the instant and range handlers go through the dispatcher.
  • Effect: behavior is unchanged: the fixture of refactor: split precompute and query crates out of data-plane (layout step 5a) #879 gives byte-identical responses and /metrics lines. One thing is faster: an unplanned query no longer waits for a query worker before it is forwarded (the dispatcher answers Unmatched at once; before, it went to a worker, which found no root).

Review guide

  • Base: refactor/layout-engines (refactor: split precompute and query crates out of data-plane (layout step 5a) #879). Stacked draft.
  • Commits:
    1. The engines' installs, PlanInstaller, QueryDispatcher, the handlers, and per-query metrics moving to the query engine.
    2. Review fixes. 3. A doc name.
    3. Whole-stack review fixes: the engines without trait objects (see Decisions), PlanInstaller without tried, pub(crate) for crate-local items.
  • Read first: crates/data-plane/src/installer.rs, crates/data-plane/src/dispatcher.rs, the query and query_range handlers in crates/data-plane/src/lib.rs, then crates/query/src/workers.rs (instant, range, the worker loop) and crates/query/src/engine.rs, then PrecomputeEngine in crates/precompute/src/engine.rs.
  • Mechanical: InstalledPrecompute is refactor: split precompute and query crates out of data-plane (layout step 5a) #879's PrecomputeEngine renamed, with start taking no query texts. InstalledQueries::range is the former answer_range of lib.rs (stepping, cache, metrics) moved, keyed by root instead of text. render reads the per-query metrics from Gauges::queries instead of Metrics::queries.

Old → new

Old New
EngineHandle::spawn: compile both, start both PlanInstaller::install → ExecutorQueryEngine::install (compile queries, start query-N) → PrecomputeEngine::install (compile ingestion, start the ingest side) → QueryDispatcher::install
data_plane::engine::install split into the two engines' installs; plan.validate() in PlanInstaller
lib.rs answer: time, cached(text), evaluate(text) QueryDispatcher::instant → InstalledQueries::instant (cache, worker)
lib.rs answer_range: steps, cache, snapshot, buffered workers, range metrics QueryDispatcher::range → InstalledQueries::range; the response body is still built in lib.rs
QueryEngine::root(text) (text → root, per call, twice per query) QueryDispatcher::resolve (once per request); the engine takes AnswerSource::Planned { plan, root }
Unanswered::NotPlanned NotAnswerableReason::Unmatched (dispatcher)
handlers' match on Unanswered for forward / refuse / reason header Fallback::new(reason, query, no_forward)
query::QueryEngine (compiled queries) query::CompiledQueries
query::workers::QueryWorkers query::workers::InstalledQueries
precompute::engine::PrecomputeEngine (#879) InstalledPrecompute; PrecomputeEngine is now the plan-less shell
internal_metrics::Metrics::{queries, query()} CompiledQueries::{metrics(), metrics_index()}; Gauges::queries

Dependency graph

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

data_plane names plan types through common now, so asap-planner and asap-executor are only its dev-dependencies (tests and micro benchmarks).

Behavior: before → after

No change, except that unplanned queries skip the worker queue. With the plan of sum by (job) (sum_over_time(data[10s])), 3 series written through 60 s and the barrier at 60 s:

Request Before and after
GET /api/v1/query?query=sum+by+(job)+(sum_over_time(data[10s]))&time=60 200, x-asap-execution: plan, {"status":"success","data":{"resultType":"vector","result":[{"metric":{"job":"j0"},"value":[60.0,"1110"]},{"metric":{"job":"j1"},"value":[60.0,"555"]}]}}
the same at time=90 (window not stored), --no-forward 422, x-asap-execution: refused, {"error":"invalid DAG: materialized view 1 has no rows tiling (80000, 90000]",…}
query=up, --no-forward 422, {"error":"the installed plan has no query \"up\"",…}
the same with forwarding proxied (x-asap-execution: forwarded), with x-asap-forward-reason for the planned query only

Interfaces

crates/data-plane/src/installer.rs (new, private module)

+/// Installs plans into both engines and the dispatcher. v1 installs one: the plan file at startup.
+pub(crate) struct PlanInstaller { /* precompute: Arc<PrecomputeEngine>, query: Arc<ExecutorQueryEngine>, dispatcher: Arc<QueryDispatcher> */ }
+impl PlanInstaller {
+    pub(crate) fn new(precompute: Arc<PrecomputeEngine>, query: Arc<ExecutorQueryEngine>, dispatcher: Arc<QueryDispatcher>) -> Self;
+    /// Validates, then installs into the query engine, the ingest engine and the dispatcher, stopping at the
+    /// first failure; queries reach a plan only through the dispatcher, which gets it last. Errs on an
+    /// invalid plan or an engine's refusal (each engine refuses a second plan).
+    pub(crate) fn install(&self, plan: InstallablePlan) -> Result<PlanId, InstallError>;
+}

crates/data-plane/src/dispatcher.rs (new)

+/// The dispatcher's verdict on one query.
+pub enum QueryOutcome<T> {
+    /// The plan answered.
+    Ready(T),
+    NotAnswerable(NotAnswerableReason),
+}
+/// Why the plan did not answer a query; the query falls back.
+pub enum NotAnswerableReason {
+    /// No plan, or no such query text in it.
+    Unmatched,
+    /// The stored data does not cover the query, or the plan changed since it was resolved: why.
+    NotReady(String),
+    /// The engine failed to run the query (planned but unsupported, or failed).
+    EngineError(QueryEngineError),
+}
+impl NotAnswerableReason { pub fn into_message(self, query: &str) -> String; }
+/// How a query the plan does not answer is answered.
+pub(crate) enum Fallback {
+    /// Proxied to Prometheus or the raw store, with `x-asap-forward-reason` when the query was planned.
+    Forward { reason: Option<String> },
+    /// `--no-forward`: 422 with the reason.
+    Refuse { reason: String },
+}
+/// Resolves each query text against the installed plan and runs it on the query engine.
+pub(crate) struct QueryDispatcher { /* engine: Arc<ExecutorQueryEngine>, plan: OnceLock<…> */ }
+impl QueryDispatcher {
+    pub fn new(engine: Arc<ExecutorQueryEngine>) -> Self;
+    pub async fn instant(&self, query: &str, time_ms: i64) -> QueryOutcome<Answer>;
+    pub async fn range(&self, query: &str, times_ms: impl Iterator<Item = i64>) -> QueryOutcome<Vec<(i64, Answer)>>;
+}

crates/data-plane/src/engine.rs

 pub struct EngineHandle {
-    precompute: PrecomputeEngine,
-    query: QueryWorkers,
+    precompute: InstalledPrecompute,
+    query: InstalledQueries,
+    dispatcher: Arc<QueryDispatcher>,
     view_tier: Option<Arc<ViewTier>>,
 }
 impl EngineHandle {
     pub fn spawn(plan_json: String, options: EngineOptions) -> anyhow::Result<(Self, Vec<String>)>;
+    /// What the HTTP routes run queries through.
+    pub fn dispatcher(&self) -> &QueryDispatcher;
+    /// For benchmarks: each planned query's measurements.
+    pub fn query_metrics(&self) -> &[(String, QueryMetrics)];
-    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 cached(&self, query: &str, time_ms: i64) -> Option<Answer>;
-    pub fn query_threads(&self) -> usize;
     // try_ingest, snapshot (now doc(hidden)), shared_nodes, query_time_results, metrics, render_metrics,
     // is_running, queued_samples, precompute_backlog, stats, advance_watermark, stop, hold_precompute: unchanged
 }

The removed methods were only the handlers' path to the query engine, which is now the dispatcher.

crates/precompute/src/engine.rs

+/// The precompute engine before and after its plan.
+pub struct PrecomputeEngine { /* options, persisted, published, installing, installed: OnceLock<InstalledPrecompute> */ }
+impl PrecomputeEngine {
+    pub fn new(options: PrecomputeOptions, persisted: Option<PersistedViews>, published: Arc<PublishedStore>) -> Self;
+    /// The threads running the installed plan; `None` before the install.
+    pub fn installed(&self) -> Option<&InstalledPrecompute>;
+    /// Compiles the ingestion and starts the threads; errs on a second plan or a plan it cannot run.
+    pub fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>;
+}
-pub struct PrecomputeEngine { /* commands, shards, shared, max_queued_samples */ }
+pub struct InstalledPrecompute { /* commands, shards, shared, max_queued_samples */ }
-pub fn start(ingestion, precompute, query_texts: &[String], options, persisted, published) -> anyhow::Result<Self>;
+fn start(ingestion, precompute, options, persisted, published) -> anyhow::Result<Self>;
 pub struct PrecomputeOptions {
+    /// The most bytes one ingestion run may hold.
+    pub run_memory_limit_bytes: usize,
     /* the other fields unchanged */
 }

crates/query/src/engine.rs (new), crates/query/src/workers.rs, crates/query/src/lib.rs

+/// How the query engine compiles and runs the plan's queries (the query subset of `EngineOptions`).
+pub struct QueryOptions {
+    pub run_memory_limit_bytes: usize,
+    pub threads: usize,
+    pub share_one_evaluation_results: bool,
+    pub query_time_results_retention_ms: u64,
+    pub query_time_results_max_bytes: usize,
+    pub result_cache: bool,
+    pub result_cache_max_bytes: usize,
+    /// Bounds how far back the result cache keeps answers.
+    pub view_retention_margin_ms: u64,
+    /// Refuse a plan with a query the engine cannot run (`--no-forward`).
+    pub refuse_unexecutable: bool,
+}
+/// The query engine over the Planner's executor.
+pub struct ExecutorQueryEngine { /* options, published, installing, installed: OnceLock<InstalledQueries> */ }
+impl ExecutorQueryEngine {
+    pub fn new(options: QueryOptions, published: Arc<PublishedStore>) -> Self;
+    pub fn installed(&self) -> Option<&InstalledQueries>;
+    /// Compiles the queries and starts `query-N`; errs on a second plan, or (refuse_unexecutable) a query it cannot run.
+    pub fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>;
+    /// One query by its root: `NotReady` before the install, for another plan, or when a window is missing;
+    /// a range is stepped and grouped by series (sorted by labels).
+    pub async fn execute(&self, source: &AnswerSource, request: &QueryRequest) -> Result<EngineQueryResult, QueryEngineError>;
+}
-pub struct QueryWorkers { /* … */ }
+pub struct InstalledQueries { /* plan, queries, compiled, threads, published */ }
+impl InstalledQueries {
-    pub fn start(query: QueryEngine, published, metrics: Arc<Metrics>, threads) -> io::Result<Self>;
+    pub(crate) fn start(plan: PlanId, compiled: CompiledQueries, published, threads) -> 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 cached(&self, query: &str, time_ms: i64) -> Option<Answer>;
+    /// From the result cache, or a worker.
+    pub async fn instant(&self, source: &AnswerSource, query: &str, time_ms: i64) -> Result<Answer, Unanswered>;
+    /// Every step, in parallel on the workers, cached ones from the cache; records the range metrics.
+    pub async fn range(&self, source: &AnswerSource, query: &str, times_ms: impl Iterator<Item = i64>) -> Result<Vec<(i64, Answer)>, Unanswered>;
     pub fn snapshot(&self) -> Arc<Snapshot>;
-    pub fn threads(&self) -> usize;
-    pub fn engine(&self) -> &QueryEngine;
+    pub fn plan(&self) -> PlanId;
+    pub fn compiled(&self) -> &CompiledQueries;
 }
-pub struct QueryEngine { … }
+pub struct CompiledQueries { /* + unexecutable, runnable, metrics; − roots */ }
 impl CompiledQueries {
-    pub fn cached(&self, query: &str, time_ms: i64) -> Option<Answer>;
+    pub fn cached(&self, root: PhysicalASAPNodeId, time_ms: i64) -> Option<Answer>;
-    pub fn evaluate(&self, query: &str, time_ms: i64, snapshot: &Snapshot) -> Result<Answer, Unanswered>;
+    pub fn evaluate(&self, root: PhysicalASAPNodeId, time_ms: i64, snapshot: &Snapshot) -> Result<Answer, Unanswered>;
-    pub fn unexecutable(&self) -> Vec<(String, String)>;
+    pub(crate) fn unexecutable(&self) -> &[(String, String)];
+    /// Each planned query's measurements, by trimmed text, sorted (for `/metrics`).
+    pub fn metrics(&self) -> &[(String, QueryMetrics)];
 }
 pub enum Unanswered {
-    NotPlanned(String),
+    /// The query was resolved against another plan than the one installed (not reached in v1).
+    PlanChanged,
     Unsupported(String), MissingRows(String), Execution(String),
 }
+impl Unanswered { /// MissingRows or PlanChanged: the boundary's NotReady.
+    pub fn is_not_ready(&self) -> bool; }

crates/internal-metrics/src/lib.rs, crates/data-plane/src/metrics_endpoint.rs

 pub struct Metrics {
-    pub queries: BTreeMap<String, QueryMetrics>,
     /* the other fields unchanged */
 }
-pub fn new(groups: &[(i64, Vec<String>)], queries: &[String]) -> Self;
+pub fn new(groups: &[(i64, Vec<String>)]) -> Self;
-pub fn query(&self, query: &str) -> Option<&QueryMetrics>;
 pub(crate) struct Gauges<'a> {
+    /// Each planned query's measurements, by query text, sorted.
+    pub queries: &'a [(String, QueryMetrics)],
     /* the other fields unchanged */
 }

Metrics loses the per-query measurements because the query engine is installed first and owns its queries; render writes them in the same places from Gauges::queries.

Usage (end to end, as crates/data-plane/src/dispatcher.rs's tests run it):

// The control plane's plan for one query, evaluated every 10 s over the gauge `data`.
let plan = test_support::plan("sum_over_time(data[10s])", false);
// EngineHandle::spawn builds the published store, PrecomputeEngine::new, ExecutorQueryEngine::new and
// QueryDispatcher::new, then PlanInstaller::install(plan): validate → query engine (compile, query-N) →
// precompute engine (compile, ingest side) → dispatcher (query texts → roots of PlanId(1)).
let (engine, _) = EngineHandle::spawn(serde_json::to_string(&plan)?, test_support::options())?;
// Remote Write's path, unchanged: InstalledPrecompute::try_ingest; 30 samples of data{job="a"} = 1.0.
engine.try_ingest(test_support::samples(30_000, 1.0))?;
// Closes and commits the windows (0, 10], (10, 20], (20, 30].
engine.advance_watermark(30_000).await?;
// GET /api/v1/query's path: resolve " sum_over_time(data[10s]) " (trimmed) → Planned { plan: 1, root },
// then InstalledQueries::instant: result cache, else a query worker.
assert!(matches!(engine.dispatcher().instant(" sum_over_time(data[10s]) ", 30_000).await,
    QueryOutcome::Ready(answer) if answer[0].value == 10.0));
// A window not stored yet: NotReady("invalid DAG: … no rows tiling (50000, 60000]"), forwarded with that reason.
// "up": Unmatched → Fallback::Forward { reason: None }, or with --no-forward
// Fallback::Refuse { reason: "the installed plan has no query \"up\"" } → 422.

Algorithm changes

None. Query matching, the result cache, stepping, the fallback rules and every engine's thread are the old code, moved.

Decisions and open questions

Needs reviewer decision: none.

Decided (judgment calls in this PR; deviations from the design and from #878):

  • The HTTP routes run queries through the dispatcher on the query engine's own answers, not through ExecutorQueryEngine::execute. QueryResult owns every series' LabelSet: converting each answer would copy every series' labels per query (2,800 label maps per step of a dashboard range), and the range writer's grouping of step answers by the labels' shared Arc (written for 241-step, 2,800-series dashboard ranges) would be lost. So QueryDispatcher calls InstalledQueries::{instant, range}; execute is for the QueryResult routes of step 8, with the same NotReady rule (Unanswered::is_not_ready).
  • QueryOutcome and NotAnswerableReason live in data-plane, as feat(common): engine boundary types and the fallback trait (layout step 4) #878 decided, and differ from #935's shapes: Ready(T) is generic over the answer (above) and carries no source (nothing logs it); NotReady(String) carries why, because today's x-asap-forward-reason header and the --no-forward 422 body say it (invalid DAG: materialized view 1 has no rows tiling …).
  • Matching is exact after trimming both texts, as today's QueryEngine::root matched (#935's resolve_planned trims too); the first equal text wins.
  • All or nothing, and install once. The installer installs the query engine first (its install only compiles and starts idle workers), then the ingest engine, then the dispatcher, and stops at the first failure: queries reach a plan only through the dispatcher, so a failed install answers nothing from the new plan. The engines install once (OnceLock) and refuse a second plan, so after the ingest engine refused a plan the query engine keeps it unused (#935 I14), and a failed install ends the binary, as a failing --plan does today. The installer keeps no install-once flag of its own: it is built and dropped in one expression at startup. Retrying would need each engine's install split into a compile step and a start step.
  • PersistedViews::plan_hash is the plan file's hash, given to the precompute engine before the plan. The view files are named by the hash of the plan file's bytes; hashing the re-serialized InstalledPlan instead would set aside every view file an older binary wrote for the same file. v1 installs the one plan file, so the two agree.
  • The engines are created before the plan, so each owns its plan-shaped state. The precompute engine creates Metrics (per refresh group) at install and the query engine its per-query QueryMetrics; the published store, created by data-plane, starts empty and the precompute engine's install publishes its initial raw data and views, as PublishedStore::new did.
  • No engine or store trait objects (whole-stack review). The first version had common::IngestEngine/QueryEngine impls, IngestEngine::ingest (retrying try_ingest every 10 ms with a copy of the batch per attempt), shutdown, execute_batch, and storage::boundary (BoundaryViewStore, BoundaryRawDataStore, RawSample::from_batch and four store reads). None had a production caller: every ingest route calls try_ingest, nothing called shutdown, the dispatcher held the concrete engine, and the only dyn use was PlanInstaller's, for a test fake. They are gone, with the traits in feat(common): engine boundary types and the fallback trait (layout step 4) #878; PlanInstaller's tests make the real engines refuse by installing a plan into them first. storage keeps its state codecs and does not depend on common.
  • QueryTimeResults<Unanswered> keeps the query engine's error type (refactor: split internal-metrics and storage crates out of data-plane (layout step 3) #877's follow-up): its waiters need MissingRows versus Execution, which QueryEngineError does not distinguish.

Verification

Run on a quiet remote host with ulimit -n raised.

Scope #879 head this PR Newly failing
cargo fmt --all -- --check pass pass —
cargo clippy --workspace --all-targets --locked -- -D warnings pass pass —
cargo test --workspace --locked 191 passed, 0 failed, 3 ignored (42 suites) 200 passed, 0 failed, 3 ignored (42 suites) none

The sorted lists of passing test names differ from #879's head only by the 9 new tests below (every old name still passes).

New tests:

Test Checks
installer::tests::installs_one_plan_into_both_engines_and_the_dispatcher a plan installs into both engines and the dispatcher as plan 1; a second plan is refused and the first keeps answering
installer::tests::a_failed_install_leaves_the_plan_as_it_was an invalid plan, a query-engine refusal and an ingest-engine refusal (each engine made to refuse by holding a plan already) stop before the next step and leave the dispatcher without a plan
dispatcher::tests::answers_a_planned_query_and_leaves_others_unmatched a planned query (text with spaces) is answered from its views; another text is Unmatched and forwarded without a reason
dispatcher::tests::a_window_not_stored_yet_is_not_ready a planned query at a window not stored is NotReady, forwarded with its reason; so is a range with such a step
dispatcher::tests::a_query_the_engine_cannot_run_is_an_engine_error a planned query whose run does not compile is an EngineError, refused with it under --no-forward
dispatcher::tests::an_unmatched_query_is_refused_without_forwarding --no-forward refuses an unmatched query, naming it
engine::tests::the_ingest_engine_installs_once_and_ingests_after_it (precompute) the plan installs once, samples after it are ingested, stop stops the engine
engine::tests::the_query_engine_installs_once_and_reports_not_ready (query) execute: NotReady before the install, for another plan id, and for missing windows (instant and range); installs once; metrics found by trimmed text
engine::tests::answers_convert_to_boundary_results (query) answers convert to an instant vector, and steps to a matrix sorted by labels

End to end: the fixture of #879 (uncommitted tests/zz_parity_dump.rs, run on #878's head and on this PR's first head) gives byte-identical status codes, headers and bodies for planned, cached, not-ready and unplanned instant and range queries, with and without --no-forward, and the same /metrics families, names and label sets: byte-identical (547 lines), on #879's head too.

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).

Independent reviews (correctness and parity; over-abstraction and dependency direction; dead code and duplication; efficiency) found no behavior change and no hot-path regression. Their findings are fixed in the third commit:

  • Its failure test checks that the query engine keeps the plan after the ingest engine refuses it (the earlier doc claimed a retry could succeed).
  • One Unanswered::is_not_ready rule for the dispatcher and execute; NotAnswerableReason::EngineError holds a QueryEngineError; Fallback::new takes the reason by value, so a forward reason is built once.
  • CompiledQueries keeps the unexecutable queries instead of a second text→root list; QueryWorkers → InstalledQueries; unused threads() deleted.
  • data-plane names plan types through common; the Planner crates are dev-dependencies.
  • A test for the trimmed metrics lookup; QueryOptions documents its fields; test- and benchmark-only accessors are doc(hidden).

Not changed, by choice: EngineOptions stays flat (nesting PrecomputeOptions/QueryOptions would change every test that sets an option); the --no-forward wording of the query engine's refusal stays (a test and users read it); the plan fixture is repeated in three crates' tests (one shared helper would need a test-only API in control_plane).

Whole-stack review fixes (fourth commit)

  • The engines are concrete types (Decisions); storage::boundary, IngestEngine::ingest/shutdown, execute_batch, RawSample::from_batch and PlanInstaller.tried are gone.
  • PlanInstaller's field is precompute, as EngineHandle names the engine.
  • pub(crate): PlanInstaller; the dispatcher module and its items (QueryDispatcher, QueryOutcome, NotAnswerableReason; no caller outside the crate) and EngineHandle::dispatcher; precompute's Ingestion, Precompute, IngestionError, ClosedWindow, Routing, Computed; query's CompiledQueries::unexecutable and ResultCache::horizon_ms.
  • async-trait leaves precompute, query and data-plane.
  • Re-verified on this head: the gate above, and the parity dump at the top of the stack byte-identical to the stack's top before these fixes.

Follow-ups

  • Done in docs(design): repository layout and engine boundaries #874 (now the stack's base): the dependency graph, the dispatcher's native answers, QueryOutcome/NotAnswerableReason in data-plane, install-once semantics, and no engine or store traits.
  • Step 6: the Prometheus HTTP routes become an adapter; the forward proxy becomes a FallbackClient.
  • A plan from the workload tracker needs its own view-file hash and an install that can be retried (compile and start split).

@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 feat: engines behind common's traits; PlanInstaller and QueryDispatcher feat: engines as concrete types; PlanInstaller and QueryDispatcher (layout step 5b) Nov 27, 2026
PrecomputeEngine implements IngestEngine and ExecutorQueryEngine
implements QueryEngine: both are created before any plan, and their
install compiles the plan and starts their threads (v1: once). The data
plane installs the plan file through PlanInstaller (query engine, ingest
engine, dispatcher, stopping at the first failure), and the HTTP query
routes run through QueryDispatcher, which matches the query text and
decides the fallback. Each planned query's measurements move from
Metrics to the query engine; /metrics is unchanged.
- PlanInstaller takes only the first install call (the engines install
  once too); its test checks the query engine keeps the plan unused
  after the ingest engine refuses it.
- NotAnswerableReason::EngineError holds a QueryEngineError; one
  Unanswered::is_not_ready rule for the dispatcher and the trait path;
  Fallback takes the reason by value, so a forward reason is built once.
- CompiledQueries keeps the unexecutable queries instead of every root;
  QueryWorkers is InstalledQueries; its unused threads() is gone.
- RawSample::from_batch interns a RawDataBatch for both the ingest
  engine and the raw-data store adapter; the store helpers the adapters
  use are pub(crate).
- data-plane names InstallablePlan and node ids through common; the
  Planner crates are dev-dependencies.
- QueryOptions documents its fields; test- and benchmark-only accessors
  are doc(hidden).
The stores and engines have one implementation each, so they are
concrete types (a trait is added with its second implementation):

- storage::boundary (BoundaryViewStore, BoundaryRawDataStore) and the
  store helpers only it used (RawData::samples, ViewStore::windows,
  evict_before, time_ranges, RawSample::from_batch) are not added;
  storage does not depend on common.
- PrecomputeEngine::install and ExecutorQueryEngine::{install, execute}
  are inherent. IngestEngine::ingest, shutdown and execute_batch are
  gone (no production caller; every ingest route calls try_ingest).
- PlanInstaller holds the two engines, not trait objects, and loses
  tried: it is built and dropped in one expression, and the engines
  refuse a second plan. Its tests make the real engines refuse by
  installing a plan into them first. Its field is precompute, as
  EngineHandle names the engine.
- pub(crate): PlanInstaller; the dispatcher module and its items (no
  caller outside the crate); precompute's Ingestion, Precompute and the
  types their methods return; query's unexecutable and horizon_ms.
- async-trait leaves precompute, query and data-plane.
@zzylol
zzylol force-pushed the refactor/layout-engines branch from 9e99e2e to 02d480a Compare November 28, 2026 00:56
@zzylol
zzylol force-pushed the refactor/layout-engines-traits branch from 4f5b4f8 to 7683fc9 Compare November 28, 2026 00:56
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