From ad1110b7ec1b21d6000381e207a9f7adb9d8b7c6 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 05:59:07 +0000 Subject: [PATCH 01/18] docs(design): repository layout and engine boundaries --- docs/design/repo-layout.md | 264 +++++++++++++++++++++++++++++++++++++ 1 file changed, 264 insertions(+) create mode 100644 docs/design/repo-layout.md diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md new file mode 100644 index 000000000..ea96f4778 --- /dev/null +++ b/docs/design/repo-layout.md @@ -0,0 +1,264 @@ +# Design: repository layout and engine boundaries + +Status: proposal, for review. Decisions are recorded at the end. + +## Audience and context + +This document is for developers of the backend. It decides two things: + +1. **Layout**: which crates and top-level folders the repository has, and + where every current file goes. +2. **Boundaries**: the interfaces between the control plane and the data + plane, and between the data plane's parts. They follow ASAPQuery's + [engine boundaries design](https://github.com/ProjectASAP/ASAPQuery/blob/main/.design_docs/asapplanner-engine-boundaries.md) + (ProjectASAP/ASAPQuery#935), so that the protocol adapters ASAPQuery has + today (Prometheus, VictoriaMetrics and OTLP ingest; Prometheus, ClickHouse + and Elastic query endpoints and fallback clients) can move here against + the same traits. + +Today the workspace has two crates: + +| Crate | Lines | Holds | +|---|---|---| +| `control_plane` | about 200 | `plan_installable` on a `PlanningWorkload`, writes the plan file | +| `data_plane` | about 17,000 | everything else: Remote Write decoding, ingest shards, push precompute, the engine around `asap-executor`, the view store (hot tier, segments, persistence, codecs), queries, result cache, raw forward, the Prometheus HTTP API, `/metrics`, the binary | + +Measurement code is in three places: `bench/demo` (the comparison against +VictoriaMetrics, the live demo, Grafana monitoring), `data_plane/examples/*_bench.rs` +(nine micro benchmarks) and `scripts/`. + +One crate for the whole data plane means nothing enforces which part may use +which. For example, the query code can reach into the store's internals. A +crate per part makes the dependency direction a compile-time rule, and it +speeds up incremental builds. + +## Layout + +```text +ASAPQuery-backend/ +├── Cargo.toml # workspace +├── crates/ +│ ├── common/ # engine boundary types and traits (see Boundaries) +│ ├── control-plane/ # workload → asap-planner → InstallablePlan +│ ├── precompute/ # IngestEngine: ingest shards, push pipelines, asap-executor ingestion +│ ├── storage/ # ViewStore + RawDataStore: hot tier, segments, persistence, codecs +│ ├── query/ # QueryEngine: planned queries over the stores, result cache +│ ├── internal-metrics/ # the backend's own measurements, exported on /metrics +│ ├── data-plane/ # the binary: CLI, PlanInstaller, QueryDispatcher, HTTP routes, wiring +│ └── adapters/ +│ ├── ingest/ # prometheus-remote-write, victoriametrics-remote-write, otlp +│ └── query/ # prometheus-http, clickhouse-http, elastic-http, fallback clients +├── benchmarks/ # the backend alone: micro (criterion) and system ingest/query +├── eval/ # cross-system experiments for the paper +│ ├── baselines// # install and configure each compared system +│ ├── workloads/ +│ ├── harness/ +│ ├── scripts/ +│ └── results/ # .gitignore'd; never committed +├── deployment/ # Dockerfiles, compose files, monitoring (Grafana, Prometheus) +├── docs/ +└── README.md +``` + +### Names + +- **`control-plane`, not `planner`.** Planning is ASAPPlanner's + (`asap-planner`, a pinned git dependency). This crate only builds the + workload and deployment inputs, calls `plan_installable` and hands the + plan on. A folder called `planner` would suggest a planner copy here and + collide with the `asap-planner` crate. +- **`internal-metrics`, not `metrics` or `telemetry`.** In a time-series + database, "metrics" are the data users write. "Telemetry" is also user + data here (OTLP is OpenTelemetry). The crate holds the backend's + measurements of itself. +- **`data-plane`** is the crate that assembles precompute, storage and query + into one process. Its binary keeps the crate's name until a product name is + decided (`[[bin]] name` can change it without moving code). +- **No `utils` crate.** A helper goes in the crate that uses it. A helper two + crates use goes in the lower of the two in the dependency graph, or in + `common` if it is part of the boundary. + +### `benchmarks/` versus `eval/` + +- `benchmarks/` measures the backend alone and guards against regressions. + It runs often and needs only this repository. +- `eval/` compares the backend with other systems for the paper. It installs + other systems, runs long and writes large results, which stay out of git. + Private workloads and anything derived from them never go into `eval/`. + +## Boundaries + +### Dependency graph + +```text + control-plane ──► asap-planner + │ + ▼ + adapters/* ──► common ◄── precompute, storage, query, internal-metrics + ▲ │ │ + │ └──► asap-executor (plan execution today) + data-plane ──► every crate above (wiring only) +``` + +- `common` depends on ASAPPlanner's plan types only (`InstallablePlan`, + `PhysicalASAPDAG`, `QueryLanguage`, …), never on the executor's runtime. + This is #935's decision 1. +- Adapters depend on `common` only: they never see an engine or a store. In + ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); + a separate `common` crate closes that here. +- `precompute`, `storage` and `query` do not depend on each other. They meet + in `common`'s traits: `precompute` writes through `ViewStore` and + `RawDataStore`, and `query` reads through them. +- Only `data-plane` knows every implementation. It builds the stores, injects + them into both engines, and owns `PlanInstaller` and `QueryDispatcher`. + +### Control plane → data plane + +The contract is the `InstallablePlan`, which is a `PhysicalASAPDAG` plus one +query text per DAG root. Today the control plane writes it as a JSON plan +file, and the data plane installs it at startup with `--plan`. This stays: + +```rust +// crates/data-plane +struct PlanInstaller { /* the two engines and the dispatcher */ } +impl PlanInstaller { + /// Validates the plan (supported operators, sources), then installs it + /// into the ingest engine, the query engine and the dispatcher, all or + /// nothing. On failure the current plan stays. + fn install(&self, plan: InstallablePlan) -> Result; +} +``` + +The control plane has two callers of `install`: +- the plan file at startup, as today; +- later, the workload tracker (#935's `QueryWorkloadTracker`). It records the + queries the HTTP endpoints receive as a `PlanningWorkload`, decides when to + replan, calls `plan_installable` and passes the plan to `install`. Like + #935's I14, v1 installs once. + +`DeploymentCapabilities` and `CostInputs` are control-plane inputs. They +describe what this deployment's engines support and what its resources cost. +They are not part of the data plane's interface. + +### Data plane parts (`crates/common`) + +These are #935's interfaces, with the same names, so adapters move unchanged: + +```rust +// Requests and results (adapters ↔ dispatcher) +struct QueryRequest { language: QueryLanguage, query: String, eval: Eval } +enum Eval { Instant { time_ms: i64 }, Range { start_ms: i64, end_ms: i64, step_ms: i64 } } +enum QueryResult { Vector(..), Matrix(..), Scalar(..), Table { columns, rows } } + +// Ingest (ingest adapters → precompute) +enum RawDataBatch { TimeSeries { series: Vec<(LabelSet, Vec<(i64, f64)>)> } } +trait IngestEngine { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; + async fn ingest(&self, batch: RawDataBatch) -> Result<(), IngestError>; // waits under backpressure + fn shutdown(&self); +} + +// Query (dispatcher → query) +enum AnswerSource { Planned { plan: PlanId, root: PhysicalASAPNodeId } } +enum EngineQueryResult { Ready { result: QueryResult }, NotReady } +trait QueryEngine { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; + async fn execute_batch(&self, queries: &[(AnswerSource, QueryRequest)]) + -> Vec>; +} + +// Stores (precompute writes, query reads) +struct ViewId { plan: PlanId, node: PhysicalASAPNodeId } +struct ViewInstanceKey { view: ViewId, window: (i64, i64) } // (start, end] +trait ViewStore { put, get, instances, evict_before, timestamp_range_per_view } +trait RawDataStore { append, read, evict } + +// Fallback (data-plane → query adapters) +trait FallbackClient { async fn execute(&self, req: &QueryRequest) -> Response; } +``` + +`QueryDispatcher` (in `data-plane`) resolves each request against the +installed plan's query texts, runs the query engine, and falls back on +`Unmatched`, `NotReady` or an engine error, as #935 specifies. + +### Where the backend differs from #935 + +| Topic | #935 (ASAPQuery) | Backend | Proposal | +|---|---|---|---| +| Query engine | ASAPPlanner's DataFusion query-time engine (ProjectASAP/ASAPPlanner#1468, a merged proposal, not yet code) | `asap-executor` | Keep `asap-executor` behind `QueryEngine`. Switching later changes only `crates/query` | +| Ingest engine | a new push engine modeled on ASAPQuery's precompute engine | ingest shards + push precompute + the executor's ingestion (docs/design/parallel-precompute.md) | Keep ours behind `IngestEngine` | +| View state | opaque `Arc`, in memory only, durability deferred | hot tier of decoded windows plus compact on-disk segments | `ViewStore` adds an encode/decode pair for durable tiers (#935's I6 anticipates it) | +| View id | `(PlanId, PhysicalASAPNodeId)` | directories per refresh group and retention | Key the store by `ViewId`. On-disk recovery across plans needs ProjectASAP/ASAPPlanner#1429, as in #935 | +| Raw data | `RawDataStore` in memory | raw samples in `store.rs`, plus optional forward to a raw store | `RawDataStore` trait over both; the forward becomes a `FallbackClient` plus an ingest tee in `data-plane` | +| Sketch kernels | move out of `asap-executor` into a shared ASAPPlanner crate (#935's decision 48) | through `asap-executor` and `asap_sketchlib` | No change until that crate exists | +| Adapters' dependency | the whole engine crate | `common` only | as in the dependency graph above | + +## Where the current files go + +| Today | New home | +|---|---| +| `control_plane/` | `crates/control-plane/` | +| `data_plane/src/{ingestion,push,series_ids}.rs` | `crates/precompute/` | +| `data_plane/src/engine.rs` | split, see below | +| `data_plane/src/{store,window_cache,memory_budget,segment,persist,state_codec}.rs` | `crates/storage/` | +| `data_plane/src/{query,result_cache}.rs` | `crates/query/` | +| `data_plane/src/raw_forward.rs` | split: the tee into `crates/data-plane/`, the proxy into `crates/adapters/query/` | +| `data_plane/src/remote_write.rs` | `crates/adapters/ingest/prometheus-remote-write/` | +| `data_plane/src/prometheus.rs` | `crates/adapters/query/prometheus-http/` | +| `data_plane/src/metrics.rs` | `crates/internal-metrics/` | +| `data_plane/src/{lib,main}.rs` | `crates/data-plane/` | +| `data_plane/tests/` | the crate whose behavior each test checks; end-to-end tests in `crates/data-plane/tests/` | +| `data_plane/examples/*_bench.rs` | `benchmarks/micro/` | +| `bench/demo/{campaign,harness,workloads,profile}` | `eval/` | +| `bench/demo/{live,run_live_demo.sh}` | `eval/demo/` | +| `bench/demo/monitoring/` | `deployment/monitoring/` | +| `scripts/ci/`, `scripts/sync-asapplanner-main.sh` | stay in `scripts/` | +| `scripts/profile.sh`, `scripts/tiered_views_cgroup.sh` | `benchmarks/scripts/` | +| `examples/*.json` | `docs/examples/` | + +`engine.rs` (about 2,700 lines) is the one file that splits rather than +moves. It holds the installed plan's compiled form and every thread that +executes it: + +| Part of `engine.rs` | New home | +|---|---| +| ingest shards, the `ingest` coordinator, the precompute pool and committer | `crates/precompute/` | +| `persist-N` threads and the view-cache monitor | `crates/storage/` | +| `query-N` workers | `crates/query/` | +| `EngineHandle`, `EngineOptions`, install | `crates/data-plane/` | + +## Migration order + +Every step keeps behavior and all tests passing. The steps are separate PRs, +each reviewed on its own: + +1. This document. +2. Folder moves only: `control_plane` → `crates/control-plane`, `data_plane` → + `crates/data-plane` (still one crate), `bench/demo` → `eval/` and + `deployment/monitoring`, micro benchmarks → `benchmarks/micro`. Paths in + scripts, CI and docs are updated. +3. Split leaf crates out of `data-plane`: `internal-metrics`, then `storage`. +4. `common` with the boundary types and traits, no implementations. +5. Split `precompute` and `query` out of `data-plane`. `storage` implements + `ViewStore` and `RawDataStore`, `precompute` implements `IngestEngine`, + and `query` implements `QueryEngine`. `PlanInstaller` and `QueryDispatcher` + are added in `data-plane`. +6. Move the existing Remote Write decoder and Prometheus HTTP API into + `crates/adapters/`. +7. Bring over ASAPQuery's ingest adapters (VictoriaMetrics Remote Write, + OTLP), after ASAPQuery's adapter extraction (ProjectASAP/ASAPQuery#936) + and `QueryRequest` change (ProjectASAP/ASAPQuery#937) merge. +8. Bring over ASAPQuery's query adapters and fallback clients (ClickHouse and + Elastic HTTP). +9. `eval/` baselines (ClickHouse and others) and `deployment/` Dockerfiles. + +## Decisions + +1. **`common` lives here for now.** ASAPQuery and this repository should + share one copy of #935's traits. The intended home is ASAPPlanner, next to + the plan types both repositories already depend on. Until then the traits + live in `crates/common`, and ASAPQuery is not changed. +2. **The workload tracker lives in `control-plane`.** It produces a planning + input. The query adapters only report each query they receive to it. +3. **No rename for now.** The binary keeps the `data-plane` name; a product + name can be set later with `[[bin]] name`. From aad66314fba6b67c3a6ee4ef99df4d53fd724dad Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 05:59:37 +0000 Subject: [PATCH 02/18] docs(design): common stays in this repository --- docs/design/repo-layout.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index ea96f4778..00c805f2c 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -254,10 +254,9 @@ each reviewed on its own: ## Decisions -1. **`common` lives here for now.** ASAPQuery and this repository should - share one copy of #935's traits. The intended home is ASAPPlanner, next to - the plan types both repositories already depend on. Until then the traits - live in `crates/common`, and ASAPQuery is not changed. +1. **`common` lives in this repository**, in `crates/common`. This work + changes neither ASAPPlanner nor ASAPQuery. The traits keep #935's names and + shapes, so ASAPQuery's adapters can move here without changes. 2. **The workload tracker lives in `control-plane`.** It produces a planning input. The query adapters only report each query they receive to it. 3. **No rename for now.** The binary keeps the `data-plane` name; a product From 1d57993325ca0d71fab19c1af7c5f61541c24f7c Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 08:54:43 +0000 Subject: [PATCH 03/18] docs(design): series_ids goes to storage; internal-metrics is a leaf --- docs/design/repo-layout.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 00c805f2c..d5af598b4 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -94,7 +94,9 @@ ASAPQuery-backend/ control-plane ──► asap-planner │ ▼ - adapters/* ──► common ◄── precompute, storage, query, internal-metrics + adapters/* ──► common ◄── precompute, storage, query + │ │ │ + └────────┴────────┴──► internal-metrics (a leaf) ▲ │ │ │ └──► asap-executor (plan execution today) data-plane ──► every crate above (wiring only) @@ -198,7 +200,8 @@ installed plan's query texts, runs the query engine, and falls back on | Today | New home | |---|---| | `control_plane/` | `crates/control-plane/` | -| `data_plane/src/{ingestion,push,series_ids}.rs` | `crates/precompute/` | +| `data_plane/src/{ingestion,push}.rs` | `crates/precompute/` | +| `data_plane/src/series_ids.rs` | `crates/storage/` (the store and segments use it; `storage` must not depend on `precompute`) | | `data_plane/src/engine.rs` | split, see below | | `data_plane/src/{store,window_cache,memory_budget,segment,persist,state_codec}.rs` | `crates/storage/` | | `data_plane/src/{query,result_cache}.rs` | `crates/query/` | From 34f9e0cbab98bc1443fad0edd595e80b17fce4b2 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 08:54:55 +0000 Subject: [PATCH 04/18] docs(design): dependency graph as a table --- docs/design/repo-layout.md | 48 ++++++++------------------------------ 1 file changed, 10 insertions(+), 38 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index d5af598b4..c04d1518f 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -91,44 +91,16 @@ ASAPQuery-backend/ ### Dependency graph ```text - control-plane ──► asap-planner - │ - ▼ - adapters/* ──► common ◄── precompute, storage, query - │ │ │ - └────────┴────────┴──► internal-metrics (a leaf) - ▲ │ │ - │ └──► asap-executor (plan execution today) - data-plane ──► every crate above (wiring only) -``` - -- `common` depends on ASAPPlanner's plan types only (`InstallablePlan`, - `PhysicalASAPDAG`, `QueryLanguage`, …), never on the executor's runtime. - This is #935's decision 1. -- Adapters depend on `common` only: they never see an engine or a store. In - ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); - a separate `common` crate closes that here. -- `precompute`, `storage` and `query` do not depend on each other. They meet - in `common`'s traits: `precompute` writes through `ViewStore` and - `RawDataStore`, and `query` reads through them. -- Only `data-plane` knows every implementation. It builds the stores, injects - them into both engines, and owns `PlanInstaller` and `QueryDispatcher`. - -### Control plane → data plane - -The contract is the `InstallablePlan`, which is a `PhysicalASAPDAG` plus one -query text per DAG root. Today the control plane writes it as a JSON plan -file, and the data plane installs it at startup with `--plan`. This stays: - -```rust -// crates/data-plane -struct PlanInstaller { /* the two engines and the dispatcher */ } -impl PlanInstaller { - /// Validates the plan (supported operators, sources), then installs it - /// into the ingest engine, the query engine and the dispatcher, all or - /// nothing. On failure the current plan stays. - fn install(&self, plan: InstallablePlan) -> Result; -} +crate depends on +------------- -------------------------------------------------- +control-plane common, asap-planner +adapters/* common +precompute common, internal-metrics, asap-executor +storage common, internal-metrics, asap-executor +query common, internal-metrics, asap-executor +common ASAPPlanner's plan types only +internal-metrics nothing in this workspace (a leaf) +data-plane every crate above (wiring only) ``` The control plane has two callers of `install`: From b21ccbf20e3577471c1b6883234e2fcf4c59dbf5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 08:55:10 +0000 Subject: [PATCH 05/18] docs(design): restore the control plane section --- docs/design/repo-layout.md | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index c04d1518f..57ac9d2c7 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -103,6 +103,35 @@ internal-metrics nothing in this workspace (a leaf) data-plane every crate above (wiring only) ``` +- `common` depends on ASAPPlanner's plan types only (`InstallablePlan`, + `PhysicalASAPDAG`, `QueryLanguage`, …), never on the executor's runtime. + This is #935's decision 1. +- Adapters depend on `common` only: they never see an engine or a store. In + ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); + a separate `common` crate closes that here. +- `precompute`, `storage` and `query` do not depend on each other. They meet + in `common`'s traits: `precompute` writes through `ViewStore` and + `RawDataStore`, and `query` reads through them. +- Only `data-plane` knows every implementation. It builds the stores, injects + them into both engines, and owns `PlanInstaller` and `QueryDispatcher`. + +### Control plane → data plane + +The contract is the `InstallablePlan`, which is a `PhysicalASAPDAG` plus one +query text per DAG root. Today the control plane writes it as a JSON plan +file, and the data plane installs it at startup with `--plan`. This stays: + +```rust +// crates/data-plane +struct PlanInstaller { /* the two engines and the dispatcher */ } +impl PlanInstaller { + /// Validates the plan (supported operators, sources), then installs it + /// into the ingest engine, the query engine and the dispatcher, all or + /// nothing. On failure the current plan stays. + fn install(&self, plan: InstallablePlan) -> Result; +} +``` + The control plane has two callers of `install`: - the plan file at startup, as today; - later, the workload tracker (#935's `QueryWorkloadTracker`). It records the From 08b84c736bd18e430bd6500efac7fd67ffc784aa Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 10:24:32 +0000 Subject: [PATCH 06/18] docs(design): match the common crate's names (#878) --- docs/design/repo-layout.md | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 57ac9d2c7..554ced4df 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -98,7 +98,7 @@ adapters/* common precompute common, internal-metrics, asap-executor storage common, internal-metrics, asap-executor query common, internal-metrics, asap-executor -common ASAPPlanner's plan types only +common asap-planner and asap-types (plan types; asap-planner itself builds on the executor) internal-metrics nothing in this workspace (a leaf) data-plane every crate above (wiring only) ``` @@ -149,8 +149,8 @@ These are #935's interfaces, with the same names, so adapters move unchanged: ```rust // Requests and results (adapters ↔ dispatcher) -struct QueryRequest { language: QueryLanguage, query: String, eval: Eval } -enum Eval { Instant { time_ms: i64 }, Range { start_ms: i64, end_ms: i64, step_ms: i64 } } +struct QueryRequest { language: QueryLanguage, query: String, eval: QueryEval } +enum QueryEval { Instant { time_ms: i64 }, Range { start_ms: i64, end_ms: i64, step_ms: i64 } } enum QueryResult { Vector(..), Matrix(..), Scalar(..), Table { columns, rows } } // Ingest (ingest adapters → precompute) @@ -172,12 +172,15 @@ trait QueryEngine { // Stores (precompute writes, query reads) struct ViewId { plan: PlanId, node: PhysicalASAPNodeId } -struct ViewInstanceKey { view: ViewId, window: (i64, i64) } // (start, end] +struct ViewInstanceKey { view: ViewId, window_ms: (i64, i64) } // (start, end] trait ViewStore { put, get, instances, evict_before, timestamp_range_per_view } -trait RawDataStore { append, read, evict } +trait RawDataStore { append, read /* None if the range reaches evicted data */, evict } // Fallback (data-plane → query adapters) -trait FallbackClient { async fn execute(&self, req: &QueryRequest) -> Response; } +trait FallbackClient { + async fn execute(&self, req: &QueryRequest, headers: &[(String, String)]) + -> Result; // status, content type, body: no HTTP crates +} ``` `QueryDispatcher` (in `data-plane`) resolves each request against the @@ -190,7 +193,7 @@ installed plan's query texts, runs the query engine, and falls back on |---|---|---|---| | Query engine | ASAPPlanner's DataFusion query-time engine (ProjectASAP/ASAPPlanner#1468, a merged proposal, not yet code) | `asap-executor` | Keep `asap-executor` behind `QueryEngine`. Switching later changes only `crates/query` | | Ingest engine | a new push engine modeled on ASAPQuery's precompute engine | ingest shards + push precompute + the executor's ingestion (docs/design/parallel-precompute.md) | Keep ours behind `IngestEngine` | -| View state | opaque `Arc`, in memory only, durability deferred | hot tier of decoded windows plus compact on-disk segments | `ViewStore` adds an encode/decode pair for durable tiers (#935's I6 anticipates it) | +| View state | opaque `Arc`, in memory only, durability deferred | hot tier of decoded windows plus compact on-disk segments | `storage` keeps its own state codecs; an encode/decode hook joins `ViewStore` only when a second implementer needs it | | View id | `(PlanId, PhysicalASAPNodeId)` | directories per refresh group and retention | Key the store by `ViewId`. On-disk recovery across plans needs ProjectASAP/ASAPPlanner#1429, as in #935 | | Raw data | `RawDataStore` in memory | raw samples in `store.rs`, plus optional forward to a raw store | `RawDataStore` trait over both; the forward becomes a `FallbackClient` plus an ingest tee in `data-plane` | | Sketch kernels | move out of `asap-executor` into a shared ASAPPlanner crate (#935's decision 48) | through `asap-executor` and `asap_sketchlib` | No change until that crate exists | From 0ed2352b22aa4f9b281a161f032c69cd90380eac Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 12:30:14 +0000 Subject: [PATCH 07/18] docs(design): engines read storage directly; native answers; install once (#879, #880) --- docs/design/repo-layout.md | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 554ced4df..e1d74160e 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -95,9 +95,9 @@ crate depends on ------------- -------------------------------------------------- control-plane common, asap-planner adapters/* common -precompute common, internal-metrics, asap-executor +precompute common, storage, internal-metrics, asap-executor storage common, internal-metrics, asap-executor -query common, internal-metrics, asap-executor +query common, storage, internal-metrics, asap-executor common asap-planner and asap-types (plan types; asap-planner itself builds on the executor) internal-metrics nothing in this workspace (a leaf) data-plane every crate above (wiring only) @@ -109,9 +109,11 @@ data-plane every crate above (wiring only) - Adapters depend on `common` only: they never see an engine or a store. In ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); a separate `common` crate closes that here. -- `precompute`, `storage` and `query` do not depend on each other. They meet - in `common`'s traits: `precompute` writes through `ViewStore` and - `RawDataStore`, and `query` reads through them. +- `precompute` and `query` do not depend on each other. Both depend on + `storage`: they read its copy-on-write snapshot and the executor's record + batches, which the `ViewStore` and `RawDataStore` traits cannot express + without copying. The traits remain the boundary for other implementations; + `storage` provides adapters for them. - Only `data-plane` knows every implementation. It builds the stores, injects them into both engines, and owns `PlanInstaller` and `QueryDispatcher`. @@ -185,7 +187,11 @@ trait FallbackClient { `QueryDispatcher` (in `data-plane`) resolves each request against the installed plan's query texts, runs the query engine, and falls back on -`Unmatched`, `NotReady` or an engine error, as #935 specifies. +`Unmatched`, `NotReady` or an engine error, as #935 specifies. On the hot +path it calls the query engine's native answer type instead of +`QueryEngine::execute_batch`, so a query does not copy every series' +labels into a `QueryResult`. `PlanInstaller` installs once, as #935's I14 +does; a retryable install comes with tracker-delivered plans. ### Where the backend differs from #935 From ecebe097b9779dfcb5b03168eba7e5c4facaf612 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 15:15:24 +0000 Subject: [PATCH 08/18] docs(design): ingest adapters decode into caller types; native answers; verbatim forward Lists Answer and ResultSample in common's block, the dependency rule for ingest adapters (common, nothing, or the adapter whose wire format they extend), why ingest adapters do not build RawDataBatch, the verbatim forward and FallbackClient as the seam for the next fallback clients, and the VictoriaMetrics Remote Write and OTLP adapter crates. --- docs/design/repo-layout.md | 48 +++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index e1d74160e..8625f779d 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -94,7 +94,7 @@ ASAPQuery-backend/ crate depends on ------------- -------------------------------------------------- control-plane common, asap-planner -adapters/* common +adapters/* common, nothing, or the adapter whose wire format they extend precompute common, storage, internal-metrics, asap-executor storage common, internal-metrics, asap-executor query common, storage, internal-metrics, asap-executor @@ -106,9 +106,13 @@ data-plane every crate above (wiring only) - `common` depends on ASAPPlanner's plan types only (`InstallablePlan`, `PhysicalASAPDAG`, `QueryLanguage`, …), never on the executor's runtime. This is #935's decision 1. -- Adapters depend on `common` only: they never see an engine or a store. In - ASAPQuery, adapters depend on the whole engine crate (#935, "Not solved"); - a separate `common` crate closes that here. +- Adapters never see an engine or a store. In ASAPQuery, adapters depend + on the whole engine crate (#935, "Not solved"); a separate `common` crate + closes that here. The ingest adapters need not even `common`: each + decodes into the caller's types (below), so `prometheus-remote-write` and + `otlp` depend on nothing in the workspace, and + `victoriametrics-remote-write` only on `prometheus-remote-write`, whose + protobuf it reads (zstd-compressed instead of snappy). - `precompute` and `query` do not depend on each other. Both depend on `storage`: they read its copy-on-write snapshot and the executor's record batches, which the `ViewStore` and `RawDataStore` traits cannot express @@ -154,8 +158,10 @@ These are #935's interfaces, with the same names, so adapters move unchanged: struct QueryRequest { language: QueryLanguage, query: String, eval: QueryEval } enum QueryEval { Instant { time_ms: i64 }, Range { start_ms: i64, end_ms: i64, step_ms: i64 } } enum QueryResult { Vector(..), Matrix(..), Scalar(..), Table { columns, rows } } +type Answer = Arc>; // an instant answer as the query engine returns it natively +struct ResultSample { labels: Arc, value: f64 } // labels shared with the stored series: no copy -// Ingest (ingest adapters → precompute) +// Ingest (data-plane → precompute) enum RawDataBatch { TimeSeries { series: Vec<(LabelSet, Vec<(i64, f64)>)> } } trait IngestEngine { fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; @@ -188,10 +194,27 @@ trait FallbackClient { `QueryDispatcher` (in `data-plane`) resolves each request against the installed plan's query texts, runs the query engine, and falls back on `Unmatched`, `NotReady` or an engine error, as #935 specifies. On the hot -path it calls the query engine's native answer type instead of +path it calls the query engine's native answer type (`Answer`) instead of `QueryEngine::execute_batch`, so a query does not copy every series' -labels into a `QueryResult`. `PlanInstaller` installs once, as #935's I14 -does; a retryable install comes with tracker-delivered plans. +labels into a `QueryResult`. + +The same holds on the ingest side. An ingest adapter does not build a +`RawDataBatch`: its decoder takes the caller's series and sample types +(the Remote Write decoder's `SampleBuilder`, which +`victoriametrics-remote-write` reuses), so `data-plane` interns each new series into the store's series +table and a Remote Write request decodes straight into the ingest engine's +samples, with no label copied per sample. `otlp` returns each point's +labels as strings, which `data-plane` interns the same way; OTLP ingest is +not on the measured path, so it copies them. + +The Prometheus HTTP routes forward what the plan does not answer verbatim: +`PrometheusHttpFallback::forward` sends the request's method, path, query +string, headers and body unchanged, so the response is byte-identical to the +server's. `PrometheusHttpFallback` also implements `FallbackClient`, the seam +the ClickHouse and Elastic fallback clients (step 8) implement. + +`PlanInstaller` installs once, as #935's I14 does; a retryable install +comes with tracker-delivered plans. ### Where the backend differs from #935 @@ -216,7 +239,8 @@ does; a retryable install comes with tracker-delivered plans. | `data_plane/src/{store,window_cache,memory_budget,segment,persist,state_codec}.rs` | `crates/storage/` | | `data_plane/src/{query,result_cache}.rs` | `crates/query/` | | `data_plane/src/raw_forward.rs` | split: the tee into `crates/data-plane/`, the proxy into `crates/adapters/query/` | -| `data_plane/src/remote_write.rs` | `crates/adapters/ingest/prometheus-remote-write/` | +| `data_plane/src/remote_write.rs` | `crates/adapters/ingest/prometheus-remote-write/` (the series interning stays in `crates/data-plane/`) | +| ASAPQuery's VictoriaMetrics Remote Write and OTLP decoders | `crates/adapters/ingest/{victoriametrics-remote-write,otlp}/`, served on ASAPQuery's routes (`/api/v1/import`, `/v1/metrics`) | | `data_plane/src/prometheus.rs` | `crates/adapters/query/prometheus-http/` | | `data_plane/src/metrics.rs` | `crates/internal-metrics/` | | `data_plane/src/{lib,main}.rs` | `crates/data-plane/` | @@ -259,8 +283,10 @@ each reviewed on its own: 6. Move the existing Remote Write decoder and Prometheus HTTP API into `crates/adapters/`. 7. Bring over ASAPQuery's ingest adapters (VictoriaMetrics Remote Write, - OTLP), after ASAPQuery's adapter extraction (ProjectASAP/ASAPQuery#936) - and `QueryRequest` change (ProjectASAP/ASAPQuery#937) merge. + OTLP over HTTP) from its main branch, with names that follow its adapter + extraction (ProjectASAP/ASAPQuery#936); neither needs its `QueryRequest` + change (ProjectASAP/ASAPQuery#937). They feed the ingest engine as Remote + Write does. 8. Bring over ASAPQuery's query adapters and fallback clients (ClickHouse and Elastic HTTP). 9. `eval/` baselines (ClickHouse and others) and `deployment/` Dockerfiles. From db23e2916563765ef35e1afff7d924621f3ae3e5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 18:13:08 +0000 Subject: [PATCH 09/18] docs(design): query adapters reach their fallback through FallbackClient; SQL not planned yet (step 8) --- docs/design/repo-layout.md | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 8625f779d..14f18ace1 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -210,8 +210,17 @@ not on the measured path, so it copies them. The Prometheus HTTP routes forward what the plan does not answer verbatim: `PrometheusHttpFallback::forward` sends the request's method, path, query string, headers and body unchanged, so the response is byte-identical to the -server's. `PrometheusHttpFallback` also implements `FallbackClient`, the seam -the ClickHouse and Elastic fallback clients (step 8) implement. +server's. `PrometheusHttpFallback` also implements `FallbackClient`. + +The ClickHouse and Elasticsearch routes have no request to forward verbatim, +so they use the seam: each parses its request into a `QueryRequest`, calls +`QueryDispatcher::dispatch` (through `QueryEngine`, with `QueryResult`), and +sends what the plan does not answer to its protocol's `FallbackClient` +(`ClickHouseHttpFallback`, `ElasticHttpFallback`). Only a PromQL request can +be the plan's: the control plane plans PromQL workloads, and `storage` holds +time series, while ASAPPlanner lowers SQL to `Table` scans and has no +Elasticsearch frontend. So today every ClickHouse and Elasticsearch query is +forwarded, even one whose text equals a planned PromQL query. `PlanInstaller` installs once, as #935's I14 does; a retryable install comes with tracker-delivered plans. @@ -227,6 +236,7 @@ comes with tracker-delivered plans. | Raw data | `RawDataStore` in memory | raw samples in `store.rs`, plus optional forward to a raw store | `RawDataStore` trait over both; the forward becomes a `FallbackClient` plus an ingest tee in `data-plane` | | Sketch kernels | move out of `asap-executor` into a shared ASAPPlanner crate (#935's decision 48) | through `asap-executor` and `asap_sketchlib` | No change until that crate exists | | Adapters' dependency | the whole engine crate | `common` only | as in the dependency graph above | +| SQL and Query DSL queries | planned and answered from views | the control plane plans PromQL only; `storage` holds no tables | The ClickHouse and Elasticsearch routes forward every query; planned answers need table sources (ingest, `RawDataStore`, a SQL catalog for the control plane) | ## Where the current files go @@ -242,6 +252,7 @@ comes with tracker-delivered plans. | `data_plane/src/remote_write.rs` | `crates/adapters/ingest/prometheus-remote-write/` (the series interning stays in `crates/data-plane/`) | | ASAPQuery's VictoriaMetrics Remote Write and OTLP decoders | `crates/adapters/ingest/{victoriametrics-remote-write,otlp}/`, served on ASAPQuery's routes (`/api/v1/import`, `/v1/metrics`) | | `data_plane/src/prometheus.rs` | `crates/adapters/query/prometheus-http/` | +| ASAPQuery's ClickHouse and Elastic query adapters and fallback clients | `crates/adapters/query/{clickhouse-http,elastic-http}/`, served on ASAPQuery's routes (`/clickhouse/query`, `/_sql`, `/_search`) when their server is given | | `data_plane/src/metrics.rs` | `crates/internal-metrics/` | | `data_plane/src/{lib,main}.rs` | `crates/data-plane/` | | `data_plane/tests/` | the crate whose behavior each test checks; end-to-end tests in `crates/data-plane/tests/` | @@ -288,7 +299,10 @@ each reviewed on its own: change (ProjectASAP/ASAPQuery#937). They feed the ingest engine as Remote Write does. 8. Bring over ASAPQuery's query adapters and fallback clients (ClickHouse and - Elastic HTTP). + Elastic HTTP), named as in #936 (`ClickHouseHttpFallback`, + `ElasticHttpFallback`) and taking #937's `QueryRequest` (already in + `common`). Their routes go through `QueryDispatcher::dispatch` and reach + their fallback through `FallbackClient`. 9. `eval/` baselines (ClickHouse and others) and `deployment/` Dockerfiles. ## Decisions From 85023f9e44e9d29f5acca9141afa9600e5c52a24 Mon Sep 17 00:00:00 2001 From: zzylol Date: Thu, 26 Nov 2026 18:33:39 +0000 Subject: [PATCH 10/18] docs(design): eval/scripts, eval/baselines and deployment Dockerfile (step 9) --- docs/design/repo-layout.md | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 14f18ace1..d7c8e0d05 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -50,12 +50,13 @@ ASAPQuery-backend/ │ └── query/ # prometheus-http, clickhouse-http, elastic-http, fallback clients ├── benchmarks/ # the backend alone: micro (criterion) and system ingest/query ├── eval/ # cross-system experiments for the paper -│ ├── baselines// # install and configure each compared system +│ ├── baselines// # compared systems that run as their own service (compose files) │ ├── workloads/ -│ ├── harness/ -│ ├── scripts/ -│ └── results/ # .gitignore'd; never committed -├── deployment/ # Dockerfiles, compose files, monitoring (Grafana, Prometheus) +│ ├── harness/ # prepare, run the arms, report +│ ├── scripts/ # entry points: fetch pinned binaries, build, run, profile +│ ├── demo/ # the live Grafana demo +│ └── campaign/ # records of past multi-host runs +├── deployment/ # Dockerfile, compose file, monitoring/ (Grafana, Prometheus) ├── docs/ └── README.md ``` @@ -83,7 +84,8 @@ ASAPQuery-backend/ - `benchmarks/` measures the backend alone and guards against regressions. It runs often and needs only this repository. - `eval/` compares the backend with other systems for the paper. It installs - other systems, runs long and writes large results, which stay out of git. + other systems, runs long and writes large results, which stay out of git + (`eval/.gitignore`). Private workloads and anything derived from them never go into `eval/`. ## Boundaries @@ -257,11 +259,14 @@ comes with tracker-delivered plans. | `data_plane/src/{lib,main}.rs` | `crates/data-plane/` | | `data_plane/tests/` | the crate whose behavior each test checks; end-to-end tests in `crates/data-plane/tests/` | | `data_plane/examples/*_bench.rs` | `benchmarks/micro/` | -| `bench/demo/{campaign,harness,workloads,profile}` | `eval/` | +| `bench/demo/{campaign,harness,workloads}` | `eval/` | | `bench/demo/{live,run_live_demo.sh}` | `eval/demo/` | | `bench/demo/monitoring/` | `deployment/monitoring/` | | `scripts/ci/`, `scripts/sync-asapplanner-main.sh` | stay in `scripts/` | | `scripts/profile.sh`, `scripts/tiered_views_cgroup.sh` | `benchmarks/scripts/` | +| `bench/demo/{run_vm_demo,fetch_binaries,build}.sh`, `bench/demo/profile/profile_query_phase.sh` | `eval/scripts/` | +| ASAPQuery's ClickHouse experiment service | `eval/baselines/clickhouse/docker-compose.yml` (image pinned) | +| (new) a single-node Elasticsearch | `eval/baselines/elasticsearch/docker-compose.yml` (image pinned) | | `examples/*.json` | `docs/examples/` | `engine.rs` (about 2,700 lines) is the one file that splits rather than @@ -303,7 +308,17 @@ each reviewed on its own: `ElasticHttpFallback`) and taking #937's `QueryRequest` (already in `common`). Their routes go through `QueryDispatcher::dispatch` and reach their fallback through `FallbackClient`. -9. `eval/` baselines (ClickHouse and others) and `deployment/` Dockerfiles. +9. `eval/` baselines and `deployment/` Dockerfiles. The entry-point scripts + move to `eval/scripts/`. Systems the harness starts itself (Prometheus, + VictoriaMetrics) stay pinned in `eval/scripts/fetch_binaries.sh` and + configured in `eval/harness/run.py`; ClickHouse and Elasticsearch get a + pinned compose file each under `eval/baselines/`, as the servers the + backend's query routes forward to. `eval/README.md` lists every baseline + and what is not ported yet (harness arms for ClickHouse and Elasticsearch, + ASAPQuery's data loaders, sampling baselines). `deployment/Dockerfile` + builds `control_plane` and `data_plane` into one image (multi-stage, + pinned bases), and `deployment/docker-compose.yml` plans a workload and + serves the plan. ## Decisions From d0686e5d9b83e12c077ee82009d8d5786bc4e5ae Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 22:23:09 +0000 Subject: [PATCH 11/18] docs(design): sync with the stack after the whole-stack review - Status accepted; the two-crate table is the starting point. - Dependency graph as built: control-plane on asap-planner only, storage on asap_sketchlib and not common, data-plane's real list, control-plane as a dev-dependency. - No engine or store traits: each has one implementation, and a trait is added with its second (decision 4). common lists what it holds: QueryResult::Table(Table), the re-exports, MAX_TIME_MS. - Install order: query, ingest, dispatcher; queries see the plan only after every engine accepts it. - Routes, including the forward-mode-only and the forward-mode-off ones; /metrics is rendered in data-plane, so internal-metrics stays a leaf. - Tests that start the engine stay in data-plane; eight micro benchmarks moved and the load generator stayed; benchmarks/scripts listed. - persist-N and view-cache code in storage, started by precompute. - Folders use hyphens, packages underscores. - Steps 2-6 keep behavior; steps 7-9 only add. --- docs/design/repo-layout.md | 193 +++++++++++++++++++++++-------------- 1 file changed, 119 insertions(+), 74 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index d7c8e0d05..ec8bea61c 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -1,6 +1,7 @@ # Design: repository layout and engine boundaries -Status: proposal, for review. Decisions are recorded at the end. +Status: accepted; the layout below is in place. Decisions are recorded at +the end. ## Audience and context @@ -14,21 +15,22 @@ This document is for developers of the backend. It decides two things: (ProjectASAP/ASAPQuery#935), so that the protocol adapters ASAPQuery has today (Prometheus, VictoriaMetrics and OTLP ingest; Prometheus, ClickHouse and Elastic query endpoints and fallback clients) can move here against - the same traits. + the same types. -Today the workspace has two crates: +The starting point: before this work the workspace had two crates. | Crate | Lines | Holds | |---|---|---| | `control_plane` | about 200 | `plan_installable` on a `PlanningWorkload`, writes the plan file | | `data_plane` | about 17,000 | everything else: Remote Write decoding, ingest shards, push precompute, the engine around `asap-executor`, the view store (hot tier, segments, persistence, codecs), queries, result cache, raw forward, the Prometheus HTTP API, `/metrics`, the binary | -Measurement code is in three places: `bench/demo` (the comparison against -VictoriaMetrics, the live demo, Grafana monitoring), `data_plane/examples/*_bench.rs` -(nine micro benchmarks) and `scripts/`. +Measurement code was in three places: `bench/demo` (the comparison against +VictoriaMetrics, the live demo, Grafana monitoring), `data_plane/examples/` +(eight micro benchmarks and the `remote_write_load` load generator) and +`scripts/`. -One crate for the whole data plane means nothing enforces which part may use -which. For example, the query code can reach into the store's internals. A +One crate for the whole data plane meant nothing enforced which part may use +which. For example, the query code could reach into the store's internals. A crate per part makes the dependency direction a compile-time rule, and it speeds up incremental builds. @@ -38,17 +40,17 @@ speeds up incremental builds. ASAPQuery-backend/ ├── Cargo.toml # workspace ├── crates/ -│ ├── common/ # engine boundary types and traits (see Boundaries) +│ ├── common/ # boundary types and the FallbackClient trait (see Boundaries) │ ├── control-plane/ # workload → asap-planner → InstallablePlan -│ ├── precompute/ # IngestEngine: ingest shards, push pipelines, asap-executor ingestion -│ ├── storage/ # ViewStore + RawDataStore: hot tier, segments, persistence, codecs -│ ├── query/ # QueryEngine: planned queries over the stores, result cache -│ ├── internal-metrics/ # the backend's own measurements, exported on /metrics -│ ├── data-plane/ # the binary: CLI, PlanInstaller, QueryDispatcher, HTTP routes, wiring +│ ├── precompute/ # the ingest engine: ingest shards, push pipelines, asap-executor ingestion +│ ├── storage/ # view and raw-data stores: hot tier, segments, persistence, codecs +│ ├── query/ # the query engine: planned queries over the stores, result cache +│ ├── internal-metrics/ # the backend's own measurements (data-plane renders /metrics) +│ ├── data-plane/ # the binary: CLI, PlanInstaller, QueryDispatcher, HTTP routes, /metrics, wiring │ └── adapters/ │ ├── ingest/ # prometheus-remote-write, victoriametrics-remote-write, otlp │ └── query/ # prometheus-http, clickhouse-http, elastic-http, fallback clients -├── benchmarks/ # the backend alone: micro (criterion) and system ingest/query +├── benchmarks/ # the backend alone: micro/ (benchmark binaries), scripts/ (profiling) ├── eval/ # cross-system experiments for the paper │ ├── baselines// # compared systems that run as their own service (compose files) │ ├── workloads/ @@ -63,6 +65,9 @@ ASAPQuery-backend/ ### Names +Folders use hyphens (`crates/control-plane`); package names use underscores +(`control_plane`), as Rust identifiers need. + - **`control-plane`, not `planner`.** Planning is ASAPPlanner's (`asap-planner`, a pinned git dependency). This crate only builds the workload and deployment inputs, calls `plan_installable` and hands the @@ -95,14 +100,14 @@ ASAPQuery-backend/ ```text crate depends on ------------- -------------------------------------------------- -control-plane common, asap-planner +control-plane asap-planner adapters/* common, nothing, or the adapter whose wire format they extend precompute common, storage, internal-metrics, asap-executor -storage common, internal-metrics, asap-executor +storage internal-metrics, asap-executor, asap_sketchlib query common, storage, internal-metrics, asap-executor common asap-planner and asap-types (plan types; asap-planner itself builds on the executor) internal-metrics nothing in this workspace (a leaf) -data-plane every crate above (wiring only) +data-plane common, precompute, storage, query, internal-metrics, every adapter (wiring only) ``` - `common` depends on ASAPPlanner's plan types only (`InstallablePlan`, @@ -115,13 +120,15 @@ data-plane every crate above (wiring only) `otlp` depend on nothing in the workspace, and `victoriametrics-remote-write` only on `prometheus-remote-write`, whose protobuf it reads (zstd-compressed instead of snappy). +- `control-plane` is a dev-dependency of `data-plane`, `precompute` and + `query` only: their tests plan workloads with it. - `precompute` and `query` do not depend on each other. Both depend on - `storage`: they read its copy-on-write snapshot and the executor's record - batches, which the `ViewStore` and `RawDataStore` traits cannot express - without copying. The traits remain the boundary for other implementations; - `storage` provides adapters for them. -- Only `data-plane` knows every implementation. It builds the stores, injects - them into both engines, and owns `PlanInstaller` and `QueryDispatcher`. + `storage` directly: they read its copy-on-write snapshot and the + executor's record batches. There is no store trait, and no engine trait: + each has one implementation, and a trait is added with its second + implementation (decision 4). +- Only `data-plane` knows every crate. It builds the stores, hands them to + both engines, and owns `PlanInstaller` and `QueryDispatcher`. ### Control plane → data plane @@ -133,9 +140,9 @@ file, and the data plane installs it at startup with `--plan`. This stays: // crates/data-plane struct PlanInstaller { /* the two engines and the dispatcher */ } impl PlanInstaller { - /// Validates the plan (supported operators, sources), then installs it - /// into the ingest engine, the query engine and the dispatcher, all or - /// nothing. On failure the current plan stays. + /// Validates the plan, then installs it into the query engine, the + /// ingest engine and the dispatcher, in that order. Queries see the plan + /// only after every engine accepts it; on failure the current plan stays. fn install(&self, plan: InstallablePlan) -> Result; } ``` @@ -153,55 +160,68 @@ They are not part of the data plane's interface. ### Data plane parts (`crates/common`) -These are #935's interfaces, with the same names, so adapters move unchanged: +These are #935's types, with the same names, so adapters move unchanged: ```rust +// Plans (installer → engines) +struct PlanId(u64); +struct InstalledPlan { id: PlanId, plan: InstallablePlan } +struct InstallError { message: String } + // Requests and results (adapters ↔ dispatcher) struct QueryRequest { language: QueryLanguage, query: String, eval: QueryEval } enum QueryEval { Instant { time_ms: i64 }, Range { start_ms: i64, end_ms: i64, step_ms: i64 } } -enum QueryResult { Vector(..), Matrix(..), Scalar(..), Table { columns, rows } } +enum QueryResult { Vector(InstantVector), Matrix(RangeVector), Scalar(Sample), Table(Table) } type Answer = Arc>; // an instant answer as the query engine returns it natively struct ResultSample { labels: Arc, value: f64 } // labels shared with the stored series: no copy -// Ingest (data-plane → precompute) -enum RawDataBatch { TimeSeries { series: Vec<(LabelSet, Vec<(i64, f64)>)> } } -trait IngestEngine { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; - async fn ingest(&self, batch: RawDataBatch) -> Result<(), IngestError>; // waits under backpressure - fn shutdown(&self); -} - -// Query (dispatcher → query) +// Query (dispatcher → query engine) enum AnswerSource { Planned { plan: PlanId, root: PhysicalASAPNodeId } } enum EngineQueryResult { Ready { result: QueryResult }, NotReady } -trait QueryEngine { - fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; - async fn execute_batch(&self, queries: &[(AnswerSource, QueryRequest)]) - -> Vec>; -} - -// Stores (precompute writes, query reads) -struct ViewId { plan: PlanId, node: PhysicalASAPNodeId } -struct ViewInstanceKey { view: ViewId, window_ms: (i64, i64) } // (start, end] -trait ViewStore { put, get, instances, evict_before, timestamp_range_per_view } -trait RawDataStore { append, read /* None if the range reaches evicted data */, evict } +struct QueryEngineError { message: String } // Fallback (data-plane → query adapters) trait FallbackClient { async fn execute(&self, req: &QueryRequest, headers: &[(String, String)]) -> Result; // status, content type, body: no HTTP crates } + +// Re-exported, so callers need no direct Planner dependency +type LabelSet = BTreeMap; +const MAX_TIME_MS: i64; // the largest time, either side of the epoch, the data plane takes +use asap_planner::{InstallablePlan, PhysicalASAPNodeId}; +use asap_types::{QueryLanguage, SqlDialect}; +``` + +The engines are concrete types with inherent methods, called by +`data-plane`: + +```rust +// crates/precompute +impl PrecomputeEngine { fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; } +// crates/query +impl ExecutorQueryEngine { + fn install(&self, plan: InstalledPlan) -> Result<(), InstallError>; + async fn execute(&self, source: &AnswerSource, request: &QueryRequest) + -> Result; +} ``` +#935 also has `IngestEngine`, `QueryEngine`, `ViewStore` and +`RawDataStore` traits. The backend has one implementation of each, so it +has no trait; each is added with its second implementation (decision 4). +Ingest routes hand samples to the precompute engine directly, and the +engines read and write `storage`'s stores directly. + `QueryDispatcher` (in `data-plane`) resolves each request against the installed plan's query texts, runs the query engine, and falls back on `Unmatched`, `NotReady` or an engine error, as #935 specifies. On the hot path it calls the query engine's native answer type (`Answer`) instead of -`QueryEngine::execute_batch`, so a query does not copy every series' +`ExecutorQueryEngine::execute`, so a query does not copy every series' labels into a `QueryResult`. -The same holds on the ingest side. An ingest adapter does not build a -`RawDataBatch`: its decoder takes the caller's series and sample types +The same holds on the ingest side. An ingest adapter builds no boundary +batch type: its decoder takes the caller's series and sample types (the Remote Write decoder's `SampleBuilder`, which `victoriametrics-remote-write` reuses), so `data-plane` interns each new series into the store's series table and a Remote Write request decodes straight into the ingest engine's @@ -216,7 +236,8 @@ server's. `PrometheusHttpFallback` also implements `FallbackClient`. The ClickHouse and Elasticsearch routes have no request to forward verbatim, so they use the seam: each parses its request into a `QueryRequest`, calls -`QueryDispatcher::dispatch` (through `QueryEngine`, with `QueryResult`), and +`QueryDispatcher::dispatch` (through `ExecutorQueryEngine::execute`, with +`QueryResult`), and sends what the plan does not answer to its protocol's `FallbackClient` (`ClickHouseHttpFallback`, `ElasticHttpFallback`). Only a PromQL request can be the plan's: the control plane plans PromQL workloads, and `storage` holds @@ -224,21 +245,39 @@ time series, while ASAPPlanner lowers SQL to `Table` scans and has no Elasticsearch frontend. So today every ClickHouse and Elasticsearch query is forwarded, even one whose text equals a planned PromQL query. -`PlanInstaller` installs once, as #935's I14 does; a retryable install -comes with tracker-delivered plans. +`PlanInstaller` installs once, as #935's I14 does: the engines refuse a +second plan. A retryable install comes with tracker-delivered plans. + +### Routes + +`data-plane` serves: + +- always: `POST /api/v1/write` (Remote Write), `/api/v1/query` and + `/api/v1/query_range`, `/api/v1/status/asap` (the installed plan and + ingestion counters), `/metrics`, `POST /api/v1/precompute/watermark` (an + event-time barrier) and `/-/ready`; +- with forward mode off: `POST /api/v1/import` (VictoriaMetrics Remote + Write) and `POST /v1/metrics` (OTLP over HTTP). Forward mode delivers + only Remote Write bodies to the raw store, which would miss their samples; +- with forward mode on: every other path, proxied to the raw store; +- with `--clickhouse-url`: `/clickhouse/query`; with `--elastic-url`: + `POST /_sql` and `/_search`. + +`/metrics` is rendered in `data-plane` (`metrics_endpoint.rs`) from the +measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. ### Where the backend differs from #935 | Topic | #935 (ASAPQuery) | Backend | Proposal | |---|---|---|---| -| Query engine | ASAPPlanner's DataFusion query-time engine (ProjectASAP/ASAPPlanner#1468, a merged proposal, not yet code) | `asap-executor` | Keep `asap-executor` behind `QueryEngine`. Switching later changes only `crates/query` | -| Ingest engine | a new push engine modeled on ASAPQuery's precompute engine | ingest shards + push precompute + the executor's ingestion (docs/design/parallel-precompute.md) | Keep ours behind `IngestEngine` | -| View state | opaque `Arc`, in memory only, durability deferred | hot tier of decoded windows plus compact on-disk segments | `storage` keeps its own state codecs; an encode/decode hook joins `ViewStore` only when a second implementer needs it | -| View id | `(PlanId, PhysicalASAPNodeId)` | directories per refresh group and retention | Key the store by `ViewId`. On-disk recovery across plans needs ProjectASAP/ASAPPlanner#1429, as in #935 | -| Raw data | `RawDataStore` in memory | raw samples in `store.rs`, plus optional forward to a raw store | `RawDataStore` trait over both; the forward becomes a `FallbackClient` plus an ingest tee in `data-plane` | +| Query engine | ASAPPlanner's DataFusion query-time engine (ProjectASAP/ASAPPlanner#1468, a merged proposal, not yet code) | `asap-executor` | Keep `asap-executor` inside `crates/query`'s `ExecutorQueryEngine`. Switching later changes only `crates/query`; a `QueryEngine` trait comes if both engines are kept | +| Ingest engine | a new push engine modeled on ASAPQuery's precompute engine | ingest shards + push precompute + the executor's ingestion (docs/design/parallel-precompute.md) | Keep ours, `crates/precompute`'s `PrecomputeEngine` | +| View state | opaque `Arc` behind a `ViewStore` trait, in memory only, durability deferred | hot tier of decoded windows plus compact on-disk segments | `storage` keeps its own state codecs; no `ViewStore` trait until a second store exists | +| View id | `(PlanId, PhysicalASAPNodeId)` | the plan file's hash, the refresh group and the node id | Keep it; a `PlanId` in the key comes with a second installed plan. On-disk recovery across plans needs ProjectASAP/ASAPPlanner#1429, as in #935 | +| Raw data | `RawDataStore` in memory | raw samples in `storage`'s store, plus optional forward to a raw store | No `RawDataStore` trait; the forward is `PrometheusHttpFallback::forward` plus an ingest tee in `data-plane` | | Sketch kernels | move out of `asap-executor` into a shared ASAPPlanner crate (#935's decision 48) | through `asap-executor` and `asap_sketchlib` | No change until that crate exists | | Adapters' dependency | the whole engine crate | `common` only | as in the dependency graph above | -| SQL and Query DSL queries | planned and answered from views | the control plane plans PromQL only; `storage` holds no tables | The ClickHouse and Elasticsearch routes forward every query; planned answers need table sources (ingest, `RawDataStore`, a SQL catalog for the control plane) | +| SQL and Query DSL queries | planned and answered from views | the control plane plans PromQL only; `storage` holds no tables | The ClickHouse and Elasticsearch routes forward every query; planned answers need table sources (ingest, a raw table store, a SQL catalog for the control plane) | ## Where the current files go @@ -252,13 +291,13 @@ comes with tracker-delivered plans. | `data_plane/src/{query,result_cache}.rs` | `crates/query/` | | `data_plane/src/raw_forward.rs` | split: the tee into `crates/data-plane/`, the proxy into `crates/adapters/query/` | | `data_plane/src/remote_write.rs` | `crates/adapters/ingest/prometheus-remote-write/` (the series interning stays in `crates/data-plane/`) | -| ASAPQuery's VictoriaMetrics Remote Write and OTLP decoders | `crates/adapters/ingest/{victoriametrics-remote-write,otlp}/`, served on ASAPQuery's routes (`/api/v1/import`, `/v1/metrics`) | +| ASAPQuery's VictoriaMetrics Remote Write and OTLP decoders | `crates/adapters/ingest/{victoriametrics-remote-write,otlp}/`, served on ASAPQuery's routes (`/api/v1/import`, `/v1/metrics`) when forward mode is off | | `data_plane/src/prometheus.rs` | `crates/adapters/query/prometheus-http/` | | ASAPQuery's ClickHouse and Elastic query adapters and fallback clients | `crates/adapters/query/{clickhouse-http,elastic-http}/`, served on ASAPQuery's routes (`/clickhouse/query`, `/_sql`, `/_search`) when their server is given | -| `data_plane/src/metrics.rs` | `crates/internal-metrics/` | +| `data_plane/src/metrics.rs` | `crates/internal-metrics/` (the `/metrics` renderer, `metrics_endpoint.rs`, stays in `crates/data-plane/`) | | `data_plane/src/{lib,main}.rs` | `crates/data-plane/` | -| `data_plane/tests/` | the crate whose behavior each test checks; end-to-end tests in `crates/data-plane/tests/` | -| `data_plane/examples/*_bench.rs` | `benchmarks/micro/` | +| `data_plane/tests/` | `crates/data-plane/tests/`: each starts the engine or the HTTP routes. Unit tests move with their code, and tests of one crate alone go to that crate's `tests/` (`crates/storage/tests/`) | +| `data_plane/examples/*_bench.rs` | `benchmarks/micro/`; the load generator `remote_write_load.rs` stays in `crates/data-plane/examples/` | | `bench/demo/{campaign,harness,workloads}` | `eval/` | | `bench/demo/{live,run_live_demo.sh}` | `eval/demo/` | | `bench/demo/monitoring/` | `deployment/monitoring/` | @@ -276,14 +315,15 @@ executes it: | Part of `engine.rs` | New home | |---|---| | ingest shards, the `ingest` coordinator, the precompute pool and committer | `crates/precompute/` | -| `persist-N` threads and the view-cache monitor | `crates/storage/` | +| `persist-N` threads and the view-cache monitor | `crates/storage/` (the code; the precompute engine's install starts them) | | `query-N` workers | `crates/query/` | | `EngineHandle`, `EngineOptions`, install | `crates/data-plane/` | ## Migration order -Every step keeps behavior and all tests passing. The steps are separate PRs, -each reviewed on its own: +Steps 2–6 keep behavior and all tests passing; steps 7–9 only add (routes, +flags, an image) and keep every existing behavior. The steps are separate +PRs, each reviewed on its own: 1. This document. 2. Folder moves only: `control_plane` → `crates/control-plane`, `data_plane` → @@ -291,11 +331,11 @@ each reviewed on its own: `deployment/monitoring`, micro benchmarks → `benchmarks/micro`. Paths in scripts, CI and docs are updated. 3. Split leaf crates out of `data-plane`: `internal-metrics`, then `storage`. -4. `common` with the boundary types and traits, no implementations. -5. Split `precompute` and `query` out of `data-plane`. `storage` implements - `ViewStore` and `RawDataStore`, `precompute` implements `IngestEngine`, - and `query` implements `QueryEngine`. `PlanInstaller` and `QueryDispatcher` - are added in `data-plane`. +4. `common` with the boundary types and the `FallbackClient` trait, no + implementations. +5. Split `precompute` and `query` out of `data-plane`, with + `PrecomputeEngine` and `ExecutorQueryEngine` taking `InstalledPlan`. + `PlanInstaller` and `QueryDispatcher` are added in `data-plane`. 6. Move the existing Remote Write decoder and Prometheus HTTP API into `crates/adapters/`. 7. Bring over ASAPQuery's ingest adapters (VictoriaMetrics Remote Write, @@ -323,9 +363,14 @@ each reviewed on its own: ## Decisions 1. **`common` lives in this repository**, in `crates/common`. This work - changes neither ASAPPlanner nor ASAPQuery. The traits keep #935's names and + changes neither ASAPPlanner nor ASAPQuery. The types keep #935's names and shapes, so ASAPQuery's adapters can move here without changes. 2. **The workload tracker lives in `control-plane`.** It produces a planning input. The query adapters only report each query they receive to it. 3. **No rename for now.** The binary keeps the `data-plane` name; a product name can be set later with `[[bin]] name`. +4. **A trait is added with its second implementation.** `FallbackClient` has + three (Prometheus, ClickHouse, Elasticsearch), called through `dyn` per + forwarded request. The engines and stores have one each, so they are + concrete types; #935's `IngestEngine`, `QueryEngine`, `ViewStore` and + `RawDataStore` come back when a second engine or store does. From 30a464dd4412fa1c8f9555a33e4d54b1097ab12b Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 04:00:29 +0000 Subject: [PATCH 12/18] docs(design): fold the still-valid backend-on-planner content into the layout doc Adds the Planner/backend responsibility table (current InstallablePlan, materialized_views, raw_data_retention, DataStore), the ingestion rules (watermark, future and late samples, first window, 503 back-pressure, event-time barrier), query forwarding and --no-forward, the rejected alternatives, and the idle-stream open question, each checked against the code. --- docs/design/repo-layout.md | 108 +++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index ec8bea61c..882ccafae 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -95,6 +95,37 @@ Folders use hyphens (`crates/control-plane`); package names use underscores ## Boundaries +### Planner and backend responsibilities + +ASAPPlanner decides what to compute, whether at ingestion or at query +time, and how long to keep it. The backend executes that plan on incoming +samples and query requests, and never changes it. + +| Concern | ASAPPlanner | Backend | +|---|---|---| +| Plan search | Stages 1–3 select one `PhysicalASAPDAG` against the cost and accuracy targets | None | +| Plan contract | `InstallablePlan { wire_version, dag, query_texts }`; the runtime reads `materialized_views()`, `ingestion_refresh_groups()` and `raw_data_retention()` from it | `control-plane` writes it; `PlanInstaller` validates and installs it | +| Operators | `asap-executor`: `compile`, `instantiate`, and the `DataStore` trait a run reads through | `precompute` runs a refresh group's ingestion run per window; `query` runs a root per evaluation; `storage`'s `RunStore` implements `DataStore` | +| Views | Each `MaterializedView`: its node, timing, lifetime, retention, `plan_id` and view state key | `storage`: hot tier, segments, persistence, eviction by retention | +| Raw samples | Which metrics a `Scan` reads and how long a query-time `Scan` looks back (`raw_data_retention()`) | `storage` keeps them by pane while a window still to close or a query-time `Scan` needs them; optional forward to a raw store | +| Ingestion, watermark, window close, late data | None | `precompute` (Ingestion rules, below) | +| Threads, scheduling, evaluation times | None | `precompute`'s shards, pool and committer; `query`'s workers | +| Queries the plan does not answer | None | `QueryDispatcher`: forward or refuse (Query forwarding, below) | +| Deployment inputs | Consumes `DeploymentCapabilities` and `CostInputs` | `control-plane` supplies them (`backend_capabilities()`) | + +Rules: + +- The Planner never sees samples, stores, clocks or services; the backend + never changes a plan. +- Every planned query runs the installed DAG through `asap-executor`, for + every query shape; each operator has one implementation, the executor's, + which the Planner's tests use too. +- A plan the backend cannot execute fails at install, before any part of + it runs: `PlanInstaller` validates it and installs it into the query + engine, then the ingest engine, and the first refusal stops it (a query + root the query engine cannot compile is refused only under + `--no-forward`; otherwise that query is forwarded). + ### Dependency graph ```text @@ -266,6 +297,54 @@ second plan. A retryable install comes with tracker-delivered plans. `/metrics` is rendered in `data-plane` (`metrics_endpoint.rs`) from the measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. +### Ingestion rules + +- **Watermark.** One, kept by the ingest coordinator: the newest sample of + any shard, capped at the wall clock, less `--allowed-lateness-ms` + (default 15 s), or a producer's barrier when that is later. It moves only + behind a flush that every shard has run, and a shard with nothing queued + answers the flush at once, so an idle shard does not hold it. A refresh + group's window `(e − W, e]` closes when the watermark reaches `e`; a + window with no sample is refreshed too, and stored empty. +- **Future samples.** A sample more than `--max-future-ms` (default 5 min) + ahead of the wall clock is dropped and counted + (`samples_dropped_future`). +- **Late samples.** A sample older than every window still to close and + every query-time `Scan`'s look-back is dropped (`samples_dropped_late`). + One a query-time `Scan` still reads is stored as raw data, but in no + view, if every window holding it has closed (`samples_late_for_views`). + A committed window is never revised. +- **First window.** The first window each refresh group sees may have + started before the data plane did, so it is skipped + (`windows_skipped_first`), unless `--stream-start-ms` says where the + producers' stream starts. +- **Back-pressure.** When more than `--max-queued-samples` (default + 2,000,000) samples wait for the engine, Remote Write and OTLP get 503 + (`IngestError::Busy`), which senders retry; a stopped engine gives 500. +- **Event-time barrier.** `POST /api/v1/precompute/watermark?time_ms=T` + states that every sample at or before `T` was written. Once every write + acknowledged before it has run, every window with `end <= T` closes, so + the last window of a series that stopped sending is refreshed. `T` is + capped at the wall clock; a repeated or lower `T` does nothing; input + stays open; a later sample for a closed window is late. With several + producers, send it only after all of them have written through `T`. + +### Query forwarding + +`QueryDispatcher` resolves a request against the plan's query texts and +runs the query engine. What the plan does not answer: + +- **Forwarded** (default): to `--prometheus-url`, or to the raw store in + forward mode (`--raw-store-url`). The response carries + `x-asap-execution: forwarded`; a planned query that was `NotReady` or hit + an engine error also carries the reason in `x-asap-forward-reason`. An + unmatched query has no reason. +- **Refused** (`--no-forward`): every answer must come from the plan. A plan + with a query the query engine cannot run is refused at install, and an + unanswered query returns 422 (`errorType: execution`) with the reason and + `x-asap-execution: refused`. `--no-forward` cannot be combined with + `--raw-store-url`, `--clickhouse-url` or `--elastic-url`. + ### Where the backend differs from #935 | Topic | #935 (ASAPQuery) | Backend | Proposal | @@ -374,3 +453,32 @@ PRs, each reviewed on its own: forwarded request. The engines and stores have one each, so they are concrete types; #935's `IngestEngine`, `QueryEngine`, `ViewStore` and `RawDataStore` come back when a second engine or store does. + +## Alternatives considered + +- **Shape-matched fast paths** (hand-written code for common query shapes + beside the DAG). Rejected: every shape would need a second + implementation kept in step with the DAG, and they cannot cover arbitrary + roots. The data plane always runs the DAG; speed comes from the + executor's columnar operators. +- **View identity, layout and eviction in ASAPPlanner.** Rejected: they are + deployment concerns. The Planner states each view's computation, timing + and retention; `storage` decides how to keep it. +- **Row-at-a-time execution.** Replaced: per-row values, clones, grouping + keys and memory accounting dominated CPU, while the sketch kernels were a + small part. The executor works on Arrow column batches with state + columns. +- **The runtime deriving storage needs from the DAG.** Replaced: the plan's + `materialized_views()` and `raw_data_retention()` give each view's + retention (range spans included) and each raw metric's look-back. +- **Storing only raw-data panes.** Rejected: the plan also stores rollups + and multi-level windows; keeping only panes would recompute them at every + evaluation or refuse them at install. + +## Open questions + +- **Idle stream.** An idle shard no longer holds the watermark, but when no + producer sends anything, the watermark stops and the last windows stay + open until a sample or a barrier arrives. Whether the data plane should + also close windows by elapsed wall-clock time, without a barrier, is + open. From 7ed5f3b027657344e1ec4b9267888c4c804fbf61 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 04:19:56 +0000 Subject: [PATCH 13/18] docs(design): close an idle stream's last windows by wall-clock time The open idle-stream question becomes decision 5: an idle watermark that advances the newest sample time by the wall-clock time since a sample last arrived, less the allowed lateness and a 1 s grace, so the last windows of a stopped stream close and a lagging stream closes nothing early. --- docs/design/repo-layout.md | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 882ccafae..39da5ea80 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -301,7 +301,8 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. - **Watermark.** One, kept by the ingest coordinator: the newest sample of any shard, capped at the wall clock, less `--allowed-lateness-ms` - (default 15 s), or a producer's barrier when that is later. It moves only + (default 15 s), a producer's barrier, or the idle watermark (decision 5), + whichever is latest; it never goes back. It moves only behind a flush that every shard has run, and a shard with nothing queued answers the flush at once, so an idle shard does not hold it. A refresh group's window `(e − W, e]` closes when the watermark reaches `e`; a @@ -453,6 +454,32 @@ PRs, each reviewed on its own: forwarded request. The engines and stores have one each, so they are concrete types; #935's `IngestEngine`, `QueryEngine`, `ViewStore` and `RawDataStore` come back when a second engine or store does. +5. **An idle stream's last windows close by wall-clock time.** While no + sample arrives, event time is taken to advance with the wall clock. The + coordinator keeps an idle watermark `t + (now − a) − L − G`: `t` the + newest sample time (capped at the wall clock), `a` the wall-clock time a + sample last arrived, `L` `--allowed-lateness-ms`, `G` a 1 s grace. A + window `(e − W, e]` so closes once no sample has come for + `e − t + L + G`, at most `W + L + G`. Counting from `t`, not from `now`, + a stream whose event time lags the wall clock (a replay or backfill) + closes no window earlier than if it kept sending. + - One idle watermark over all shards, kept by the coordinator; a sample + on any shard resets `a`. + - The coordinator checks it every tick (100 ms). When it would close a + window, the coordinator first flushes every shard, as for a barrier, + and takes `now` and `a` at that flush, so samples still queued reset + `a` and close nothing. + - The barrier is unchanged; the latest of the three closes. + - A sample for a window closed this way is late, dropped and counted as + any other (`samples_dropped_late`, `samples_late_for_views`). + - Windows closed ahead of the samples and barriers are counted + (`asap_windows_closed_by_wall_clock_total`). + - Nothing closes before the first sample, and after a restart nothing + closes by wall clock until a sample arrives; `--stream-start-ms` only + makes the first window complete, as before. + - A stream whose event time runs slower than the wall clock with gaps + longer than `L + G` breaks the assumption; it needs a larger + `--allowed-lateness-ms`. ## Alternatives considered @@ -474,11 +501,3 @@ PRs, each reviewed on its own: - **Storing only raw-data panes.** Rejected: the plan also stores rollups and multi-level windows; keeping only panes would recompute them at every evaluation or refuse them at install. - -## Open questions - -- **Idle stream.** An idle shard no longer holds the watermark, but when no - producer sends anything, the watermark stops and the last windows stay - open until a sample or a barrier arrives. Whether the data plane should - also close windows by elapsed wall-clock time, without a barrier, is - open. From 8d2121bacf473d86054ccf1a25753e3500a1a1da Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 05:50:59 +0000 Subject: [PATCH 14/18] docs(design): idle watermark: which samples reset it, and what t is capped at --- docs/design/repo-layout.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 39da5ea80..6ed2745bf 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -457,14 +457,15 @@ PRs, each reviewed on its own: 5. **An idle stream's last windows close by wall-clock time.** While no sample arrives, event time is taken to advance with the wall clock. The coordinator keeps an idle watermark `t + (now − a) − L − G`: `t` the - newest sample time (capped at the wall clock), `a` the wall-clock time a - sample last arrived, `L` `--allowed-lateness-ms`, `G` a 1 s grace. A + newest sample time (capped at `a`), `a` the wall-clock time of the flush + that last ran a sample, `L` `--allowed-lateness-ms`, `G` a 1 s grace. A window `(e − W, e]` so closes once no sample has come for `e − t + L + G`, at most `W + L + G`. Counting from `t`, not from `now`, a stream whose event time lags the wall clock (a replay or backfill) closes no window earlier than if it kept sending. - - One idle watermark over all shards, kept by the coordinator; a sample - on any shard resets `a`. + - One idle watermark over all shards, kept by the coordinator. A sample + ingestion keeps, on any shard, resets `a`; unrouted, late and future + samples do not. - The coordinator checks it every tick (100 ms). When it would close a window, the coordinator first flushes every shard, as for a barrier, and takes `now` and `a` at that flush, so samples still queued reset From b5d77528fd71fc34fa35c4907f346963dedbed77 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 14:04:42 +0000 Subject: [PATCH 15/18] docs(design): the idle time is measured on the monotonic clock --- docs/design/repo-layout.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 6ed2745bf..33aaa5cae 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -458,7 +458,9 @@ PRs, each reviewed on its own: sample arrives, event time is taken to advance with the wall clock. The coordinator keeps an idle watermark `t + (now − a) − L − G`: `t` the newest sample time (capped at `a`), `a` the wall-clock time of the flush - that last ran a sample, `L` `--allowed-lateness-ms`, `G` a 1 s grace. A + that last ran a sample, `L` `--allowed-lateness-ms`, `G` a 1 s grace; + `now − a` is measured on the monotonic clock (`Instant`), so a step of + the system clock does not move it. A window `(e − W, e]` so closes once no sample has come for `e − t + L + G`, at most `W + L + G`. Counting from `t`, not from `now`, a stream whose event time lags the wall clock (a replay or backfill) From da3ce9c2505b5fc20ee6c35b47b13052fe54a8d8 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:21:28 +0000 Subject: [PATCH 16/18] docs(design): late samples merge into committed windows within retention A sample of a committed window still within its views' retention is merged into it (store and file replaced, cached results made stale); beyond retention it is dropped and counted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/repo-layout.md | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 33aaa5cae..f74494b27 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -310,11 +310,18 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. - **Future samples.** A sample more than `--max-future-ms` (default 5 min) ahead of the wall clock is dropped and counted (`samples_dropped_future`). -- **Late samples.** A sample older than every window still to close and - every query-time `Scan`'s look-back is dropped (`samples_dropped_late`). - One a query-time `Scan` still reads is stored as raw data, but in no - view, if every window holding it has closed (`samples_late_for_views`). - A committed window is never revised. +- **Late samples.** A sample of a window already committed, while the + window is within its views' retention, is merged into it + (`samples_merged_late`): the committer batches a window's late samples, + runs the window's views over them alone, merges the resulting states + into the committed ones (and the change into the committed windows of + the groups that read those views), replaces the window in the view + store and in its file, and makes the cached query results that read it + stale. The window then holds what it would have held had the samples + come on time. A sample beyond retention, with no window still to close + and no query-time `Scan`'s look-back to take it, is dropped + (`samples_dropped_late`). One a query-time `Scan` still reads is also + stored as raw data. - **First window.** The first window each refresh group sees may have started before the data plane did, so it is skipped (`windows_skipped_first`), unless `--stream-start-ms` says where the @@ -327,7 +334,8 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. acknowledged before it has run, every window with `end <= T` closes, so the last window of a series that stopped sending is refreshed. `T` is capped at the wall clock; a repeated or lower `T` does nothing; input - stays open; a later sample for a closed window is late. With several + stays open; a later sample for a closed window is late, and merged + into it within retention (Late samples). With several producers, send it only after all of them have written through `T`. ### Query forwarding @@ -473,16 +481,19 @@ PRs, each reviewed on its own: and takes `now` and `a` at that flush, so samples still queued reset `a` and close nothing. - The barrier is unchanged; the latest of the three closes. - - A sample for a window closed this way is late, dropped and counted as - any other (`samples_dropped_late`, `samples_late_for_views`). + - A sample for a window closed this way is late, as any other: merged + into the window within its views' retention (`samples_merged_late`), + dropped and counted beyond it (`samples_dropped_late`), so a producer + that pauses and resumes loses no window. - Windows closed ahead of the samples and barriers are counted (`asap_windows_closed_by_wall_clock_total`). - Nothing closes before the first sample, and after a restart nothing closes by wall clock until a sample arrives; `--stream-start-ms` only makes the first window complete, as before. - A stream whose event time runs slower than the wall clock with gaps - longer than `L + G` breaks the assumption; it needs a larger - `--allowed-lateness-ms`. + longer than `L + G` breaks the assumption: its windows close early + and are answered from part of their samples until the rest merge in. + A larger `--allowed-lateness-ms` avoids the partial answers. ## Alternatives considered From c361a9228e71f61a5994b500239cfbd9c90fc9e2 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:18:41 +0000 Subject: [PATCH 17/18] docs(design): order-sensitive late samples recompute from raw; shards wait for a pass's routing after a flush Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/repo-layout.md | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index f74494b27..4d4b317df 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -304,7 +304,10 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. (default 15 s), a producer's barrier, or the idle watermark (decision 5), whichever is latest; it never goes back. It moves only behind a flush that every shard has run, and a shard with nothing queued - answers the flush at once, so an idle shard does not hold it. A refresh + answers the flush at once, so an idle shard does not hold it. A shard + that answered a flush routes no more samples until it has the routing + of that pass, so a sample is never routed by the windows open before a + pass closed one. A refresh group's window `(e − W, e]` closes when the watermark reaches `e`; a window with no sample is refreshed too, and stored empty. - **Future samples.** A sample more than `--max-future-ms` (default 5 min) @@ -318,7 +321,13 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. the groups that read those views), replaces the window in the view store and in its file, and makes the cached query results that read it stale. The window then holds what it would have held had the samples - come on time. A sample beyond retention, with no window still to close + come on time. A group whose states depend on the order of their + samples (counters for `rate`/`increase`, `irate`) is not merged: it + keeps its raw samples for its views' retention, and its window is + computed again from them, late samples included, replacing the stored + one (and the windows built from it are computed again). KLL sketches + (within their error bound) and floating-point sums (in their last bits) + are merged. A sample beyond retention, with no window still to close and no query-time `Scan`'s look-back to take it, is dropped (`samples_dropped_late`). One a query-time `Scan` still reads is also stored as raw data. From e3f1134431920d09a6d5d5304b0c2629dcd1ff84 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 01:56:49 +0000 Subject: [PATCH 18/18] docs(design): counter raw samples kept compressed; narrow levels kept as long as wider levels computed again read them Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/repo-layout.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/docs/design/repo-layout.md b/docs/design/repo-layout.md index 4d4b317df..920e1b164 100644 --- a/docs/design/repo-layout.md +++ b/docs/design/repo-layout.md @@ -323,9 +323,14 @@ measurements `internal-metrics` keeps, so `internal-metrics` stays a leaf. stale. The window then holds what it would have held had the samples come on time. A group whose states depend on the order of their samples (counters for `rate`/`increase`, `irate`) is not merged: it - keeps its raw samples for its views' retention, and its window is - computed again from them, late samples included, replacing the stored - one (and the windows built from it are computed again). KLL sketches + keeps its raw samples for its views' retention, those behind every + window still to close as compressed XOR chunks (Prometheus-style: + delta-of-delta timestamps, XOR'd values), and its window is computed + again from them, late samples included, replacing the stored one. The + windows built from it are computed again from the narrower windows, + which are kept as long as those wider windows reach back (their + retention plus their width), so a late sample within the widest + level's retention always reaches every level. KLL sketches (within their error bound) and floating-point sums (in their last bits) are merged. A sample beyond retention, with no window still to close and no query-time `Scan`'s look-back to take it, is dropped