Repository navigation
Conversation
zzylol
added a commit
that referenced
this pull request
Nov 26, 2026
This was referenced Nov 26, 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
force-pushed
the
refactor/layout-engines
branch
from
November 28, 2026 00:56
9e99e2e to
02d480a
Compare
zzylol
force-pushed
the
refactor/layout-engines-traits
branch
from
November 28, 2026 00:56
4f5b4f8 to
7683fc9
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
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.docs/design/repo-layout.md(docs(design): repository layout and engine boundaries #874).precompute::engine::PrecomputeEngineandquery::ExecutorQueryEngineare created before any plan, and their inherentinstall(InstalledPlan)compiles the plan and starts their threads (v1: once);ExecutorQueryEngine::executeanswers oneQueryRequestwithcommon::EngineQueryResult. They are concrete types, not trait objects: each has one implementation.data-planeaddsPlanInstaller(validate, then query engine, ingest engine, dispatcher, stopping at the first failure; v1 installs once) andQueryDispatcher(exact query-text match, run, fallback decision), and the instant and range handlers go through the dispatcher./metricslines. One thing is faster: an unplanned query no longer waits for a query worker before it is forwarded (the dispatcher answersUnmatchedat once; before, it went to a worker, which found no root).Review guide
refactor/layout-engines(refactor: split precompute and query crates out of data-plane (layout step 5a) #879). Stacked draft.PlanInstaller,QueryDispatcher, the handlers, and per-query metrics moving to the query engine.PlanInstallerwithouttried,pub(crate)for crate-local items.crates/data-plane/src/installer.rs,crates/data-plane/src/dispatcher.rs, thequeryandquery_rangehandlers incrates/data-plane/src/lib.rs, thencrates/query/src/workers.rs(instant,range, the worker loop) andcrates/query/src/engine.rs, thenPrecomputeEngineincrates/precompute/src/engine.rs.InstalledPrecomputeis refactor: split precompute and query crates out of data-plane (layout step 5a) #879'sPrecomputeEnginerenamed, withstarttaking no query texts.InstalledQueries::rangeis the formeranswer_rangeoflib.rs(stepping, cache, metrics) moved, keyed by root instead of text.renderreads the per-query metrics fromGauges::queriesinstead ofMetrics::queries.Old → new
EngineHandle::spawn: compile both, start bothPlanInstaller::install→ExecutorQueryEngine::install(compile queries, startquery-N) →PrecomputeEngine::install(compile ingestion, start the ingest side) →QueryDispatcher::installdata_plane::engine::installplan.validate()inPlanInstallerlib.rsanswer: time,cached(text),evaluate(text)QueryDispatcher::instant→InstalledQueries::instant(cache, worker)lib.rsanswer_range: steps, cache, snapshot, buffered workers, range metricsQueryDispatcher::range→InstalledQueries::range; the response body is still built inlib.rsQueryEngine::root(text)(text → root, per call, twice per query)QueryDispatcher::resolve(once per request); the engine takesAnswerSource::Planned { plan, root }Unanswered::NotPlannedNotAnswerableReason::Unmatched(dispatcher)matchonUnansweredfor forward / refuse / reason headerFallback::new(reason, query, no_forward)query::QueryEngine(compiled queries)query::CompiledQueriesquery::workers::QueryWorkersquery::workers::InstalledQueriesprecompute::engine::PrecomputeEngine(#879)InstalledPrecompute;PrecomputeEngineis now the plan-less shellinternal_metrics::Metrics::{queries, query()}CompiledQueries::{metrics(), metrics_index()};Gauges::queriesDependency graph
data_planenames plan types throughcommonnow, soasap-plannerandasap-executorare 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:GET /api/v1/query?query=sum+by+(job)+(sum_over_time(data[10s]))&time=60x-asap-execution: plan,{"status":"success","data":{"resultType":"vector","result":[{"metric":{"job":"j0"},"value":[60.0,"1110"]},{"metric":{"job":"j1"},"value":[60.0,"555"]}]}}time=90(window not stored),--no-forwardx-asap-execution: refused,{"error":"invalid DAG: materialized view 1 has no rows tiling (80000, 90000]",…}query=up,--no-forward{"error":"the installed plan has no query \"up\"",…}x-asap-execution: forwarded), withx-asap-forward-reasonfor the planned query onlyInterfaces
crates/data-plane/src/installer.rs(new, private module)crates/data-plane/src/dispatcher.rs(new)crates/data-plane/src/engine.rspub 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.rscrates/query/src/engine.rs(new),crates/query/src/workers.rs,crates/query/src/lib.rscrates/internal-metrics/src/lib.rs,crates/data-plane/src/metrics_endpoint.rspub 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 */ }Metricsloses the per-query measurements because the query engine is installed first and owns its queries;renderwrites them in the same places fromGauges::queries.Usage (end to end, as
crates/data-plane/src/dispatcher.rs's tests run it):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):
ExecutorQueryEngine::execute.QueryResultowns 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' sharedArc(written for 241-step, 2,800-series dashboard ranges) would be lost. SoQueryDispatchercallsInstalledQueries::{instant, range};executeis for theQueryResultroutes of step 8, with the sameNotReadyrule (Unanswered::is_not_ready).QueryOutcomeandNotAnswerableReasonlive indata-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 nosource(nothing logs it);NotReady(String)carries why, because today'sx-asap-forward-reasonheader and the--no-forward422 body say it (invalid DAG: materialized view 1 has no rows tiling …).QueryEngine::rootmatched (#935'sresolve_plannedtrims too); the first equal text wins.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--plandoes 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_hashis 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-serializedInstalledPlaninstead would set aside every view file an older binary wrote for the same file. v1 installs the one plan file, so the two agree.Metrics(per refresh group) at install and the query engine its per-queryQueryMetrics; the published store, created bydata-plane, starts empty and the precompute engine's install publishes its initial raw data and views, asPublishedStore::newdid.common::IngestEngine/QueryEngineimpls,IngestEngine::ingest(retryingtry_ingestevery 10 ms with a copy of the batch per attempt),shutdown,execute_batch, andstorage::boundary(BoundaryViewStore,BoundaryRawDataStore,RawSample::from_batchand four store reads). None had a production caller: every ingest route callstry_ingest, nothing calledshutdown, the dispatcher held the concrete engine, and the onlydynuse wasPlanInstaller'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.storagekeeps its state codecs and does not depend oncommon.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 needMissingRowsversusExecution, whichQueryEngineErrordoes not distinguish.Verification
Run on a quiet remote host with
ulimit -nraised.cargo fmt --all -- --checkcargo clippy --workspace --all-targets --locked -- -D warningscargo test --workspace --lockedThe 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:
installer::tests::installs_one_plan_into_both_engines_and_the_dispatcherinstaller::tests::a_failed_install_leaves_the_plan_as_it_wasdispatcher::tests::answers_a_planned_query_and_leaves_others_unmatchedUnmatchedand forwarded without a reasondispatcher::tests::a_window_not_stored_yet_is_not_readyNotReady, forwarded with its reason; so is a range with such a stepdispatcher::tests::a_query_the_engine_cannot_run_is_an_engine_errorEngineError, refused with it under--no-forwarddispatcher::tests::an_unmatched_query_is_refused_without_forwarding--no-forwardrefuses an unmatched query, naming itengine::tests::the_ingest_engine_installs_once_and_ingests_after_it(precompute)stopstops the engineengine::tests::the_query_engine_installs_once_and_reports_not_ready(query)execute:NotReadybefore the install, for another plan id, and for missing windows (instant and range); installs once; metrics found by trimmed textengine::tests::answers_convert_to_boundary_results(query)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/metricsfamilies, 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:
ingest_bench 10000 120 views 1 persist: every write acknowledgedview_read_bench 10000 40 15(KLL): pread cold / warm, ns per rowAll 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:
Unanswered::is_not_readyrule for the dispatcher andexecute;NotAnswerableReason::EngineErrorholds aQueryEngineError;Fallback::newtakes the reason by value, so a forward reason is built once.CompiledQuerieskeeps the unexecutable queries instead of a second text→root list;QueryWorkers→InstalledQueries; unusedthreads()deleted.data-planenames plan types throughcommon; the Planner crates are dev-dependencies.QueryOptionsdocuments its fields; test- and benchmark-only accessors aredoc(hidden).Not changed, by choice:
EngineOptionsstays flat (nestingPrecomputeOptions/QueryOptionswould change every test that sets an option); the--no-forwardwording 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 incontrol_plane).Whole-stack review fixes (fourth commit)
storage::boundary,IngestEngine::ingest/shutdown,execute_batch,RawSample::from_batchandPlanInstaller.triedare gone.PlanInstaller's field isprecompute, asEngineHandlenames the engine.pub(crate):PlanInstaller; thedispatchermodule and its items (QueryDispatcher,QueryOutcome,NotAnswerableReason; no caller outside the crate) andEngineHandle::dispatcher; precompute'sIngestion,Precompute,IngestionError,ClosedWindow,Routing,Computed; query'sCompiledQueries::unexecutableandResultCache::horizon_ms.async-traitleavesprecompute,queryanddata-plane.Follow-ups
QueryOutcome/NotAnswerableReasonindata-plane, install-once semantics, and no engine or store traits.FallbackClient.