From bd154aedae10658258ee2f6b1970fd418809cecb Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 14:47:35 +0000 Subject: [PATCH 01/21] docs(design): leaf sketch views precomputed in the collector The collector (OTAP asap_sketches) builds pushed leaf views' per-series ASAPv1 states; the backend ingests them on /v1/metrics into the view store. Rule-based push-down in the control plane, Prometheus (t - range, t] windows on both sides, parameter checks, dedup and late merges. --- docs/design/collector-sketch-ingest.md | 604 +++++++++++++++++++++++++ 1 file changed, 604 insertions(+) create mode 100644 docs/design/collector-sketch-ingest.md diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md new file mode 100644 index 000000000..73efc15a6 --- /dev/null +++ b/docs/design/collector-sketch-ingest.md @@ -0,0 +1,604 @@ +# Design: leaf sketch views precomputed in the collector + +Status: proposal, for review. Decisions are recorded at the end. + +## Audience and context + +This document is for developers of the backend and of ASAPCollector-public, +the collector built on OTAP Dataflow (OpenTelemetry Arrow's dataflow engine) +whose `asap_sketches` processor builds windowed sketches at the edge. It +decides how the collector builds some of a plan's leaf views and how the +backend ingests the resulting states, so that the backend stores and answers +them as if its own precompute had built them. + +Today every sample travels raw to the backend: the collector (or the +application) sends OTLP or Remote Write, and the backend's precompute builds +every view. A leaf view such as "a DDSketch per series per 5 s tumbling +window" folds the samples of one series and one window into one state, and +the collector can build exactly that state before the network. For a series +sampled at 10 Hz, 50 samples become one state. + +Terms, as in ASAPPlanner: + +- **View**: a materialized node of the plan, identified by `ViewId { plan, + node }`. +- **Leaf view**: a view whose input is a raw `Scan`. +- **Tumbling window**: a window of fixed width `w` on multiples of `w`; the + window ending at `e` covers `(e − w, e]`. +- **State**: the summary of one series (or group) in one window; a sketch + state is `asap_sketchlib`'s ASAPv1 bytes. +- **Chain**: the views and query-time merges that build a longer range from + a leaf's windows (`SummaryTumblingWindowChain`, then `TimeRange` and + `SummaryMerge`). +- **Pushed view**: a leaf view the collector builds; the backend only stores + and reads it. + +Scope: + +- ASAPPlanner does not change. Which views are pushed is a deployment + decision the backend's control plane makes after planning (decision 1). +- The backend changes in four places: a new ingest adapter, a new `common` + type, the view store's write path, and the control plane. +- The collector changes in one place, its window boundary and filter + configuration, in its own repository. + +## Components + +```text + ┌──────────────────────────── collector ────────────────────────────┐ + application ── OTLP ──▶ │ receiver ─┬─▶ asap_sketches (one per pushed view) ─▶ OTLP exporter │──┐ sketch path + │ └─▶ raw forward ─────────────────────────▶ OTLP exporter │──┤ raw path + └───────────────────────────────────────────────────────────────────┘ │ + ▲ collector config (TOML) │ + │ ▼ + workload ─▶ control-plane ─▶ InstallablePlan ────┼──────────────▶ data-plane POST /v1/metrics + │ (asap-planner, unchanged) │ ├─ record without sketch.envelope ─▶ otlp ─▶ IngestEngine (raw path) + └─ emit_collector_config ───────────┘ └─ record with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch + + PushedViews file ───────────────▶ data-plane ─▶ precompute committer ─▶ storage (view store, persistence) +``` + +| Component | Crate or repository | Role | +|---|---|---| +| Push-down rule | `crates/control-plane` | Picks the pushable leaf views of the installed plan (rule below) | +| Collector config emitter | `crates/control-plane` (`control_plane --emit-collector-config`) | Writes one `asap_sketches` processor block per pushed view, and the `PushedViews` file the data plane reads | +| `asap_sketches` processor | ASAPCollector-public | Builds each pushed view's per-series states over tumbling windows and exports them as OTLP summary points carrying `sketch.envelope` | +| `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Decodes those OTLP records into a `common::ViewStateBatch`; never reads the sketch bytes | +| `ViewStateBatch` | `crates/common` (new type) | Pushed states between the adapter and the ingest engine | +| `/v1/metrics` route | `crates/data-plane` | One route for both paths: a data point with `sketch.envelope` goes to the sketch path, any other to the raw path | +| Pushed-state ingest | `crates/precompute` | Maps `agg_id` to the view, checks the state against the plan, stages it until the window commits, deduplicates, merges late states | +| Late-state merge | `crates/storage` | Replaces a committed window's rows with merged rows and persists them | + +The raw path stays (decision 3). The raw samples of a metric still go to the +backend when a view that is not pushed reads that metric, when a query-time +`Scan` reads it, and for the fallback: when a pushed view misses a window +(the collector was down), the query engine reports `NotReady` and the +dispatcher forwards the query, as for any view that is not ready. + +### Dependencies + +Following the layout rules (adapters see no engine and no store): + +```text +crate depends on +----------------- ------------------------------------------------------ +asap-sketch-otlp common (ViewStateBatch), otlp (its protobuf types) +precompute + decoding ASAPv1 through storage's existing codec (persist.rs decode_sketch) +control-plane unchanged dependencies (asap-planner, common) +``` + +The adapter does not decode ASAPv1: it hands the bytes on. Decoding needs +the executor's kernels, and `storage` already rebuilds every kernel from +ASAPv1 for persistence (`decode_sketch`), so the ingest engine reuses that. + +## Algorithm + +### 1. Push-down rule (control plane) + +The first version is rule based, with no cost comparison (decision 6). A +view of the installed plan is pushed if and only if all of these hold: + +1. **Leaf on raw input.** It is a `SummaryTumblingWindowChain` whose child is + a `Scan` of a `TimeSeries` source, with no node in between. +2. **Per series.** Its reduction is `PerEntity`: one state per series and + window. A view that reduces across series (`Reduce [...]`) is not pushed, + because one collector does not see every series of a group. +3. **Tumbling window.** It has a `tumbling_window_width_ms`; the collector's + `window_size` is set to it and `window_slide` is left out. +4. **Supported sketch and parameters.** Its summary type and parameters map + to an `asap_sketches` sketch type with the same parameters: + + | Plan summary | Plan parameters | `sketch_type` | `sketch_params` | + |---|---|---|---| + | `Sketch: DDSketch` | `alpha` | `ddsketch` | `relative_accuracy = alpha` | + | `Sketch: KLL` | `k` | `kll` | `k` | + | `Sketch: HLL` | precision 14 only | `hll` | none (fixed at 14) | + | `Sketch: CountSketch` | rows × columns | `countsketch` | `depth`, `width` | + | `Sketch: CountMin` | rows × columns | `countminsketch` | `depth`, `width` | + | `Sketch: CountMinHeap` | rows × columns, heap size | `countminsketch_heap` | `rows`, `columns`, `k` | + + The input must also match what the collector inserts: DDSketch and KLL + insert each sample's value (the plan's `input` is `item: null, weight: + SampleValue`); the frequency and cardinality sketches insert a key, and + are pushed only when the plan's item is a label the collector keys by + (`per_attribute`). Any other summary (exact aggregates, UnivMon, Hydra, + KMV, an HLL of another precision) is not pushed. +5. **Expressible filter.** Its `Scan` has a metric name, and its predicates + and the view's `filter` are a conjunction of label equalities and + inequalities (`=`, `!=`), which the collector's `LabelMatcher` evaluates. + A regular-expression matcher is not pushed. The collector exposes + matchers in its configuration only after the collector change below. + +**Exact aggregates stay in the backend.** The collector's `asap_sketches` +processor builds only the six sketches above. Its `Exact` type +(`EXv1`, the exact baseline window holding every value) is a baseline for +comparisons, not a `sum`, `max` or counter state, and has no +`sketch_type` spelling. Views of `ExactAggregate` (`Sum`, `Max`, `Min`, +`Rate`, `Increase`, …) are therefore not pushed. They become pushable when +the collector builds those states, with counter-reset handling for `Rate` +and `Increase`. + +**Known limitation: sparse series.** The rule ignores size. A series with few +samples per window can produce a sketch state larger than its raw samples +(a DDSketch with one sample still carries its header, mapping and bins, +against about 16 bytes for the raw sample). Step 4 measures where this +happens. Push-down that compares costs is future work; it needs a general +planner capability (costing where a view is built), to be discussed later. + +### 2. Collector configuration (control plane) + +For each pushed view the control plane writes one processor block (worked +example below). The fields are fixed by the view: + +| Field | Value | Why | +|---|---|---| +| `id` | `asap_view_` | One processor per view | +| `sketch_type`, `sketch_params` | from the table in step 1 | The state must decode as the view's kernel with the plan's parameters | +| `window_size` | `tumbling_window_width_ms` | Same windows as the view | +| `output_metric_name` | the `Scan`'s metric name | Series identity: `__name__` must equal the raw series' name | +| `agg_id` | the view id, encoded as below | Maps a state back to its view | +| `matchers` | the metric name, then each `=` / `!=` predicate | The processor would otherwise fold every metric it receives (its series key has no metric name) | +| `transmit_sketch` | `true` | Full ASAPv1 states (decision 2) | +| `aggregate_by` | `[]` | Per series: every label is part of the key | +| `omit_resource_attrs`, `global_aggregation`, `emit_window_stats` | `false` | Any of them changes the series' labels, and with them its identity | + +`agg_id` is a `u64` in the collector and an `IntValue` (signed 64-bit) on the +OTLP wire. It encodes the view: the low 32 bits are the node id; the high 31 +bits are the plan's fingerprint (the hash of the plan file that the view +files' segment headers already name), truncated. A state built under another +plan's configuration then never lands in this plan's view of the same node +id. + +The same command writes the `PushedViews` file the data plane takes with +`--pushed-views`: per pushed view, its node, its `agg_id`, its kernel and +parameters, and the metric. The data plane does not change the +`InstallablePlan`; it reads the plan and this file. + +The precompute engine skips the pushed views: at install it compiles each +refresh group without the pushed leaf views (and without a `Scan` only they +read). The query engine is unchanged; it reads a pushed view from the store +like any other. + +### 3. Window semantics: Prometheus's `(t − range, t]` + +Both sides use Prometheus's boundary (decision 4). Prometheus 3.x range +selectors are left-open and right-closed. Its querying documentation +(Range Vector Selectors) says: "The range is a left-open and right-closed +interval, i.e. samples with timestamps coinciding with the left boundary of +the range are excluded from the selection, while samples coinciding with the +right boundary of the range are included in the selection." Its 3.0 +migration guide ("Range selectors and lookback exclude samples coinciding +with the left boundary") records the change from the earlier left-closed +form. OTLP's metrics data model uses the same interval for a delta point, +`(start, end]` ("The time interval is inclusive of the end time"). + +- **Backend: already matches.** `storage::store::window_end` puts a sample at + `t` in the window ending at `⌈t / w⌉ · w`, so windows are `(e − w, e]`, and + `ViewInstanceKey::window_ms` is `(start, end]`. +- **Collector: must change.** `WindowState::init_window` and + `advance_window` put a sample at `t` in `[⌊t / w⌋ · w, ⌊t / w⌋ · w + w)`, + and `SketchEnvelope` documents `window_start_ms` as inclusive and + `window_end_ms` as exclusive. At 10 Hz with 5 s windows every 50th sample + lies on a boundary, and the two sides put it in different windows, so a + pushed view and a backend-built view of the same data differ. + +The collector change, in its own repository and PR (step 5 of the plan): + +1. A sample at `t` belongs to the window ending at `⌈t / w⌉ · w`; a window + closes when a sample later than its end arrives (`t > end`, not `≥`), or + on the idle timer as today. +2. A sample is placed by its own timestamp, not into the active window: + today a sample older than the active window (out of order, from another + source) lands in the active window. It goes to its own window while that + window is open, and is dropped and counted once it is closed. +3. `window_start_ms` is exclusive and `window_end_ms` inclusive, in the + envelope, the `sketch.window_*_ms` attributes and the OTLP point times. +4. `matchers` (name, `=` or `!=`, value; `__name__` for the metric) in + `AsapSketchesUserConfig`, passed to `PrecomputeConfig::matchers`, which + the runtime already evaluates but the TOML does not expose. + +### 4. The sketch path in the data plane + +`POST /v1/metrics` decodes the request once. Each summary data point that +carries a `sketch.envelope` bytes attribute is a pushed state; every other +point is a raw sample, as today. A request may carry both. + +The adapter (`asap-sketch-otlp`) reads, per pushed state: + +| Field | Where on the wire | Check | +|---|---|---| +| `agg_id` | Resource attribute `sketch.agg_id` (int) | present | +| sketch type | Resource attribute `sketch.type` (`DDSketch`, `KLLSketch`, `HLLSketch`, `CountSketch`, `CountMinSketch`, `CountMinSketchWithHeap`) | known | +| schema version | Resource attribute `sketch.schema_version` | ≤ the highest supported | +| labels | Resource attributes, then Scope (`asap.series`) attributes, then point attributes, without any `sketch.*` key; `__name__` = metric name | the merge order the raw OTLP adapter uses | +| window | point attributes `sketch.window_start_ms`, `sketch.window_end_ms` | equal to the point's `start_time_unix_nano` / `time_unix_nano` in ms; `start < end` | +| state | point attribute `sketch.envelope` (bytes) | non-empty | +| sample count | point `count` | none | + +`sketch.series_id` is ignored: it is the collector's local counter and +restarts with it; the labels are the identity. `sketch.size` is ignored: the +parameters are checked from the decoded state. + +The ingest engine then, per state: + +1. **View.** Looks up `agg_id` in the `PushedViews` map. Unknown → rejected + (`reason="unknown_view"`). +2. **Window.** Requires `end − start` = the view's width and `end` a multiple + of it. Otherwise rejected (`reason="window"`). +3. **Parameters.** Decodes the ASAPv1 bytes with `storage`'s codec into the + view's kernel and compares the decoded sketch's parameters (DDSketch + `alpha`, KLL `k`, rows × columns, heap size, HLL precision, hash seed) + with the plan's, exactly (decision 5). A state that does not decode, or + decodes with other parameters, is rejected (`reason="decode"`, + `reason="params"`). +4. **Series.** Interns the label set into the store's series table, as the + raw path does, so the view row's `$promql_series_identity` is the same + canonical JSON a raw sample of that series gets. +5. **Stage, dedup, commit.** See below. + +Every rejection increments +`asap_pushed_states_rejected_total{view, reason}` and logs once per view and +reason per minute; the request still returns 200 with the rejected count, as +the raw OTLP route reports `rejected`. + +### 5. Staging, deduplication, late states + +The view store appends a view's windows in order and each window once, and +other refresh groups may read a pushed view (a wider level of its chain), so +a pushed window is committed once and whole. The engine stages pushed states +per `(view, window)` and commits through the precompute committer, the same +path that commits a window it built (readers, `RefreshTaskGraph` ordering, +persistence and the memory budget all apply). + +- **Commit time.** No raw samples of a pushed view's metric need reach the + backend, so the raw watermark cannot close its windows. A pushed window + commits when the wall clock passes `end + push_grace_ms` (default 10 s: + the collector's 5 s idle-close grace plus an export interval). +- **Duplicates.** A state for a `(view, series, window)` that already has a + state with the same bytes (compared by a 64-bit hash of the envelope, kept + per key for the view's retention) is ignored and counted + (`asap_pushed_states_duplicate_total{view}`). This covers exporter + retries. +- **Second states.** A state for a `(view, series, window)` that already has + a state with other bytes is merged into it (sketch merge). This covers two + partial states: a collector that restarted inside a window, or two + collectors that each saw part of one series. Merging is safe because the + states are full, not deltas, and each partial covers different samples. +- **Late states.** A state that arrives after its window committed: + - within the view's retention, it is merged into the committed window + (deduplicated as above), through `merge_late_rows` below, which writes + the merged window to memory and to its view file; + `asap_pushed_states_late_merged_total{view}`; + - beyond the retention, it is dropped; + `asap_pushed_states_late_dropped_total{view}`. + +A late merge changes a window a query may already have read. The result +cache keeps final answers per evaluation time, so the merge drops the cached +answers whose range covers the merged window (open question 6). + +## Code interface + +### `crates/common` + +```rust +/// States the collector built for pushed views: what the sketch-path ingest +/// adapter hands the ingest engine. Never data between operators. +#[derive(Debug, Clone, PartialEq)] +pub struct ViewStateBatch { + pub states: Vec, +} + +/// One series' state of one pushed view in one window. +#[derive(Debug, Clone, PartialEq)] +pub struct PushedViewState { + /// The view, as the collector config encodes it (see `AggId`). + pub agg_id: AggId, + /// Which sketch the bytes hold, as the record declares it. + pub sketch: PushedSketch, + /// ASAPv1 envelope bytes from `asap_sketchlib`: the full state. + pub asapv1: Vec, + /// The series' labels, `__name__` included. + pub labels: LabelSet, + /// The window `(start_ms, end_ms]`. + pub window_ms: (i64, i64), + /// Samples folded into the state, as the collector counted them. + pub sample_count: u64, +} + +/// A pushed view's id on the wire: plan fingerprint (high 31 bits) and +/// node id (low 32 bits). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct AggId(pub u64); + +/// The sketches the collector builds. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PushedSketch { DDSketch, Kll, Hll, CountSketch, CountMin, CountMinHeap } + +/// What happened to a batch's states. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ViewStateIngestReport { + pub staged: u64, + pub duplicate: u64, + pub late_merged: u64, + pub late_dropped: u64, + /// Rejected states by reason (`unknown_view`, `window`, `decode`, `params`). + pub rejected: BTreeMap<&'static str, u64>, +} + +/// Takes states the collector built for pushed views. Implemented by the +/// ingest engine, next to `IngestEngine`. +#[async_trait] +pub trait ViewStateIngest: Send + Sync { + /// Checks, stages or merges each state; waits under backpressure as + /// `IngestEngine::ingest` does. + async fn ingest_view_states(&self, batch: ViewStateBatch) + -> Result; +} +``` + +`ViewStore::put`'s contract ("each key is put once and never rewritten") +gains one exception, for late states: + +```rust +pub trait ViewStore: Send + Sync { + // put, get, instances, evict_before, timestamp_range_per_view: unchanged + + /// Replaces the committed instance under `key` with `instance` (the old + /// one merged with late states). `false` when `key` is not stored + /// (evicted, or never committed). + fn replace(&self, key: ViewInstanceKey, instance: ViewInstance) -> bool; +} +``` + +and the backend's own store, which the engines use directly: + +```rust +// crates/storage/src/store.rs +impl ViewStore { + /// Replaces the rows of `view`'s committed window `time_range_ms` with + /// `batches` (copy on write: runs reading the old rows keep them); the + /// window is re-queued for its view file. `Err` when the window is not + /// stored. + pub fn merge_late_rows( + &mut self, + view: &MaterializedView, + time_range_ms: (i64, i64), + batches: Vec, + ) -> Result<(), Error>; +} +``` + +### `crates/adapters/ingest/asap-sketch-otlp` + +```rust +/// Why a request's pushed states could not be read (the whole request is +/// refused with 400; per-state problems are counted, not errors). +#[derive(Debug, thiserror::Error, PartialEq)] +pub enum SketchOtlpError { + #[error("sketch record without {0}")] + MissingAttribute(&'static str), + #[error("unknown sketch.type {0:?}")] + UnknownSketchType(String), + #[error("sketch.schema_version {0} is newer than supported")] + SchemaVersion(u64), + #[error("window attributes ({start_ms}, {end_ms}] disagree with the point's times")] + Window { start_ms: i64, end_ms: i64 }, +} + +/// Whether an OTLP data point carries a pushed state (a `sketch.envelope` +/// bytes attribute): the route's test for the sketch path. +pub fn is_sketch_point(attributes: &[KeyValue]) -> bool; + +/// The pushed states of a decoded OTLP metrics request; points without +/// `sketch.envelope` are left to the raw `otlp` decoder. +pub fn decode_view_states( + request: &ExportMetricsServiceRequest, +) -> Result; +``` + +The raw `otlp` decoder already skips points that carry a sketch payload; it +learns `sketch.envelope` as one more such attribute, so one request body is +decoded by both and each point is read once. + +### `crates/control-plane` + +```rust +/// A leaf view the collector builds, and how. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct PushedView { + pub node: PhysicalASAPNodeId, + pub agg_id: u64, + pub metric: String, + /// Label matchers: the metric name, then the Scan's predicates. + pub matchers: Vec, + pub sketch_type: &'static str, + pub sketch_params: BTreeMap<&'static str, f64>, + pub window_ms: u64, +} + +/// Why a leaf view is not pushed, for the command's report. +#[derive(Debug, Clone, PartialEq)] +pub enum NotPushed { + NotOnRawScan, + NotPerSeries, + NotTumbling, + UnsupportedSummary(String), + UnsupportedParameters(String), + FilterNotExpressible(String), +} + +/// The installed plan's pushed views, by the rule of this design, and why +/// each other leaf view is not pushed. +pub fn pushed_views(plan: &InstallablePlan) + -> (Vec, Vec<(PhysicalASAPNodeId, NotPushed)>); + +/// The collector TOML: one `asap_sketches` processor block per pushed view. +pub fn emit_collector_config(views: &[PushedView]) -> String; +``` + +CLI: `control_plane --plan --emit-collector-config + --pushed-views ` reads a saved plan and +writes both files; the data plane takes `--pushed-views +`. + +## Worked example: q01 + +The query, from the `smoke` workload: `quantile_over_time(0.99, data[1m])`, +evaluated every 5 s, 10 samples/s per series. The plan the control plane +selects has, for q01: + +```text +node 0 Scan data (ts, value, $promql_series_identity) +node 1 SummaryTumblingWindowChain DDSketch α 0.05, PerEntity, 5 000 ms tumbling, + (view, ingestion time, retention 120 s) filter none +node 2 TimeRange 60 s (query time) reads node 1's windows in (T − 60 s, T] +node 3 SummaryMerge (query time) merges them per series +node 4 SummaryEstimate q = 0.99 +node 5 Project (root) (ts, value, $promql_series_identity) +``` + +Node 1 passes the rule: its child is a `Scan` of `data`, it is `PerEntity`, +tumbling at 5 s, DDSketch with α 0.05 maps to `relative_accuracy = 0.05`, +and it has no predicate or filter. The command writes the block below +(for illustration, a plan whose fingerprint truncates to `0x2acbeb01`, so +`agg_id` = `0x2acbeb01_00000001`): + +```toml +# Pushed view: node 1 (SummaryTumblingWindowChain DDSketch, alpha 0.05, +# PerEntity, 5000 ms tumbling) of the installed plan. +[[pipelines.metrics.processors]] +id = "asap_view_1" +plugin = "asap_sketches" + + [pipelines.metrics.processors.config] + sketch_type = "ddsketch" + window_size = "5s" + output_metric_name = "data" + agg_id = 3083816759392731137 + transmit_sketch = true + aggregate_by = [] + omit_resource_attrs = false + global_aggregation = false + emit_window_stats = false + # Requires the collector's matchers option (collector change, item 4). + matchers = [{ name = "__name__", op = "=", value = "data" }] + + [pipelines.metrics.processors.config.sketch_params] + relative_accuracy = 0.05 +``` + +and `pushed-views.json`: + +```json +[{"node": 1, "agg_id": 3083816759392731137, "metric": "data", + "matchers": [{"name": "__name__", "op": "=", "value": "data"}], + "sketch_type": "ddsketch", "sketch_params": {"relative_accuracy": 0.05}, + "window_ms": 5000}] +``` + +For one series `data{region="r0",service="s0",job="j0",label_0="l0"}`, the +collector folds the 50 samples with timestamps in `(T − 5 s, T]` into one +DDSketch and exports one summary point: Resource `sketch.agg_id = +3083816759392731137`, `sketch.type = "DDSketch"`; Scope `asap.series` with +the four labels; metric `data`; point `sketch.window_start_ms = T − 5000`, +`sketch.window_end_ms = T`, `sketch.envelope = `, `count = 50`. + +The backend keeps exactly what its own precompute keeps for node 1: per +series, one DDSketch state per 5 s window, for the view's 120 s retention +(24 windows). At evaluation time `T` (a multiple of 5 s), q01 runs at query +time as before: node 2 selects the 12 windows ending in `(T − 60 s, T]`, +node 3 merges the 12 states of each series into one, and node 4 reads the +0.99 quantile. That merge chain, the result cache and the fallback do not +change. The backend no longer runs node 1, and `data`'s raw samples still +arrive because node 6 (`max_over_time(data[30s])`) reads them. + +## The benchmark queries + +The five dashboard queries (`smoke` widths; q05 is q01 as a range panel): + +| Query | Leaf view | Pushed | Why | +|---|---|---|---| +| q01 `quantile_over_time(0.99, data[1m])` | DDSketch α 0.05, per series, 5 s tumbling, on `Scan data` | yes | passes every rule | +| q02 `topk(10, sum by (region, service, job) (rate(data_total[1m])))` | `ExactAggregate Rate`, per series, 5 s tumbling | no | exact counter state: the collector builds none | +| q03 `max_over_time(data[30s])` | `ExactAggregate Max`, per series, 5 s tumbling | no | exact aggregate: the collector builds none | +| q04 `sum by (region, service) (increase(data_total[1m]))` | `ExactAggregate Increase`, per series, 5 s tumbling | no | exact counter state | +| q05 q01 as a range panel (60 s span, 5 s step) | the same view as q01 | yes | shares q01's leaf; earlier steps come from the result cache | + +So for this workload the collector builds one view, the backend still builds +three, and both metrics' raw samples still reach the backend. Step 4 +measures what that saves; a workload whose metric is read only by pushed +views saves the raw samples too. + +## Plan + +Separate PRs, each reviewed on its own: + +1. This document. +2. `ViewStateBatch` and `ViewStateIngest` in `common`; the + `asap-sketch-otlp` adapter; the `/v1/metrics` split; staging, dedup, + late merge and `ViewStore::merge_late_rows`. Test data: real ASAPv1 + records the collector emits (captured OTLP bodies, checked in with the + collector commit that wrote them), for each of the six sketch types, + including one with mismatched parameters, one duplicate and one late + state. +3. The control plane's push-down rule, `--emit-collector-config` and + `--pushed-views`; the precompute engine skips pushed views. Tests: the + `smoke` plan emits exactly the q01 block above; a plan with a regex + matcher, a `Reduce` leaf or a sliding window pushes nothing. +4. End-to-end comparison, collector + backend against backend only, on the + same feed: answers equal (exact views) or within the plan's error + (sketch views) at every evaluation; backend ingest CPU, network bytes + between collector and backend, and collector CPU; including a sparse + series case for the limitation above. +5. In the collector repository: the window boundary and filter change + (algorithm step 3). It lands before step 4, which needs equal windows. + +## Decisions + +1. **ASAPPlanner does not change.** Which views the collector builds is a + deployment decision the backend's control plane makes on the installed + plan; the plan and its `InstallablePlan` format are unchanged. +2. **The collector is ASAPCollector-public (OTAP), sending full ASAPv1 + states.** No deltas: each record holds the whole state of one series in + one window. +3. **Two paths.** The raw path (raw OTLP or Remote Write to the backend) + stays, for views that are not pushed, query-time `Scan`s and the + fallback. The sketch path carries pushed states on the same + `/v1/metrics` route; a record with `sketch.envelope` takes the sketch + path. +4. **Prometheus window semantics on both sides**: `(t − range, t]`, as + Prometheus 3.x range selectors. The backend already uses it; the + collector changes in its own PR. +5. **Parameters match the plan exactly**; the backend rejects a state whose + decoded parameters differ, and counts it. A state delivered twice for the + same view, series and window is ignored the second time, and counted. + A late state within retention is merged into the stored state; beyond + retention it is dropped and counted. +6. **Rule-based push-down first**: a view is pushed iff its leaf reads raw + input directly, is per series, uses a tumbling window, its sketch type + and parameters are among the collector's (DDSketch, KLL, HLL, + CountSketch, Count-Min, Count-Min-heap), and its filter is expressible in + the collector's configuration. No cost comparison. Exact aggregates stay + in the backend, since the collector builds none. Cost-based push-down is + future work and needs a general planner capability. +7. **`agg_id` is the view id**, and the backend's precompute skips pushed + views. From f49a2a83b33125f2bb2c92babf33e3e23e6f5494 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 15:22:11 +0000 Subject: [PATCH 02/21] docs(design): collector reads planner sub-DAGs; views keyed by definition_id The control plane sends each pushed view's sub-DAG of the installed plan (planner serde) to the collector, which depends on the planner's types crate. States carry view_coverage.definition_id and selection instead of agg_id. Adds the OTAP Schema/Dictionary/Record mapping with planner names, the transport recommendation (OTLP HTTP first, OTAP Arrow next), the benchmark query set, and the revised open questions. --- docs/design/collector-sketch-ingest.md | 809 +++++++++++++++++-------- 1 file changed, 567 insertions(+), 242 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 73efc15a6..f7868b3a8 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -18,54 +18,78 @@ window" folds the samples of one series and one window into one state, and the collector can build exactly that state before the network. For a series sampled at 10 Hz, 50 samples become one state. -Terms, as in ASAPPlanner: - -- **View**: a materialized node of the plan, identified by `ViewId { plan, - node }`. -- **Leaf view**: a view whose input is a raw `Scan`. +The collector is told what to build in the planner's own terms: for each +pushed view the control plane sends the view's sub-DAG of the installed +ASAPPlanner plan (`Scan` → `SummaryTumblingWindowChain`, with schema, +summary type, parameters and window), and the collector depends on +ASAPPlanner's types crate to read it. Every state the collector emits +carries the view's planner content id, so the backend finds the view by +design rather than by a number both sides agree on. + +Terms, as in ASAPPlanner (`asap-types`): + +- **Plan**: the `InstallablePlan` the control plane writes: `wire_version`, + `dag: PhysicalASAPDAG` (`nodes`, `edges`, `roots`, `scalar_roots`) and + `query_texts`. +- **View**: a materialized node of the plan: a `PhysicalASAPDAGNode` whose + `lifetime` is `AcrossEvaluations`, with `retention_ms` and + `view_coverage` set. +- **View coverage**: `view_coverage` = `{definition_id, selection}`. + `definition_id` is the plan-scope content id of what the view computes + (the 128-bit FNV-1a hash, in hex, of the expanded definition), equal + across plans, processes and restarts for the same computation. + `selection` is the rows that went in: the label matchers lifted out of + the `Scan`, and, for a range over a chain, the time interval. +- **Parameters**: the node's `parameters: SketchParams` (θ), for example + `{"DDSketch": {"alpha": 0.05}}`. Not part of `definition_id` (below). +- **Leaf view**: a view whose child is a raw `Scan`. +- **Sub-DAG**: a leaf view's node, its `Scan` node and the edge between + them, as a `PhysicalASAPDAG` with `roots = [view node]`. - **Tumbling window**: a window of fixed width `w` on multiples of `w`; the window ending at `e` covers `(e − w, e]`. -- **State**: the summary of one series (or group) in one window; a sketch - state is `asap_sketchlib`'s ASAPv1 bytes. -- **Chain**: the views and query-time merges that build a longer range from - a leaf's windows (`SummaryTumblingWindowChain`, then `TimeRange` and - `SummaryMerge`). +- **State**: the summary of one series in one window; a sketch state is + `asap_sketchlib`'s ASAPv1 bytes. - **Pushed view**: a leaf view the collector builds; the backend only stores and reads it. Scope: -- ASAPPlanner does not change. Which views are pushed is a deployment - decision the backend's control plane makes after planning (decision 1). +- ASAPPlanner does not change. It already exports what this design needs: + the plan's serde types (`PhysicalASAPDAG`, `PhysicalASAPDAGNode`, + `PhysicalASAPDAGEdge`, `ViewCoverage`, `SketchParams`), the content id + on each view, the view's parameters, window width, schema and retention. + Where a public read path is missing, it is listed as an open question + with the minimal need, not as a planner change. - The backend changes in four places: a new ingest adapter, a new `common` type, the view store's write path, and the control plane. -- The collector changes in one place, its window boundary and filter - configuration, in its own repository. +- The collector changes in its own repository: a dependency on the + planner's types crate, a sub-DAG loader, id stamping, and the + window-boundary, out-of-order and matcher fixes. ## Components ```text ┌──────────────────────────── collector ────────────────────────────┐ - application ── OTLP ──▶ │ receiver ─┬─▶ asap_sketches (one per pushed view) ─▶ OTLP exporter │──┐ sketch path - │ └─▶ raw forward ─────────────────────────▶ OTLP exporter │──┤ raw path + application ── OTLP ──▶ │ receiver ─┬─▶ asap_sketches (planner_views) ─────▶ OTLP exporter │──┐ sketch path + │ └─▶ raw forward ───────────────────────▶ OTLP exporter │──┤ raw path └───────────────────────────────────────────────────────────────────┘ │ - ▲ collector config (TOML) │ + ▲ pushed-views.json (planner sub-DAGs) │ │ ▼ workload ─▶ control-plane ─▶ InstallablePlan ────┼──────────────▶ data-plane POST /v1/metrics │ (asap-planner, unchanged) │ ├─ record without sketch.envelope ─▶ otlp ─▶ IngestEngine (raw path) - └─ emit_collector_config ───────────┘ └─ record with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch - + PushedViews file ───────────────▶ data-plane ─▶ precompute committer ─▶ storage (view store, persistence) + └─ pushed_view_dags ────────────────┘ └─ record with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch + (same file) ──────────────────────▶ data-plane ─▶ precompute committer ─▶ storage (view store, persistence) ``` | Component | Crate or repository | Role | |---|---|---| | Push-down rule | `crates/control-plane` | Picks the pushable leaf views of the installed plan (rule below) | -| Collector config emitter | `crates/control-plane` (`control_plane --emit-collector-config`) | Writes one `asap_sketches` processor block per pushed view, and the `PushedViews` file the data plane reads | -| `asap_sketches` processor | ASAPCollector-public | Builds each pushed view's per-series states over tumbling windows and exports them as OTLP summary points carrying `sketch.envelope` | +| Sub-DAG extraction | `crates/control-plane` (`control_plane --emit-pushed-views`) | Writes `pushed-views.json`: each pushed view's sub-DAG, serialized with the planner's own serde | +| `asap_sketches` processor | ASAPCollector-public | Loads `pushed-views.json` at start, builds each view's per-series states over tumbling windows, and exports OTLP summary points carrying `sketch.envelope` and `sketch.definition_id` | | `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Decodes those OTLP records into a `common::ViewStateBatch`; never reads the sketch bytes | | `ViewStateBatch` | `crates/common` (new type) | Pushed states between the adapter and the ingest engine | | `/v1/metrics` route | `crates/data-plane` | One route for both paths: a data point with `sketch.envelope` goes to the sketch path, any other to the raw path | -| Pushed-state ingest | `crates/precompute` | Maps `agg_id` to the view, checks the state against the plan, stages it until the window commits, deduplicates, merges late states | +| Pushed-state ingest | `crates/precompute` | Finds the view by `definition_id` and selection, checks the state against the plan, stages it until the window commits, deduplicates, merges late states | | Late-state merge | `crates/storage` | Replaces a committed window's rows with merged rows and persists them | The raw path stays (decision 3). The raw samples of a metric still go to the @@ -79,106 +103,255 @@ dispatcher forwards the query, as for any view that is not ready. Following the layout rules (adapters see no engine and no store): ```text -crate depends on ------------------ ------------------------------------------------------ -asap-sketch-otlp common (ViewStateBatch), otlp (its protobuf types) -precompute + decoding ASAPv1 through storage's existing codec (persist.rs decode_sketch) -control-plane unchanged dependencies (asap-planner, common) +crate / repository depends on +------------------- ------------------------------------------------------ +asap-sketch-otlp common (ViewStateBatch), otlp (its protobuf types) +precompute + decoding ASAPv1 through storage's existing codec (persist.rs decode_sketch) +control-plane unchanged dependencies (asap-planner, common) +ASAPCollector-public + asap-types (ASAPPlanner's types crate), pinned git rev ``` The adapter does not decode ASAPv1: it hands the bytes on. Decoding needs the executor's kernels, and `storage` already rebuilds every kernel from ASAPv1 for persistence (`decode_sketch`), so the ingest engine reuses that. +`asap-types` brings `serde`, `serde_json`, `thiserror` 2 and +`asap_sketchlib` (for `SketchAlgorithm`) into the collector build; no +executor, frontend or solver (open question 12). + ## Algorithm ### 1. Push-down rule (control plane) The first version is rule based, with no cost comparison (decision 6). A -view of the installed plan is pushed if and only if all of these hold: - -1. **Leaf on raw input.** It is a `SummaryTumblingWindowChain` whose child is - a `Scan` of a `TimeSeries` source, with no node in between. -2. **Per series.** Its reduction is `PerEntity`: one state per series and - window. A view that reduces across series (`Reduce [...]`) is not pushed, - because one collector does not see every series of a group. -3. **Tumbling window.** It has a `tumbling_window_width_ms`; the collector's - `window_size` is set to it and `window_slide` is left out. -4. **Supported sketch and parameters.** Its summary type and parameters map - to an `asap_sketches` sketch type with the same parameters: - - | Plan summary | Plan parameters | `sketch_type` | `sketch_params` | +node of the installed plan's `dag` is pushed if and only if all of these +hold, read from its planner fields: + +1. **View at ingestion.** `lifetime` is `AcrossEvaluations`, + `output_state.timing` is `ingestion_time`, and `view_coverage` is set. +2. **Leaf on raw input.** `payload` is `ASAP.SummaryTumblingWindowChain` + whose `child` is a node with payload `NonASAP.Scan` and `source` + `TimeSeries { metric }`, with no node in between. +3. **Per series.** `reduction` is `PerEntity`: one state per series and + window. A `Reduce [...]` view is not pushed, because one collector does + not see every series of a group. +4. **Tumbling window.** `tumbling_window_width_ms` is set; it becomes the + collector's window. +5. **Supported sketch and parameters.** `summary_type` is + `{"Sketch": }` and `parameters` the matching `SketchParams`, + both in the collector's table: + + | `summary_type` | `parameters` | collector sketch | collector parameters | |---|---|---|---| - | `Sketch: DDSketch` | `alpha` | `ddsketch` | `relative_accuracy = alpha` | - | `Sketch: KLL` | `k` | `kll` | `k` | - | `Sketch: HLL` | precision 14 only | `hll` | none (fixed at 14) | - | `Sketch: CountSketch` | rows × columns | `countsketch` | `depth`, `width` | - | `Sketch: CountMin` | rows × columns | `countminsketch` | `depth`, `width` | - | `Sketch: CountMinHeap` | rows × columns, heap size | `countminsketch_heap` | `rows`, `columns`, `k` | - - The input must also match what the collector inserts: DDSketch and KLL - insert each sample's value (the plan's `input` is `item: null, weight: - SampleValue`); the frequency and cardinality sketches insert a key, and - are pushed only when the plan's item is a label the collector keys by - (`per_attribute`). Any other summary (exact aggregates, UnivMon, Hydra, - KMV, an HLL of another precision) is not pushed. -5. **Expressible filter.** Its `Scan` has a metric name, and its predicates - and the view's `filter` are a conjunction of label equalities and - inequalities (`=`, `!=`), which the collector's `LabelMatcher` evaluates. - A regular-expression matcher is not pushed. The collector exposes - matchers in its configuration only after the collector change below. + | `{"Sketch": "DDSketch"}` | `DDSketch { alpha }` | `ddsketch` | `relative_accuracy = alpha` | + | `{"Sketch": "Kll"}` | `Kll { k }` | `kll` | `k` | + | `{"Sketch": "Hll"}` | `Hll { precision: 14 }` only | `hll` | none (fixed at 14) | + | `{"Sketch": "CountSketch"}` | `CountSketch { width, depth }` | `countsketch` | `width`, `depth` | + | `{"Sketch": "Cms"}` | `Cms { width, depth }` | `countminsketch` | `width`, `depth` | + | `{"Sketch": "CmsWithHeap"}` | `CmsWithHeap { width, depth, heap_size }` | `countminsketch_heap` | `columns = width`, `rows = depth`, `k = heap_size` | + + The `input` must match what the collector inserts: DDSketch and KLL + insert each sample's value (`input` is `{"item": null, "weight": + {"Column": "SampleValue"}}`); the frequency and cardinality sketches + insert a key and are pushed only when the item is a label the collector + keys by. Any other summary (`ExactAggregate`, UnivMon, Hydra, KMV, an + HLL of another precision) is not pushed. +6. **Expressible filter.** The chain's `filter` is `null`, and the `Scan`'s + `predicates` are a conjunction of `Compare` nodes with `op` `Eq` or `Ne` + between a label column and a `Utf8` literal (PromQL `=`, `!=`), which + the collector's `LabelMatcher` evaluates. A regular-expression matcher + is not pushed. **Exact aggregates stay in the backend.** The collector's `asap_sketches` -processor builds only the six sketches above. Its `Exact` type -(`EXv1`, the exact baseline window holding every value) is a baseline for -comparisons, not a `sum`, `max` or counter state, and has no -`sketch_type` spelling. Views of `ExactAggregate` (`Sum`, `Max`, `Min`, -`Rate`, `Increase`, …) are therefore not pushed. They become pushable when -the collector builds those states, with counter-reset handling for `Rate` -and `Increase`. +processor builds only the six sketches above. Its `Exact` type (`EXv1`, +the exact baseline window holding every value) is a baseline for +comparisons, not a `sum`, `max` or counter state. Views of `ExactAggregate` +(`Sum`, `Max`, `Min`, `Counter`, …) are therefore not pushed. They become +pushable when the collector builds those states, with counter-reset +handling for `Counter`. **Known limitation: sparse series.** The rule ignores size. A series with few samples per window can produce a sketch state larger than its raw samples (a DDSketch with one sample still carries its header, mapping and bins, -against about 16 bytes for the raw sample). Step 4 measures where this -happens. Push-down that compares costs is future work; it needs a general -planner capability (costing where a view is built), to be discussed later. +against about 16 bytes for the raw sample). Step 4 of the plan measures +where this happens. Push-down that compares costs is future work; it needs +a general planner capability (costing where a view is built), to be +discussed later. -### 2. Collector configuration (control plane) +### 2. Sub-DAG extraction and the pushed-views file (control plane) -For each pushed view the control plane writes one processor block (worked -example below). The fields are fixed by the view: +For each pushed view the control plane copies, from the installed +`dag`, the view node and its `Scan` node (both unchanged, node ids +included) and the one edge between them, and sets `roots = [view node]`, +`scalar_roots = []`. Nothing is re-derived or renamed: the collector reads +the same values the backend's precompute would compile. -| Field | Value | Why | -|---|---|---| -| `id` | `asap_view_` | One processor per view | -| `sketch_type`, `sketch_params` | from the table in step 1 | The state must decode as the view's kernel with the plan's parameters | -| `window_size` | `tumbling_window_width_ms` | Same windows as the view | -| `output_metric_name` | the `Scan`'s metric name | Series identity: `__name__` must equal the raw series' name | -| `agg_id` | the view id, encoded as below | Maps a state back to its view | -| `matchers` | the metric name, then each `=` / `!=` predicate | The processor would otherwise fold every metric it receives (its series key has no metric name) | -| `transmit_sketch` | `true` | Full ASAPv1 states (decision 2) | -| `aggregate_by` | `[]` | Per series: every label is part of the key | -| `omit_resource_attrs`, `global_aggregation`, `emit_window_stats` | `false` | Any of them changes the series' labels, and with them its identity | - -`agg_id` is a `u64` in the collector and an `IntValue` (signed 64-bit) on the -OTLP wire. It encodes the view: the low 32 bits are the node id; the high 31 -bits are the plan's fingerprint (the hash of the plan file that the view -files' segment headers already name), truncated. A state built under another -plan's configuration then never lands in this plan's view of the same node -id. - -The same command writes the `PushedViews` file the data plane takes with -`--pushed-views`: per pushed view, its node, its `agg_id`, its kernel and -parameters, and the metric. The data plane does not change the -`InstallablePlan`; it reads the plan and this file. +It writes them to one JSON file, serialized with the planner types' own +serde: + +```json +{"planner_wire_version": 15, "views": [, ...]} +``` + +`planner_wire_version` is the plan's `wire_version`. The collector loads +the file once at start (recommended over a control endpoint: one file, no +new protocol, and a plan change is a collector restart anyway, below). The +data plane takes the same file with `--pushed-views`; it does not change +the `InstallablePlan`. The precompute engine skips the pushed views: at install it compiles each refresh group without the pushed leaf views (and without a `Scan` only they read). The query engine is unchanged; it reads a pushed view from the store like any other. -### 3. Window semantics: Prometheus's `(t − range, t]` +**Plan reinstall.** A view whose computation did not change keeps its +`definition_id`, so its states keep matching across a reinstall even if its +node id changes. The control plane writes a new file; the collector picks +it up on restart. Until then, states of views the new plan no longer has +are rejected as `unknown_view`, and the views the new plan adds are built +by the collector only after its restart (the backend reports them +`NotReady` meanwhile, and the dispatcher forwards those queries). + +### 3. The collector: load, check, build, stamp + +At start, with `planner_views: ` in its processor config, the +`asap_sketches` processor: + +1. **Loads** the file with `serde_json` into the planner types. A + `planner_wire_version` other than the one its pinned `asap-types` + writes is a load error. +2. **Checks each sub-DAG's shape** and refuses to start, naming the view's + `definition_id` and the first failing field, unless the sub-DAG is + exactly: two nodes, one `Input` edge, root = the + `SummaryTumblingWindowChain`, child a `Scan` of `TimeSeries { metric }`, + `reduction` `PerEntity`, `filter` `null`, a summary type and parameters + from the table in step 1, `Scan` predicates only label `Eq`/`Ne` + against a string, and `view_coverage` present. These are the push-down + rule's conditions; the collector checks them again so a hand-edited or + stale file fails at load rather than producing wrong states. +3. **Maps** each view to its internal window state: sketch and parameters + from the table (an out-of-range value is a load error, never replaced + by a default), window = `tumbling_window_width_ms`, matchers = + `__name__ = metric` plus each `Scan` predicate, one state per series + with every label in the key. +4. **Stamps** every emitted state with the view's `definition_id` and + `selection` and the window (attribute names in §4). + +With `planner_views` set, the per-sketch fields of the processor config +(`sketch_type`, `sketch_params`, `window_size`, `window_slide`, +`output_metric_name`, `agg_id`, `aggregate_by`, `omit_resource_attrs`, +`global_aggregation`, `emit_window_stats`, `transmit_sketch = false`) are a +config error: the file is the only source of truth. The pipeline YAML then +names one `asap_sketches` node and does not change when the plan does. + +### 4. OTAP tiers: what goes in Schema, Dictionary and Record + +The collector's data model (its `docs/data_model.md`) splits a sketch +stream into OTAP's three tiers by rate of change: **Schema** (config-time, +once per stream), **Dictionary** (once per series), **Record** (once per +state). The planner's view fields fall into the same tiers by design: + +| Tier | Planner source | Collector field (OTLP placement) | Backend handling | +|---|---|---|---| +| Schema | `view_coverage.definition_id` | `sketch.definition_id` (Resource, string, 32 hex), replaces `sketch.agg_id` | Look up the installed views with this id; none → reject `unknown_view` | +| Schema | `view_coverage.selection` (non-time part: lifted label matchers) | `sketch.selection` (Resource, the planner's JSON of the selection) | Parse to `Vec`, compare with `==` to pick among views of one id | +| Schema | `summary_type` + `parameters` | `sketch.type` (Resource); the parameters are inside the ASAPv1 envelope (`sketch.size` ignored) | Decode the envelope, compare its parameters with the view's `parameters` | +| Schema | `tumbling_window_width_ms` | none; implied by the view | Check `end − start` = width and `end` a multiple of it | +| Schema | ASAPv1 format version | `sketch.schema_version` (Resource) | ≤ highest supported | +| Schema | stream identity (not planner) | `sketch.stream_id` (Resource, random 128-bit per collector start) | Key of the Dictionary cache below | +| Dictionary | `Scan.source.TimeSeries.metric` + the series' labels (the view's group key column `$promql_series_identity`) | metric name; Scope attributes (labels) and `sketch.series_id` | Intern once per `(stream_id, series_id)` into the store's series table | +| Record | the time part of the selection: this window `(end − w, end]` | point `sketch.window_start_ms` (exclusive), `sketch.window_end_ms` (inclusive), and the point times | The state's window key | +| Record | the view's `state` column | point `sketch.envelope` (ASAPv1 bytes), `count` | Stage, dedup, commit (§7) | + +How `view_coverage` itself splits: + +| `view_coverage` part | Example (q01) | Tier | Why | +|---|---|---|---| +| `definition_id` | `5597d603bdf9f1a148d7c7e5344c1a97` | Schema | Constant per view | +| `selection`, label boxes | `[{"columns": []}]` (no matcher); with `data{region="r0"}`: `region in ["r0"]` | Schema | Constant per view | +| `selection`, time interval | none on a chain's own coverage; each window is `(end − 5 s, end]` | Record | Differs per state | + +A chain view's stored `selection` carries no time column: its rows are +indexed by `window_end`, and the time part appears only on the `TimeRange` +above it. So the Record's window is exactly the time part the view's rows +add, in Prometheus's `(t − range, t]` form (§5). + +`definition_id` does not cover the parameters or the selection: the +planner computes it from the memo group's expression, which holds neither. +Checked on the benchmark plan: q01 with α 0.05 and with α 0.01 both give +`5597d603bdf9f1a148d7c7e5344c1a97`; `data{region="r0"}` moves the matcher +into `selection`. A view is therefore identified by `(definition_id, +selection)`, and its parameters are checked from the decoded state (open +question 11). + +As entities, with planner names (one stream may carry several views, and +the same labels under two views are two Dictionary entries, as in the +collector's data model): + +```mermaid +erDiagram + SKETCH_STREAM ||--o{ SCHEMA : schema + SCHEMA ||--o{ DICTIONARY : dictionary + DICTIONARY ||--o{ LABELS : labels + DICTIONARY ||--o{ RECORD : records + SKETCH_STREAM{ + stream_id string "random per collector start" + } + SCHEMA{ + definition_id string "view_coverage.definition_id" + selection json "view_coverage.selection, non-time part" + summary_type string "e.g. Sketch DDSketch" + parameters json "SketchParams, also inside the envelope" + tumbling_window_width_ms u64 + schema_version u32 "ASAPv1" + } + DICTIONARY{ + series_id u32 + definition_id string "references SCHEMA" + metric string "Scan source TimeSeries metric" + } + LABELS{ + series_id u32 "references DICTIONARY" + key string + value string + } + RECORD{ + series_id u32 "references DICTIONARY" + window_start_ms i64 "exclusive" + window_end_ms i64 "inclusive" + envelope bytes "ASAPv1 state" + count u64 + } +``` + +**Transport.** OTAP Arrow keeps the tiers on the wire: over one stream, +Schema and Dictionary are sent once and Records reference them. OTLP HTTP +flattens them: each request repeats the Resource (Schema) and Scope +(labels) above its points, so labels and Schema attributes travel once per +request and series rather than once per stream. The logical mapping above +is the same in both. + +*Recommendation: v1 accepts OTLP HTTP; an OTAP Arrow receiver follows.* +Every collector deployment exports with `urn:otel:exporter:otlp_http` +today, and the backend already serves `/v1/metrics`, so v1 needs no new +listener. Decoding OTAP Arrow with the collector's own crates +(`otel-arrow-dfe-pdata` and its engine crates) would bring `datafusion` +53 and `tonic` 0.14 next to the backend's `datafusion` 54 and `tonic` +0.12: two copies of each in the build. The Arrow receiver is the next +step, built on the `arrow-ipc` 58 and `tonic` the backend already has and +fed by the collector's `urn:otel:exporter:otap` (open question 13). With +OTLP the Dictionary saving is still had on the backend side: the adapter +interns each `(stream_id, series_id)` once and reuses the series id for +every later record. + +**Collector restart.** A restart starts a new stream: new `stream_id`, and +the collector's `series_id` counter starts again at 1. The backend never +reuses a translation across streams, so a reset counter cannot alias two +series; the new stream's Dictionary entries are interned again (to the +same backend series, since the labels are the same). Entries of a stream +not seen for the longest view retention are dropped. + +### 5. Window semantics: Prometheus's `(t − range, t]` Both sides use Prometheus's boundary (decision 4). Prometheus 3.x range selectors are left-open and right-closed. Its querying documentation @@ -189,7 +362,10 @@ right boundary of the range are included in the selection." Its 3.0 migration guide ("Range selectors and lookback exclude samples coinciding with the left boundary") records the change from the earlier left-closed form. OTLP's metrics data model uses the same interval for a delta point, -`(start, end]` ("The time interval is inclusive of the end time"). +`(start, end]` ("The time interval is inclusive of the end time"). The +planner's selection algebra writes PromQL `m[5m]` the same way: lower +`Excluded(EvaluationTimePlusMs(-300000))`, upper +`Included(EvaluationTimePlusMs(0))`. - **Backend: already matches.** `storage::store::window_end` puts a sample at `t` in the window ending at `⌈t / w⌉ · w`, so windows are `(e − w, e]`, and @@ -201,7 +377,7 @@ form. OTLP's metrics data model uses the same interval for a delta point, lies on a boundary, and the two sides put it in different windows, so a pushed view and a backend-built view of the same data differ. -The collector change, in its own repository and PR (step 5 of the plan): +The collector change: 1. A sample at `t` belongs to the window ending at `⌈t / w⌉ · w`; a window closes when a sample later than its end arrives (`t > end`, not `≥`), or @@ -212,47 +388,45 @@ The collector change, in its own repository and PR (step 5 of the plan): window is open, and is dropped and counted once it is closed. 3. `window_start_ms` is exclusive and `window_end_ms` inclusive, in the envelope, the `sketch.window_*_ms` attributes and the OTLP point times. -4. `matchers` (name, `=` or `!=`, value; `__name__` for the metric) in - `AsapSketchesUserConfig`, passed to `PrecomputeConfig::matchers`, which - the runtime already evaluates but the TOML does not expose. +4. Matchers (name, `=` or `!=`, value; `__name__` for the metric), passed + to `PrecomputeConfig::matchers`, which the runtime already evaluates; + with `planner_views` they come from the `Scan` predicates. -### 4. The sketch path in the data plane +### 6. The sketch path in the data plane `POST /v1/metrics` decodes the request once. Each summary data point that carries a `sketch.envelope` bytes attribute is a pushed state; every other point is a raw sample, as today. A request may carry both. -The adapter (`asap-sketch-otlp`) reads, per pushed state: - -| Field | Where on the wire | Check | -|---|---|---| -| `agg_id` | Resource attribute `sketch.agg_id` (int) | present | -| sketch type | Resource attribute `sketch.type` (`DDSketch`, `KLLSketch`, `HLLSketch`, `CountSketch`, `CountMinSketch`, `CountMinSketchWithHeap`) | known | -| schema version | Resource attribute `sketch.schema_version` | ≤ the highest supported | -| labels | Resource attributes, then Scope (`asap.series`) attributes, then point attributes, without any `sketch.*` key; `__name__` = metric name | the merge order the raw OTLP adapter uses | -| window | point attributes `sketch.window_start_ms`, `sketch.window_end_ms` | equal to the point's `start_time_unix_nano` / `time_unix_nano` in ms; `start < end` | -| state | point attribute `sketch.envelope` (bytes) | non-empty | -| sample count | point `count` | none | - -`sketch.series_id` is ignored: it is the collector's local counter and -restarts with it; the labels are the identity. `sketch.size` is ignored: the -parameters are checked from the decoded state. +The adapter (`asap-sketch-otlp`) reads, per pushed state, the fields of the +tier table in §4, and requires: `sketch.definition_id`, +`sketch.selection`, `sketch.stream_id` and `sketch.series_id` present; +`sketch.type` known; `sketch.schema_version` ≤ the highest supported; the +window attributes equal to the point's `start_time_unix_nano` / +`time_unix_nano` in ms with `start < end`; `sketch.envelope` non-empty. +Labels are Resource attributes, then Scope attributes, then point +attributes, without any `sketch.*` key, with `__name__` = metric name (the +raw OTLP adapter's merge order). The ingest engine then, per state: -1. **View.** Looks up `agg_id` in the `PushedViews` map. Unknown → rejected - (`reason="unknown_view"`). -2. **Window.** Requires `end − start` = the view's width and `end` a multiple - of it. Otherwise rejected (`reason="window"`). +1. **View.** Looks up the installed views with this `definition_id` and an + equal `selection`. None → rejected (`reason="unknown_view"`; for + example a collector still running a file from an earlier plan). +2. **Window.** Requires `end − start` = the view's + `tumbling_window_width_ms` and `end` a multiple of it. Otherwise + rejected (`reason="window"`). 3. **Parameters.** Decodes the ASAPv1 bytes with `storage`'s codec into the - view's kernel and compares the decoded sketch's parameters (DDSketch - `alpha`, KLL `k`, rows × columns, heap size, HLL precision, hash seed) - with the plan's, exactly (decision 5). A state that does not decode, or - decodes with other parameters, is rejected (`reason="decode"`, - `reason="params"`). -4. **Series.** Interns the label set into the store's series table, as the - raw path does, so the view row's `$promql_series_identity` is the same - canonical JSON a raw sample of that series gets. + view's kernel and compares the decoded parameters with the view's + `parameters`, exactly (decision 5). A matching id does not imply + matching parameters (§4), so this check is required, not a formality. + A state that does not decode, or decodes with other parameters, is + rejected (`reason="decode"`, `reason="params"`). +4. **Series.** Translates `(stream_id, series_id)` through the + per-stream Dictionary cache; on a miss, interns the record's label set + into the store's series table, as the raw path does, so the view row's + `$promql_series_identity` is the same canonical JSON a raw sample of + that series gets. 5. **Stage, dedup, commit.** See below. Every rejection increments @@ -260,7 +434,7 @@ Every rejection increments reason per minute; the request still returns 200 with the rejected count, as the raw OTLP route reports `rejected`. -### 5. Staging, deduplication, late states +### 7. Staging, deduplication, late states The view store appends a view's windows in order and each window once, and other refresh groups may read a pushed view (a wider level of its chain), so @@ -310,12 +484,17 @@ pub struct ViewStateBatch { /// One series' state of one pushed view in one window. #[derive(Debug, Clone, PartialEq)] pub struct PushedViewState { - /// The view, as the collector config encodes it (see `AggId`). - pub agg_id: AggId, + /// The view's `view_coverage.definition_id` (32 hex digits). + pub definition_id: String, + /// The view's `view_coverage.selection`, as the planner serializes it. + pub selection: Vec, /// Which sketch the bytes hold, as the record declares it. pub sketch: PushedSketch, /// ASAPv1 envelope bytes from `asap_sketchlib`: the full state. pub asapv1: Vec, + /// The collector stream and its series id: the Dictionary key. + pub stream_id: u128, + pub series_id: u32, /// The series' labels, `__name__` included. pub labels: LabelSet, /// The window `(start_ms, end_ms]`. @@ -324,14 +503,9 @@ pub struct PushedViewState { pub sample_count: u64, } -/// A pushed view's id on the wire: plan fingerprint (high 31 bits) and -/// node id (low 32 bits). -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct AggId(pub u64); - /// The sketches the collector builds. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum PushedSketch { DDSketch, Kll, Hll, CountSketch, CountMin, CountMinHeap } +pub enum PushedSketch { DDSketch, Kll, Hll, CountSketch, Cms, CmsWithHeap } /// What happened to a batch's states. #[derive(Debug, Clone, Default, PartialEq, Eq)] @@ -355,6 +529,9 @@ pub trait ViewStateIngest: Send + Sync { } ``` +`SelectionBox` is `asap_types::ir::properties::selection::SelectionBox`, +which `common` can already name. + `ViewStore::put`'s contract ("each key is put once and never rewritten") gains one exception, for late states: @@ -400,6 +577,8 @@ pub enum SketchOtlpError { UnknownSketchType(String), #[error("sketch.schema_version {0} is newer than supported")] SchemaVersion(u64), + #[error("sketch.selection is not a planner selection: {0}")] + Selection(String), #[error("window attributes ({start_ms}, {end_ms}] disagree with the point's times")] Window { start_ms: i64, end_ms: i64 }, } @@ -422,17 +601,16 @@ decoded by both and each point is read once. ### `crates/control-plane` ```rust -/// A leaf view the collector builds, and how. +/// The file the collector and the data plane load: each pushed view's +/// sub-DAG of the installed plan, in the planner's serde. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct PushedView { - pub node: PhysicalASAPNodeId, - pub agg_id: u64, - pub metric: String, - /// Label matchers: the metric name, then the Scan's predicates. - pub matchers: Vec, - pub sketch_type: &'static str, - pub sketch_params: BTreeMap<&'static str, f64>, - pub window_ms: u64, +#[serde(deny_unknown_fields)] +pub struct PushedViewsFile { + /// The installed plan's `wire_version`. + pub planner_wire_version: u32, + /// One per pushed view: its node, its `Scan` and the edge between + /// them; `roots = [view node]`. + pub views: Vec, } /// Why a leaf view is not pushed, for the command's report. @@ -446,137 +624,174 @@ pub enum NotPushed { FilterNotExpressible(String), } -/// The installed plan's pushed views, by the rule of this design, and why -/// each other leaf view is not pushed. -pub fn pushed_views(plan: &InstallablePlan) - -> (Vec, Vec<(PhysicalASAPNodeId, NotPushed)>); - -/// The collector TOML: one `asap_sketches` processor block per pushed view. -pub fn emit_collector_config(views: &[PushedView]) -> String; +/// The installed plan's pushed views, by the rule of this design, as +/// sub-DAGs, and why each other view is not pushed. +pub fn pushed_view_dags(plan: &InstallablePlan) + -> (PushedViewsFile, Vec<(PhysicalASAPNodeId, NotPushed)>); ``` -CLI: `control_plane --plan --emit-collector-config - --pushed-views ` reads a saved plan and -writes both files; the data plane takes `--pushed-views -`. +CLI: `control_plane --plan --emit-pushed-views +` reads a saved plan and writes the file; the data plane +takes `--pushed-views `. ## Worked example: q01 -The query, from the `smoke` workload: `quantile_over_time(0.99, data[1m])`, -evaluated every 5 s, 10 samples/s per series. The plan the control plane -selects has, for q01: +The query, from the benchmark set: `quantile_over_time(0.99, data[1m])`, +evaluated every 5 s, 10 samples/s per series, with a 5 % relative error +target. The plan the planner selects has, for q01: ```text -node 0 Scan data (ts, value, $promql_series_identity) -node 1 SummaryTumblingWindowChain DDSketch α 0.05, PerEntity, 5 000 ms tumbling, - (view, ingestion time, retention 120 s) filter none -node 2 TimeRange 60 s (query time) reads node 1's windows in (T − 60 s, T] -node 3 SummaryMerge (query time) merges them per series -node 4 SummaryEstimate q = 0.99 -node 5 Project (root) (ts, value, $promql_series_identity) +n0 Scan data (IngestionTime, None) shared with q02 and q03's chains +n1 SummaryTumblingWindowChain (IngestionTime, AcrossEvaluations) DDSketch α 0.05, PerEntity, 5 000 ms, retention 60 s +n2 TimeRange 60s (QueryTime) reads n1's windows in (T − 60 s, T] +n3 SummaryMerge (QueryTime) merges them per series +n4 SummaryEstimate Quantile(q=0.99) +n5 Project (root) ``` -Node 1 passes the rule: its child is a `Scan` of `data`, it is `PerEntity`, -tumbling at 5 s, DDSketch with α 0.05 maps to `relative_accuracy = 0.05`, -and it has no predicate or filter. The command writes the block below -(for illustration, a plan whose fingerprint truncates to `0x2acbeb01`, so -`agg_id` = `0x2acbeb01_00000001`): - -```toml -# Pushed view: node 1 (SummaryTumblingWindowChain DDSketch, alpha 0.05, -# PerEntity, 5000 ms tumbling) of the installed plan. -[[pipelines.metrics.processors]] -id = "asap_view_1" -plugin = "asap_sketches" - - [pipelines.metrics.processors.config] - sketch_type = "ddsketch" - window_size = "5s" - output_metric_name = "data" - agg_id = 3083816759392731137 - transmit_sketch = true - aggregate_by = [] - omit_resource_attrs = false - global_aggregation = false - emit_window_stats = false - # Requires the collector's matchers option (collector change, item 4). - matchers = [{ name = "__name__", op = "=", value = "data" }] - - [pipelines.metrics.processors.config.sketch_params] - relative_accuracy = 0.05 +n1 passes the rule. Its sub-DAG in `pushed-views.json` (schemas +shortened to their field names; the file carries them in full): + +```json +{"planner_wire_version": 15, "views": [{ + "nodes": [ + {"id": 0, + "payload": {"NonASAP": {"Scan": { + "source": {"TimeSeries": {"metric": "data"}}, + "predicates": [], + "schema": {"fields": ["ts", "value", "$promql_series_identity"], "...": "..."}}}}, + "output_state": {"timing": "ingestion_time", "primitive": "Raw"}, + "lifetime": "None", + "output_schema": {"...": "..."}}, + {"id": 1, + "payload": {"ASAP": {"SummaryTumblingWindowChain": { + "child": 0, + "summary_type": {"Sketch": "DDSketch"}, + "input": {"item": null, "weight": {"Column": "SampleValue"}}, + "reduction": "PerEntity", + "filter": null, + "tumbling_window_width_ms": 5000}}}, + "output_state": {"timing": "ingestion_time", "primitive": "SummaryState"}, + "lifetime": {"AcrossEvaluations": "Memory"}, + "parameters": {"DDSketch": {"alpha": 0.05}}, + "output_schema": {"fields": ["window_end", "state", "$promql_series_identity"], "...": "..."}, + "retention_ms": 60000, + "view_coverage": { + "definition_id": "5597d603bdf9f1a148d7c7e5344c1a97", + "selection": [{"columns": []}]}}], + "edges": [{"producer": 0, "consumer": 1, "role": "Input", + "intermediate_schema": {"...": "..."}, + "data_state": {"timing": "ingestion_time", "primitive": "Raw"}, + "grouping": "NotApplicable", "window": "NotApplicable"}], + "roots": [1], + "scalar_roots": []}]} ``` -and `pushed-views.json`: +The collector maps it to: DDSketch with `relative_accuracy = 0.05`, 5 s +tumbling windows `(e − 5 s, e]`, matcher `__name__ = "data"`, one state per +series. Its pipeline config names only the file: -```json -[{"node": 1, "agg_id": 3083816759392731137, "metric": "data", - "matchers": [{"name": "__name__", "op": "=", "value": "data"}], - "sketch_type": "ddsketch", "sketch_params": {"relative_accuracy": 0.05}, - "window_ms": 5000}] +```yaml +sketch: + type: urn:asap:processor:asap_sketches + config: + planner_views: /etc/asap/pushed-views.json ``` For one series `data{region="r0",service="s0",job="j0",label_0="l0"}`, the collector folds the 50 samples with timestamps in `(T − 5 s, T]` into one -DDSketch and exports one summary point: Resource `sketch.agg_id = -3083816759392731137`, `sketch.type = "DDSketch"`; Scope `asap.series` with -the four labels; metric `data`; point `sketch.window_start_ms = T − 5000`, -`sketch.window_end_ms = T`, `sketch.envelope = `, `count = 50`. - -The backend keeps exactly what its own precompute keeps for node 1: per -series, one DDSketch state per 5 s window, for the view's 120 s retention -(24 windows). At evaluation time `T` (a multiple of 5 s), q01 runs at query -time as before: node 2 selects the 12 windows ending in `(T − 60 s, T]`, -node 3 merges the 12 states of each series into one, and node 4 reads the -0.99 quantile. That merge chain, the result cache and the fallback do not -change. The backend no longer runs node 1, and `data`'s raw samples still -arrive because node 6 (`max_over_time(data[30s])`) reads them. +DDSketch and exports one summary point: + +| Where | Attribute | Value | +|---|---|---| +| Resource (Schema) | `sketch.definition_id` | `"5597d603bdf9f1a148d7c7e5344c1a97"` | +| Resource (Schema) | `sketch.selection` | `"[{\"columns\":[]}]"` | +| Resource (Schema) | `sketch.type` | `"DDSketch"` | +| Resource (Schema) | `sketch.schema_version` | `1` | +| Resource (Schema) | `sketch.stream_id` | `"9b1e…"` (random at collector start) | +| Scope (Dictionary) | `sketch.series_id` | `17` | +| Scope (Dictionary) | labels | `region="r0"`, `service="s0"`, `job="j0"`, `label_0="l0"` | +| Metric | name | `data` | +| Point (Record) | `sketch.window_start_ms` | `T − 5000` (exclusive) | +| Point (Record) | `sketch.window_end_ms` | `T` (inclusive) | +| Point (Record) | `sketch.envelope` | ASAPv1 bytes | +| Point (Record) | `count` | `50` | + +The backend finds n1 by `definition_id` and selection, checks that the +window is 5 s wide and ends on a multiple of 5 s, decodes the envelope and +checks α = 0.05, translates `(stream_id, 17)` to its series id, and stages +the state. It keeps exactly what its own precompute keeps for n1: per +series, one DDSketch state per 5 s window, for the view's 60 s retention +(12 windows). At evaluation time `T` (a multiple of 5 s), q01 runs at query +time as before: n2 selects the 12 windows ending in `(T − 60 s, T]`, n3 +merges the 12 states of each series into one, and n4 reads the 0.99 +quantile. That chain, the result cache and the fallback do not change. The +backend no longer runs n1, and `data`'s raw samples still arrive because +the `Scan` n0 also feeds q02's and q03's chains. ## The benchmark queries -The five dashboard queries (`smoke` widths; q05 is q01 as a range panel): +All five are evaluated every 5 s over 1 m ranges; the planner builds each +one's leaf as a 5 s tumbling chain over its `Scan`: -| Query | Leaf view | Pushed | Why | +| Query | Leaf view (summary type, reduction) | Pushed | Why | |---|---|---|---| -| q01 `quantile_over_time(0.99, data[1m])` | DDSketch α 0.05, per series, 5 s tumbling, on `Scan data` | yes | passes every rule | -| q02 `topk(10, sum by (region, service, job) (rate(data_total[1m])))` | `ExactAggregate Rate`, per series, 5 s tumbling | no | exact counter state: the collector builds none | -| q03 `max_over_time(data[30s])` | `ExactAggregate Max`, per series, 5 s tumbling | no | exact aggregate: the collector builds none | -| q04 `sum by (region, service) (increase(data_total[1m]))` | `ExactAggregate Increase`, per series, 5 s tumbling | no | exact counter state | -| q05 q01 as a range panel (60 s span, 5 s step) | the same view as q01 | yes | shares q01's leaf; earlier steps come from the result cache | +| q01 `quantile_over_time(0.99, data[1m])` | `Sketch: DDSketch` α 0.05, `PerEntity` | yes | passes every rule | +| q02 `max_over_time(data[1m])` | `ExactAggregate: Max`, `PerEntity` | no | exact aggregate: the collector builds none | +| q03 `sum_over_time(data[1m])` | `ExactAggregate: Sum`, `PerEntity` | no | exact aggregate | +| q04 `rate(data_total[1m])` | `ExactAggregate: Counter`, `PerEntity` | no | exact counter state | +| q05 `sum by (region, service) (sum_over_time(data[1m]))` | `ExactAggregate: Sum`, `PerEntity`; the `sum by` runs at query time | no | exact aggregate | So for this workload the collector builds one view, the backend still builds -three, and both metrics' raw samples still reach the backend. Step 4 -measures what that saves; a workload whose metric is read only by pushed -views saves the raw samples too. +four, and both metrics' raw samples still reach the backend. Step 4 of the +plan measures what that saves; a workload whose metric is read only by +pushed views saves the raw samples too. ## Plan -Separate PRs, each reviewed on its own: +Separate PRs, each reviewed on its own. + +Backend: 1. This document. 2. `ViewStateBatch` and `ViewStateIngest` in `common`; the - `asap-sketch-otlp` adapter; the `/v1/metrics` split; staging, dedup, + `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by + `definition_id` and selection, the Dictionary cache, staging, dedup, late merge and `ViewStore::merge_late_rows`. Test data: real ASAPv1 records the collector emits (captured OTLP bodies, checked in with the collector commit that wrote them), for each of the six sketch types, - including one with mismatched parameters, one duplicate and one late - state. -3. The control plane's push-down rule, `--emit-collector-config` and - `--pushed-views`; the precompute engine skips pushed views. Tests: the - `smoke` plan emits exactly the q01 block above; a plan with a regex - matcher, a `Reduce` leaf or a sliding window pushes nothing. + including one with mismatched parameters, one unknown id, one duplicate, + one late state and one restart (new `stream_id`, reused `series_id`). +3. The control plane's push-down rule and `--emit-pushed-views`; the data + plane's `--pushed-views`; the precompute engine skips pushed views. + Tests: the benchmark plan pushes exactly q01's sub-DAG above; a plan + with a regex matcher, a `Reduce` leaf or an `ExactAggregate` leaf pushes + nothing; the written file deserializes into `PhysicalASAPDAG`s that + pass the planner's `validate`. 4. End-to-end comparison, collector + backend against backend only, on the same feed: answers equal (exact views) or within the plan's error (sketch views) at every evaluation; backend ingest CPU, network bytes between collector and backend, and collector CPU; including a sparse series case for the limitation above. -5. In the collector repository: the window boundary and filter change - (algorithm step 3). It lands before step 4, which needs equal windows. + +Collector (ASAPCollector-public): + +5. `asap-types` as a pinned git dependency (same rev as the backend's + planner pin); the `planner_views` loader with the shape check and the + mapping table; config errors for the per-sketch fields when it is set. +6. Stamping: `sketch.definition_id`, `sketch.selection` and + `sketch.stream_id` on the Resource, replacing `sketch.agg_id`; + `series_id` per (view, series). +7. The window boundary `(e − w, e]`, placement by sample timestamp with + drop-and-count after close, and matchers (§5). It lands before step 4, + which needs equal windows. ## Decisions 1. **ASAPPlanner does not change.** Which views the collector builds is a deployment decision the backend's control plane makes on the installed - plan; the plan and its `InstallablePlan` format are unchanged. + plan; the plan and its `InstallablePlan` format are unchanged. The + planner already exports the types and ids the collector reads. 2. **The collector is ASAPCollector-public (OTAP), sending full ASAPv1 states.** No deltas: each record holds the whole state of one series in one window. @@ -596,9 +811,119 @@ Separate PRs, each reviewed on its own: 6. **Rule-based push-down first**: a view is pushed iff its leaf reads raw input directly, is per series, uses a tumbling window, its sketch type and parameters are among the collector's (DDSketch, KLL, HLL, - CountSketch, Count-Min, Count-Min-heap), and its filter is expressible in - the collector's configuration. No cost comparison. Exact aggregates stay - in the backend, since the collector builds none. Cost-based push-down is - future work and needs a general planner capability. -7. **`agg_id` is the view id**, and the backend's precompute skips pushed - views. + CountSketch, Count-Min, Count-Min-heap), and its filter is expressible + by the collector's matchers. No cost comparison. Exact aggregates stay + in the backend, since the collector builds none. Cost-based push-down + is future work and needs a general planner capability. +7. **The collector receives the planner's own view definitions.** The + control plane sends each pushed view's sub-DAG of the installed plan, + serialized with the planner's serde; the collector depends on the + planner's types crate, pinned. Every emitted state carries the view's + `view_coverage.definition_id` (with its selection) and its window, and + the backend matches it against the installed plan's views. This + replaces a numeric `agg_id` and a hand-written collector config. The + backend's precompute skips pushed views. + +## Open questions + +Each with a recommendation. + +1. **Dedup vs. merge of a second state for the same (view, series, + window).** *Recommend:* §7's reading: a byte-identical state is a + duplicate and ignored; a state with other bytes is merged (collector + restart mid-window, two collectors with parts of one series). The + alternative, "any second state is ignored", is simpler but loses data + on a restart. +2. **How the collector encodes the window.** *Recommend:* `(start, end]` + in the envelope, the attributes and the point times after the collector + change; the adapter requires the three to agree and the width and + alignment to match the view, and rejects and counts anything else. +3. **Clock skew and commit time.** *Recommend:* commit on the backend's + wall clock at `end + push_grace_ms` (default 10 s); treat later states + as late (merge within retention); export a per-view histogram of + arrival delay. Hosts are assumed to run NTP. +4. **Result cache after a late merge.** *Recommend:* drop cached answers + whose evaluation range covers the merged window. The alternative is not + to cache answers whose newest window is still inside the grace period. +5. **sketchlib versions differ.** The collector pins `asap_sketchlib` + `60101c6`, the backend `355093f`, and the planner `389530c`; the + collector's HLL is an Ertl HLL, the backend's kernel Classic. + *Recommend:* PR 2's captured records are the compatibility test, one per + sketch type. Until the pins agree, leave HLL off the pushable list if + its envelope does not decode into the backend kernel. +6. **Selective raw forwarding.** A metric whose views are all pushed need + not reach the backend raw. *Recommend:* the pushed-views file later also + lists the metrics the backend still reads raw (a `Scan` not only under + pushed views); in v1 the collector keeps forwarding everything. +7. **Out-of-order samples in the collector.** *Recommend:* include the fix + in the collector's window PR: place each sample by its own timestamp, + and drop and count it once its window has closed. +8. **Planner types pin and compatibility between collector and backend.** + Both read the same JSON; the types are `deny_unknown_fields` and the + plan carries `wire_version` (15 today). *Recommend:* the collector pins + the same ASAPPlanner rev as the backend's `asap-planner` pin and is + bumped in the same change; the loader refuses a file whose + `planner_wire_version` differs from its own, so a mismatch fails at + start, not as wrong states. +9. **Serde stability of the planner types.** The plan-file format is the + planner's own and versioned by `INSTALLABLE_PLAN_WIRE_VERSION`; there is + no promise across versions. *Recommend:* rely on it only between equal + wire versions (question 8); PR 3 checks in the benchmark's + `pushed-views.json` and tests that it deserializes and validates, so a + planner bump that changes the format shows up as a failing test. +10. **Plan reinstall.** Unchanged views keep their `definition_id`. + *Recommend:* the control plane rewrites the file and the collector + restarts on every reinstall; states of unchanged views keep matching + across it, states of removed views are rejected as `unknown_view` until + the restart, and new views are `NotReady` (forwarded) until the + collector builds them. A live reload is later work. +11. **`definition_id` does not cover parameters or selection.** Verified on + the benchmark plan: α 0.05 and α 0.01 give the same id, and a label + matcher moves into `selection`. *Recommend:* identify a pushed view by + `(definition_id, selection)`, sent once per Resource, and check the + parameters from the decoded state (§6 step 3). If one plan ever holds + two views with equal id and selection but different parameters, the + decoded parameters pick the view; the control plane reports such a + plan. +12. **Dependency weight on the collector build.** `asap-types` adds + `serde_json`, `thiserror` 2 and a second `asap_sketchlib` rev (the + planner's) to the collector; it brings no executor, frontend or solver. + *Recommend:* accept it; it disappears with question 5's single + sketchlib pin. Measure the collector's clean build time before and + after in PR 5. +13. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP + HTTP (every collector deployment exports `otlp_http` today; the backend + already serves `/v1/metrics`; the Dictionary saving is recovered by the + `(stream_id, series_id)` cache). Next, an OTAP Arrow receiver fed by + `urn:otel:exporter:otap`, decoding with the `arrow-ipc` and `tonic` + the backend already builds, rather than the collector's + `otel-arrow-dfe-*` crates, which would add a second `datafusion` (53 + next to 54) and `tonic` (0.14 next to 0.12). +14. **Stream identity on OTLP.** OTLP HTTP has no stream, so the Dictionary + key needs one. *Recommend:* `sketch.stream_id`, a random 128-bit value + the collector draws at start and puts on every Resource; on OTAP Arrow + the gRPC stream is the stream. A restart is a new stream, which + replaces the earlier concern that `sketch.series_id` resets on restart. +15. **Reading `definition_id` from outside the planner.** In the planner's + types, `ViewCoverage`'s fields are crate-private and its + `definition_id()` accessor exists only under the `test-support` + feature; edges likewise have no public constructor outside it. Serde + reads and writes all of them. *Minimal need:* a public read of a plan + node's view coverage id and selection from a deserialized plan. + *Recommend:* until the planner offers one, both sides read the two + values from the node's JSON (`view_coverage.definition_id`, + `view_coverage.selection`), and the control plane builds a sub-DAG by + filtering the installed DAG's `nodes` and cloning its `edges`, which + the public fields allow; neither enables `test-support` in production. +16. **Sub-DAG validity.** No planner function extracts a sub-DAG. + *Minimal need:* that a two-node DAG copied from an installed plan, with + `roots = [view]`, passes `PhysicalASAPDAG::validate`. *Recommend:* the + collector's loader calls `validate` on each sub-DAG and PR 3 tests it + on the benchmark plan; if `validate` refuses such a DAG, the loader + keeps only its own shape check and the need is filed against the + planner in planner terms. +17. **One processor for all views, or one per view.** *Recommend:* one + `asap_sketches` node that builds every view in the file, so the + pipeline YAML never changes with the plan; the processor keys state by + (view, series), as the collector's data model already allows several + Schemas on one stream. From 09194a609d2cfc497b263cbee0359b5251b8de94 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 16:33:36 +0000 Subject: [PATCH 03/21] docs(design): key pushed states by the planner's view state key Identity is the planner's ViewStateKey plus concrete selection; the pushed-views file carries plan_id, backend_reads_raw and commit_grace_ms. The collector declares its capabilities and the control plane's rule reads them. ViewStateBatch is nested by OTAP tier, the window travels as OTLP point times, PushedSketch is gone. v1 drops late states instead of merging them; dedup keeps a hash set per window until commit. --- docs/design/collector-sketch-ingest.md | 1131 +++++++++++------------- 1 file changed, 527 insertions(+), 604 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index f7868b3a8..1aba0be6c 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -16,32 +16,38 @@ application) sends OTLP or Remote Write, and the backend's precompute builds every view. A leaf view such as "a DDSketch per series per 5 s tumbling window" folds the samples of one series and one window into one state, and the collector can build exactly that state before the network. For a series -sampled at 10 Hz, 50 samples become one state. +sampled at 10 Hz, 50 samples become one state. When no other reader needs a +metric's raw samples, the collector stops sending them to the backend. The collector is told what to build in the planner's own terms: for each pushed view the control plane sends the view's sub-DAG of the installed -ASAPPlanner plan (`Scan` → `SummaryTumblingWindowChain`, with schema, -summary type, parameters and window), and the collector depends on -ASAPPlanner's types crate to read it. Every state the collector emits -carries the view's planner content id, so the backend finds the view by -design rather than by a number both sides agree on. +ASAPPlanner plan, and the collector depends on ASAPPlanner's types crate to +read it. Every state carries the planner's **view state key**, so the backend +finds the view by what the state is, not by a number both sides agree on. Terms, as in ASAPPlanner (`asap-types`): - **Plan**: the `InstallablePlan` the control plane writes: `wire_version`, `dag: PhysicalASAPDAG` (`nodes`, `edges`, `roots`, `scalar_roots`) and - `query_texts`. -- **View**: a materialized node of the plan: a `PhysicalASAPDAGNode` whose - `lifetime` is `AcrossEvaluations`, with `retention_ms` and - `view_coverage` set. -- **View coverage**: `view_coverage` = `{definition_id, selection}`. - `definition_id` is the plan-scope content id of what the view computes - (the 128-bit FNV-1a hash, in hex, of the expanded definition), equal - across plans, processes and restarts for the same computation. - `selection` is the rows that went in: the label matchers lifted out of - the `Scan`, and, for a range over a chain, the time interval. -- **Parameters**: the node's `parameters: SketchParams` (θ), for example - `{"DDSketch": {"alpha": 0.05}}`. Not part of `definition_id` (below). + `query_texts`. **Plan id**: `PhysicalASAPDAG::plan_id()`, a content hash + of the DAG (equal DAGs, equal ids). +- **View**: a materialized node of the plan, as `PhysicalASAPDAG::materialized_views()` + returns it (`MaterializedView`). Within one installed plan a view is + `(plan_id, node_id)`. +- **View state key**: `MaterializedView::view_state_key()`, what the + view's stored state is: + + ```rust + pub struct ViewStateKey { + pub definition_id: String, // what is computed (view_coverage.definition_id) + pub window: Option, // ViewWindow::Tumbling { width_ms } for a chain + pub logical_properties: LogicalProperties, // θ, e.g. {"parameters": {"DDSketch": {"alpha": 0.05}}} + } + ``` + + Two views with equal key and equal concrete selection (the rows that went + in: `view_coverage.selection`) hold the same state, in any plan. Refresh + mode, retention and storage medium are not in the key. - **Leaf view**: a view whose child is a raw `Scan`. - **Sub-DAG**: a leaf view's node, its `Scan` node and the edge between them, as a `PhysicalASAPDAG` with `roots = [view node]`. @@ -54,49 +60,48 @@ Terms, as in ASAPPlanner (`asap-types`): Scope: -- ASAPPlanner does not change. It already exports what this design needs: - the plan's serde types (`PhysicalASAPDAG`, `PhysicalASAPDAGNode`, - `PhysicalASAPDAGEdge`, `ViewCoverage`, `SketchParams`), the content id - on each view, the view's parameters, window width, schema and retention. - Where a public read path is missing, it is listed as an open question - with the minimal need, not as a planner change. -- The backend changes in four places: a new ingest adapter, a new `common` - type, the view store's write path, and the control plane. -- The collector changes in its own repository: a dependency on the - planner's types crate, a sub-DAG loader, id stamping, and the - window-boundary, out-of-order and matcher fixes. +- The design needs the planner's view state key and plan id, which the + planner is adding; implementation starts after they merge. It needs no + other planner change. +- The backend changes in four places: a new ingest adapter, new `common` + types, the pushed-state ingest in precompute, and the control plane. +- The collector changes in its own repository: a capabilities command, the + `asap-types` dependency and a sub-DAG loader, key stamping, the + window-boundary, out-of-order and matcher fixes, and a raw-forward filter. ## Components ```text - ┌──────────────────────────── collector ────────────────────────────┐ - application ── OTLP ──▶ │ receiver ─┬─▶ asap_sketches (planner_views) ─────▶ OTLP exporter │──┐ sketch path - │ └─▶ raw forward ───────────────────────▶ OTLP exporter │──┤ raw path - └───────────────────────────────────────────────────────────────────┘ │ - ▲ pushed-views.json (planner sub-DAGs) │ - │ ▼ - workload ─▶ control-plane ─▶ InstallablePlan ────┼──────────────▶ data-plane POST /v1/metrics - │ (asap-planner, unchanged) │ ├─ record without sketch.envelope ─▶ otlp ─▶ IngestEngine (raw path) - └─ pushed_view_dags ────────────────┘ └─ record with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch - (same file) ──────────────────────▶ data-plane ─▶ precompute committer ─▶ storage (view store, persistence) + ┌───────────────────────────────── collector ─────────────────────────────────┐ + application ─ OTLP ─▶│ receiver ─┬─▶ asap_sketches (planner_views) ───────────────────▶ OTLP exporter│─┐ sketch path + │ └─▶ raw forward (drops metrics with backend_reads_raw = false) ─▶ ...│─┤ raw path + └─────────────────────────────────────────────────────────────────────────────┘ │ + asap_sketches --print-capabilities ─▶ capabilities.json ▲ pushed-views.json │ + │ │ ▼ + workload ─▶ control-plane ─▶ InstallablePlan ─┼──────────────────────┼──────▶ data-plane POST /v1/metrics + │ (asap-planner) ▼ │ ├─ point without sketch.envelope ─▶ otlp ─▶ IngestEngine + └─ push-down rule (reads capabilities.json) ────────────┘ └─ point with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch + (same pushed-views.json) ───────────────────────────────▶ data-plane ─▶ ViewStateIngest ─▶ precompute committer ─▶ view store ``` | Component | Crate or repository | Role | |---|---|---| -| Push-down rule | `crates/control-plane` | Picks the pushable leaf views of the installed plan (rule below) | -| Sub-DAG extraction | `crates/control-plane` (`control_plane --emit-pushed-views`) | Writes `pushed-views.json`: each pushed view's sub-DAG, serialized with the planner's own serde | -| `asap_sketches` processor | ASAPCollector-public | Loads `pushed-views.json` at start, builds each view's per-series states over tumbling windows, and exports OTLP summary points carrying `sketch.envelope` and `sketch.definition_id` | -| `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Decodes those OTLP records into a `common::ViewStateBatch`; never reads the sketch bytes | -| `ViewStateBatch` | `crates/common` (new type) | Pushed states between the adapter and the ingest engine | -| `/v1/metrics` route | `crates/data-plane` | One route for both paths: a data point with `sketch.envelope` goes to the sketch path, any other to the raw path | -| Pushed-state ingest | `crates/precompute` | Finds the view by `definition_id` and selection, checks the state against the plan, stages it until the window commits, deduplicates, merges late states | -| Late-state merge | `crates/storage` | Replaces a committed window's rows with merged rows and persists them | - -The raw path stays (decision 3). The raw samples of a metric still go to the -backend when a view that is not pushed reads that metric, when a query-time -`Scan` reads it, and for the fallback: when a pushed view misses a window -(the collector was down), the query engine reports `NotReady` and the -dispatcher forwards the query, as for any view that is not ready. +| Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares what the collector can build (§1) | +| Push-down rule | `crates/control-plane` | Picks the pushable leaf views of the installed plan against the capabilities; the only copy of the rule | +| Pushed-views file | `crates/control-plane` (`--emit-pushed-views`) | Each pushed view's sub-DAG, the plan id, which metrics the backend still reads raw, the commit grace | +| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, builds each view's per-series states, stamps the view state key, exports OTLP summary points with `sketch.envelope` | +| Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | +| `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Turns those points into `common::ViewStateBatch`es; never reads the sketch bytes | +| Pushed-state ingest | `crates/precompute` | Finds the view by key and selection, stages, deduplicates and merges until commit, drops late states | + +**Raw path.** The raw path stays (decision 3) for every metric the backend +still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` +of it feeds a view that is not pushed or runs at query time. A metric whose +only readers are pushed views is marked `false`, and the collector's raw +forward to the backend drops it. When a pushed view misses a window (the +collector was down), the query engine reports `NotReady` and the dispatcher +forwards the query to the fallback store, which receives raw samples on its +own path, not through this forward. ### Dependencies @@ -111,245 +116,201 @@ control-plane unchanged dependencies (asap-planner, common) ASAPCollector-public + asap-types (ASAPPlanner's types crate), pinned git rev ``` -The adapter does not decode ASAPv1: it hands the bytes on. Decoding needs -the executor's kernels, and `storage` already rebuilds every kernel from -ASAPv1 for persistence (`decode_sketch`), so the ingest engine reuses that. +The adapter does not decode ASAPv1. The ingest engine decodes each state +into the view's kernel with `storage`'s `decode_sketch`, because the store +holds engine-native states and a second state of one window is merged. +Decoding is not an identity check: θ is already in the key. `asap-types` brings `serde`, `serde_json`, `thiserror` 2 and -`asap_sketchlib` (for `SketchAlgorithm`) into the collector build; no -executor, frontend or solver (open question 12). +`asap_sketchlib` into the collector build; no executor, frontend or solver +(open question 4). ## Algorithm -### 1. Push-down rule (control plane) +### 1. Capabilities and the push-down rule (control plane) -The first version is rule based, with no cost comparison (decision 6). A -node of the installed plan's `dag` is pushed if and only if all of these -hold, read from its planner fields: +The collector declares what it can build; the backend holds no table of the +collector's sketches. `asap_sketches --print-capabilities` prints, for +today's collector (planner names; the collector maps them to its own): -1. **View at ingestion.** `lifetime` is `AcrossEvaluations`, - `output_state.timing` is `ingestion_time`, and `view_coverage` is set. +```json +{"capabilities_version": 1, + "summaries": [ + {"summary_type": {"Sketch": "DDSketch"}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, + {"summary_type": {"Sketch": "Kll"}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, + {"summary_type": {"Sketch": "Hll"}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, + {"summary_type": {"Sketch": "CountSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary_type": {"Sketch": "Cms"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary_type": {"Sketch": "CmsWithHeap"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}], + "reductions": ["PerEntity"], + "windows": ["Tumbling"], + "predicate_ops": ["Eq", "Ne"], + "window_close_delay_ms": 6000} +``` + +- `input: "value"`: the summary's `input` is `{"item": null, "weight": + {"Column": "SampleValue"}}`. `input: "label"`: `item` is one label column. +- `predicate_ops`: `Compare` of a label column with a `Utf8` literal (PromQL + `=`, `!=`); regular expressions are not supported. +- `window_close_delay_ms`: the longest time after a window's end before the + collector emits it: the 5 s idle-close grace plus the 1 s timer period. +- The ranges are the ones the collector's config validation enforces; the + command prints them from that code, so the two cannot drift. + +The control plane reads the file with `--collector-capabilities ` +and refuses a `capabilities_version` it does not know. A node of the +installed plan's `dag` is pushed if and only if all of these hold, read +from its planner fields (no cost comparison, +decision 6): + +1. **View at ingestion.** It is a `MaterializedView`, refreshed at + ingestion (`output_state.timing` is `ingestion_time`). 2. **Leaf on raw input.** `payload` is `ASAP.SummaryTumblingWindowChain` - whose `child` is a node with payload `NonASAP.Scan` and `source` - `TimeSeries { metric }`, with no node in between. -3. **Per series.** `reduction` is `PerEntity`: one state per series and - window. A `Reduce [...]` view is not pushed, because one collector does - not see every series of a group. -4. **Tumbling window.** `tumbling_window_width_ms` is set; it becomes the - collector's window. -5. **Supported sketch and parameters.** `summary_type` is - `{"Sketch": }` and `parameters` the matching `SketchParams`, - both in the collector's table: - - | `summary_type` | `parameters` | collector sketch | collector parameters | - |---|---|---|---| - | `{"Sketch": "DDSketch"}` | `DDSketch { alpha }` | `ddsketch` | `relative_accuracy = alpha` | - | `{"Sketch": "Kll"}` | `Kll { k }` | `kll` | `k` | - | `{"Sketch": "Hll"}` | `Hll { precision: 14 }` only | `hll` | none (fixed at 14) | - | `{"Sketch": "CountSketch"}` | `CountSketch { width, depth }` | `countsketch` | `width`, `depth` | - | `{"Sketch": "Cms"}` | `Cms { width, depth }` | `countminsketch` | `width`, `depth` | - | `{"Sketch": "CmsWithHeap"}` | `CmsWithHeap { width, depth, heap_size }` | `countminsketch_heap` | `columns = width`, `rows = depth`, `k = heap_size` | - - The `input` must match what the collector inserts: DDSketch and KLL - insert each sample's value (`input` is `{"item": null, "weight": - {"Column": "SampleValue"}}`); the frequency and cardinality sketches - insert a key and are pushed only when the item is a label the collector - keys by. Any other summary (`ExactAggregate`, UnivMon, Hydra, KMV, an - HLL of another precision) is not pushed. -6. **Expressible filter.** The chain's `filter` is `null`, and the `Scan`'s - `predicates` are a conjunction of `Compare` nodes with `op` `Eq` or `Ne` - between a label column and a `Utf8` literal (PromQL `=`, `!=`), which - the collector's `LabelMatcher` evaluates. A regular-expression matcher - is not pushed. - -**Exact aggregates stay in the backend.** The collector's `asap_sketches` -processor builds only the six sketches above. Its `Exact` type (`EXv1`, -the exact baseline window holding every value) is a baseline for -comparisons, not a `sum`, `max` or counter state. Views of `ExactAggregate` -(`Sum`, `Max`, `Min`, `Counter`, …) are therefore not pushed. They become -pushable when the collector builds those states, with counter-reset -handling for `Counter`. - -**Known limitation: sparse series.** The rule ignores size. A series with few -samples per window can produce a sketch state larger than its raw samples -(a DDSketch with one sample still carries its header, mapping and bins, + whose `child` is a `NonASAP.Scan` of `TimeSeries { metric }`, with no + node in between, and the chain's `filter` is `null`. +3. **Within the capabilities.** `summary_type`, `input` and every + `parameters` value match one `summaries` entry; `reduction` is in + `reductions` (`PerEntity`: a `Reduce [...]` view is not pushed, because + one collector does not see every series of a group); the window kind is + in `windows`; the `Scan`'s `predicates` are a conjunction of + `predicate_ops` comparisons. + +**Exact aggregates stay in the backend.** The collector's `Exact` type +(`EXv1`, every value of a window) is a baseline for comparisons, not a +`sum`, `max` or counter state, and it is not in the capabilities. Views of +`ExactAggregate` become pushable when the collector declares them. + +**Known limitation: sparse series.** The rule ignores size. A series with +few samples per window can produce a state larger than its raw samples (a +DDSketch with one sample still carries its header, mapping and bins, against about 16 bytes for the raw sample). Step 4 of the plan measures -where this happens. Push-down that compares costs is future work; it needs -a general planner capability (costing where a view is built), to be -discussed later. +where this happens. Cost-based push-down is future work; it needs a general +planner capability (costing where a view is built). -### 2. Sub-DAG extraction and the pushed-views file (control plane) +### 2. The pushed-views file (control plane) -For each pushed view the control plane copies, from the installed -`dag`, the view node and its `Scan` node (both unchanged, node ids -included) and the one edge between them, and sets `roots = [view node]`, -`scalar_roots = []`. Nothing is re-derived or renamed: the collector reads -the same values the backend's precompute would compile. - -It writes them to one JSON file, serialized with the planner types' own -serde: +For each pushed view the control plane copies, from the installed `dag`, +the view node and its `Scan` node (unchanged, node ids included) and the +one edge between them, and sets `roots = [view node]`, `scalar_roots = +[]`. It writes one JSON file, with the planner types' own serde: ```json -{"planner_wire_version": 15, "views": [, ...]} +{"planner_wire_version": 15, + "plan_id": "", + "commit_grace_ms": 8000, + "backend_reads_raw": {"data": true, "data_total": true}, + "views": [, ...]} ``` -`planner_wire_version` is the plan's `wire_version`. The collector loads -the file once at start (recommended over a control endpoint: one file, no -new protocol, and a plan change is a collector restart anyway, below). The -data plane takes the same file with `--pushed-views`; it does not change -the `InstallablePlan`. - -The precompute engine skips the pushed views: at install it compiles each -refresh group without the pushed leaf views (and without a `Scan` only they -read). The query engine is unchanged; it reads a pushed view from the store -like any other. - -**Plan reinstall.** A view whose computation did not change keeps its -`definition_id`, so its states keep matching across a reinstall even if its -node id changes. The control plane writes a new file; the collector picks -it up on restart. Until then, states of views the new plan no longer has -are rejected as `unknown_view`, and the views the new plan adds are built -by the collector only after its restart (the backend reports them -`NotReady` meanwhile, and the dispatcher forwards those queries). +- `backend_reads_raw` lists every metric a `Scan` of the plan reads. +- `commit_grace_ms` is computed as in §6. + +The collector loads the file once at start (a plan change is a collector +restart, open question 3). The data plane takes the same file with +`--pushed-views` and refuses it, at start and on each install, when its +`plan_id` differs from the installed plan's. The precompute engine then +compiles each refresh group without the pushed views (and without a `Scan` +only they read). The query engine is unchanged; it reads a pushed view +from the store like any other. ### 3. The collector: load, check, build, stamp At start, with `planner_views: ` in its processor config, the `asap_sketches` processor: -1. **Loads** the file with `serde_json` into the planner types. A - `planner_wire_version` other than the one its pinned `asap-types` - writes is a load error. -2. **Checks each sub-DAG's shape** and refuses to start, naming the view's - `definition_id` and the first failing field, unless the sub-DAG is - exactly: two nodes, one `Input` edge, root = the - `SummaryTumblingWindowChain`, child a `Scan` of `TimeSeries { metric }`, - `reduction` `PerEntity`, `filter` `null`, a summary type and parameters - from the table in step 1, `Scan` predicates only label `Eq`/`Ne` - against a string, and `view_coverage` present. These are the push-down - rule's conditions; the collector checks them again so a hand-edited or - stale file fails at load rather than producing wrong states. -3. **Maps** each view to its internal window state: sketch and parameters - from the table (an out-of-range value is a load error, never replaced - by a default), window = `tumbling_window_width_ms`, matchers = - `__name__ = metric` plus each `Scan` predicate, one state per series - with every label in the key. -4. **Stamps** every emitted state with the view's `definition_id` and - `selection` and the window (attribute names in §4). +1. **Loads** the file into the planner types. A `planner_wire_version` + other than its pinned `asap-types` writes is a load error. +2. **Checks that it can execute each sub-DAG**, and refuses to start, + naming the view and the first failing field, unless: it is two nodes and + one `Input` edge, root a `SummaryTumblingWindowChain` over a `Scan` of + `TimeSeries { metric }`, and its summary, parameters, reduction, window + and predicates are within the collector's own capabilities (the same + table `--print-capabilities` prints). It does not check *whether* the + view should be pushed (timing, lifetime): that is the control plane's + rule, written once. +3. **Reads each view's key** with `materialized_views()` on the sub-DAG and + `view_state_key()`: the key depends only on the view node, so it equals + the installed plan's. The selection is `coverage().selection()`. +4. **Builds** each view: sketch and parameters from θ (an out-of-range + value is a load error, never replaced by a default), window = + `ViewWindow::Tumbling.width_ms`, matchers = `__name__ = metric` plus each + `Scan` predicate, one state per series with every label in the key. +5. **Stamps** every emitted state with the key and selection (§4). With `planner_views` set, the per-sketch fields of the processor config (`sketch_type`, `sketch_params`, `window_size`, `window_slide`, `output_metric_name`, `agg_id`, `aggregate_by`, `omit_resource_attrs`, `global_aggregation`, `emit_window_stats`, `transmit_sketch = false`) are a -config error: the file is the only source of truth. The pipeline YAML then -names one `asap_sketches` node and does not change when the plan does. +config error: the file is the only source of truth. The pipeline YAML names +one `asap_sketches` node and does not change with the plan. -### 4. OTAP tiers: what goes in Schema, Dictionary and Record +The collector's raw forward drops samples of every metric the file marks +`backend_reads_raw: false`, and forwards all others (including metrics the +plan does not read). -The collector's data model (its `docs/data_model.md`) splits a sketch -stream into OTAP's three tiers by rate of change: **Schema** (config-time, -once per stream), **Dictionary** (once per series), **Record** (once per -state). The planner's view fields fall into the same tiers by design: +### 4. OTAP tiers: Schema, Dictionary, Record -| Tier | Planner source | Collector field (OTLP placement) | Backend handling | -|---|---|---|---| -| Schema | `view_coverage.definition_id` | `sketch.definition_id` (Resource, string, 32 hex), replaces `sketch.agg_id` | Look up the installed views with this id; none → reject `unknown_view` | -| Schema | `view_coverage.selection` (non-time part: lifted label matchers) | `sketch.selection` (Resource, the planner's JSON of the selection) | Parse to `Vec`, compare with `==` to pick among views of one id | -| Schema | `summary_type` + `parameters` | `sketch.type` (Resource); the parameters are inside the ASAPv1 envelope (`sketch.size` ignored) | Decode the envelope, compare its parameters with the view's `parameters` | -| Schema | `tumbling_window_width_ms` | none; implied by the view | Check `end − start` = width and `end` a multiple of it | -| Schema | ASAPv1 format version | `sketch.schema_version` (Resource) | ≤ highest supported | -| Schema | stream identity (not planner) | `sketch.stream_id` (Resource, random 128-bit per collector start) | Key of the Dictionary cache below | -| Dictionary | `Scan.source.TimeSeries.metric` + the series' labels (the view's group key column `$promql_series_identity`) | metric name; Scope attributes (labels) and `sketch.series_id` | Intern once per `(stream_id, series_id)` into the store's series table | -| Record | the time part of the selection: this window `(end − w, end]` | point `sketch.window_start_ms` (exclusive), `sketch.window_end_ms` (inclusive), and the point times | The state's window key | -| Record | the view's `state` column | point `sketch.envelope` (ASAPv1 bytes), `count` | Stage, dedup, commit (§7) | - -How `view_coverage` itself splits: - -| `view_coverage` part | Example (q01) | Tier | Why | -|---|---|---|---| -| `definition_id` | `5597d603bdf9f1a148d7c7e5344c1a97` | Schema | Constant per view | -| `selection`, label boxes | `[{"columns": []}]` (no matcher); with `data{region="r0"}`: `region in ["r0"]` | Schema | Constant per view | -| `selection`, time interval | none on a chain's own coverage; each window is `(end − 5 s, end]` | Record | Differs per state | - -A chain view's stored `selection` carries no time column: its rows are -indexed by `window_end`, and the time part appears only on the `TimeRange` -above it. So the Record's window is exactly the time part the view's rows -add, in Prometheus's `(t − range, t]` form (§5). - -`definition_id` does not cover the parameters or the selection: the -planner computes it from the memo group's expression, which holds neither. -Checked on the benchmark plan: q01 with α 0.05 and with α 0.01 both give -`5597d603bdf9f1a148d7c7e5344c1a97`; `data{region="r0"}` moves the matcher -into `selection`. A view is therefore identified by `(definition_id, -selection)`, and its parameters are checked from the decoded state (open -question 11). - -As entities, with planner names (one stream may carry several views, and -the same labels under two views are two Dictionary entries, as in the -collector's data model): +The collector's data model (its `docs/data_model.md`) splits a sketch +stream into OTAP's three tiers by rate of change: **Schema** (once per +stream and view), **Dictionary** (once per series), **Record** (once per +state). The backend's `ViewStateBatch` keeps the same nesting, so Schema and +Dictionary are not repeated in every record: + +| Tier | Planner source | OTLP placement | `ViewStateBatch` field | Backend handling | +|---|---|---|---|---| +| Stream | none | `sketch.stream_id` (Resource; random 128-bit per collector start) | `stream_id` | Key of the series cache | +| Schema | `view_state_key()` | `sketch.view_state_key` (Resource; the key's JSON) | `views[].key` | Find the view, with the selection | +| Schema | `coverage().selection()` (lifted label matchers) | `sketch.selection` (Resource; the planner's JSON) | `views[].selection` | as above | +| Schema | ASAPv1 format version | `sketch.schema_version` (Resource) | none (checked by the adapter) | ≤ highest supported | +| Schema | none | `sketch.type` (Resource) | none | Not read (decision 11) | +| Dictionary | `Scan` metric + the series' labels (`$promql_series_identity`) | metric name; `sketch.series_id` and labels (Scope) | `views[].series: (series_id, labels)` | Interned once per `(stream_id, view, series_id)` | +| Record | the window `(end − w, end]`, `w` from the key | point `start_time_unix_nano` (exclusive), `time_unix_nano` (inclusive) | `records[].window_end_ms` | Window key; `end` must be a multiple of `w` | +| Record | the view's `state` column | point `sketch.envelope` (ASAPv1 bytes), `count` | `records[].asapv1`, `sample_count` | Stage, dedup, merge, commit (§6) | + +A chain view's selection carries no time column: its rows are indexed by +`window_end`, and the time part appears only on the `TimeRange` above it. +So the Record's window is exactly the time part the rows add, in +Prometheus's `(t − range, t]` form (§5). ```mermaid erDiagram - SKETCH_STREAM ||--o{ SCHEMA : schema - SCHEMA ||--o{ DICTIONARY : dictionary - DICTIONARY ||--o{ LABELS : labels - DICTIONARY ||--o{ RECORD : records - SKETCH_STREAM{ - stream_id string "random per collector start" + STREAM ||--o{ VIEW : views + VIEW ||--o{ SERIES : series + SERIES ||--o{ RECORD : records + STREAM{ + stream_id u128 "random per collector start" } - SCHEMA{ - definition_id string "view_coverage.definition_id" - selection json "view_coverage.selection, non-time part" - summary_type string "e.g. Sketch DDSketch" - parameters json "SketchParams, also inside the envelope" - tumbling_window_width_ms u64 - schema_version u32 "ASAPv1" + VIEW{ + key ViewStateKey "definition_id, window, logical_properties" + selection json "coverage selection" } - DICTIONARY{ - series_id u32 - definition_id string "references SCHEMA" - metric string "Scan source TimeSeries metric" - } - LABELS{ - series_id u32 "references DICTIONARY" - key string - value string + SERIES{ + series_id u32 "per stream and view" + labels LabelSet "__name__ included" } RECORD{ - series_id u32 "references DICTIONARY" - window_start_ms i64 "exclusive" - window_end_ms i64 "inclusive" - envelope bytes "ASAPv1 state" - count u64 + series_id u32 "references SERIES" + window_end_ms i64 "inclusive; start = end - width" + asapv1 bytes "full state" + sample_count u64 } ``` **Transport.** OTAP Arrow keeps the tiers on the wire: over one stream, Schema and Dictionary are sent once and Records reference them. OTLP HTTP -flattens them: each request repeats the Resource (Schema) and Scope -(labels) above its points, so labels and Schema attributes travel once per -request and series rather than once per stream. The logical mapping above -is the same in both. - -*Recommendation: v1 accepts OTLP HTTP; an OTAP Arrow receiver follows.* -Every collector deployment exports with `urn:otel:exporter:otlp_http` -today, and the backend already serves `/v1/metrics`, so v1 needs no new -listener. Decoding OTAP Arrow with the collector's own crates -(`otel-arrow-dfe-pdata` and its engine crates) would bring `datafusion` -53 and `tonic` 0.14 next to the backend's `datafusion` 54 and `tonic` -0.12: two copies of each in the build. The Arrow receiver is the next -step, built on the `arrow-ipc` 58 and `tonic` the backend already has and -fed by the collector's `urn:otel:exporter:otap` (open question 13). With -OTLP the Dictionary saving is still had on the backend side: the adapter -interns each `(stream_id, series_id)` once and reuses the series id for -every later record. +repeats the Resource (Schema) and Scope (labels) in every request. v1 +accepts OTLP HTTP (every collector deployment exports with +`urn:otel:exporter:otlp_http` today, and the backend already serves +`/v1/metrics`); the OTLP adapter builds the nesting above, and the series +cache still interns each series once per stream. A later OTAP Arrow +adapter fills the same `ViewStateBatch` (open question 5). **Collector restart.** A restart starts a new stream: new `stream_id`, and -the collector's `series_id` counter starts again at 1. The backend never -reuses a translation across streams, so a reset counter cannot alias two -series; the new stream's Dictionary entries are interned again (to the -same backend series, since the labels are the same). Entries of a stream -not seen for the longest view retention are dropped. +`series_id` starts again at 1. The backend never reuses a translation +across streams, so a reset counter cannot alias two series; the new +stream's series are interned again (to the same backend series, since the +labels are the same). Entries of a stream not seen for the longest view +retention are dropped. ### 5. Window semantics: Prometheus's `(t − range, t]` @@ -374,23 +335,21 @@ planner's selection algebra writes PromQL `m[5m]` the same way: lower `advance_window` put a sample at `t` in `[⌊t / w⌋ · w, ⌊t / w⌋ · w + w)`, and `SketchEnvelope` documents `window_start_ms` as inclusive and `window_end_ms` as exclusive. At 10 Hz with 5 s windows every 50th sample - lies on a boundary, and the two sides put it in different windows, so a - pushed view and a backend-built view of the same data differ. + lies on a boundary, and the two sides put it in different windows. The collector change: 1. A sample at `t` belongs to the window ending at `⌈t / w⌉ · w`; a window closes when a sample later than its end arrives (`t > end`, not `≥`), or on the idle timer as today. -2. A sample is placed by its own timestamp, not into the active window: - today a sample older than the active window (out of order, from another - source) lands in the active window. It goes to its own window while that - window is open, and is dropped and counted once it is closed. -3. `window_start_ms` is exclusive and `window_end_ms` inclusive, in the - envelope, the `sketch.window_*_ms` attributes and the OTLP point times. -4. Matchers (name, `=` or `!=`, value; `__name__` for the metric), passed - to `PrecomputeConfig::matchers`, which the runtime already evaluates; - with `planner_views` they come from the `Scan` predicates. +2. A sample is placed by its own timestamp, not into the active window + (today an out-of-order sample lands in the active window). It goes to its + own window while that window is open, and is dropped and counted once it + is closed. +3. `SketchEnvelope` and the OTLP point times use `(start, end]`; the + `sketch.window_start_ms` / `sketch.window_end_ms` attributes are removed. +4. Matchers (name, `=` or `!=`, value; `__name__` for the metric) go to + `PrecomputeConfig::matchers`, which the runtime already evaluates. ### 6. The sketch path in the data plane @@ -398,218 +357,205 @@ The collector change: carries a `sketch.envelope` bytes attribute is a pushed state; every other point is a raw sample, as today. A request may carry both. -The adapter (`asap-sketch-otlp`) reads, per pushed state, the fields of the -tier table in §4, and requires: `sketch.definition_id`, -`sketch.selection`, `sketch.stream_id` and `sketch.series_id` present; -`sketch.type` known; `sketch.schema_version` ≤ the highest supported; the -window attributes equal to the point's `start_time_unix_nano` / -`time_unix_nano` in ms with `start < end`; `sketch.envelope` non-empty. -Labels are Resource attributes, then Scope attributes, then point -attributes, without any `sketch.*` key, with `__name__` = metric name (the -raw OTLP adapter's merge order). - -The ingest engine then, per state: - -1. **View.** Looks up the installed views with this `definition_id` and an - equal `selection`. None → rejected (`reason="unknown_view"`; for - example a collector still running a file from an earlier plan). -2. **Window.** Requires `end − start` = the view's - `tumbling_window_width_ms` and `end` a multiple of it. Otherwise - rejected (`reason="window"`). -3. **Parameters.** Decodes the ASAPv1 bytes with `storage`'s codec into the - view's kernel and compares the decoded parameters with the view's - `parameters`, exactly (decision 5). A matching id does not imply - matching parameters (§4), so this check is required, not a formality. - A state that does not decode, or decodes with other parameters, is - rejected (`reason="decode"`, `reason="params"`). -4. **Series.** Translates `(stream_id, series_id)` through the - per-stream Dictionary cache; on a miss, interns the record's label set - into the store's series table, as the raw path does, so the view row's +The adapter groups the pushed points by `sketch.stream_id`, then by +(`sketch.view_state_key`, `sketch.selection`), into one `ViewStateBatch` +per stream. It refuses the request (400) when a Resource lacks one of these +attributes or they do not parse, or `sketch.schema_version` is newer than +supported. Labels are Resource attributes, then Scope attributes, then +point attributes, without any `sketch.*` key, with `__name__` = metric name +(the raw OTLP adapter's merge order). + +The ingest engine then, per view and record: + +1. **View.** Looks up the installed views with this key and selection + (an index built at install from `materialized_views()`). None → rejected + (`reason="unknown_view"`), whatever differs: another definition, θ or + width, or a view the installed plan no longer has. Views of one plan + with equal key and selection hold the same state; the record is stored + for each. +2. **Window.** `window_end_ms` must be a multiple of the key's width; + otherwise rejected (`reason="window"`). +3. **Series.** Translates `(stream_id, view, series_id)` through the series + cache, filled from the batch's `series` table; on a miss, interns the + labels into the store's series table, as the raw path does, so the row's `$promql_series_identity` is the same canonical JSON a raw sample of - that series gets. -5. **Stage, dedup, commit.** See below. - -Every rejection increments -`asap_pushed_states_rejected_total{view, reason}` and logs once per view and -reason per minute; the request still returns 200 with the rejected count, as -the raw OTLP route reports `rejected`. - -### 7. Staging, deduplication, late states - -The view store appends a view's windows in order and each window once, and -other refresh groups may read a pushed view (a wider level of its chain), so -a pushed window is committed once and whole. The engine stages pushed states -per `(view, window)` and commits through the precompute committer, the same -path that commits a window it built (readers, `RefreshTaskGraph` ordering, -persistence and the memory budget all apply). - + that series gets. A `series_id` in neither → rejected + (`reason="unknown_series"`). +4. **Decode.** Decodes the ASAPv1 bytes into the view's kernel; failure → + rejected (`reason="decode"`). +5. **Stage, dedup, merge, commit**, below. + +Every rejection increments `asap_pushed_states_rejected_total{view, +reason}` and logs once per view and reason per minute; the request still +returns 200 with the counts, as the raw OTLP route reports `rejected`. + +**Staging.** The view store appends a view's windows in order and each +window once, so a pushed window is committed once and whole. The engine +stages states per `(view, window)` and commits through the precompute +committer, the same path that commits a window it built (readers, +`RefreshTaskGraph` ordering, persistence and the memory budget all apply). + +- **Duplicates.** Until commit, the engine keeps the set of 64-bit envelope + hashes seen per `(view, series, window)`. A state whose hash is in the set + is ignored and counted (`duplicate`). A set, not the last hash, so that a + retry of one partial state after another partial was merged is still + caught. +- **Second states.** A state with a new hash for a `(view, series, window)` + is merged into the staged one (sketch merge): a collector that restarted + inside a window, or two collectors that each saw part of one series. + States are full, not deltas, and each partial covers other samples. - **Commit time.** No raw samples of a pushed view's metric need reach the - backend, so the raw watermark cannot close its windows. A pushed window - commits when the wall clock passes `end + push_grace_ms` (default 10 s: - the collector's 5 s idle-close grace plus an export interval). -- **Duplicates.** A state for a `(view, series, window)` that already has a - state with the same bytes (compared by a 64-bit hash of the envelope, kept - per key for the view's retention) is ignored and counted - (`asap_pushed_states_duplicate_total{view}`). This covers exporter - retries. -- **Second states.** A state for a `(view, series, window)` that already has - a state with other bytes is merged into it (sketch merge). This covers two - partial states: a collector that restarted inside a window, or two - collectors that each saw part of one series. Merging is safe because the - states are full, not deltas, and each partial covers different samples. -- **Late states.** A state that arrives after its window committed: - - within the view's retention, it is merged into the committed window - (deduplicated as above), through `merge_late_rows` below, which writes - the merged window to memory and to its view file; - `asap_pushed_states_late_merged_total{view}`; - - beyond the retention, it is dropped; - `asap_pushed_states_late_dropped_total{view}`. - -A late merge changes a window a query may already have read. The result -cache keeps final answers per evaluation time, so the merge drops the cached -answers whose range covers the merged window (open question 6). + backend, so the raw watermark cannot close its windows. A window commits + when the backend's wall clock passes `end + commit_grace_ms`, with + + `commit_grace_ms = window_close_delay_ms + export_interval_ms + clock_skew_allowance_ms` + + from the capabilities (6 s today), the collector pipeline's export + interval (`--collector-export-interval-ms`, default 0: today's pipelines + export each processor message at once), and an allowance for clock skew + (default 2 s). Default: 8 s. The control plane writes it into the file; + each pushed view's retention must exceed it. +- **No states.** A window with no staged state at commit time is not + stored; a query that reads it gets `NotReady` and is forwarded to the + fallback (open question 9). +- **Late states.** A state that arrives after its window committed is + dropped and counted (`late_dropped`), whatever its reason: an export + slower than the grace, or a collector clock behind the backend's by more + than the allowance. The window then answers without that series' state. + A histogram of arrival delay (`end` to arrival) per view shows when the + grace must grow. v1 has no late merge (decision 9). ## Code interface ### `crates/common` ```rust -/// States the collector built for pushed views: what the sketch-path ingest -/// adapter hands the ingest engine. Never data between operators. +use asap_types::plan::materialized_view::ViewStateKey; +use asap_types::ir::properties::selection::SelectionBox; + +/// Pushed states from one collector stream: what the sketch-path ingest +/// adapter hands the ingest engine. Nested by OTAP tier, so a view's key and +/// a series' labels appear once, not per record. Never data between operators. #[derive(Debug, Clone, PartialEq)] pub struct ViewStateBatch { - pub states: Vec, + /// Random per collector start; scopes `series_id`. + pub stream_id: u128, + pub views: Vec, } -/// One series' state of one pushed view in one window. +/// One pushed view's states in the batch. #[derive(Debug, Clone, PartialEq)] -pub struct PushedViewState { - /// The view's `view_coverage.definition_id` (32 hex digits). - pub definition_id: String, - /// The view's `view_coverage.selection`, as the planner serializes it. +pub struct PushedViewStates { + pub key: ViewStateKey, + /// The view's coverage selection, as the planner serializes it. pub selection: Vec, - /// Which sketch the bytes hold, as the record declares it. - pub sketch: PushedSketch, - /// ASAPv1 envelope bytes from `asap_sketchlib`: the full state. - pub asapv1: Vec, - /// The collector stream and its series id: the Dictionary key. - pub stream_id: u128, + /// Series of this view's records: the OTLP adapter lists every series in + /// the request, an OTAP adapter only new Dictionary entries. + pub series: Vec<(u32, LabelSet)>, + pub records: Vec, +} + +/// One series' state in one window `(window_end_ms − width, window_end_ms]`. +#[derive(Debug, Clone, PartialEq)] +pub struct ViewStateRecord { pub series_id: u32, - /// The series' labels, `__name__` included. - pub labels: LabelSet, - /// The window `(start_ms, end_ms]`. - pub window_ms: (i64, i64), + pub window_end_ms: i64, + /// ASAPv1 bytes from `asap_sketchlib`: the full state. + pub asapv1: Vec, /// Samples folded into the state, as the collector counted them. pub sample_count: u64, } -/// The sketches the collector builds. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum PushedSketch { DDSketch, Kll, Hll, CountSketch, Cms, CmsWithHeap } - -/// What happened to a batch's states. +/// What happened to a batch's records. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct ViewStateIngestReport { pub staged: u64, pub duplicate: u64, - pub late_merged: u64, + pub merged: u64, pub late_dropped: u64, - /// Rejected states by reason (`unknown_view`, `window`, `decode`, `params`). + /// By reason: `unknown_view`, `window`, `unknown_series`, `decode`. pub rejected: BTreeMap<&'static str, u64>, } -/// Takes states the collector built for pushed views. Implemented by the -/// ingest engine, next to `IngestEngine`. +/// Takes pushed states. Implemented by the ingest engine, next to `IngestEngine`. #[async_trait] pub trait ViewStateIngest: Send + Sync { - /// Checks, stages or merges each state; waits under backpressure as + /// Checks, stages or merges each record; waits under backpressure as /// `IngestEngine::ingest` does. async fn ingest_view_states(&self, batch: ViewStateBatch) -> Result; } ``` -`SelectionBox` is `asap_types::ir::properties::selection::SelectionBox`, -which `common` can already name. - -`ViewStore::put`'s contract ("each key is put once and never rewritten") -gains one exception, for late states: - -```rust -pub trait ViewStore: Send + Sync { - // put, get, instances, evict_before, timestamp_range_per_view: unchanged - - /// Replaces the committed instance under `key` with `instance` (the old - /// one merged with late states). `false` when `key` is not stored - /// (evicted, or never committed). - fn replace(&self, key: ViewInstanceKey, instance: ViewInstance) -> bool; -} -``` - -and the backend's own store, which the engines use directly: - -```rust -// crates/storage/src/store.rs -impl ViewStore { - /// Replaces the rows of `view`'s committed window `time_range_ms` with - /// `batches` (copy on write: runs reading the old rows keep them); the - /// window is re-queued for its view file. `Err` when the window is not - /// stored. - pub fn merge_late_rows( - &mut self, - view: &MaterializedView, - time_range_ms: (i64, i64), - batches: Vec, - ) -> Result<(), Error>; -} -``` +`ViewStore` is unchanged: every pushed window is `put` once, at commit. ### `crates/adapters/ingest/asap-sketch-otlp` ```rust -/// Why a request's pushed states could not be read (the whole request is -/// refused with 400; per-state problems are counted, not errors). +/// Why a request's pushed states could not be read; the whole request is +/// refused with 400. Per-record problems are counted, not errors. #[derive(Debug, thiserror::Error, PartialEq)] pub enum SketchOtlpError { - #[error("sketch record without {0}")] + #[error("sketch Resource without {0}")] MissingAttribute(&'static str), - #[error("unknown sketch.type {0:?}")] - UnknownSketchType(String), - #[error("sketch.schema_version {0} is newer than supported")] - SchemaVersion(u64), + #[error("sketch.view_state_key is not a planner view state key: {0}")] + ViewStateKey(String), #[error("sketch.selection is not a planner selection: {0}")] Selection(String), - #[error("window attributes ({start_ms}, {end_ms}] disagree with the point's times")] - Window { start_ms: i64, end_ms: i64 }, + #[error("sketch.schema_version {0} is newer than supported")] + SchemaVersion(u64), } /// Whether an OTLP data point carries a pushed state (a `sketch.envelope` /// bytes attribute): the route's test for the sketch path. pub fn is_sketch_point(attributes: &[KeyValue]) -> bool; -/// The pushed states of a decoded OTLP metrics request; points without -/// `sketch.envelope` are left to the raw `otlp` decoder. +/// The pushed states of a decoded OTLP request, one batch per stream; points +/// without `sketch.envelope` are left to the raw `otlp` decoder. pub fn decode_view_states( request: &ExportMetricsServiceRequest, -) -> Result; +) -> Result, SketchOtlpError>; ``` The raw `otlp` decoder already skips points that carry a sketch payload; it -learns `sketch.envelope` as one more such attribute, so one request body is -decoded by both and each point is read once. +learns `sketch.envelope` as one more, so each point is read once. ### `crates/control-plane` ```rust -/// The file the collector and the data plane load: each pushed view's -/// sub-DAG of the installed plan, in the planner's serde. +/// What `asap_sketches --print-capabilities` prints (§1). +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorCapabilities { + pub capabilities_version: u32, + pub summaries: Vec, + /// Reduction variant names: `PerEntity`. + pub reductions: Vec, + pub windows: Vec, + pub predicate_ops: Vec, + pub window_close_delay_ms: u64, +} + +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SummaryCapability { + pub summary_type: FieldDataType, + pub input: SummaryInputKind, // Value | Label + pub parameters: BTreeMap, // gt, ge, lt, le: Option +} + +/// The file the collector and the data plane load. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct PushedViewsFile { - /// The installed plan's `wire_version`. pub planner_wire_version: u32, - /// One per pushed view: its node, its `Scan` and the edge between - /// them; `roots = [view node]`. + /// `PhysicalASAPDAG::plan_id()` of the installed plan. + pub plan_id: String, + pub commit_grace_ms: u64, + /// Per metric a `Scan` reads: whether a view that is not pushed, or a + /// query-time `Scan`, still reads its raw samples. + pub backend_reads_raw: BTreeMap, + /// One sub-DAG per pushed view; `roots = [view node]`. pub views: Vec, } @@ -617,22 +563,23 @@ pub struct PushedViewsFile { #[derive(Debug, Clone, PartialEq)] pub enum NotPushed { NotOnRawScan, - NotPerSeries, - NotTumbling, - UnsupportedSummary(String), - UnsupportedParameters(String), - FilterNotExpressible(String), + NotInCapabilities(String), } -/// The installed plan's pushed views, by the rule of this design, as -/// sub-DAGs, and why each other view is not pushed. -pub fn pushed_view_dags(plan: &InstallablePlan) - -> (PushedViewsFile, Vec<(PhysicalASAPNodeId, NotPushed)>); +/// The installed plan's pushed views and why each other view is not pushed. +pub fn pushed_view_dags( + plan: &InstallablePlan, + capabilities: &CollectorCapabilities, + export_interval_ms: u64, +) -> (PushedViewsFile, Vec<(PhysicalASAPNodeId, NotPushed)>); ``` -CLI: `control_plane --plan --emit-pushed-views -` reads a saved plan and writes the file; the data plane -takes `--pushed-views `. +`FieldDataType` (the chain's `summary_type`) and `CompareOpKind` are the +planner's types. CLI: +`control_plane --plan --collector-capabilities + [--collector-export-interval-ms ] +--emit-pushed-views `; the data plane takes +`--pushed-views `. ## Worked example: q01 @@ -653,7 +600,9 @@ n1 passes the rule. Its sub-DAG in `pushed-views.json` (schemas shortened to their field names; the file carries them in full): ```json -{"planner_wire_version": 15, "views": [{ +{"planner_wire_version": 15, "plan_id": "…", "commit_grace_ms": 8000, + "backend_reads_raw": {"data": true, "data_total": true}, + "views": [{ "nodes": [ {"id": 0, "payload": {"NonASAP": {"Scan": { @@ -687,9 +636,12 @@ shortened to their field names; the file carries them in full): "scalar_roots": []}]} ``` -The collector maps it to: DDSketch with `relative_accuracy = 0.05`, 5 s -tumbling windows `(e − 5 s, e]`, matcher `__name__ = "data"`, one state per -series. Its pipeline config names only the file: +n1's view state key is `{"definition_id": +"5597d603bdf9f1a148d7c7e5344c1a97", "window": {"tumbling": {"width_ms": +5000}}, "logical_properties": {"parameters": {"DDSketch": {"alpha": +0.05}}}}`. The collector maps it to DDSketch with `relative_accuracy = +0.05`, 5 s windows `(e − 5 s, e]`, matcher `__name__ = "data"`, one state +per series. Its pipeline config names only the file: ```yaml sketch: @@ -702,32 +654,32 @@ For one series `data{region="r0",service="s0",job="j0",label_0="l0"}`, the collector folds the 50 samples with timestamps in `(T − 5 s, T]` into one DDSketch and exports one summary point: -| Where | Attribute | Value | +| Where (tier) | Attribute | Value | |---|---|---| -| Resource (Schema) | `sketch.definition_id` | `"5597d603bdf9f1a148d7c7e5344c1a97"` | +| Resource (stream) | `sketch.stream_id` | `"9b1e…"` (random at collector start) | +| Resource (Schema) | `sketch.view_state_key` | n1's key above, as JSON | | Resource (Schema) | `sketch.selection` | `"[{\"columns\":[]}]"` | -| Resource (Schema) | `sketch.type` | `"DDSketch"` | | Resource (Schema) | `sketch.schema_version` | `1` | -| Resource (Schema) | `sketch.stream_id` | `"9b1e…"` (random at collector start) | +| Resource (Schema) | `sketch.type` | `"DDSketch"` (not read by the backend) | | Scope (Dictionary) | `sketch.series_id` | `17` | | Scope (Dictionary) | labels | `region="r0"`, `service="s0"`, `job="j0"`, `label_0="l0"` | | Metric | name | `data` | -| Point (Record) | `sketch.window_start_ms` | `T − 5000` (exclusive) | -| Point (Record) | `sketch.window_end_ms` | `T` (inclusive) | +| Point (Record) | `start_time_unix_nano` | `T − 5 s` (exclusive) | +| Point (Record) | `time_unix_nano` | `T` (inclusive) | | Point (Record) | `sketch.envelope` | ASAPv1 bytes | | Point (Record) | `count` | `50` | -The backend finds n1 by `definition_id` and selection, checks that the -window is 5 s wide and ends on a multiple of 5 s, decodes the envelope and -checks α = 0.05, translates `(stream_id, 17)` to its series id, and stages -the state. It keeps exactly what its own precompute keeps for n1: per -series, one DDSketch state per 5 s window, for the view's 60 s retention -(12 windows). At evaluation time `T` (a multiple of 5 s), q01 runs at query -time as before: n2 selects the 12 windows ending in `(T − 60 s, T]`, n3 -merges the 12 states of each series into one, and n4 reads the 0.99 -quantile. That chain, the result cache and the fallback do not change. The -backend no longer runs n1, and `data`'s raw samples still arrive because -the `Scan` n0 also feeds q02's and q03's chains. +The adapter makes one `ViewStateBatch` with one `PushedViewStates` (n1's +key and selection), one series `(17, labels)` and one record `(17, T, +bytes, 50)`. The backend finds n1 by key and selection, checks that `T` is +a multiple of 5 s, translates `(stream_id, n1, 17)` to its series id, +decodes the state and stages it; at `T + 8 s` it commits the window. It +keeps exactly what its own precompute keeps for n1: per series, one +DDSketch state per 5 s window, for 60 s (12 windows). At evaluation time +`T`, q01 runs at query time as before: n2 selects the 12 windows ending in +`(T − 60 s, T]`, n3 merges them per series, n4 reads the 0.99 quantile. The +backend no longer runs n1. `data`'s raw samples still arrive, because n0 +also feeds q02's and q03's chains (`backend_reads_raw.data = true`). ## The benchmark queries @@ -737,193 +689,164 @@ one's leaf as a 5 s tumbling chain over its `Scan`: | Query | Leaf view (summary type, reduction) | Pushed | Why | |---|---|---|---| | q01 `quantile_over_time(0.99, data[1m])` | `Sketch: DDSketch` α 0.05, `PerEntity` | yes | passes every rule | -| q02 `max_over_time(data[1m])` | `ExactAggregate: Max`, `PerEntity` | no | exact aggregate: the collector builds none | -| q03 `sum_over_time(data[1m])` | `ExactAggregate: Sum`, `PerEntity` | no | exact aggregate | -| q04 `rate(data_total[1m])` | `ExactAggregate: Counter`, `PerEntity` | no | exact counter state | -| q05 `sum by (region, service) (sum_over_time(data[1m]))` | `ExactAggregate: Sum`, `PerEntity`; the `sum by` runs at query time | no | exact aggregate | - -So for this workload the collector builds one view, the backend still builds -four, and both metrics' raw samples still reach the backend. Step 4 of the -plan measures what that saves; a workload whose metric is read only by -pushed views saves the raw samples too. +| q02 `max_over_time(data[1m])` | `ExactAggregate: Max`, `PerEntity` | no | not in the capabilities | +| q03 `sum_over_time(data[1m])` | `ExactAggregate: Sum`, `PerEntity` | no | not in the capabilities | +| q04 `rate(data_total[1m])` | `ExactAggregate: Counter`, `PerEntity` | no | not in the capabilities | +| q05 `sum by (region, service) (sum_over_time(data[1m]))` | `ExactAggregate: Sum`, `PerEntity`; the `sum by` runs at query time | no | not in the capabilities | + +For this workload the collector builds one view, the backend still builds +four, and both metrics are `backend_reads_raw: true`, so every raw sample +still reaches the backend. The expected benefit here is about zero: the +backend saves only n1's DDSketch updates, and the network carries the +pushed states on top of the unchanged raw samples. With q01 alone, `data` +is read only by n1, so it is marked `false` and its raw samples no longer +reach the backend: 50 samples per series per window become one state. ## Plan -Separate PRs, each reviewed on its own. +Separate PRs, each reviewed on its own. Backend implementation starts after +the planner's view state key and plan id merge; the backend and collector +then bump their planner pin to that revision. Backend: 1. This document. 2. `ViewStateBatch` and `ViewStateIngest` in `common`; the - `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by - `definition_id` and selection, the Dictionary cache, staging, dedup, - late merge and `ViewStore::merge_late_rows`. Test data: real ASAPv1 - records the collector emits (captured OTLP bodies, checked in with the - collector commit that wrote them), for each of the six sketch types, - including one with mismatched parameters, one unknown id, one duplicate, - one late state and one restart (new `stream_id`, reused `series_id`). -3. The control plane's push-down rule and `--emit-pushed-views`; the data - plane's `--pushed-views`; the precompute engine skips pushed views. - Tests: the benchmark plan pushes exactly q01's sub-DAG above; a plan - with a regex matcher, a `Reduce` leaf or an `ExactAggregate` leaf pushes - nothing; the written file deserializes into `PhysicalASAPDAG`s that - pass the planner's `validate`. + `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by key and + selection, the series cache, staging, the hash set, merge before commit, + commit at grace, late drop. Test data: real ASAPv1 records the collector + emits (captured OTLP bodies, checked in with the collector commit that + wrote them), for each of the six sketch types, including one unknown key + (other θ), one duplicate after a merge, one late state and one restart + (new `stream_id`, reused `series_id`). +3. The control plane's rule with `--collector-capabilities`, + `--emit-pushed-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, + `commit_grace_ms`); the data plane's `--pushed-views` with the plan-id + check; precompute skips pushed views. Tests: the benchmark plan pushes + exactly q01's sub-DAG and marks both metrics raw; a q01-only plan marks + `data` `false`; a regex matcher, a `Reduce` leaf or an `ExactAggregate` + leaf pushes nothing; a file of another plan id is refused; the written + file deserializes and `materialized_views()` on each sub-DAG gives the + installed view's key. 4. End-to-end comparison, collector + backend against backend only, on the - same feed: answers equal (exact views) or within the plan's error - (sketch views) at every evaluation; backend ingest CPU, network bytes - between collector and backend, and collector CPU; including a sparse - series case for the limitation above. + same feed, for two workloads: the five-query benchmark set (expected + benefit about zero, above) and q01 alone (the pushed metric has only + pushed readers, so its raw samples stay at the collector). Answers equal + (exact views) or within the plan's error (sketch views) at every + evaluation; backend ingest CPU, network bytes between collector and + backend, collector CPU, `late_dropped`; including a sparse-series case. Collector (ASAPCollector-public): -5. `asap-types` as a pinned git dependency (same rev as the backend's - planner pin); the `planner_views` loader with the shape check and the - mapping table; config errors for the per-sketch fields when it is set. -6. Stamping: `sketch.definition_id`, `sketch.selection` and - `sketch.stream_id` on the Resource, replacing `sketch.agg_id`; - `series_id` per (view, series). -7. The window boundary `(e − w, e]`, placement by sample timestamp with +5. `--print-capabilities`, printed from the config validation code. +6. `asap-types` as a pinned git dependency (the backend's planner pin); the + `planner_views` loader with the executability check; key and selection + stamping (`sketch.view_state_key`, `sketch.selection`, `sketch.stream_id` + on the Resource, replacing `sketch.agg_id`); `series_id` per (view, + series); config errors for the per-sketch fields when it is set. +7. The window boundary `(e − w, e]` in `SketchEnvelope` and the point + times (window attributes removed), placement by sample timestamp with drop-and-count after close, and matchers (§5). It lands before step 4, which needs equal windows. +8. The raw-forward filter by `backend_reads_raw`. + +**Future work.** Late merge into a committed window (a store `replace`, a +view-file rewrite and result-cache invalidation), only if step 4 or +production shows a late rate worth it, measured by `late_dropped` and the +arrival-delay histogram. Cost-based push-down. The OTAP Arrow adapter. ## Decisions -1. **ASAPPlanner does not change.** Which views the collector builds is a - deployment decision the backend's control plane makes on the installed - plan; the plan and its `InstallablePlan` format are unchanged. The - planner already exports the types and ids the collector reads. +1. **The planner's identity, no other planner change.** A pushed state is + identified by the planner's view state key plus its concrete selection; + within the installed plan a view is `(plan_id, node_id)`. θ and window + width are in the key, so a state of another θ or width is simply + `unknown_view`. Which views the collector builds is a deployment decision + the backend's control plane makes on the installed plan. 2. **The collector is ASAPCollector-public (OTAP), sending full ASAPv1 states.** No deltas: each record holds the whole state of one series in one window. -3. **Two paths.** The raw path (raw OTLP or Remote Write to the backend) - stays, for views that are not pushed, query-time `Scan`s and the - fallback. The sketch path carries pushed states on the same - `/v1/metrics` route; a record with `sketch.envelope` takes the sketch - path. -4. **Prometheus window semantics on both sides**: `(t − range, t]`, as - Prometheus 3.x range selectors. The backend already uses it; the - collector changes in its own PR. -5. **Parameters match the plan exactly**; the backend rejects a state whose - decoded parameters differ, and counts it. A state delivered twice for the - same view, series and window is ignored the second time, and counted. - A late state within retention is merged into the stored state; beyond - retention it is dropped and counted. -6. **Rule-based push-down first**: a view is pushed iff its leaf reads raw - input directly, is per series, uses a tumbling window, its sketch type - and parameters are among the collector's (DDSketch, KLL, HLL, - CountSketch, Count-Min, Count-Min-heap), and its filter is expressible - by the collector's matchers. No cost comparison. Exact aggregates stay - in the backend, since the collector builds none. Cost-based push-down - is future work and needs a general planner capability. -7. **The collector receives the planner's own view definitions.** The - control plane sends each pushed view's sub-DAG of the installed plan, - serialized with the planner's serde; the collector depends on the - planner's types crate, pinned. Every emitted state carries the view's - `view_coverage.definition_id` (with its selection) and its window, and - the backend matches it against the installed plan's views. This - replaces a numeric `agg_id` and a hand-written collector config. The - backend's precompute skips pushed views. +3. **Two paths.** The raw path stays for every metric the backend still + reads raw. The sketch path carries pushed states on the same + `/v1/metrics` route; a point with `sketch.envelope` takes it. +4. **Prometheus window semantics on both sides**: `(t − range, t]`. The + backend already uses it; the collector changes in its own PR. The window + travels as the OTLP point times; its width comes from the key. +5. **Dedup and merge before commit.** A state whose envelope hash was + already seen for its view, series and window is ignored and counted; a + state with a new hash is merged. +6. **Rule-based push-down first**, against the collector's declared + capabilities. No cost comparison. Exact aggregates stay in the backend + until the collector declares them. +7. **The collector receives the planner's own view definitions**: each + pushed view's sub-DAG, in the planner's serde; the collector depends on + the planner's types crate, pinned. This replaces a numeric `agg_id` and + a hand-written collector config. The backend's precompute skips pushed + views. The data plane refuses a pushed-views file of another `plan_id`. +8. **The collector declares its capabilities** (`--print-capabilities`); + the control plane's rule reads them. The rule exists once, in the control + plane; the collector checks only that it can execute each sub-DAG. +9. **No late merge in v1.** A state after commit is dropped and counted. + The store's put-once contract is unchanged. +10. **Raw forwarding follows the readers.** The file lists, per metric, + whether the backend still reads it raw; the collector drops raw + samples to the backend for metrics marked `false`. +11. **`sketch.type` is informational.** The collector keeps emitting it + (its data model and its other sinks use it); the backend never reads it, + since the key's θ names the sketch and the ASAPv1 bytes carry their own + kind. +12. **`ViewStateBatch` is nested by OTAP tier** (stream → view → series → + records); the OTLP adapter builds the nesting, an OTAP adapter fills the + same type. ## Open questions Each with a recommendation. -1. **Dedup vs. merge of a second state for the same (view, series, - window).** *Recommend:* §7's reading: a byte-identical state is a - duplicate and ignored; a state with other bytes is merged (collector - restart mid-window, two collectors with parts of one series). The - alternative, "any second state is ignored", is simpler but loses data - on a restart. -2. **How the collector encodes the window.** *Recommend:* `(start, end]` - in the envelope, the attributes and the point times after the collector - change; the adapter requires the three to agree and the width and - alignment to match the view, and rejects and counts anything else. -3. **Clock skew and commit time.** *Recommend:* commit on the backend's - wall clock at `end + push_grace_ms` (default 10 s); treat later states - as late (merge within retention); export a per-view histogram of - arrival delay. Hosts are assumed to run NTP. -4. **Result cache after a late merge.** *Recommend:* drop cached answers - whose evaluation range covers the merged window. The alternative is not - to cache answers whose newest window is still inside the grace period. -5. **sketchlib versions differ.** The collector pins `asap_sketchlib` +1. **sketchlib versions differ.** The collector pins `asap_sketchlib` `60101c6`, the backend `355093f`, and the planner `389530c`; the collector's HLL is an Ertl HLL, the backend's kernel Classic. *Recommend:* PR 2's captured records are the compatibility test, one per - sketch type. Until the pins agree, leave HLL off the pushable list if - its envelope does not decode into the backend kernel. -6. **Selective raw forwarding.** A metric whose views are all pushed need - not reach the backend raw. *Recommend:* the pushed-views file later also - lists the metrics the backend still reads raw (a `Scan` not only under - pushed views); in v1 the collector keeps forwarding everything. -7. **Out-of-order samples in the collector.** *Recommend:* include the fix - in the collector's window PR: place each sample by its own timestamp, - and drop and count it once its window has closed. -8. **Planner types pin and compatibility between collector and backend.** - Both read the same JSON; the types are `deny_unknown_fields` and the - plan carries `wire_version` (15 today). *Recommend:* the collector pins - the same ASAPPlanner rev as the backend's `asap-planner` pin and is - bumped in the same change; the loader refuses a file whose - `planner_wire_version` differs from its own, so a mismatch fails at - start, not as wrong states. -9. **Serde stability of the planner types.** The plan-file format is the - planner's own and versioned by `INSTALLABLE_PLAN_WIRE_VERSION`; there is - no promise across versions. *Recommend:* rely on it only between equal - wire versions (question 8); PR 3 checks in the benchmark's - `pushed-views.json` and tests that it deserializes and validates, so a - planner bump that changes the format shows up as a failing test. -10. **Plan reinstall.** Unchanged views keep their `definition_id`. - *Recommend:* the control plane rewrites the file and the collector - restarts on every reinstall; states of unchanged views keep matching - across it, states of removed views are rejected as `unknown_view` until - the restart, and new views are `NotReady` (forwarded) until the - collector builds them. A live reload is later work. -11. **`definition_id` does not cover parameters or selection.** Verified on - the benchmark plan: α 0.05 and α 0.01 give the same id, and a label - matcher moves into `selection`. *Recommend:* identify a pushed view by - `(definition_id, selection)`, sent once per Resource, and check the - parameters from the decoded state (§6 step 3). If one plan ever holds - two views with equal id and selection but different parameters, the - decoded parameters pick the view; the control plane reports such a - plan. -12. **Dependency weight on the collector build.** `asap-types` adds - `serde_json`, `thiserror` 2 and a second `asap_sketchlib` rev (the - planner's) to the collector; it brings no executor, frontend or solver. - *Recommend:* accept it; it disappears with question 5's single - sketchlib pin. Measure the collector's clean build time before and - after in PR 5. -13. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP - HTTP (every collector deployment exports `otlp_http` today; the backend - already serves `/v1/metrics`; the Dictionary saving is recovered by the - `(stream_id, series_id)` cache). Next, an OTAP Arrow receiver fed by - `urn:otel:exporter:otap`, decoding with the `arrow-ipc` and `tonic` - the backend already builds, rather than the collector's - `otel-arrow-dfe-*` crates, which would add a second `datafusion` (53 - next to 54) and `tonic` (0.14 next to 0.12). -14. **Stream identity on OTLP.** OTLP HTTP has no stream, so the Dictionary - key needs one. *Recommend:* `sketch.stream_id`, a random 128-bit value - the collector draws at start and puts on every Resource; on OTAP Arrow - the gRPC stream is the stream. A restart is a new stream, which - replaces the earlier concern that `sketch.series_id` resets on restart. -15. **Reading `definition_id` from outside the planner.** In the planner's - types, `ViewCoverage`'s fields are crate-private and its - `definition_id()` accessor exists only under the `test-support` - feature; edges likewise have no public constructor outside it. Serde - reads and writes all of them. *Minimal need:* a public read of a plan - node's view coverage id and selection from a deserialized plan. - *Recommend:* until the planner offers one, both sides read the two - values from the node's JSON (`view_coverage.definition_id`, - `view_coverage.selection`), and the control plane builds a sub-DAG by - filtering the installed DAG's `nodes` and cloning its `edges`, which - the public fields allow; neither enables `test-support` in production. -16. **Sub-DAG validity.** No planner function extracts a sub-DAG. - *Minimal need:* that a two-node DAG copied from an installed plan, with - `roots = [view]`, passes `PhysicalASAPDAG::validate`. *Recommend:* the - collector's loader calls `validate` on each sub-DAG and PR 3 tests it - on the benchmark plan; if `validate` refuses such a DAG, the loader - keeps only its own shape check and the need is filed against the - planner in planner terms. -17. **One processor for all views, or one per view.** *Recommend:* one - `asap_sketches` node that builds every view in the file, so the - pipeline YAML never changes with the plan; the processor keys state by - (view, series), as the collector's data model already allows several - Schemas on one stream. + sketch type. Until the pins agree, leave HLL out of the collector's + printed capabilities if its envelope does not decode into the backend + kernel. +2. **Planner pin and file format.** Both sides read the same JSON with + `deny_unknown_fields`, versioned by `INSTALLABLE_PLAN_WIRE_VERSION` + (15 today), with no promise across versions. *Recommend:* the collector + pins the backend's planner rev and is bumped in the same change; the + loader refuses another `planner_wire_version`; PR 3 checks in the + benchmark's `pushed-views.json` and tests that it deserializes, so a + format change fails a test. +3. **Plan reinstall.** A view whose definition, θ and width did not change + keeps its key across plans. *Recommend:* the control plane rewrites the + file and the collector restarts on every reinstall. Until then, states + of unchanged views keep matching, states of removed views are + `unknown_view`, and new views are `NotReady` (forwarded). A live reload + is later work. +4. **Dependency weight on the collector build.** `asap-types` adds + `serde_json`, `thiserror` 2 and a second `asap_sketchlib` rev. + *Recommend:* accept it; it shrinks with question 1's single pin. Measure + the collector's clean build time before and after in PR 6. +5. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP + HTTP. Next, an OTAP Arrow adapter fed by `urn:otel:exporter:otap`, + decoding with the `arrow-ipc` and `tonic` the backend already builds, + rather than the collector's `otel-arrow-dfe-*` crates, which would add a + second `datafusion` (53 next to 54) and `tonic` (0.14 next to 0.12). +6. **Stream identity on OTLP.** OTLP HTTP has no stream. *Recommend:* + `sketch.stream_id`, a random 128-bit value drawn at collector start; on + OTAP Arrow the gRPC stream is the stream. +7. **Sub-DAG validity.** No planner function extracts a sub-DAG. + *Recommend:* the loader calls `materialized_views()` on each sub-DAG, + which validates it, and PR 3 tests this on the benchmark plan. If the + planner refuses such a DAG, file the need against the planner in its + terms. +8. **One processor for all views, or one per view.** *Recommend:* one + `asap_sketches` node that builds every view in the file, keyed by (view, + series); the pipeline YAML never changes with the plan. +9. **A window with no state at commit time.** It may mean the collector + was down, or that no series had samples. *Recommend:* do not store it; + queries over it are `NotReady` and forwarded to the fallback, which is + correct in both cases. Revisit if idle views forward often. +10. **Clock-skew allowance.** *Recommend:* 2 s by default (hosts run NTP, + which keeps them within milliseconds); raise it if the arrival-delay + histogram or `late_dropped` shows skew. From 6c6b5b885a491038a9c9232f1ed552a77a70ffc7 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 16:35:55 +0000 Subject: [PATCH 04/21] docs(design): rename pushed view to collector view A collector view is a materialized view of the installed plan that the collector builds instead of the backend. Renames the file (collector-views.json), CLI flags, types, function and metrics to match. --- docs/design/collector-sketch-ingest.md | 139 +++++++++++++------------ 1 file changed, 70 insertions(+), 69 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 1aba0be6c..65d6d5acb 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -20,7 +20,7 @@ sampled at 10 Hz, 50 samples become one state. When no other reader needs a metric's raw samples, the collector stops sending them to the backend. The collector is told what to build in the planner's own terms: for each -pushed view the control plane sends the view's sub-DAG of the installed +collector view the control plane sends the view's sub-DAG of the installed ASAPPlanner plan, and the collector depends on ASAPPlanner's types crate to read it. Every state carries the planner's **view state key**, so the backend finds the view by what the state is, not by a number both sides agree on. @@ -55,8 +55,9 @@ Terms, as in ASAPPlanner (`asap-types`): window ending at `e` covers `(e − w, e]`. - **State**: the summary of one series in one window; a sketch state is `asap_sketchlib`'s ASAPv1 bytes. -- **Pushed view**: a leaf view the collector builds; the backend only stores - and reads it. +- **Collector view**: a materialized view of the installed plan that the + collector builds instead of the backend (here always a leaf view); the + backend only stores and reads it. Scope: @@ -64,7 +65,7 @@ Scope: planner is adding; implementation starts after they merge. It needs no other planner change. - The backend changes in four places: a new ingest adapter, new `common` - types, the pushed-state ingest in precompute, and the control plane. + types, the collector-state ingest in precompute, and the control plane. - The collector changes in its own repository: a capabilities command, the `asap-types` dependency and a sub-DAG loader, key stamping, the window-boundary, out-of-order and matcher fixes, and a raw-forward filter. @@ -76,29 +77,29 @@ Scope: application ─ OTLP ─▶│ receiver ─┬─▶ asap_sketches (planner_views) ───────────────────▶ OTLP exporter│─┐ sketch path │ └─▶ raw forward (drops metrics with backend_reads_raw = false) ─▶ ...│─┤ raw path └─────────────────────────────────────────────────────────────────────────────┘ │ - asap_sketches --print-capabilities ─▶ capabilities.json ▲ pushed-views.json │ + asap_sketches --print-capabilities ─▶ capabilities.json ▲ collector-views.json │ │ │ ▼ workload ─▶ control-plane ─▶ InstallablePlan ─┼──────────────────────┼──────▶ data-plane POST /v1/metrics │ (asap-planner) ▼ │ ├─ point without sketch.envelope ─▶ otlp ─▶ IngestEngine - └─ push-down rule (reads capabilities.json) ────────────┘ └─ point with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch - (same pushed-views.json) ───────────────────────────────▶ data-plane ─▶ ViewStateIngest ─▶ precompute committer ─▶ view store + └─ collector view rule (reads capabilities.json) ───────┘ └─ point with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch + (same collector-views.json) ────────────────────────────▶ data-plane ─▶ ViewStateIngest ─▶ precompute committer ─▶ view store ``` | Component | Crate or repository | Role | |---|---|---| | Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares what the collector can build (§1) | -| Push-down rule | `crates/control-plane` | Picks the pushable leaf views of the installed plan against the capabilities; the only copy of the rule | -| Pushed-views file | `crates/control-plane` (`--emit-pushed-views`) | Each pushed view's sub-DAG, the plan id, which metrics the backend still reads raw, the commit grace | +| Collector view rule | `crates/control-plane` | Picks the leaf views of the installed plan the collector can build against the capabilities; the only copy of the rule | +| Collector-views file | `crates/control-plane` (`--emit-collector-views`) | Each collector view's sub-DAG, the plan id, which metrics the backend still reads raw, the commit grace | | `asap_sketches` processor | ASAPCollector-public | Loads the file at start, builds each view's per-series states, stamps the view state key, exports OTLP summary points with `sketch.envelope` | | Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | | `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Turns those points into `common::ViewStateBatch`es; never reads the sketch bytes | -| Pushed-state ingest | `crates/precompute` | Finds the view by key and selection, stages, deduplicates and merges until commit, drops late states | +| Collector-state ingest | `crates/precompute` | Finds the view by key and selection, stages, deduplicates and merges until commit, drops late states | **Raw path.** The raw path stays (decision 3) for every metric the backend still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` -of it feeds a view that is not pushed or runs at query time. A metric whose -only readers are pushed views is marked `false`, and the collector's raw -forward to the backend drops it. When a pushed view misses a window (the +of it feeds a view that is not a collector view or runs at query time. A metric whose +only readers are collector views is marked `false`, and the collector's raw +forward to the backend drops it. When a collector view misses a window (the collector was down), the query engine reports `NotReady` and the dispatcher forwards the query to the fallback store, which receives raw samples on its own path, not through this forward. @@ -127,7 +128,7 @@ Decoding is not an identity check: θ is already in the key. ## Algorithm -### 1. Capabilities and the push-down rule (control plane) +### 1. Capabilities and the collector view rule (control plane) The collector declares what it can build; the backend holds no table of the collector's sketches. `asap_sketches --print-capabilities` prints, for @@ -159,7 +160,7 @@ today's collector (planner names; the collector maps them to its own): The control plane reads the file with `--collector-capabilities ` and refuses a `capabilities_version` it does not know. A node of the -installed plan's `dag` is pushed if and only if all of these hold, read +installed plan's `dag` is a collector view if and only if all of these hold, read from its planner fields (no cost comparison, decision 6): @@ -170,7 +171,7 @@ decision 6): node in between, and the chain's `filter` is `null`. 3. **Within the capabilities.** `summary_type`, `input` and every `parameters` value match one `summaries` entry; `reduction` is in - `reductions` (`PerEntity`: a `Reduce [...]` view is not pushed, because + `reductions` (`PerEntity`: a `Reduce [...]` view is not a collector view, because one collector does not see every series of a group); the window kind is in `windows`; the `Scan`'s `predicates` are a conjunction of `predicate_ops` comparisons. @@ -178,18 +179,18 @@ decision 6): **Exact aggregates stay in the backend.** The collector's `Exact` type (`EXv1`, every value of a window) is a baseline for comparisons, not a `sum`, `max` or counter state, and it is not in the capabilities. Views of -`ExactAggregate` become pushable when the collector declares them. +`ExactAggregate` become collector views when the collector declares them. **Known limitation: sparse series.** The rule ignores size. A series with few samples per window can produce a state larger than its raw samples (a DDSketch with one sample still carries its header, mapping and bins, against about 16 bytes for the raw sample). Step 4 of the plan measures -where this happens. Cost-based push-down is future work; it needs a general +where this happens. Cost-based choice of collector views is future work; it needs a general planner capability (costing where a view is built). -### 2. The pushed-views file (control plane) +### 2. The collector-views file (control plane) -For each pushed view the control plane copies, from the installed `dag`, +For each collector view the control plane copies, from the installed `dag`, the view node and its `Scan` node (unchanged, node ids included) and the one edge between them, and sets `roots = [view node]`, `scalar_roots = []`. It writes one JSON file, with the planner types' own serde: @@ -207,10 +208,10 @@ one edge between them, and sets `roots = [view node]`, `scalar_roots = The collector loads the file once at start (a plan change is a collector restart, open question 3). The data plane takes the same file with -`--pushed-views` and refuses it, at start and on each install, when its +`--collector-views` and refuses it, at start and on each install, when its `plan_id` differs from the installed plan's. The precompute engine then -compiles each refresh group without the pushed views (and without a `Scan` -only they read). The query engine is unchanged; it reads a pushed view +compiles each refresh group without the collector views (and without a `Scan` +only they read). The query engine is unchanged; it reads a collector view from the store like any other. ### 3. The collector: load, check, build, stamp @@ -226,7 +227,7 @@ At start, with `planner_views: ` in its processor config, the `TimeSeries { metric }`, and its summary, parameters, reduction, window and predicates are within the collector's own capabilities (the same table `--print-capabilities` prints). It does not check *whether* the - view should be pushed (timing, lifetime): that is the control plane's + view should be a collector view (timing, lifetime): that is the control plane's rule, written once. 3. **Reads each view's key** with `materialized_views()` on the sub-DAG and `view_state_key()`: the key depends only on the view node, so it equals @@ -354,10 +355,10 @@ The collector change: ### 6. The sketch path in the data plane `POST /v1/metrics` decodes the request once. Each summary data point that -carries a `sketch.envelope` bytes attribute is a pushed state; every other +carries a `sketch.envelope` bytes attribute is a collector state; every other point is a raw sample, as today. A request may carry both. -The adapter groups the pushed points by `sketch.stream_id`, then by +The adapter groups the collector-state points by `sketch.stream_id`, then by (`sketch.view_state_key`, `sketch.selection`), into one `ViewStateBatch` per stream. It refuses the request (400) when a Resource lacks one of these attributes or they do not parse, or `sketch.schema_version` is newer than @@ -385,12 +386,12 @@ The ingest engine then, per view and record: rejected (`reason="decode"`). 5. **Stage, dedup, merge, commit**, below. -Every rejection increments `asap_pushed_states_rejected_total{view, +Every rejection increments `asap_collector_states_rejected_total{view, reason}` and logs once per view and reason per minute; the request still returns 200 with the counts, as the raw OTLP route reports `rejected`. **Staging.** The view store appends a view's windows in order and each -window once, so a pushed window is committed once and whole. The engine +window once, so a collector view's window is committed once and whole. The engine stages states per `(view, window)` and commits through the precompute committer, the same path that commits a window it built (readers, `RefreshTaskGraph` ordering, persistence and the memory budget all apply). @@ -404,7 +405,7 @@ committer, the same path that commits a window it built (readers, is merged into the staged one (sketch merge): a collector that restarted inside a window, or two collectors that each saw part of one series. States are full, not deltas, and each partial covers other samples. -- **Commit time.** No raw samples of a pushed view's metric need reach the +- **Commit time.** No raw samples of a collector view's metric need reach the backend, so the raw watermark cannot close its windows. A window commits when the backend's wall clock passes `end + commit_grace_ms`, with @@ -414,7 +415,7 @@ committer, the same path that commits a window it built (readers, interval (`--collector-export-interval-ms`, default 0: today's pipelines export each processor message at once), and an allowance for clock skew (default 2 s). Default: 8 s. The control plane writes it into the file; - each pushed view's retention must exceed it. + each collector view's retention must exceed it. - **No states.** A window with no staged state at commit time is not stored; a query that reads it gets `NotReady` and is forwarded to the fallback (open question 9). @@ -433,19 +434,19 @@ committer, the same path that commits a window it built (readers, use asap_types::plan::materialized_view::ViewStateKey; use asap_types::ir::properties::selection::SelectionBox; -/// Pushed states from one collector stream: what the sketch-path ingest +/// Collector states from one collector stream: what the sketch-path ingest /// adapter hands the ingest engine. Nested by OTAP tier, so a view's key and /// a series' labels appear once, not per record. Never data between operators. #[derive(Debug, Clone, PartialEq)] pub struct ViewStateBatch { /// Random per collector start; scopes `series_id`. pub stream_id: u128, - pub views: Vec, + pub views: Vec, } -/// One pushed view's states in the batch. +/// One collector view's states in the batch. #[derive(Debug, Clone, PartialEq)] -pub struct PushedViewStates { +pub struct CollectorViewStates { pub key: ViewStateKey, /// The view's coverage selection, as the planner serializes it. pub selection: Vec, @@ -477,7 +478,7 @@ pub struct ViewStateIngestReport { pub rejected: BTreeMap<&'static str, u64>, } -/// Takes pushed states. Implemented by the ingest engine, next to `IngestEngine`. +/// Takes collector states. Implemented by the ingest engine, next to `IngestEngine`. #[async_trait] pub trait ViewStateIngest: Send + Sync { /// Checks, stages or merges each record; waits under backpressure as @@ -487,12 +488,12 @@ pub trait ViewStateIngest: Send + Sync { } ``` -`ViewStore` is unchanged: every pushed window is `put` once, at commit. +`ViewStore` is unchanged: every collector view window is `put` once, at commit. ### `crates/adapters/ingest/asap-sketch-otlp` ```rust -/// Why a request's pushed states could not be read; the whole request is +/// Why a request's collector states could not be read; the whole request is /// refused with 400. Per-record problems are counted, not errors. #[derive(Debug, thiserror::Error, PartialEq)] pub enum SketchOtlpError { @@ -506,11 +507,11 @@ pub enum SketchOtlpError { SchemaVersion(u64), } -/// Whether an OTLP data point carries a pushed state (a `sketch.envelope` +/// Whether an OTLP data point carries a collector state (a `sketch.envelope` /// bytes attribute): the route's test for the sketch path. pub fn is_sketch_point(attributes: &[KeyValue]) -> bool; -/// The pushed states of a decoded OTLP request, one batch per stream; points +/// The collector states of a decoded OTLP request, one batch per stream; points /// without `sketch.envelope` are left to the raw `otlp` decoder. pub fn decode_view_states( request: &ExportMetricsServiceRequest, @@ -547,39 +548,39 @@ pub struct SummaryCapability { /// The file the collector and the data plane load. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] -pub struct PushedViewsFile { +pub struct CollectorViewsFile { pub planner_wire_version: u32, /// `PhysicalASAPDAG::plan_id()` of the installed plan. pub plan_id: String, pub commit_grace_ms: u64, - /// Per metric a `Scan` reads: whether a view that is not pushed, or a + /// Per metric a `Scan` reads: whether a view that is not a collector view, or a /// query-time `Scan`, still reads its raw samples. pub backend_reads_raw: BTreeMap, - /// One sub-DAG per pushed view; `roots = [view node]`. + /// One sub-DAG per collector view; `roots = [view node]`. pub views: Vec, } -/// Why a leaf view is not pushed, for the command's report. +/// Why a leaf view is not a collector view, for the command's report. #[derive(Debug, Clone, PartialEq)] -pub enum NotPushed { +pub enum NotCollectorView { NotOnRawScan, NotInCapabilities(String), } -/// The installed plan's pushed views and why each other view is not pushed. -pub fn pushed_view_dags( +/// The installed plan's collector views and why each other view is not. +pub fn collector_view_dags( plan: &InstallablePlan, capabilities: &CollectorCapabilities, export_interval_ms: u64, -) -> (PushedViewsFile, Vec<(PhysicalASAPNodeId, NotPushed)>); +) -> (CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotCollectorView)>); ``` `FieldDataType` (the chain's `summary_type`) and `CompareOpKind` are the planner's types. CLI: `control_plane --plan --collector-capabilities [--collector-export-interval-ms ] ---emit-pushed-views `; the data plane takes -`--pushed-views `. +--emit-collector-views `; the data plane takes +`--collector-views `. ## Worked example: q01 @@ -596,7 +597,7 @@ n4 SummaryEstimate Quantile(q=0.99) n5 Project (root) ``` -n1 passes the rule. Its sub-DAG in `pushed-views.json` (schemas +n1 passes the rule. Its sub-DAG in `collector-views.json` (schemas shortened to their field names; the file carries them in full): ```json @@ -647,7 +648,7 @@ per series. Its pipeline config names only the file: sketch: type: urn:asap:processor:asap_sketches config: - planner_views: /etc/asap/pushed-views.json + planner_views: /etc/asap/collector-views.json ``` For one series `data{region="r0",service="s0",job="j0",label_0="l0"}`, the @@ -669,7 +670,7 @@ DDSketch and exports one summary point: | Point (Record) | `sketch.envelope` | ASAPv1 bytes | | Point (Record) | `count` | `50` | -The adapter makes one `ViewStateBatch` with one `PushedViewStates` (n1's +The adapter makes one `ViewStateBatch` with one `CollectorViewStates` (n1's key and selection), one series `(17, labels)` and one record `(17, T, bytes, 50)`. The backend finds n1 by key and selection, checks that `T` is a multiple of 5 s, translates `(stream_id, n1, 17)` to its series id, @@ -686,7 +687,7 @@ also feeds q02's and q03's chains (`backend_reads_raw.data = true`). All five are evaluated every 5 s over 1 m ranges; the planner builds each one's leaf as a 5 s tumbling chain over its `Scan`: -| Query | Leaf view (summary type, reduction) | Pushed | Why | +| Query | Leaf view (summary type, reduction) | Collector view | Why | |---|---|---|---| | q01 `quantile_over_time(0.99, data[1m])` | `Sketch: DDSketch` α 0.05, `PerEntity` | yes | passes every rule | | q02 `max_over_time(data[1m])` | `ExactAggregate: Max`, `PerEntity` | no | not in the capabilities | @@ -698,7 +699,7 @@ For this workload the collector builds one view, the backend still builds four, and both metrics are `backend_reads_raw: true`, so every raw sample still reaches the backend. The expected benefit here is about zero: the backend saves only n1's DDSketch updates, and the network carries the -pushed states on top of the unchanged raw samples. With q01 alone, `data` +collector states on top of the unchanged raw samples. With q01 alone, `data` is read only by n1, so it is marked `false` and its raw samples no longer reach the backend: 50 samples per series per window become one state. @@ -720,18 +721,18 @@ Backend: (other θ), one duplicate after a merge, one late state and one restart (new `stream_id`, reused `series_id`). 3. The control plane's rule with `--collector-capabilities`, - `--emit-pushed-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, - `commit_grace_ms`); the data plane's `--pushed-views` with the plan-id - check; precompute skips pushed views. Tests: the benchmark plan pushes - exactly q01's sub-DAG and marks both metrics raw; a q01-only plan marks + `--emit-collector-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, + `commit_grace_ms`); the data plane's `--collector-views` with the plan-id + check; precompute skips collector views. Tests: the benchmark plan + gives exactly q01's sub-DAG as a collector view and marks both metrics raw; a q01-only plan marks `data` `false`; a regex matcher, a `Reduce` leaf or an `ExactAggregate` - leaf pushes nothing; a file of another plan id is refused; the written + leaf gives no collector view; a file of another plan id is refused; the written file deserializes and `materialized_views()` on each sub-DAG gives the installed view's key. 4. End-to-end comparison, collector + backend against backend only, on the same feed, for two workloads: the five-query benchmark set (expected - benefit about zero, above) and q01 alone (the pushed metric has only - pushed readers, so its raw samples stay at the collector). Answers equal + benefit about zero, above) and q01 alone (the metric has only collector-view + readers, so its raw samples stay at the collector). Answers equal (exact views) or within the plan's error (sketch views) at every evaluation; backend ingest CPU, network bytes between collector and backend, collector CPU, `late_dropped`; including a sparse-series case. @@ -753,11 +754,11 @@ Collector (ASAPCollector-public): **Future work.** Late merge into a committed window (a store `replace`, a view-file rewrite and result-cache invalidation), only if step 4 or production shows a late rate worth it, measured by `late_dropped` and the -arrival-delay histogram. Cost-based push-down. The OTAP Arrow adapter. +arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow adapter. ## Decisions -1. **The planner's identity, no other planner change.** A pushed state is +1. **The planner's identity, no other planner change.** A collector state is identified by the planner's view state key plus its concrete selection; within the installed plan a view is `(plan_id, node_id)`. θ and window width are in the key, so a state of another θ or width is simply @@ -767,7 +768,7 @@ arrival-delay histogram. Cost-based push-down. The OTAP Arrow adapter. states.** No deltas: each record holds the whole state of one series in one window. 3. **Two paths.** The raw path stays for every metric the backend still - reads raw. The sketch path carries pushed states on the same + reads raw. The sketch path carries collector states on the same `/v1/metrics` route; a point with `sketch.envelope` takes it. 4. **Prometheus window semantics on both sides**: `(t − range, t]`. The backend already uses it; the collector changes in its own PR. The window @@ -775,14 +776,14 @@ arrival-delay histogram. Cost-based push-down. The OTAP Arrow adapter. 5. **Dedup and merge before commit.** A state whose envelope hash was already seen for its view, series and window is ignored and counted; a state with a new hash is merged. -6. **Rule-based push-down first**, against the collector's declared +6. **Rule-based choice of collector views first**, against the collector's declared capabilities. No cost comparison. Exact aggregates stay in the backend until the collector declares them. 7. **The collector receives the planner's own view definitions**: each - pushed view's sub-DAG, in the planner's serde; the collector depends on + collector view's sub-DAG, in the planner's serde; the collector depends on the planner's types crate, pinned. This replaces a numeric `agg_id` and - a hand-written collector config. The backend's precompute skips pushed - views. The data plane refuses a pushed-views file of another `plan_id`. + a hand-written collector config. The backend's precompute skips collector + views. The data plane refuses a collector-views file of another `plan_id`. 8. **The collector declares its capabilities** (`--print-capabilities`); the control plane's rule reads them. The rule exists once, in the control plane; the collector checks only that it can execute each sub-DAG. @@ -815,7 +816,7 @@ Each with a recommendation. (15 today), with no promise across versions. *Recommend:* the collector pins the backend's planner rev and is bumped in the same change; the loader refuses another `planner_wire_version`; PR 3 checks in the - benchmark's `pushed-views.json` and tests that it deserializes, so a + benchmark's `collector-views.json` and tests that it deserializes, so a format change fails a test. 3. **Plan reinstall.** A view whose definition, θ and width did not change keeps its key across plans. *Recommend:* the control plane rewrites the From 8d5a9c96ad044873c51b28b57d1662332e821e6c Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 16:37:08 +0000 Subject: [PATCH 05/21] docs(design): one latest planner and sketchlib for all three repos Former open questions 1 and 2 become Decision 13: the backend and the collector pin the same latest ASAPPlanner main, all three repos pin the same latest asap_sketchlib main, bumped together; the collector refuses another planner wire version. The Plan gains a pin-bump first step. --- docs/design/collector-sketch-ingest.md | 88 +++++++++++++------------- 1 file changed, 45 insertions(+), 43 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 65d6d5acb..b8f225ec0 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -124,7 +124,7 @@ Decoding is not an identity check: θ is already in the key. `asap-types` brings `serde`, `serde_json`, `thiserror` 2 and `asap_sketchlib` into the collector build; no executor, frontend or solver -(open question 4). +(open question 2). ## Algorithm @@ -184,7 +184,7 @@ decision 6): **Known limitation: sparse series.** The rule ignores size. A series with few samples per window can produce a state larger than its raw samples (a DDSketch with one sample still carries its header, mapping and bins, -against about 16 bytes for the raw sample). Step 4 of the plan measures +against about 16 bytes for the raw sample). Step 5 of the plan measures where this happens. Cost-based choice of collector views is future work; it needs a general planner capability (costing where a view is built). @@ -207,7 +207,7 @@ one edge between them, and sets `roots = [view node]`, `scalar_roots = - `commit_grace_ms` is computed as in §6. The collector loads the file once at start (a plan change is a collector -restart, open question 3). The data plane takes the same file with +restart, open question 1). The data plane takes the same file with `--collector-views` and refuses it, at start and on each install, when its `plan_id` differs from the installed plan's. The precompute engine then compiles each refresh group without the collector views (and without a `Scan` @@ -304,7 +304,7 @@ accepts OTLP HTTP (every collector deployment exports with `urn:otel:exporter:otlp_http` today, and the backend already serves `/v1/metrics`); the OTLP adapter builds the nesting above, and the series cache still interns each series once per stream. A later OTAP Arrow -adapter fills the same `ViewStateBatch` (open question 5). +adapter fills the same `ViewStateBatch` (open question 3). **Collector restart.** A restart starts a new stream: new `stream_id`, and `series_id` starts again at 1. The backend never reuses a translation @@ -418,7 +418,7 @@ committer, the same path that commits a window it built (readers, each collector view's retention must exceed it. - **No states.** A window with no staged state at commit time is not stored; a query that reads it gets `NotReady` and is forwarded to the - fallback (open question 9). + fallback (open question 7). - **Late states.** A state that arrives after its window committed is dropped and counted (`late_dropped`), whatever its reason: an export slower than the grace, or a collector clock behind the backend's by more @@ -706,13 +706,18 @@ reach the backend: 50 samples per series per window become one state. ## Plan Separate PRs, each reviewed on its own. Backend implementation starts after -the planner's view state key and plan id merge; the backend and collector -then bump their planner pin to that revision. +the planner's view state key and plan id merge and step 1 has bumped the +pins to a planner revision that has them. + +Pins (all three repositories): + +1. Bump the ASAPPlanner and `asap_sketchlib` pins to the latest main + (Decision 13), in the planner, then the backend, then the collector. Backend: -1. This document. -2. `ViewStateBatch` and `ViewStateIngest` in `common`; the +2. This document. +3. `ViewStateBatch` and `ViewStateIngest` in `common`; the `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by key and selection, the series cache, staging, the hash set, merge before commit, commit at grace, late drop. Test data: real ASAPv1 records the collector @@ -720,7 +725,7 @@ Backend: wrote them), for each of the six sketch types, including one unknown key (other θ), one duplicate after a merge, one late state and one restart (new `stream_id`, reused `series_id`). -3. The control plane's rule with `--collector-capabilities`, +4. The control plane's rule with `--collector-capabilities`, `--emit-collector-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, `commit_grace_ms`); the data plane's `--collector-views` with the plan-id check; precompute skips collector views. Tests: the benchmark plan @@ -729,7 +734,7 @@ Backend: leaf gives no collector view; a file of another plan id is refused; the written file deserializes and `materialized_views()` on each sub-DAG gives the installed view's key. -4. End-to-end comparison, collector + backend against backend only, on the +5. End-to-end comparison, collector + backend against backend only, on the same feed, for two workloads: the five-query benchmark set (expected benefit about zero, above) and q01 alone (the metric has only collector-view readers, so its raw samples stay at the collector). Answers equal @@ -739,20 +744,20 @@ Backend: Collector (ASAPCollector-public): -5. `--print-capabilities`, printed from the config validation code. -6. `asap-types` as a pinned git dependency (the backend's planner pin); the +6. `--print-capabilities`, printed from the config validation code. +7. `asap-types` as a pinned git dependency (the backend's planner pin); the `planner_views` loader with the executability check; key and selection stamping (`sketch.view_state_key`, `sketch.selection`, `sketch.stream_id` on the Resource, replacing `sketch.agg_id`); `series_id` per (view, series); config errors for the per-sketch fields when it is set. -7. The window boundary `(e − w, e]` in `SketchEnvelope` and the point +8. The window boundary `(e − w, e]` in `SketchEnvelope` and the point times (window attributes removed), placement by sample timestamp with - drop-and-count after close, and matchers (§5). It lands before step 4, + drop-and-count after close, and matchers (§5). It lands before step 5, which needs equal windows. -8. The raw-forward filter by `backend_reads_raw`. +9. The raw-forward filter by `backend_reads_raw`. **Future work.** Late merge into a committed window (a store `replace`, a -view-file rewrite and result-cache invalidation), only if step 4 or +view-file rewrite and result-cache invalidation), only if step 5 or production shows a late rate worth it, measured by `late_dropped` and the arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow adapter. @@ -799,55 +804,52 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 12. **`ViewStateBatch` is nested by OTAP tier** (stream → view → series → records); the OTLP adapter builds the nesting, an OTAP adapter fills the same type. +13. **One planner and one sketchlib, the latest.** The backend and the + collector pin the same ASAPPlanner revision, the latest main; the + planner, the backend and the collector pin the same `asap_sketchlib` + revision, the latest main. All three are bumped together. Both sides + read the same JSON with `deny_unknown_fields`, versioned by + `INSTALLABLE_PLAN_WIRE_VERSION`, and the collector refuses a + collector-views file with another `planner_wire_version`. PR 3's + captured records stay the compatibility test, one per sketch type, and + PR 4 checks in the benchmark's `collector-views.json` and tests that it + deserializes, so a format change fails a test. No sketch type, HLL + included, is left out on version grounds. ## Open questions Each with a recommendation. -1. **sketchlib versions differ.** The collector pins `asap_sketchlib` - `60101c6`, the backend `355093f`, and the planner `389530c`; the - collector's HLL is an Ertl HLL, the backend's kernel Classic. - *Recommend:* PR 2's captured records are the compatibility test, one per - sketch type. Until the pins agree, leave HLL out of the collector's - printed capabilities if its envelope does not decode into the backend - kernel. -2. **Planner pin and file format.** Both sides read the same JSON with - `deny_unknown_fields`, versioned by `INSTALLABLE_PLAN_WIRE_VERSION` - (15 today), with no promise across versions. *Recommend:* the collector - pins the backend's planner rev and is bumped in the same change; the - loader refuses another `planner_wire_version`; PR 3 checks in the - benchmark's `collector-views.json` and tests that it deserializes, so a - format change fails a test. -3. **Plan reinstall.** A view whose definition, θ and width did not change +1. **Plan reinstall.** A view whose definition, θ and width did not change keeps its key across plans. *Recommend:* the control plane rewrites the file and the collector restarts on every reinstall. Until then, states of unchanged views keep matching, states of removed views are `unknown_view`, and new views are `NotReady` (forwarded). A live reload is later work. -4. **Dependency weight on the collector build.** `asap-types` adds - `serde_json`, `thiserror` 2 and a second `asap_sketchlib` rev. - *Recommend:* accept it; it shrinks with question 1's single pin. Measure - the collector's clean build time before and after in PR 6. -5. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP +2. **Dependency weight on the collector build.** `asap-types` adds + `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin + (Decision 13) it adds no second sketchlib. *Recommend:* accept it. + Measure the collector's clean build time before and after in PR 7. +3. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP HTTP. Next, an OTAP Arrow adapter fed by `urn:otel:exporter:otap`, decoding with the `arrow-ipc` and `tonic` the backend already builds, rather than the collector's `otel-arrow-dfe-*` crates, which would add a second `datafusion` (53 next to 54) and `tonic` (0.14 next to 0.12). -6. **Stream identity on OTLP.** OTLP HTTP has no stream. *Recommend:* +4. **Stream identity on OTLP.** OTLP HTTP has no stream. *Recommend:* `sketch.stream_id`, a random 128-bit value drawn at collector start; on OTAP Arrow the gRPC stream is the stream. -7. **Sub-DAG validity.** No planner function extracts a sub-DAG. +5. **Sub-DAG validity.** No planner function extracts a sub-DAG. *Recommend:* the loader calls `materialized_views()` on each sub-DAG, - which validates it, and PR 3 tests this on the benchmark plan. If the + which validates it, and PR 4 tests this on the benchmark plan. If the planner refuses such a DAG, file the need against the planner in its terms. -8. **One processor for all views, or one per view.** *Recommend:* one +6. **One processor for all views, or one per view.** *Recommend:* one `asap_sketches` node that builds every view in the file, keyed by (view, series); the pipeline YAML never changes with the plan. -9. **A window with no state at commit time.** It may mean the collector +7. **A window with no state at commit time.** It may mean the collector was down, or that no series had samples. *Recommend:* do not store it; queries over it are `NotReady` and forwarded to the fallback, which is correct in both cases. Revisit if idle views forward often. -10. **Clock-skew allowance.** *Recommend:* 2 s by default (hosts run NTP, +8. **Clock-skew allowance.** *Recommend:* 2 s by default (hosts run NTP, which keeps them within milliseconds); raise it if the arrival-delay histogram or `late_dropped` shows skew. From c9ac1ad6c87bc9e725f1bb63118dbc6100bb1129 Mon Sep 17 00:00:00 2001 From: zzylol Date: Fri, 27 Nov 2026 21:57:57 +0000 Subject: [PATCH 06/21] docs(design): decide open questions as decisions 14-21 All eight recommendations accepted. The planner's view state key and plan id are on the planner main; the remaining prerequisite is the pin bump. --- docs/design/collector-sketch-ingest.md | 92 +++++++++++++------------- 1 file changed, 45 insertions(+), 47 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index b8f225ec0..9b0dd7d36 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -61,9 +61,10 @@ Terms, as in ASAPPlanner (`asap-types`): Scope: -- The design needs the planner's view state key and plan id, which the - planner is adding; implementation starts after they merge. It needs no - other planner change. +- The design needs the planner's view state key and plan id, which are on + the planner's main. The remaining prerequisite is the backend's planner + and `asap_sketchlib` pin bump (Plan, step 1). It needs no other planner + change. - The backend changes in four places: a new ingest adapter, new `common` types, the collector-state ingest in precompute, and the control plane. - The collector changes in its own repository: a capabilities command, the @@ -124,7 +125,7 @@ Decoding is not an identity check: θ is already in the key. `asap-types` brings `serde`, `serde_json`, `thiserror` 2 and `asap_sketchlib` into the collector build; no executor, frontend or solver -(open question 2). +(decision 15). ## Algorithm @@ -207,7 +208,7 @@ one edge between them, and sets `roots = [view node]`, `scalar_roots = - `commit_grace_ms` is computed as in §6. The collector loads the file once at start (a plan change is a collector -restart, open question 1). The data plane takes the same file with +restart, decision 14). The data plane takes the same file with `--collector-views` and refuses it, at start and on each install, when its `plan_id` differs from the installed plan's. The precompute engine then compiles each refresh group without the collector views (and without a `Scan` @@ -304,7 +305,7 @@ accepts OTLP HTTP (every collector deployment exports with `urn:otel:exporter:otlp_http` today, and the backend already serves `/v1/metrics`); the OTLP adapter builds the nesting above, and the series cache still interns each series once per stream. A later OTAP Arrow -adapter fills the same `ViewStateBatch` (open question 3). +adapter fills the same `ViewStateBatch` (decision 16). **Collector restart.** A restart starts a new stream: new `stream_id`, and `series_id` starts again at 1. The backend never reuses a translation @@ -418,7 +419,7 @@ committer, the same path that commits a window it built (readers, each collector view's retention must exceed it. - **No states.** A window with no staged state at commit time is not stored; a query that reads it gets `NotReady` and is forwarded to the - fallback (open question 7). + fallback (decision 20). - **Late states.** A state that arrives after its window committed is dropped and counted (`late_dropped`), whatever its reason: an export slower than the grace, or a collector clock behind the backend's by more @@ -705,9 +706,9 @@ reach the backend: 50 samples per series per window become one state. ## Plan -Separate PRs, each reviewed on its own. Backend implementation starts after -the planner's view state key and plan id merge and step 1 has bumped the -pins to a planner revision that has them. +Separate PRs, each reviewed on its own. The planner's view state key and +plan id are on its main; backend implementation starts once step 1 has +bumped the pins to a planner revision that has them. Pins (all three repositories): @@ -810,46 +811,43 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad revision, the latest main. All three are bumped together. Both sides read the same JSON with `deny_unknown_fields`, versioned by `INSTALLABLE_PLAN_WIRE_VERSION`, and the collector refuses a - collector-views file with another `planner_wire_version`. PR 3's + collector-views file with another `planner_wire_version`. Step 3's captured records stay the compatibility test, one per sketch type, and - PR 4 checks in the benchmark's `collector-views.json` and tests that it + step 4 checks in the benchmark's `collector-views.json` and tests that it deserializes, so a format change fails a test. No sketch type, HLL included, is left out on version grounds. +14. **Plan reinstall.** A view whose definition, θ and width did not change + keeps its key across plans. The control plane rewrites the file and the + collector restarts on every reinstall. Until then, states of unchanged + views keep matching, states of removed views are `unknown_view`, and new + views are `NotReady` (forwarded). A live reload is later work. +15. **Dependency weight on the collector build.** `asap-types` adds + `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin (Decision + 13) it adds no second sketchlib. Accept it. Measure the collector's clean build + time before and after in step 7. +16. **Transport: OTLP HTTP or OTAP Arrow.** V1 accepts OTLP HTTP. Next, an + OTAP Arrow adapter fed by `urn:otel:exporter:otap`, decoding with the + `arrow-ipc` and `tonic` the backend already builds, rather than the + collector's `otel-arrow-dfe-*` crates, which would add a second + `datafusion` (53 next to 54) and `tonic` (0.14 next to 0.12). +17. **Stream identity on OTLP.** OTLP HTTP has no stream. + `sketch.stream_id`, a random 128-bit value drawn at collector start; on + OTAP Arrow the gRPC stream is the stream. +18. **Sub-DAG validity.** No planner function extracts a sub-DAG. The loader + calls `materialized_views()` on each sub-DAG, which validates it, and + step 4 tests this on the benchmark plan. If the planner refuses such a DAG, + file the need against the planner in its terms. +19. **One processor for all views, or one per view.** One `asap_sketches` + node that builds every view in the file, keyed by (view, series); the + pipeline YAML never changes with the plan. +20. **A window with no state at commit time.** It may mean the collector was + down, or that no series had samples. Do not store it; queries over it + are `NotReady` and forwarded to the fallback, which is correct in both + cases. Revisit if idle views forward often. +21. **Clock-skew allowance.** 2 s by default (hosts run NTP, which keeps + them within milliseconds); raise it if the arrival-delay histogram or + `late_dropped` shows skew. ## Open questions -Each with a recommendation. - -1. **Plan reinstall.** A view whose definition, θ and width did not change - keeps its key across plans. *Recommend:* the control plane rewrites the - file and the collector restarts on every reinstall. Until then, states - of unchanged views keep matching, states of removed views are - `unknown_view`, and new views are `NotReady` (forwarded). A live reload - is later work. -2. **Dependency weight on the collector build.** `asap-types` adds - `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin - (Decision 13) it adds no second sketchlib. *Recommend:* accept it. - Measure the collector's clean build time before and after in PR 7. -3. **Transport: OTLP HTTP or OTAP Arrow.** *Recommend:* v1 accepts OTLP - HTTP. Next, an OTAP Arrow adapter fed by `urn:otel:exporter:otap`, - decoding with the `arrow-ipc` and `tonic` the backend already builds, - rather than the collector's `otel-arrow-dfe-*` crates, which would add a - second `datafusion` (53 next to 54) and `tonic` (0.14 next to 0.12). -4. **Stream identity on OTLP.** OTLP HTTP has no stream. *Recommend:* - `sketch.stream_id`, a random 128-bit value drawn at collector start; on - OTAP Arrow the gRPC stream is the stream. -5. **Sub-DAG validity.** No planner function extracts a sub-DAG. - *Recommend:* the loader calls `materialized_views()` on each sub-DAG, - which validates it, and PR 4 tests this on the benchmark plan. If the - planner refuses such a DAG, file the need against the planner in its - terms. -6. **One processor for all views, or one per view.** *Recommend:* one - `asap_sketches` node that builds every view in the file, keyed by (view, - series); the pipeline YAML never changes with the plan. -7. **A window with no state at commit time.** It may mean the collector - was down, or that no series had samples. *Recommend:* do not store it; - queries over it are `NotReady` and forwarded to the fallback, which is - correct in both cases. Revisit if idle views forward often. -8. **Clock-skew allowance.** *Recommend:* 2 s by default (hosts run NTP, - which keeps them within milliseconds); raise it if the arrival-delay - histogram or `late_dropped` shows skew. +None open. From 49620cc208f8e5fae852347ec227330c097a7063 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 01:33:44 +0000 Subject: [PATCH 07/21] docs(design): collector state ingest is a PrecomputeEngine method, not a trait The layout stack deleted IngestEngine and the common ViewStore trait; a trait is added with its second implementation. --- docs/design/collector-sketch-ingest.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 9b0dd7d36..eacce1357 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -81,9 +81,9 @@ Scope: asap_sketches --print-capabilities ─▶ capabilities.json ▲ collector-views.json │ │ │ ▼ workload ─▶ control-plane ─▶ InstallablePlan ─┼──────────────────────┼──────▶ data-plane POST /v1/metrics - │ (asap-planner) ▼ │ ├─ point without sketch.envelope ─▶ otlp ─▶ IngestEngine + │ (asap-planner) ▼ │ ├─ point without sketch.envelope ─▶ otlp ─▶ PrecomputeEngine::try_ingest └─ collector view rule (reads capabilities.json) ───────┘ └─ point with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch - (same collector-views.json) ────────────────────────────▶ data-plane ─▶ ViewStateIngest ─▶ precompute committer ─▶ view store + (same collector-views.json) ────────────────────────────▶ data-plane ─▶ PrecomputeEngine::ingest_collector_states ─▶ committer ─▶ storage::ViewStore ``` | Component | Crate or repository | Role | @@ -436,7 +436,8 @@ use asap_types::plan::materialized_view::ViewStateKey; use asap_types::ir::properties::selection::SelectionBox; /// Collector states from one collector stream: what the sketch-path ingest -/// adapter hands the ingest engine. Nested by OTAP tier, so a view's key and +/// adapter hands `PrecomputeEngine`. In `common` because the adapter depends only on `common` +/// and must produce it. Nested by OTAP tier, so a view's key and /// a series' labels appear once, not per record. Never data between operators. #[derive(Debug, Clone, PartialEq)] pub struct ViewStateBatch { @@ -470,7 +471,7 @@ pub struct ViewStateRecord { /// What happened to a batch's records. #[derive(Debug, Clone, Default, PartialEq, Eq)] -pub struct ViewStateIngestReport { +pub struct CollectorStateIngestReport { pub staged: u64, pub duplicate: u64, pub merged: u64, @@ -479,17 +480,16 @@ pub struct ViewStateIngestReport { pub rejected: BTreeMap<&'static str, u64>, } -/// Takes collector states. Implemented by the ingest engine, next to `IngestEngine`. -#[async_trait] -pub trait ViewStateIngest: Send + Sync { +impl PrecomputeEngine { /// Checks, stages or merges each record; waits under backpressure as - /// `IngestEngine::ingest` does. - async fn ingest_view_states(&self, batch: ViewStateBatch) - -> Result; + /// `try_ingest` does. A method, not a trait: a trait is added with its + /// second implementation, and there is one. + pub async fn ingest_collector_states(&self, batch: ViewStateBatch) + -> Result; } ``` -`ViewStore` is unchanged: every collector view window is `put` once, at commit. +`storage::ViewStore` is unchanged: every collector view window is written once, at commit. ### `crates/adapters/ingest/asap-sketch-otlp` @@ -718,7 +718,7 @@ Pins (all three repositories): Backend: 2. This document. -3. `ViewStateBatch` and `ViewStateIngest` in `common`; the +3. `ViewStateBatch` in `common`, `PrecomputeEngine::ingest_collector_states` and `CollectorStateIngestReport` in `precompute`; the `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by key and selection, the series cache, staging, the hash set, merge before commit, commit at grace, late drop. Test data: real ASAPv1 records the collector From f1e8ff6bdd6e0cbaf51bd0135d87c7e13c096a26 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 01:40:42 +0000 Subject: [PATCH 08/21] docs(design): collector view states use the raw samples' OTAP structure Schema, Dictionary and Record tiers as for raw samples; only the Record differs. The view identity (plan_id, node_id, view state key) is metric metadata, and the view metric is named .asap_view. because OTLP metric metadata is non-identifying. Dictionary entries are the received ones and labels come from the raw path's label function. Resource-level sketch.* identity, sketch.series_id and the stream-scoped series cache are removed; the OTLP adapter branches only at the Record. --- docs/design/collector-sketch-ingest.md | 431 +++++++++++++++---------- 1 file changed, 254 insertions(+), 177 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index eacce1357..861744930 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -22,8 +22,12 @@ metric's raw samples, the collector stops sending them to the backend. The collector is told what to build in the planner's own terms: for each collector view the control plane sends the view's sub-DAG of the installed ASAPPlanner plan, and the collector depends on ASAPPlanner's types crate to -read it. Every state carries the planner's **view state key**, so the backend -finds the view by what the state is, not by a number both sides agree on. +read it. Collector view states travel in exactly the OTAP structure of raw +samples: the same Schema, Dictionary and Record tiers, with the same +Dictionary entries; only the Record content differs (a window state instead +of a sample). The view identity (plan id, node id and the planner's **view +state key**) is Schema-level metric metadata, so every state names its view +through its metric. Terms, as in ASAPPlanner (`asap-types`): @@ -45,9 +49,10 @@ Terms, as in ASAPPlanner (`asap-types`): } ``` - Two views with equal key and equal concrete selection (the rows that went - in: `view_coverage.selection`) hold the same state, in any plan. Refresh - mode, retention and storage medium are not in the key. + Refresh mode, retention and storage medium are not in the key. +- **View identity**: `(plan_id, node_id, view state key)`, what a collector + state carries. `(plan_id, node_id)` finds the view; the key must equal + that node's key. - **Leaf view**: a view whose child is a raw `Scan`. - **Sub-DAG**: a leaf view's node, its `Scan` node and the edge between them, as a `PhysicalASAPDAG` with `roots = [view node]`. @@ -65,11 +70,13 @@ Scope: the planner's main. The remaining prerequisite is the backend's planner and `asap_sketchlib` pin bump (Plan, step 1). It needs no other planner change. -- The backend changes in four places: a new ingest adapter, new `common` - types, the collector-state ingest in precompute, and the control plane. +- The backend changes in four places: the OTLP ingest adapter (the Record + branch), new `common` types, the collector-state ingest in precompute, and + the control plane. - The collector changes in its own repository: a capabilities command, the - `asap-types` dependency and a sub-DAG loader, key stamping, the - window-boundary, out-of-order and matcher fixes, and a raw-forward filter. + `asap-types` dependency and a sub-DAG loader, view identity in metric + metadata, the window-boundary, out-of-order and matcher fixes, and a + raw-forward filter. ## Components @@ -81,9 +88,10 @@ Scope: asap_sketches --print-capabilities ─▶ capabilities.json ▲ collector-views.json │ │ │ ▼ workload ─▶ control-plane ─▶ InstallablePlan ─┼──────────────────────┼──────▶ data-plane POST /v1/metrics - │ (asap-planner) ▼ │ ├─ point without sketch.envelope ─▶ otlp ─▶ PrecomputeEngine::try_ingest - └─ collector view rule (reads capabilities.json) ───────┘ └─ point with sketch.envelope ─▶ asap-sketch-otlp ─▶ ViewStateBatch - (same collector-views.json) ────────────────────────────▶ data-plane ─▶ PrecomputeEngine::ingest_collector_states ─▶ committer ─▶ storage::ViewStore + │ (asap-planner) ▼ │ otlp: one walk, Schema + Dictionary decoded once; branch at the Record: + └─ collector view rule (reads capabilities.json) ───────┘ ├─ point without sketch.envelope ─▶ Point ─▶ PrecomputeEngine::try_ingest + (same collector-views.json) ────────────────────────────▶ └─ point with sketch.envelope ─▶ ViewStateBatch + ─▶ PrecomputeEngine::ingest_collector_states ─▶ committer ─▶ storage::ViewStore ``` | Component | Crate or repository | Role | @@ -91,10 +99,10 @@ Scope: | Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares what the collector can build (§1) | | Collector view rule | `crates/control-plane` | Picks the leaf views of the installed plan the collector can build against the capabilities; the only copy of the rule | | Collector-views file | `crates/control-plane` (`--emit-collector-views`) | Each collector view's sub-DAG, the plan id, which metrics the backend still reads raw, the commit grace | -| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, builds each view's per-series states, stamps the view state key, exports OTLP summary points with `sketch.envelope` | +| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, builds each view's per-series states, writes the view identity into metric metadata, exports summary points with `sketch.envelope` | | Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | -| `asap-sketch-otlp` | `crates/adapters/ingest/asap-sketch-otlp` (new) | Turns those points into `common::ViewStateBatch`es; never reads the sketch bytes | -| Collector-state ingest | `crates/precompute` | Finds the view by key and selection, stages, deduplicates and merges until commit, drops late states | +| OTLP adapter | `crates/adapters/ingest/otlp` | Decodes Schema and Dictionary as for raw samples; a point with `sketch.envelope` becomes a `common::ViewStateBatch` record; never reads the sketch bytes | +| Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states | **Raw path.** The raw path stays (decision 3) for every metric the backend still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` @@ -112,13 +120,13 @@ Following the layout rules (adapters see no engine and no store): ```text crate / repository depends on ------------------- ------------------------------------------------------ -asap-sketch-otlp common (ViewStateBatch), otlp (its protobuf types) +otlp + common (ViewStateBatch); adapters may depend on common only precompute + decoding ASAPv1 through storage's existing codec (persist.rs decode_sketch) control-plane unchanged dependencies (asap-planner, common) ASAPCollector-public + asap-types (ASAPPlanner's types crate), pinned git rev ``` -The adapter does not decode ASAPv1. The ingest engine decodes each state +The OTLP adapter does not decode ASAPv1. The ingest engine decodes each state into the view's kernel with `storage`'s `decode_sketch`, because the store holds engine-native states and a second state of one window is merged. Decoding is not an identity check: θ is already in the key. @@ -232,12 +240,21 @@ At start, with `planner_views: ` in its processor config, the rule, written once. 3. **Reads each view's key** with `materialized_views()` on the sub-DAG and `view_state_key()`: the key depends only on the view node, so it equals - the installed plan's. The selection is `coverage().selection()`. + the installed plan's. 4. **Builds** each view: sketch and parameters from θ (an out-of-range value is a load error, never replaced by a default), window = `ViewWindow::Tumbling.width_ms`, matchers = `__name__ = metric` plus each - `Scan` predicate, one state per series with every label in the key. -5. **Stamps** every emitted state with the key and selection (§4). + `Scan` predicate, one state per series. A series is what it is for the + raw forward: the received Resource, Scope and point attributes, kept as + received (no flattening, no label dropping). +5. **Stamps** the view identity: each view is one Metric entry per + Resource and Scope, whose `metadata` carries `(plan_id, node_id, key)` + and whose name is `.asap_view.` (§4). The series' + Resource, Scope and point attributes are copied unchanged, so the + Dictionary entries are the raw forward's. `SketchEnvelope` carries the + view identity in place of `agg_id`; the OTAP codec writes it through + `MetricView::metadata` (empty today) and reads it back, and + `window_merge` keys series by it. With `planner_views` set, the per-sketch fields of the processor config (`sketch_type`, `sketch_params`, `window_size`, `window_slide`, @@ -252,22 +269,65 @@ plan does not read). ### 4. OTAP tiers: Schema, Dictionary, Record -The collector's data model (its `docs/data_model.md`) splits a sketch -stream into OTAP's three tiers by rate of change: **Schema** (once per -stream and view), **Dictionary** (once per series), **Record** (once per -state). The backend's `ViewStateBatch` keeps the same nesting, so Schema and -Dictionary are not repeated in every record: +OTAP splits a metrics stream into three tiers by rate of change: **Schema** +(per metric), **Dictionary** (per series), **Record** (per point). +Collector view states use exactly the structure of raw samples; only the +Record content differs: -| Tier | Planner source | OTLP placement | `ViewStateBatch` field | Backend handling | +| Tier | Raw samples | Collector view states | `ViewStateBatch` | Backend handling | |---|---|---|---|---| -| Stream | none | `sketch.stream_id` (Resource; random 128-bit per collector start) | `stream_id` | Key of the series cache | -| Schema | `view_state_key()` | `sketch.view_state_key` (Resource; the key's JSON) | `views[].key` | Find the view, with the selection | -| Schema | `coverage().selection()` (lifted label matchers) | `sketch.selection` (Resource; the planner's JSON) | `views[].selection` | as above | -| Schema | ASAPv1 format version | `sketch.schema_version` (Resource) | none (checked by the adapter) | ≤ highest supported | -| Schema | none | `sketch.type` (Resource) | none | Not read (decision 11) | -| Dictionary | `Scan` metric + the series' labels (`$promql_series_identity`) | metric name; `sketch.series_id` and labels (Scope) | `views[].series: (series_id, labels)` | Interned once per `(stream_id, view, series_id)` | -| Record | the window `(end − w, end]`, `w` from the key | point `start_time_unix_nano` (exclusive), `time_unix_nano` (inclusive) | `records[].window_end_ms` | Window key; `end` must be a multiple of `w` | -| Record | the view's `state` column | point `sketch.envelope` (ASAPv1 bytes), `count` | `records[].asapv1`, `sample_count` | Stage, dedup, merge, commit (§6) | +| Schema (per metric) | `Metric`: name, type, unit | the source metric's unit and description; name `.asap_view.`, type Summary; `metadata`: `asap.plan_id`, `asap.node_id`, `asap.view_state_key` | `views[]`: `plan_id`, `node_id`, `key` | Find the view, check the key and name | +| Dictionary (per series) | Resource + Scope + point attributes → labels | identical: the source samples' Resource, Scope and point attributes, as received | `views[].series[].labels` | The raw path's label function; interned as the raw path interns | +| Record (per point) | `time_unix_nano` + value | window `(start_time_unix_nano, time_unix_nano]`; point attribute `sketch.envelope` (ASAPv1 bytes); `count` (samples) | `series[].records[]`: `window_end_ms`, `asapv1`, `sample_count` | Stage, dedup, merge, commit (§6) | + +**Which view.** A record belongs to its Metric entry, whose metadata +carries the view identity, so every record names its view through its +metric, with no per-record identity attribute. Two views over one source +metric (DDSketch α 0.05 and KLL, or two window widths) are two Metric +entries. `sketch.envelope` is the only attribute a state adds to its +point. + +**Metric metadata survives the path.** OTLP `Metric.metadata` is +`repeated KeyValue metadata = 12` in the protobuf both sides build +(`opentelemetry-proto` 0.28 in the backend; otel-arrow's pdata protos in +the collector). OTAP Arrow keeps it: the encoder writes `metric.metadata()` +into the `METRIC_ATTRS` table keyed by metric id, and the OTAP-to-OTLP +conversion writes those rows back as field 12. No processor between +`asap_sketches` and the exporter merges metrics. + +**Why the name changes.** The proto defines metric metadata as +"non-identifying; consumers SHOULD NOT need to be aware of these +attributes". Two Metric entries `data` that differ only in metadata, with +equal point attributes and window times, are one stream to a consumer that +follows the specification, and a Summary `data` next to the raw gauge `data` +is a type conflict. The view's own name keeps them apart without relying on +metadata: `.asap_view.`. The backend reads identity from +the metadata only, checks the name, and stores the rows under the `Scan`'s +metric (`__name__ = data`), so `$promql_series_identity` is exactly what a +raw sample of that series gets and queries are unaffected. Names containing +`.asap_view.` are reserved. + +**Labels.** The backend builds a state's labels with the raw OTLP path's +function, with the Prometheus convention for resource attributes: they are +not copied into labels; `service.name` (prefixed by `service.namespace/` +when set) becomes `job`, `service.instance.id` becomes `instance`, and an +optional allow-list promotes named resource attributes (Prometheus's +`promote_resource_attributes`). Equal Dictionary entries therefore give +equal labels on both paths. + +Where each planner field travels: + +| Planner field | Where | +|---|---| +| `PhysicalASAPDAG::plan_id()` | Schema: `asap.plan_id` | +| view node id | Schema: `asap.node_id` and the name suffix | +| `view_coverage.definition_id` | Schema: in `asap.view_state_key` | +| `parameters` (θ) | Schema: the key's `logical_properties` | +| `tumbling_window_width_ms` | Schema: the key's `window`; each window's end in the Record | +| `view_coverage.selection` | not sent: the collector applies the `Scan`'s predicates; the backend knows the view's selection from `(plan_id, node_id)` | +| `Scan` `TimeSeries.metric` | Schema: the name prefix; `__name__` of the stored labels | +| `$promql_series_identity` | Dictionary: built by the label function | +| the view's `state` column | Record: `sketch.envelope` | A chain view's selection carries no time column: its rows are indexed by `window_end`, and the time part appears only on the `TimeRange` above it. @@ -276,43 +336,33 @@ Prometheus's `(t − range, t]` form (§5). ```mermaid erDiagram - STREAM ||--o{ VIEW : views - VIEW ||--o{ SERIES : series + SCHEMA ||--o{ SERIES : series SERIES ||--o{ RECORD : records - STREAM{ - stream_id u128 "random per collector start" - } - VIEW{ + SCHEMA{ + plan_id string "PhysicalASAPDAG::plan_id()" + node_id PhysicalASAPNodeId "the view node" key ViewStateKey "definition_id, window, logical_properties" - selection json "coverage selection" + name string "metric.asap_view.node_id" } SERIES{ - series_id u32 "per stream and view" - labels LabelSet "__name__ included" + labels LabelSet "raw path's label function; __name__ = Scan metric" } RECORD{ - series_id u32 "references SERIES" window_end_ms i64 "inclusive; start = end - width" - asapv1 bytes "full state" - sample_count u64 + asapv1 bytes "sketch.envelope, the full state" + sample_count u64 "count" } ``` -**Transport.** OTAP Arrow keeps the tiers on the wire: over one stream, -Schema and Dictionary are sent once and Records reference them. OTLP HTTP -repeats the Resource (Schema) and Scope (labels) in every request. v1 +**Transport.** Over OTLP HTTP each request carries the full Resource, +Scope and point attributes, as for raw samples. Over OTAP Arrow the tiers +are tables joined by native ids (`parent_id`), with dictionary-encoded +strings. Neither needs an ASAP series id or a stream-scoped cache. v1 accepts OTLP HTTP (every collector deployment exports with `urn:otel:exporter:otlp_http` today, and the backend already serves -`/v1/metrics`); the OTLP adapter builds the nesting above, and the series -cache still interns each series once per stream. A later OTAP Arrow -adapter fills the same `ViewStateBatch` (decision 16). - -**Collector restart.** A restart starts a new stream: new `stream_id`, and -`series_id` starts again at 1. The backend never reuses a translation -across streams, so a reset counter cannot alias two series; the new -stream's series are interned again (to the same backend series, since the -labels are the same). Entries of a stream not seen for the longest view -retention are dropped. +`/v1/metrics`); a later OTAP Arrow adapter fills the same `ViewStateBatch` +(decision 16). A restarted collector sends the same Dictionary entries, so +its states land on the same backend series. ### 5. Window semantics: Prometheus's `(t − range, t]` @@ -355,34 +405,32 @@ The collector change: ### 6. The sketch path in the data plane -`POST /v1/metrics` decodes the request once. Each summary data point that -carries a `sketch.envelope` bytes attribute is a collector state; every other -point is a raw sample, as today. A request may carry both. - -The adapter groups the collector-state points by `sketch.stream_id`, then by -(`sketch.view_state_key`, `sketch.selection`), into one `ViewStateBatch` -per stream. It refuses the request (400) when a Resource lacks one of these -attributes or they do not parse, or `sketch.schema_version` is newer than -supported. Labels are Resource attributes, then Scope attributes, then -point attributes, without any `sketch.*` key, with `__name__` = metric name -(the raw OTLP adapter's merge order). +`POST /v1/metrics` decodes the request once, in the `otlp` adapter's one +walk: Resource, Scope and Metric (Schema) and the point attributes +(Dictionary) are read by the raw path's code. The walk branches only at the +Record: a data point with a `sketch.envelope` bytes attribute is a +collector state, every other point a raw sample, as today. A request may +carry both. + +For a state, the adapter reads the view identity from its Metric's +`metadata` and refuses the request (400) when one of `asap.plan_id`, +`asap.node_id`, `asap.view_state_key` is missing or does not parse. Labels +come from the raw path's label function (§4), without `sketch.envelope`, +with `__name__` = the source metric (the name before `.asap_view.`). States +are grouped by `(plan_id, node_id)`, then by labels, into one +`ViewStateBatch` per request. The ingest engine then, per view and record: -1. **View.** Looks up the installed views with this key and selection - (an index built at install from `materialized_views()`). None → rejected - (`reason="unknown_view"`), whatever differs: another definition, θ or - width, or a view the installed plan no longer has. Views of one plan - with equal key and selection hold the same state; the record is stored - for each. +1. **View.** `plan_id` must be the installed plan's; otherwise rejected + (`reason="other_plan"`). `node_id` must be a collector view of that plan + whose `view_state_key()` equals the key and whose `Scan` metric and node + id give the Metric's name; otherwise rejected (`reason="unknown_view"`). 2. **Window.** `window_end_ms` must be a multiple of the key's width; otherwise rejected (`reason="window"`). -3. **Series.** Translates `(stream_id, view, series_id)` through the series - cache, filled from the batch's `series` table; on a miss, interns the - labels into the store's series table, as the raw path does, so the row's - `$promql_series_identity` is the same canonical JSON a raw sample of - that series gets. A `series_id` in neither → rejected - (`reason="unknown_series"`). +3. **Series.** Interns the labels into the store's series table, as the raw + path does, so the row's `$promql_series_identity` is the same canonical + JSON a raw sample of that series gets. 4. **Decode.** Decodes the ASAPv1 bytes into the view's kernel; failure → rejected (`reason="decode"`). 5. **Stage, dedup, merge, commit**, below. @@ -433,35 +481,39 @@ committer, the same path that commits a window it built (readers, ```rust use asap_types::plan::materialized_view::ViewStateKey; -use asap_types::ir::properties::selection::SelectionBox; +use asap_types::plan::PhysicalASAPNodeId; -/// Collector states from one collector stream: what the sketch-path ingest -/// adapter hands `PrecomputeEngine`. In `common` because the adapter depends only on `common` -/// and must produce it. Nested by OTAP tier, so a view's key and -/// a series' labels appear once, not per record. Never data between operators. -#[derive(Debug, Clone, PartialEq)] +/// The collector states of one OTLP request: what the OTLP adapter hands +/// `PrecomputeEngine`. In `common` because the adapter depends only on +/// `common` and must produce it. Nested as the OTAP tiers (Schema → +/// Dictionary → Record). Never data between operators. +#[derive(Debug, Clone, PartialEq, Default)] pub struct ViewStateBatch { - /// Random per collector start; scopes `series_id`. - pub stream_id: u128, pub views: Vec, } -/// One collector view's states in the batch. +/// One collector view's states (Schema tier: the Metric's metadata). #[derive(Debug, Clone, PartialEq)] pub struct CollectorViewStates { + /// `PhysicalASAPDAG::plan_id()` of the plan the collector loaded. + pub plan_id: String, + pub node_id: PhysicalASAPNodeId, pub key: ViewStateKey, - /// The view's coverage selection, as the planner serializes it. - pub selection: Vec, - /// Series of this view's records: the OTLP adapter lists every series in - /// the request, an OTAP adapter only new Dictionary entries. - pub series: Vec<(u32, LabelSet)>, + pub series: Vec, +} + +/// One series' states (Dictionary tier). +#[derive(Debug, Clone, PartialEq)] +pub struct CollectorSeriesStates { + /// Built by the raw OTLP path's label function; `__name__` is the + /// source metric. + pub labels: LabelSet, pub records: Vec, } -/// One series' state in one window `(window_end_ms − width, window_end_ms]`. +/// One state in one window `(window_end_ms − width, window_end_ms]` (Record tier). #[derive(Debug, Clone, PartialEq)] pub struct ViewStateRecord { - pub series_id: u32, pub window_end_ms: i64, /// ASAPv1 bytes from `asap_sketchlib`: the full state. pub asapv1: Vec, @@ -476,7 +528,7 @@ pub struct CollectorStateIngestReport { pub duplicate: u64, pub merged: u64, pub late_dropped: u64, - /// By reason: `unknown_view`, `window`, `unknown_series`, `decode`. + /// By reason: `other_plan`, `unknown_view`, `window`, `decode`. pub rejected: BTreeMap<&'static str, u64>, } @@ -491,36 +543,31 @@ impl PrecomputeEngine { `storage::ViewStore` is unchanged: every collector view window is written once, at commit. -### `crates/adapters/ingest/asap-sketch-otlp` +### `crates/adapters/ingest/otlp` ```rust -/// Why a request's collector states could not be read; the whole request is -/// refused with 400. Per-record problems are counted, not errors. -#[derive(Debug, thiserror::Error, PartialEq)] -pub enum SketchOtlpError { - #[error("sketch Resource without {0}")] - MissingAttribute(&'static str), - #[error("sketch.view_state_key is not a planner view state key: {0}")] - ViewStateKey(String), - #[error("sketch.selection is not a planner selection: {0}")] - Selection(String), - #[error("sketch.schema_version {0} is newer than supported")] - SchemaVersion(u64), +/// A decoded request: raw samples and collector states, from one walk. +pub struct Decoded { + pub points: Vec, + pub view_states: ViewStateBatch, } -/// Whether an OTLP data point carries a collector state (a `sketch.envelope` -/// bytes attribute): the route's test for the sketch path. -pub fn is_sketch_point(attributes: &[KeyValue]) -> bool; +pub fn decode(body: &[u8], content_encoding: Option<&str>, limits: &Limits) + -> Result; // was -> Vec -/// The collector states of a decoded OTLP request, one batch per stream; points -/// without `sketch.envelope` are left to the raw `otlp` decoder. -pub fn decode_view_states( - request: &ExportMetricsServiceRequest, -) -> Result, SketchOtlpError>; +pub enum OtlpError { + // ... existing variants ... + /// A point with `sketch.envelope` under a Metric whose metadata lacks + /// or misstates the view identity; the whole request is refused (400). + #[error("metric {metric}: view identity: {reason}")] + ViewIdentity { metric: String, reason: String }, +} ``` -The raw `otlp` decoder already skips points that carry a sketch payload; it -learns `sketch.envelope` as one more, so each point is read once. +The raw points' label function is the one states use, and it follows the +resource-attribute convention of §4. The raw decoder's skip list of sketch +payload attributes learns `sketch.envelope`, which now selects the Record +branch. ### `crates/control-plane` @@ -652,30 +699,40 @@ sketch: planner_views: /etc/asap/collector-views.json ``` -For one series `data{region="r0",service="s0",job="j0",label_0="l0"}`, the -collector folds the 50 samples with timestamps in `(T − 5 s, T]` into one -DDSketch and exports one summary point: +For one series, received with Resource `service.name = "j0"` and point +attributes `region="r0"`, `service="s0"`, `label_0="l0"`, the collector +folds the 50 samples with timestamps in `(T − 5 s, T]` into one DDSketch and +exports, under the same Resource and Scope as the raw samples (OTLP JSON, +shortened): -| Where (tier) | Attribute | Value | -|---|---|---| -| Resource (stream) | `sketch.stream_id` | `"9b1e…"` (random at collector start) | -| Resource (Schema) | `sketch.view_state_key` | n1's key above, as JSON | -| Resource (Schema) | `sketch.selection` | `"[{\"columns\":[]}]"` | -| Resource (Schema) | `sketch.schema_version` | `1` | -| Resource (Schema) | `sketch.type` | `"DDSketch"` (not read by the backend) | -| Scope (Dictionary) | `sketch.series_id` | `17` | -| Scope (Dictionary) | labels | `region="r0"`, `service="s0"`, `job="j0"`, `label_0="l0"` | -| Metric | name | `data` | -| Point (Record) | `start_time_unix_nano` | `T − 5 s` (exclusive) | -| Point (Record) | `time_unix_nano` | `T` (inclusive) | -| Point (Record) | `sketch.envelope` | ASAPv1 bytes | -| Point (Record) | `count` | `50` | - -The adapter makes one `ViewStateBatch` with one `CollectorViewStates` (n1's -key and selection), one series `(17, labels)` and one record `(17, T, -bytes, 50)`. The backend finds n1 by key and selection, checks that `T` is -a multiple of 5 s, translates `(stream_id, n1, 17)` to its series id, -decodes the state and stages it; at `T + 8 s` it commits the window. It +```json +{"name": "data.asap_view.1", + "unit": "", + "metadata": [ + {"key": "asap.plan_id", "value": {"stringValue": "…"}}, + {"key": "asap.node_id", "value": {"intValue": "1"}}, + {"key": "asap.view_state_key", "value": {"stringValue": + "{\"definition_id\":\"5597d603bdf9f1a148d7c7e5344c1a97\",\"window\":{\"tumbling\":{\"width_ms\":5000}},\"logical_properties\":{\"parameters\":{\"DDSketch\":{\"alpha\":0.05}}}}"}}], + "summary": {"dataPoints": [{ + "attributes": [ + {"key": "region", "value": {"stringValue": "r0"}}, + {"key": "service", "value": {"stringValue": "s0"}}, + {"key": "label_0", "value": {"stringValue": "l0"}}, + {"key": "sketch.envelope", "value": {"bytesValue": ""}}], + "startTimeUnixNano": "", + "timeUnixNano": "", + "count": "50"}]}} +``` + +The Resource, Scope and the first three point attributes are exactly the +raw samples'; the labels are `data{job="j0",region="r0",service="s0",label_0="l0"}` +on both paths. + +The adapter makes one `ViewStateBatch` with one `CollectorViewStates` +(plan id, node 1, n1's key), one series (those labels) and one record `(T, +bytes, 50)`. The backend finds n1 by `(plan_id, 1)`, checks the key and the +name, checks that `T` is a multiple of 5 s, interns the labels, decodes the +state and stages it; at `T + 8 s` it commits the window. It keeps exactly what its own precompute keeps for n1: per series, one DDSketch state per 5 s window, for 60 s (12 windows). At evaluation time `T`, q01 runs at query time as before: n2 selects the 12 windows ending in @@ -719,13 +776,15 @@ Backend: 2. This document. 3. `ViewStateBatch` in `common`, `PrecomputeEngine::ingest_collector_states` and `CollectorStateIngestReport` in `precompute`; the - `asap-sketch-otlp` adapter; the `/v1/metrics` split; lookup by key and - selection, the series cache, staging, the hash set, merge before commit, - commit at grace, late drop. Test data: real ASAPv1 records the collector - emits (captured OTLP bodies, checked in with the collector commit that - wrote them), for each of the six sketch types, including one unknown key - (other θ), one duplicate after a merge, one late state and one restart - (new `stream_id`, reused `series_id`). + `otlp` adapter's Record branch and the resource-attribute convention in + its label function (raw path included); lookup by `(plan_id, node_id)` + and key check, staging, the hash set, merge before commit, commit at + grace, late drop. Test data: real ASAPv1 records the collector emits + (captured OTLP bodies, checked in with the collector commit that wrote + them), for each of the six sketch types, including two views over one + metric, one key that differs from the node's (other θ), one state of + another plan id, one duplicate after a merge, one late state, and one + series sent raw and as a state that gets equal labels. 4. The control plane's rule with `--collector-capabilities`, `--emit-collector-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, `commit_grace_ms`); the data plane's `--collector-views` with the plan-id @@ -747,10 +806,13 @@ Collector (ASAPCollector-public): 6. `--print-capabilities`, printed from the config validation code. 7. `asap-types` as a pinned git dependency (the backend's planner pin); the - `planner_views` loader with the executability check; key and selection - stamping (`sketch.view_state_key`, `sketch.selection`, `sketch.stream_id` - on the Resource, replacing `sketch.agg_id`); `series_id` per (view, - series); config errors for the per-sketch fields when it is set. + `planner_views` loader with the executability check; the view identity + in `SketchEnvelope` (replacing `agg_id`), written as metric metadata and + the view name by the OTAP codec, read back on decode, and keyed on by + `window_merge`; each series' received Resource, Scope and point + attributes kept and emitted unchanged (the Resource-level `sketch.*` + attributes and `sketch.series_id` removed); config errors for the + per-sketch fields when it is set. 8. The window boundary `(e − w, e]` in `SketchEnvelope` and the point times (window attributes removed), placement by sample timestamp with drop-and-count after close, and matchers (§5). It lands before step 5, @@ -764,12 +826,13 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad ## Decisions -1. **The planner's identity, no other planner change.** A collector state is - identified by the planner's view state key plus its concrete selection; - within the installed plan a view is `(plan_id, node_id)`. θ and window - width are in the key, so a state of another θ or width is simply - `unknown_view`. Which views the collector builds is a deployment decision - the backend's control plane makes on the installed plan. +1. **The planner's identity, no other planner change.** A collector state + names its view by `(plan_id, node_id)` and carries the planner's view + state key, which must equal that node's key; θ and window width are in + the key, so a state of another θ or width is `unknown_view`. The + selection is not sent: the node defines it. Which views the collector + builds is a deployment decision the backend's control plane makes on the + installed plan. 2. **The collector is ASAPCollector-public (OTAP), sending full ASAPv1 states.** No deltas: each record holds the whole state of one series in one window. @@ -798,13 +861,18 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 10. **Raw forwarding follows the readers.** The file lists, per metric, whether the backend still reads it raw; the collector drops raw samples to the backend for metrics marked `false`. -11. **`sketch.type` is informational.** The collector keeps emitting it - (its data model and its other sinks use it); the backend never reads it, - since the key's θ names the sketch and the ASAPv1 bytes carry their own - kind. -12. **`ViewStateBatch` is nested by OTAP tier** (stream → view → series → - records); the OTLP adapter builds the nesting, an OTAP adapter fills the - same type. +11. **The raw samples' OTAP structure.** Collector view states use the + Schema, Dictionary and Record tiers exactly as raw samples do; only the + Record differs (window times, `sketch.envelope`, `count`). The view + identity is metric metadata (`asap.plan_id`, `asap.node_id`, + `asap.view_state_key`); the Dictionary entries are the received ones. + No Resource-level `sketch.*` attributes (`definition_id`, `selection`, + `stream_id`, `type`, `schema_version`), no `sketch.series_id`, no + stream-scoped series cache: ASAPv1 bytes carry their own kind and + version. +12. **`ViewStateBatch` mirrors the tiers** (view → series → records); the + OTLP adapter builds it in the raw path's walk, branching only at the + Record, and an OTAP adapter fills the same type. 13. **One planner and one sketchlib, the latest.** The backend and the collector pin the same ASAPPlanner revision, the latest main; the planner, the backend and the collector pin the same `asap_sketchlib` @@ -816,11 +884,12 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad step 4 checks in the benchmark's `collector-views.json` and tests that it deserializes, so a format change fails a test. No sketch type, HLL included, is left out on version grounds. -14. **Plan reinstall.** A view whose definition, θ and width did not change - keeps its key across plans. The control plane rewrites the file and the - collector restarts on every reinstall. Until then, states of unchanged - views keep matching, states of removed views are `unknown_view`, and new - views are `NotReady` (forwarded). A live reload is later work. +14. **Plan reinstall.** The control plane rewrites the file and the + collector restarts on every reinstall. Until then the collector's states + carry the old `plan_id` and are rejected (`other_plan`); the collector + views' windows in between are `NotReady` (forwarded). Matching unchanged + views across plans would need the selection on the wire; a live reload + is later work. 15. **Dependency weight on the collector build.** `asap-types` adds `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin (Decision 13) it adds no second sketchlib. Accept it. Measure the collector's clean build @@ -830,9 +899,12 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad `arrow-ipc` and `tonic` the backend already builds, rather than the collector's `otel-arrow-dfe-*` crates, which would add a second `datafusion` (53 next to 54) and `tonic` (0.14 next to 0.12). -17. **Stream identity on OTLP.** OTLP HTTP has no stream. - `sketch.stream_id`, a random 128-bit value drawn at collector start; on - OTAP Arrow the gRPC stream is the stream. +17. **View metric name `.asap_view.`.** OTLP defines + metric metadata as non-identifying, so a consumer that follows the + specification may treat two views over one metric, or a view and the + raw metric, as one stream. The name keeps them distinct; identity is + still read from the metadata, and the backend stores the rows under the + `Scan`'s metric, so queries are unaffected. `.asap_view.` is reserved. 18. **Sub-DAG validity.** No planner function extracts a sub-DAG. The loader calls `materialized_views()` on each sub-DAG, which validates it, and step 4 tests this on the benchmark plan. If the planner refuses such a DAG, @@ -847,6 +919,11 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 21. **Clock-skew allowance.** 2 s by default (hosts run NTP, which keeps them within milliseconds); raise it if the arrival-delay histogram or `late_dropped` shows skew. +22. **One label function for both paths**, with Prometheus's convention for + resource attributes: not copied into labels; `service.name` (with + `service.namespace/`) → `job`, `service.instance.id` → `instance`; an + optional allow-list promotes named attributes. Equal Dictionary entries + give equal labels whichever path carried them. ## Open questions From 30c4b0dae51bbc15f189c1ec38f3a4e0ecb8cb0c Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 03:58:03 +0000 Subject: [PATCH 09/21] docs(design): generic collector sub-DAG rule, planner-vocabulary capabilities, executor as target The collector view rule assigns nodes bottom-up from the Scans (capabilities, inputs on the collector, ingestion time, local to the partition) and cuts the maximal sub-DAG; collector-views.json lists its outputs. Capabilities use the planner's DeploymentCapabilities and OperatorKind plus a placement. Tiers map to the cut node's identity, key columns and window result. Target: the collector embeds asap-executor; v1 scope (leaf views) is unchanged. --- docs/design/collector-sketch-ingest.md | 420 +++++++++++++++++-------- 1 file changed, 294 insertions(+), 126 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 861744930..d06c2fa2f 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -1,4 +1,4 @@ -# Design: leaf sketch views precomputed in the collector +# Design: plan sub-DAGs precomputed in the collector (v1: leaf sketch views) Status: proposal, for review. Decisions are recorded at the end. @@ -7,9 +7,12 @@ Status: proposal, for review. Decisions are recorded at the end. This document is for developers of the backend and of ASAPCollector-public, the collector built on OTAP Dataflow (OpenTelemetry Arrow's dataflow engine) whose `asap_sketches` processor builds windowed sketches at the edge. It -decides how the collector builds some of a plan's leaf views and how the -backend ingests the resulting states, so that the backend stores and answers -them as if its own precompute had built them. +decides which part of a plan the collector runs, how it is told, and how +the backend ingests what it sends, so that the backend stores and answers +the results as if its own precompute had built them. The rule is general: +the collector runs the largest bottom-up sub-DAG of the plan that its +declared capabilities and data partition allow. v1 implements it for +today's collector, whose capabilities make that sub-DAG a leaf view. Today every sample travels raw to the backend: the collector (or the application) sends OTLP or Remote Write, and the backend's precompute builds @@ -19,9 +22,9 @@ the collector can build exactly that state before the network. For a series sampled at 10 Hz, 50 samples become one state. When no other reader needs a metric's raw samples, the collector stops sending them to the backend. -The collector is told what to build in the planner's own terms: for each -collector view the control plane sends the view's sub-DAG of the installed -ASAPPlanner plan, and the collector depends on ASAPPlanner's types crate to +The collector is told what to build in the planner's own terms: the +control plane sends the collector's sub-DAG of the installed ASAPPlanner +plan and the nodes whose results leave it, and the collector depends on ASAPPlanner's types crate to read it. Collector view states travel in exactly the OTAP structure of raw samples: the same Schema, Dictionary and Record tiers, with the same Dictionary entries; only the Record content differs (a window state instead @@ -53,16 +56,20 @@ Terms, as in ASAPPlanner (`asap-types`): - **View identity**: `(plan_id, node_id, view state key)`, what a collector state carries. `(plan_id, node_id)` finds the view; the key must equal that node's key. -- **Leaf view**: a view whose child is a raw `Scan`. -- **Sub-DAG**: a leaf view's node, its `Scan` node and the edge between - them, as a `PhysicalASAPDAG` with `roots = [view node]`. +- **Collector sub-DAG**: the nodes of the installed plan assigned to the + collector (§1) and the edges between them, as a `PhysicalASAPDAG` whose + `roots` are its outputs. +- **Cut edge**: an edge whose producer is in the collector sub-DAG and whose + consumer is not. Its producer is an **output** of the sub-DAG. +- **Leaf view**: a view whose only inputs, down to a raw `Scan`, are + per-series filters; v1's collector sub-DAGs are leaf views. - **Tumbling window**: a window of fixed width `w` on multiples of `w`; the window ending at `e` covers `(e − w, e]`. - **State**: the summary of one series in one window; a sketch state is `asap_sketchlib`'s ASAPv1 bytes. -- **Collector view**: a materialized view of the installed plan that the - collector builds instead of the backend (here always a leaf view); the - backend only stores and reads it. +- **Collector view**: an output of the collector sub-DAG that is not a + `Scan`: a materialized view the collector builds instead of the backend; + the backend only stores and reads it. A `Scan` output is the raw path. Scope: @@ -74,7 +81,7 @@ Scope: branch), new `common` types, the collector-state ingest in precompute, and the control plane. - The collector changes in its own repository: a capabilities command, the - `asap-types` dependency and a sub-DAG loader, view identity in metric + `asap-types` dependency and a sub-DAG loader (later `asap-executor`, §7), view identity in metric metadata, the window-boundary, out-of-order and matcher fixes, and a raw-forward filter. @@ -96,18 +103,19 @@ Scope: | Component | Crate or repository | Role | |---|---|---| -| Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares what the collector can build (§1) | -| Collector view rule | `crates/control-plane` | Picks the leaf views of the installed plan the collector can build against the capabilities; the only copy of the rule | -| Collector-views file | `crates/control-plane` (`--emit-collector-views`) | Each collector view's sub-DAG, the plan id, which metrics the backend still reads raw, the commit grace | -| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, builds each view's per-series states, writes the view identity into metric metadata, exports summary points with `sketch.envelope` | +| Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares, in the planner's vocabulary, what the collector can run and how series are placed on its instances (§1) | +| Collector view rule | `crates/control-plane` | Assigns nodes of the installed plan to the collector bottom-up against the capabilities and cuts the collector sub-DAG; the only copy of the rule | +| Collector-views file | `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw, the commit grace | +| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, runs the sub-DAG (v1: builds each leaf view's per-series states), writes the view identity into metric metadata, exports summary points with `sketch.envelope` | | Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | | OTLP adapter | `crates/adapters/ingest/otlp` | Decodes Schema and Dictionary as for raw samples; a point with `sketch.envelope` becomes a `common::ViewStateBatch` record; never reads the sketch bytes | | Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states | **Raw path.** The raw path stays (decision 3) for every metric the backend still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` -of it feeds a view that is not a collector view or runs at query time. A metric whose -only readers are collector views is marked `false`, and the collector's raw +of it has a consumer outside the collector sub-DAG (a cut edge from the +`Scan`) or runs at query time. A metric whose +only readers are on the collector is marked `false`, and the collector's raw forward to the backend drops it. When a collector view misses a window (the collector was down), the query engine reports `NotReady` and the dispatcher forwards the query to the fallback store, which receives raw samples on its @@ -132,63 +140,112 @@ holds engine-native states and a second state of one window is merged. Decoding is not an identity check: θ is already in the key. `asap-types` brings `serde`, `serde_json`, `thiserror` 2 and -`asap_sketchlib` into the collector build; no executor, frontend or solver -(decision 15). +`asap_sketchlib` into the collector build; no frontend or solver +(decision 15). The executor comes in the step after v1 (§7). ## Algorithm ### 1. Capabilities and the collector view rule (control plane) -The collector declares what it can build; the backend holds no table of the -collector's sketches. `asap_sketches --print-capabilities` prints, for -today's collector (planner names; the collector maps them to its own): +The collector declares what it can run, in the planner's own vocabulary; +the backend holds no table of the collector's operators or sketches. +`asap_sketches --print-capabilities` prints, for today's collector: ```json {"capabilities_version": 1, - "summaries": [ - {"summary_type": {"Sketch": "DDSketch"}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, - {"summary_type": {"Sketch": "Kll"}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, - {"summary_type": {"Sketch": "Hll"}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, - {"summary_type": {"Sketch": "CountSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, - {"summary_type": {"Sketch": "Cms"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, - {"summary_type": {"Sketch": "CmsWithHeap"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}], - "reductions": ["PerEntity"], - "windows": ["Tumbling"], - "predicate_ops": ["Eq", "Ne"], + "executor": { + "supported_summaries": [ + {"summary_type": "DDSketch", "readouts": []}, + {"summary_type": "KLL", "readouts": []}, + {"summary_type": "HLL", "readouts": []}, + {"summary_type": "CountSketch", "readouts": []}, + {"summary_type": "CountMinSketch", "readouts": []}, + {"summary_type": "CountMinSketchWithHeap", "readouts": []}], + "raw_data_retained": false, + "query_time_results_retained": false, + "counter_semantics": {"reset_handling": false, "extrapolation": false}, + "state_not_mergeable_across_windows": [], + "excluded_candidates": []}, + "operators": [ + {"kind": "Scan", "sources": ["TimeSeries"], "predicate_ops": ["Eq", "Ne"]}, + {"kind": "Filter", "predicate_ops": ["Eq", "Ne"]}, + {"kind": "SummaryTumblingWindowChain", "reductions": ["PerEntity"], "predicate_ops": ["Eq", "Ne"], + "summaries": [ + {"summary_type": {"Sketch": "DDSketch"}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, + {"summary_type": {"Sketch": "KLL"}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, + {"summary_type": {"Sketch": "HLL"}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, + {"summary_type": {"Sketch": "CountSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary_type": {"Sketch": "CountMinSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary_type": {"Sketch": "CountMinSketchWithHeap"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}]}], + "placement": {"partitioned_by": "series"}, "window_close_delay_ms": 6000} ``` -- `input: "value"`: the summary's `input` is `{"item": null, "weight": - {"Column": "SampleValue"}}`. `input: "label"`: `item` is one label column. -- `predicate_ops`: `Compare` of a label column with a `Utf8` literal (PromQL - `=`, `!=`); regular expressions are not supported. +- `executor`: ASAPPlanner's `DeploymentCapabilities`, with its own serde + (`asap_types::deployment_capabilities`). Today's collector builds states + but answers no readout (no `SummaryEstimate`), keeps no raw data and no + query-time result, and has no counter functions. +- `operators`: each entry is a planner `OperatorKind` with the argument + constraints the collector accepts; an operator not listed is not run. + `predicate_ops` are `CompareOpKind`s of a label column with a `Utf8` + literal (PromQL `=`, `!=`; no regular expressions), for a `Scan`'s + `predicates`, a `Filter`'s `pred` and a chain's `filter`. A chain's + `summary_type`, `input` and every `parameters` value must match one + `summaries` entry. `input: "value"`: the summary's `input` is `{"item": + null, "weight": {"Column": "SampleValue"}}`; `input: "label"`: `item` is + one label column. The ranges are the ones the collector's config + validation enforces; the command prints them from that code, so the two + cannot drift. +- `placement`: how series are partitioned across collector instances. + `"series"`: all samples of one series reach one instance (a restart or + handoff may split a window, which the backend merges, §6). + `{"labels": ["service"]}`: all series with equal values of those labels + reach one instance. - `window_close_delay_ms`: the longest time after a window's end before the collector emits it: the 5 s idle-close grace plus the 1 s timer period. -- The ranges are the ones the collector's config validation enforces; the - command prints them from that code, so the two cannot drift. The control plane reads the file with `--collector-capabilities ` -and refuses a `capabilities_version` it does not know. A node of the -installed plan's `dag` is a collector view if and only if all of these hold, read -from its planner fields (no cost comparison, -decision 6): - -1. **View at ingestion.** It is a `MaterializedView`, refreshed at - ingestion (`output_state.timing` is `ingestion_time`). -2. **Leaf on raw input.** `payload` is `ASAP.SummaryTumblingWindowChain` - whose `child` is a `NonASAP.Scan` of `TimeSeries { metric }`, with no - node in between, and the chain's `filter` is `null`. -3. **Within the capabilities.** `summary_type`, `input` and every - `parameters` value match one `summaries` entry; `reduction` is in - `reductions` (`PerEntity`: a `Reduce [...]` view is not a collector view, because - one collector does not see every series of a group); the window kind is - in `windows`; the `Scan`'s `predicates` are a conjunction of - `predicate_ops` comparisons. +and refuses a `capabilities_version` it does not know. It assigns nodes of +the installed plan's `dag` to the collector bottom-up from the `Scan`s, +from their planner fields only (no cost comparison, decision 6). A node is +assigned if and only if all of these hold: + +1. **Within the capabilities.** Its `OperatorKind` is in `operators` and its + arguments meet that entry's constraints; any summary it builds is in + `executor.supported_summaries`, and any readout it answers is listed + there. +2. **Inputs on the collector.** Every input is a `Scan` of raw data + (`TimeSeries { metric }`) or a node already assigned. +3. **At ingestion.** It runs at ingestion time (`output_state.timing` is + `ingestion_time`). +4. **Local to the partition.** It is correct on one instance's data per + `placement`. Per-series operators (`Scan`, a label `Filter`, a + `PerEntity` chain) always are. An operator that groups by `G` + (`Reduce(G)`) is local only if each group lands on one instance: with + `{"labels": L}`, `L ⊆ G`; with `"series"`, never. A non-local but + mergeable aggregate is future work (partial aggregation: the collector + sends a partial state, a backend `SummaryMerge` combines them). + +The assigned nodes form the maximal collector sub-DAG. Each cut edge's +producer is an output: a `Scan` output is the raw path (its metric is +`backend_reads_raw: true`); any other output must be a materialized view +whose result has a wire encoding, a state (ASAPv1 for a sketch) or an exact +value. An output that is not a materialized view would have to feed a +backend run at ingestion time, which is future work with partial +aggregation; v1 unassigns it and the nodes above it, and repeats until every +output is a `Scan` or a view. + +With today's capabilities the rule gives back the leaf rule: the only +operators are `Scan`, `Filter` and a `PerEntity` chain, and the chain is a +view at ingestion, so each collector view is a leaf view (`Scan`, optional +label `Filter`s, chain), and the `TimeRange`, `SummaryMerge` and +`SummaryEstimate` above it stay in the backend. **Exact aggregates stay in the backend.** The collector's `Exact` type (`EXv1`, every value of a window) is a baseline for comparisons, not a `sum`, `max` or counter state, and it is not in the capabilities. Views of -`ExactAggregate` become collector views when the collector declares them. +`ExactAggregate` become collector views when the collector declares them +(§7: with the executor embedded, it declares what the executor runs). **Known limitation: sparse series.** The rule ignores size. A series with few samples per window can produce a state larger than its raw samples (a @@ -199,19 +256,24 @@ planner capability (costing where a view is built). ### 2. The collector-views file (control plane) -For each collector view the control plane copies, from the installed `dag`, -the view node and its `Scan` node (unchanged, node ids included) and the -one edge between them, and sets `roots = [view node]`, `scalar_roots = -[]`. It writes one JSON file, with the planner types' own serde: +The control plane copies the collector sub-DAG from the installed `dag` +(nodes unchanged, node ids included, and the edges between them; a `Scan` +that feeds no collector node is left out), lists its collector views as +`outputs`, and sets `roots = outputs`, `scalar_roots = []`. It writes one JSON file, with the planner types' +own serde: ```json -{"planner_wire_version": 15, +{"planner_wire_version": 16, "plan_id": "", "commit_grace_ms": 8000, "backend_reads_raw": {"data": true, "data_total": true}, - "views": [, ...]} + "outputs": [, ...], + "dag": } ``` +- `outputs` are the collector views, named explicitly rather than assumed + to be a chain at the root: the backend ingests exactly these nodes' + results, and nothing else in `dag` leaves the collector. - `backend_reads_raw` lists every metric a `Scan` of the plan reads. - `commit_grace_ms` is computed as in §6. @@ -219,8 +281,8 @@ The collector loads the file once at start (a plan change is a collector restart, decision 14). The data plane takes the same file with `--collector-views` and refuses it, at start and on each install, when its `plan_id` differs from the installed plan's. The precompute engine then -compiles each refresh group without the collector views (and without a `Scan` -only they read). The query engine is unchanged; it reads a collector view +compiles each refresh group without the collector sub-DAG's nodes (and +without a `Scan` only they read). The query engine is unchanged; it reads a collector view from the store like any other. ### 3. The collector: load, check, build, stamp @@ -230,21 +292,22 @@ At start, with `planner_views: ` in its processor config, the 1. **Loads** the file into the planner types. A `planner_wire_version` other than its pinned `asap-types` writes is a load error. -2. **Checks that it can execute each sub-DAG**, and refuses to start, - naming the view and the first failing field, unless: it is two nodes and - one `Input` edge, root a `SummaryTumblingWindowChain` over a `Scan` of - `TimeSeries { metric }`, and its summary, parameters, reduction, window - and predicates are within the collector's own capabilities (the same - table `--print-capabilities` prints). It does not check *whether* the - view should be a collector view (timing, lifetime): that is the control plane's - rule, written once. -3. **Reads each view's key** with `materialized_views()` on the sub-DAG and - `view_state_key()`: the key depends only on the view node, so it equals - the installed plan's. -4. **Builds** each view: sketch and parameters from θ (an out-of-range +2. **Checks that it can execute the sub-DAG**, and refuses to start, + naming the node and the first failing field, unless every node and its + arguments are within the collector's own capabilities (the same table + `--print-capabilities` prints). In v1 that means each output is a + `SummaryTumblingWindowChain` over a `Scan` of `TimeSeries { metric }`, + with only label `Filter`s between them. It does not check *whether* a + node should be on the collector (timing, placement): that is the control + plane's rule, written once. +3. **Reads each output's key** with `materialized_views()` on the sub-DAG + and `view_state_key()`: the key depends only on the view node, so it + equals the installed plan's. +4. **Builds** each view (v1, on the existing processor; §7 for the + executor): sketch and parameters from θ (an out-of-range value is a load error, never replaced by a default), window = `ViewWindow::Tumbling.width_ms`, matchers = `__name__ = metric` plus each - `Scan` predicate, one state per series. A series is what it is for the + `Scan`, `Filter` and chain-`filter` predicate, one state per series. A series is what it is for the raw forward: the received Resource, Scope and point attributes, kept as received (no flattening, no label dropping). 5. **Stamps** the view identity: each view is one Metric entry per @@ -270,9 +333,19 @@ plan does not read). ### 4. OTAP tiers: Schema, Dictionary, Record OTAP splits a metrics stream into three tiers by rate of change: **Schema** -(per metric), **Dictionary** (per series), **Record** (per point). -Collector view states use exactly the structure of raw samples; only the -Record content differs: +(per metric), **Dictionary** (per series), **Record** (per point). For any +collector view (any output of the collector sub-DAG) the tiers map as: + +- **Schema** = the output node's identity: `(plan_id, node_id, + ViewStateKey)`. +- **Dictionary** = the key columns of the node's `output_schema`. For a + per-series view they are the series labels, identical to the raw + samples'; for a view grouped by `G` they would be the `G` labels. +- **Record** = the window and the node's result in it: a state (ASAPv1 for + a sketch) or an exact value. + +v1's views are per-series, so collector view states use exactly the +structure of raw samples; only the Record content differs: | Tier | Raw samples | Collector view states | `ViewStateBatch` | Backend handling | |---|---|---|---|---| @@ -336,20 +409,20 @@ Prometheus's `(t − range, t]` form (§5). ```mermaid erDiagram - SCHEMA ||--o{ SERIES : series - SERIES ||--o{ RECORD : records + SCHEMA ||--o{ KEY : keys + KEY ||--o{ RECORD : records SCHEMA{ plan_id string "PhysicalASAPDAG::plan_id()" - node_id PhysicalASAPNodeId "the view node" + node_id PhysicalASAPNodeId "the output node (collector view)" key ViewStateKey "definition_id, window, logical_properties" name string "metric.asap_view.node_id" } - SERIES{ - labels LabelSet "raw path's label function; __name__ = Scan metric" + KEY{ + labels LabelSet "key columns of output_schema; per-series view: series labels, __name__ = Scan metric" } RECORD{ window_end_ms i64 "inclusive; start = end - width" - asapv1 bytes "sketch.envelope, the full state" + asapv1 bytes "sketch.envelope: the full state (or an exact value)" sample_count u64 "count" } ``` @@ -475,6 +548,25 @@ committer, the same path that commits a window it built (readers, A histogram of arrival delay (`end` to arrival) per view shows when the grace must grow. v1 has no late merge (decision 9). +### 7. Target: the collector runs `asap-executor` + +The target design (decision 25) is that the collector embeds ASAPPlanner's +`asap-executor` and runs `compile` and `instantiate` on its sub-DAG, as the +backend does on the whole plan. Its capabilities are then the executor's +(the same `DeploymentCapabilities` and operator list), and both sides run +the same code, so a state the collector builds is the state the backend +would have built, and any sub-DAG the rule assigns can run without +collector-specific code. + +v1 keeps mapping leaf views onto the existing `asap_sketches` processor +(§3); embedding the executor is the next step. It adds `arrow`, `ahash`, +`chrono`, `futures`, `regex` and `xxhash-rust` to the collector build +(`arrow` is already there through OTAP); step 10 measures the build time, +binary size and resident memory per view before it replaces the processor's +own sketch code. Partial aggregation (a non-local mergeable aggregate as +collector partial state plus a backend `SummaryMerge`) is future work on top +of it. + ## Code interface ### `crates/common` @@ -577,14 +669,34 @@ branch. #[serde(deny_unknown_fields)] pub struct CollectorCapabilities { pub capabilities_version: u32, - pub summaries: Vec, - /// Reduction variant names: `PerEntity`. - pub reductions: Vec, - pub windows: Vec, - pub predicate_ops: Vec, + /// The planner's own executor capabilities, unchanged serde. + pub executor: DeploymentCapabilities, + pub operators: Vec, + pub placement: Placement, pub window_close_delay_ms: u64, } +/// One operator the collector runs, with its argument constraints. A +/// constraint that does not apply to `kind` is a load error. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OperatorCapability { + pub kind: OperatorKind, + /// `Scan`: the source variants, e.g. `TimeSeries`. + #[serde(default)] + pub sources: Vec, + /// Label comparisons with a `Utf8` literal, in `Scan.predicates`, + /// `Filter.pred` or a chain's `filter`. + #[serde(default)] + pub predicate_ops: Vec, + /// Chain: `Reduction` variant names, e.g. `PerEntity`. + #[serde(default)] + pub reductions: Vec, + /// Chain: the summary types it builds, with parameter ranges. + #[serde(default)] + pub summaries: Vec, +} + #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] pub struct SummaryCapability { @@ -593,6 +705,20 @@ pub struct SummaryCapability { pub parameters: BTreeMap, // gt, ge, lt, le: Option } +/// How series are partitioned across collector instances. +/// JSON: `{"partitioned_by": "series"}` or `{"partitioned_by": {"labels": [..]}}`. +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum PartitionedBy { + Series, + Labels(Vec), +} +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Placement { + pub partitioned_by: PartitionedBy, +} + /// The file the collector and the data plane load. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -601,30 +727,36 @@ pub struct CollectorViewsFile { /// `PhysicalASAPDAG::plan_id()` of the installed plan. pub plan_id: String, pub commit_grace_ms: u64, - /// Per metric a `Scan` reads: whether a view that is not a collector view, or a + /// Per metric a `Scan` reads: whether a node off the collector, or a /// query-time `Scan`, still reads its raw samples. pub backend_reads_raw: BTreeMap, - /// One sub-DAG per collector view; `roots = [view node]`. - pub views: Vec, + /// The collector views: the cut nodes whose results the backend ingests. + pub outputs: Vec, + /// The collector sub-DAG; `roots = outputs`. + pub dag: PhysicalASAPDAG, } -/// Why a leaf view is not a collector view, for the command's report. +/// Why a node is not on the collector, for the command's report. #[derive(Debug, Clone, PartialEq)] -pub enum NotCollectorView { - NotOnRawScan, +pub enum NotOnCollector { NotInCapabilities(String), + InputNotOnCollector, + NotAtIngestion, + NotLocalToPartition, + /// v1: a cut producer that is not a materialized view. + OutputNotAView, } -/// The installed plan's collector views and why each other view is not. -pub fn collector_view_dags( +/// The installed plan's collector sub-DAG and why each other node is not on it. +pub fn collector_sub_dag( plan: &InstallablePlan, capabilities: &CollectorCapabilities, export_interval_ms: u64, -) -> (CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotCollectorView)>); +) -> (CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>); ``` -`FieldDataType` (the chain's `summary_type`) and `CompareOpKind` are the -planner's types. CLI: +`DeploymentCapabilities`, `OperatorKind`, `FieldDataType` (the chain's +`summary_type`) and `CompareOpKind` are the planner's types. CLI: `control_plane --plan --collector-capabilities [--collector-export-interval-ms ] --emit-collector-views `; the data plane takes @@ -645,13 +777,18 @@ n4 SummaryEstimate Quantile(q=0.99) n5 Project (root) ``` -n1 passes the rule. Its sub-DAG in `collector-views.json` (schemas +n0 and n1 are assigned (n0 a raw `Scan`; n1 a `PerEntity` chain within +the capabilities, at ingestion); n2 runs at query time, so the edge n1 → n2 +is cut and n1 is the one output. n0 also feeds q02's and q03's chains, +which are not in the capabilities, so the edges from n0 to them are cut +too and `data` stays raw. The sub-DAG in `collector-views.json` (schemas shortened to their field names; the file carries them in full): ```json -{"planner_wire_version": 15, "plan_id": "…", "commit_grace_ms": 8000, +{"planner_wire_version": 16, "plan_id": "…", "commit_grace_ms": 8000, "backend_reads_raw": {"data": true, "data_total": true}, - "views": [{ + "outputs": [1], + "dag": { "nodes": [ {"id": 0, "payload": {"NonASAP": {"Scan": { @@ -682,7 +819,7 @@ shortened to their field names; the file carries them in full): "data_state": {"timing": "ingestion_time", "primitive": "Raw"}, "grouping": "NotApplicable", "window": "NotApplicable"}], "roots": [1], - "scalar_roots": []}]} + "scalar_roots": []}} ``` n1's view state key is `{"definition_id": @@ -785,15 +922,19 @@ Backend: metric, one key that differs from the node's (other θ), one state of another plan id, one duplicate after a merge, one late state, and one series sent raw and as a state that gets equal labels. -4. The control plane's rule with `--collector-capabilities`, - `--emit-collector-views` (sub-DAGs, `plan_id`, `backend_reads_raw`, - `commit_grace_ms`); the data plane's `--collector-views` with the plan-id - check; precompute skips collector views. Tests: the benchmark plan - gives exactly q01's sub-DAG as a collector view and marks both metrics raw; a q01-only plan marks - `data` `false`; a regex matcher, a `Reduce` leaf or an `ExactAggregate` - leaf gives no collector view; a file of another plan id is refused; the written - file deserializes and `materialized_views()` on each sub-DAG gives the - installed view's key. +4. The control plane's bottom-up rule with `--collector-capabilities` + (the four conditions, the cut, the view check on outputs), + `--emit-collector-views` (sub-DAG, `outputs`, `plan_id`, + `backend_reads_raw`, `commit_grace_ms`); the data plane's + `--collector-views` with the plan-id check; precompute skips the + collector sub-DAG. Tests: the benchmark plan gives exactly `outputs = + [n1]` and marks both metrics raw; a q01-only plan marks `data` `false`; a + regex matcher, a `Reduce` leaf or an `ExactAggregate` leaf gives no + collector view; with capabilities that list `Aggregate`, a `Reduce(G)` + is assigned under `{"labels": L}` with `L ⊆ G` and not under `"series"`; + a file of another plan id is refused; the written file deserializes and + `materialized_views()` on its sub-DAG gives each output's installed + key. 5. End-to-end comparison, collector + backend against backend only, on the same feed, for two workloads: the five-query benchmark set (expected benefit about zero, above) and q01 alone (the metric has only collector-view @@ -818,8 +959,14 @@ Collector (ASAPCollector-public): drop-and-count after close, and matchers (§5). It lands before step 5, which needs equal windows. 9. The raw-forward filter by `backend_reads_raw`. - -**Future work.** Late merge into a committed window (a store `replace`, a +10. Embed `asap-executor` (§7): run `compile` and `instantiate` on the + sub-DAG, print the executor's capabilities, and retire the processor's + own sketch code once answers match. Measure first: clean build time, + binary size, and resident memory per view and per series, against + the processor. + +**Future work.** Partial aggregation (collector partial states of a +non-local mergeable aggregate, merged by a backend `SummaryMerge`). Late merge into a committed window (a store `replace`, a view-file rewrite and result-cache invalidation), only if step 5 or production shows a late rate worth it, measured by `late_dropped` and the arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow adapter. @@ -848,14 +995,14 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 6. **Rule-based choice of collector views first**, against the collector's declared capabilities. No cost comparison. Exact aggregates stay in the backend until the collector declares them. -7. **The collector receives the planner's own view definitions**: each - collector view's sub-DAG, in the planner's serde; the collector depends on +7. **The collector receives the planner's own view definitions**: the + collector sub-DAG and its `outputs`, in the planner's serde; the collector depends on the planner's types crate, pinned. This replaces a numeric `agg_id` and - a hand-written collector config. The backend's precompute skips collector - views. The data plane refuses a collector-views file of another `plan_id`. + a hand-written collector config. The backend's precompute skips the + collector sub-DAG. The data plane refuses a collector-views file of another `plan_id`. 8. **The collector declares its capabilities** (`--print-capabilities`); the control plane's rule reads them. The rule exists once, in the control - plane; the collector checks only that it can execute each sub-DAG. + plane; the collector checks only that it can execute the sub-DAG. 9. **No late merge in v1.** A state after commit is dropped and counted. The store's put-once contract is unchanged. 10. **Raw forwarding follows the readers.** The file lists, per metric, @@ -893,7 +1040,8 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 15. **Dependency weight on the collector build.** `asap-types` adds `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin (Decision 13) it adds no second sketchlib. Accept it. Measure the collector's clean build - time before and after in step 7. + time before and after in step 7. The executor (decision 25) is measured + separately in step 10. 16. **Transport: OTLP HTTP or OTAP Arrow.** V1 accepts OTLP HTTP. Next, an OTAP Arrow adapter fed by `urn:otel:exporter:otap`, decoding with the `arrow-ipc` and `tonic` the backend already builds, rather than the @@ -906,7 +1054,7 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad still read from the metadata, and the backend stores the rows under the `Scan`'s metric, so queries are unaffected. `.asap_view.` is reserved. 18. **Sub-DAG validity.** No planner function extracts a sub-DAG. The loader - calls `materialized_views()` on each sub-DAG, which validates it, and + calls `materialized_views()` on the sub-DAG, which validates it, and step 4 tests this on the benchmark plan. If the planner refuses such a DAG, file the need against the planner in its terms. 19. **One processor for all views, or one per view.** One `asap_sketches` @@ -924,6 +1072,26 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad `service.namespace/`) → `job`, `service.instance.id` → `instance`; an optional allow-list promotes named attributes. Equal Dictionary entries give equal labels whichever path carried them. +23. **A generic collector-view rule.** Nodes are assigned bottom-up from + the `Scan`s when their operator and arguments are in the capabilities, + every input is a raw `Scan` or an assigned node, they run at ingestion, + and they are correct on one instance's partition. The maximal such + sub-DAG is cut; its outputs are listed in the file. Today's leaf rule is + the case of today's capabilities, so v1's scope is unchanged. +24. **Capabilities in the planner's vocabulary.** `executor` is the + planner's `DeploymentCapabilities`, `operators` are `OperatorKind`s with + argument constraints, and `placement` says how series are partitioned, + so a new collector operator is a capabilities change, not a backend + change. +25. **Target: the collector embeds `asap-executor`.** It compiles and + instantiates its sub-DAG as the backend does, so its capabilities are + the executor's and both sides run the same code. v1 maps leaf views + onto the existing processor; the embedding is the next step, after its + dependency and memory cost is measured (step 10). +26. **Partial aggregation is future work.** A non-local mergeable aggregate + (a group spread over instances) would cross the cut as a partial state + merged by a backend `SummaryMerge`; v1 keeps it, and every node above + it, in the backend. ## Open questions From 02436b0502bc4d3e75df49fd8311b3677b86f120 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 04:33:23 +0000 Subject: [PATCH 10/21] docs(design): state each collector capability once Sketch parameter ranges, input kind and readouts live in the executor's supported_summaries entry; predicate_ops is shared by every operator that takes a predicate; operators keep only operator-specific limits. Adds a worked example of moving the cut and of placement keeping a group-by in the backend. --- docs/design/collector-sketch-ingest.md | 155 ++++++++++++++++--------- 1 file changed, 100 insertions(+), 55 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index d06c2fa2f..0c026414e 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -155,47 +155,54 @@ the backend holds no table of the collector's operators or sketches. {"capabilities_version": 1, "executor": { "supported_summaries": [ - {"summary_type": "DDSketch", "readouts": []}, - {"summary_type": "KLL", "readouts": []}, - {"summary_type": "HLL", "readouts": []}, - {"summary_type": "CountSketch", "readouts": []}, - {"summary_type": "CountMinSketch", "readouts": []}, - {"summary_type": "CountMinSketchWithHeap", "readouts": []}], + {"summary": {"summary_type": "DDSketch", "readouts": []}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, + {"summary": {"summary_type": "KLL", "readouts": []}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, + {"summary": {"summary_type": "HLL", "readouts": []}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, + {"summary": {"summary_type": "CountSketch", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary": {"summary_type": "CountMinSketch", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, + {"summary": {"summary_type": "CountMinSketchWithHeap", "readouts": []}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}], "raw_data_retained": false, "query_time_results_retained": false, "counter_semantics": {"reset_handling": false, "extrapolation": false}, "state_not_mergeable_across_windows": [], "excluded_candidates": []}, + "predicate_ops": ["Eq", "Ne"], "operators": [ - {"kind": "Scan", "sources": ["TimeSeries"], "predicate_ops": ["Eq", "Ne"]}, - {"kind": "Filter", "predicate_ops": ["Eq", "Ne"]}, - {"kind": "SummaryTumblingWindowChain", "reductions": ["PerEntity"], "predicate_ops": ["Eq", "Ne"], - "summaries": [ - {"summary_type": {"Sketch": "DDSketch"}, "input": "value", "parameters": {"alpha": {"gt": 0, "lt": 1}}}, - {"summary_type": {"Sketch": "KLL"}, "input": "value", "parameters": {"k": {"ge": 8, "le": 2147483647}}}, - {"summary_type": {"Sketch": "HLL"}, "input": "label", "parameters": {"precision": {"ge": 14, "le": 14}}}, - {"summary_type": {"Sketch": "CountSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, - {"summary_type": {"Sketch": "CountMinSketch"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}}}, - {"summary_type": {"Sketch": "CountMinSketchWithHeap"}, "input": "label", "parameters": {"width": {"ge": 1}, "depth": {"ge": 1}, "heap_size": {"ge": 1}}}]}], + {"kind": "Scan", "sources": ["TimeSeries"]}, + {"kind": "Filter"}, + {"kind": "SummaryTumblingWindowChain", "reductions": ["PerEntity"]}], "placement": {"partitioned_by": "series"}, "window_close_delay_ms": 6000} ``` -- `executor`: ASAPPlanner's `DeploymentCapabilities`, with its own serde - (`asap_types::deployment_capabilities`). Today's collector builds states - but answers no readout (no `SummaryEstimate`), keeps no raw data and no - query-time result, and has no counter functions. -- `operators`: each entry is a planner `OperatorKind` with the argument - constraints the collector accepts; an operator not listed is not run. - `predicate_ops` are `CompareOpKind`s of a label column with a `Utf8` - literal (PromQL `=`, `!=`; no regular expressions), for a `Scan`'s - `predicates`, a `Filter`'s `pred` and a chain's `filter`. A chain's - `summary_type`, `input` and every `parameters` value must match one - `summaries` entry. `input: "value"`: the summary's `input` is `{"item": - null, "weight": {"Column": "SampleValue"}}`; `input: "label"`: `item` is - one label column. The ranges are the ones the collector's config - validation enforces; the command prints them from that code, so the two - cannot drift. +Each capability is stated once. The sketches, with their parameter ranges, +input kind and readouts, are only in `executor.supported_summaries`; the +predicates every operator accepts are only in `predicate_ops`; `operators` +lists operator kinds and the limits that belong to one operator. + +- `executor`: ASAPPlanner's `DeploymentCapabilities`, with its serde + (`asap_types::deployment_capabilities`), except that the planner's + `SupportedSummary` (`summary_type` and `readouts`; unchanged, it has no + field for the rest) is wrapped by the collector's own entry + `{"summary": , "input": ..., "parameters": ...}`. The + control plane reads the entries, builds the planner's + `DeploymentCapabilities` from their `summary` fields, and keeps `input` + and `parameters` for the rule. `input: "value"`: the summary's `input` is + `{"item": null, "weight": {"Column": "SampleValue"}}`; `input: "label"`: + `item` is one label column. `parameters` are the ranges the collector's + config validation enforces; the command prints them from that code, so + the two cannot drift. `readouts: []` because the collector reads no value + from a sketch yet; a sketch's readouts are filled when `SummaryEstimate` + is supported. Today's collector keeps no raw data and no query-time + result, and has no counter functions. +- `predicate_ops`: `CompareOpKind`s of a label column with a `Utf8` literal + (PromQL `=`, `!=`; no regular expressions), for every operator that takes + a predicate: a `Scan`'s `predicates`, a `Filter`'s `pred`, a chain's + `filter`. +- `operators`: each entry is a planner `OperatorKind`; an operator not + listed is not run. Its other fields are limits of that operator only: + `sources` (`Scan`: the source variants), `reductions` (a chain: `Reduction` + variant names). - `placement`: how series are partitioned across collector instances. `"series"`: all samples of one series reach one instance (a restart or handoff may split a window, which the backend merges, §6). @@ -211,9 +218,9 @@ from their planner fields only (no cost comparison, decision 6). A node is assigned if and only if all of these hold: 1. **Within the capabilities.** Its `OperatorKind` is in `operators` and its - arguments meet that entry's constraints; any summary it builds is in - `executor.supported_summaries`, and any readout it answers is listed - there. + arguments meet that entry's limits and `predicate_ops`; any summary it + builds is in `executor.supported_summaries` with its `input` and + `parameters` in range, and any readout it answers is listed there. 2. **Inputs on the collector.** Every input is a `Scan` of raw data (`TimeSeries { metric }`) or a node already assigned. 3. **At ingestion.** It runs at ingestion time (`output_state.timing` is @@ -247,6 +254,33 @@ label `Filter`s, chain), and the `TimeRange`, `SummaryMerge` and `ExactAggregate` become collector views when the collector declares them (§7: with the executor embedded, it declares what the executor runs). +**Moving the cut: one line per operator.** Take `quantile_over_time(0.99, +data[1m])` with the rule unchanged. Today the cut is the chain: the merge of +a minute of windows and the quantile run in the backend. If the collector +supports more, only the capabilities change, and the planner (reading the +same `executor` capabilities) may then put these nodes at ingestion: + +```text +n1 SummaryTumblingWindowChain DDSketch -> a view today +n2 SummaryMergeWindows last 60 s, per series (IngestionTime) +n3 SummaryEstimate Quantile(0.99) (IngestionTime) +``` + +- Add `{"kind": "SummaryMergeWindows"}` to `operators`: n2 meets rule 1, so + the cut moves up to n2 and the view is the merged state. +- Also set DDSketch's `"readouts": ["Quantile"]` in + `executor.supported_summaries` and add `{"kind": "SummaryEstimate"}`: n3 + is assigned, the cut moves to n3 and the view is an exact value. The + statistic is stated once, as the sketch's readout. + +No code changes: the rule, the file formats and the views file are the same. +`placement` keeps what is not local in the backend. For `sum by (region) +(quantile_over_time(0.99, data[1m]))` the `Aggregate` over regions needs +`{"kind": "Aggregate"}` listed, and rule 4 then decides: with +`"partitioned_by": "series"` a region's series are on several instances, so +the `sum by (region)` stays on the backend; with `{"labels": ["region"]}` +each region is on one instance and the `Aggregate` is assigned too. + **Known limitation: sparse series.** The rule ignores size. A series with few samples per window can produce a state larger than its raw samples (a DDSketch with one sample still carries its header, mapping and bins, @@ -669,15 +703,20 @@ branch. #[serde(deny_unknown_fields)] pub struct CollectorCapabilities { pub capabilities_version: u32, - /// The planner's own executor capabilities, unchanged serde. - pub executor: DeploymentCapabilities, + /// The planner's `DeploymentCapabilities` serde, with each + /// `supported_summaries` entry a `CollectorSummary`; the control plane + /// builds the planner type from the entries' `summary` fields. + pub executor: CollectorExecutor, + /// Label comparisons with a `Utf8` literal, for every operator that + /// takes a predicate. + pub predicate_ops: Vec, pub operators: Vec, pub placement: Placement, pub window_close_delay_ms: u64, } -/// One operator the collector runs, with its argument constraints. A -/// constraint that does not apply to `kind` is a load error. +/// One operator the collector runs, with the limits of that operator only. +/// A limit that does not apply to `kind` is a load error. #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] pub struct OperatorCapability { @@ -685,23 +724,26 @@ pub struct OperatorCapability { /// `Scan`: the source variants, e.g. `TimeSeries`. #[serde(default)] pub sources: Vec, - /// Label comparisons with a `Utf8` literal, in `Scan.predicates`, - /// `Filter.pred` or a chain's `filter`. - #[serde(default)] - pub predicate_ops: Vec, /// Chain: `Reduction` variant names, e.g. `PerEntity`. #[serde(default)] pub reductions: Vec, - /// Chain: the summary types it builds, with parameter ranges. - #[serde(default)] - pub summaries: Vec, } +/// `executor`: every `DeploymentCapabilities` field with its planner serde, +/// except `supported_summaries`, whose entries are `CollectorSummary`s. +pub struct CollectorExecutor { + pub supported_summaries: Vec, + #[serde(flatten)] + pub rest: DeploymentCapabilities, // its own `supported_summaries` stays `None` +} + +/// An entry of `executor.supported_summaries`: the planner's +/// `SupportedSummary` (unchanged) plus what only the collector states. #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(deny_unknown_fields)] -pub struct SummaryCapability { - pub summary_type: FieldDataType, - pub input: SummaryInputKind, // Value | Label +pub struct CollectorSummary { + pub summary: SupportedSummary, // summary_type + readouts + pub input: SummaryInputKind, // Value | Label pub parameters: BTreeMap, // gt, ge, lt, le: Option } @@ -755,8 +797,8 @@ pub fn collector_sub_dag( ) -> (CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>); ``` -`DeploymentCapabilities`, `OperatorKind`, `FieldDataType` (the chain's -`summary_type`) and `CompareOpKind` are the planner's types. CLI: +`DeploymentCapabilities`, `SupportedSummary`, `OperatorKind` and +`CompareOpKind` are the planner's types, unchanged. CLI: `control_plane --plan --collector-capabilities [--collector-export-interval-ms ] --emit-collector-views `; the data plane takes @@ -1078,11 +1120,14 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad and they are correct on one instance's partition. The maximal such sub-DAG is cut; its outputs are listed in the file. Today's leaf rule is the case of today's capabilities, so v1's scope is unchanged. -24. **Capabilities in the planner's vocabulary.** `executor` is the - planner's `DeploymentCapabilities`, `operators` are `OperatorKind`s with - argument constraints, and `placement` says how series are partitioned, - so a new collector operator is a capabilities change, not a backend - change. +24. **Capabilities in the planner's vocabulary, each stated once.** + `executor` is the planner's `DeploymentCapabilities`, each sketch once + with its parameter ranges, input kind and readouts (the planner's + `SupportedSummary` wrapped by the collector's entry, planner type + unchanged); `predicate_ops` is shared by every operator that takes a + predicate; `operators` are `OperatorKind`s with only their own limits; + `placement` says how series are partitioned. A new collector operator + is one line, not a backend change. 25. **Target: the collector embeds `asap-executor`.** It compiles and instantiates its sub-DAG as the backend does, so its capabilities are the executor's and both sides run the same code. v1 maps leaf views From f167ddcde126696f10ebdb2481b7aba7aecdc2a4 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 05:46:10 +0000 Subject: [PATCH 11/21] Collector design: v1 embeds the executor via a thin driver; spike results --- docs/design/collector-sketch-ingest.md | 127 ++++++++++++++++++------- 1 file changed, 92 insertions(+), 35 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 0c026414e..3cdab15b9 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -106,7 +106,7 @@ Scope: | Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares, in the planner's vocabulary, what the collector can run and how series are placed on its instances (§1) | | Collector view rule | `crates/control-plane` | Assigns nodes of the installed plan to the collector bottom-up against the capabilities and cuts the collector sub-DAG; the only copy of the rule | | Collector-views file | `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw, the commit grace | -| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, runs the sub-DAG (v1: builds each leaf view's per-series states), writes the view identity into metric metadata, exports summary points with `sketch.envelope` | +| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, runs the sub-DAG (v1: builds each leaf view's per-series states with the embedded executor), writes the view identity into metric metadata, exports summary points with `sketch.envelope` | | Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | | OTLP adapter | `crates/adapters/ingest/otlp` | Decodes Schema and Dictionary as for raw samples; a point with `sketch.envelope` becomes a `common::ViewStateBatch` record; never reads the sketch bytes | | Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states | @@ -141,7 +141,7 @@ Decoding is not an identity check: θ is already in the key. `asap-types` brings `serde`, `serde_json`, `thiserror` 2 and `asap_sketchlib` into the collector build; no frontend or solver -(decision 15). The executor comes in the step after v1 (§7). +(decision 15). `asap-executor` adds no third-party crate to the lock (§7). ## Algorithm @@ -337,8 +337,8 @@ At start, with `planner_views: ` in its processor config, the 3. **Reads each output's key** with `materialized_views()` on the sub-DAG and `view_state_key()`: the key depends only on the view node, so it equals the installed plan's. -4. **Builds** each view (v1, on the existing processor; §7 for the - executor): sketch and parameters from θ (an out-of-range +4. **Builds** each view (v1: the executor through a thin driver; §7 for the + options): sketch and parameters from θ (an out-of-range value is a load error, never replaced by a default), window = `ViewWindow::Tumbling.width_ms`, matchers = `__name__ = metric` plus each `Scan`, `Filter` and chain-`filter` predicate, one state per series. A series is what it is for the @@ -582,24 +582,62 @@ committer, the same path that commits a window it built (readers, A histogram of arrival delay (`end` to arrival) per view shows when the grace must grow. v1 has no late merge (decision 9). -### 7. Target: the collector runs `asap-executor` - -The target design (decision 25) is that the collector embeds ASAPPlanner's -`asap-executor` and runs `compile` and `instantiate` on its sub-DAG, as the -backend does on the whole plan. Its capabilities are then the executor's -(the same `DeploymentCapabilities` and operator list), and both sides run -the same code, so a state the collector builds is the state the backend -would have built, and any sub-DAG the rule assigns can run without -collector-specific code. - -v1 keeps mapping leaf views onto the existing `asap_sketches` processor -(§3); embedding the executor is the next step. It adds `arrow`, `ahash`, -`chrono`, `futures`, `regex` and `xxhash-rust` to the collector build -(`arrow` is already there through OTAP); step 10 measures the build time, -binary size and resident memory per view before it replaces the processor's -own sketch code. Partial aggregation (a non-local mergeable aggregate as -collector partial state plus a backend `SummaryMerge`) is future work on top -of it. +**Envelope hash and implementation.** The envelope hash depends on which +implementation produced the state: the executor shrinks sealed states, so an +old-processor collector and an executor collector give different hashes, and +therefore different bytes, for equal states. In a mixed rollout the +duplicate check does not recognise such a pair as a duplicate, and the +second state takes the merge path, which handles it. + +### 7. The collector runs `asap-executor` + +The collector embeds ASAPPlanner's `asap-executor` and runs `compile` and +`instantiate` on its sub-DAG, as the backend does on the whole plan +(decision 25). Its capabilities are then the executor's (the same +`DeploymentCapabilities` and operator list), and a state the collector +builds is the state the backend would have built. + +**Options.** + +- **A (v1): a thin collector-side driver over the executor's public APIs.** + The driver feeds each raw sample into the per-window run, closes a window + at its end, and encodes the resulting state as ASAPv1. It is small and + needs nothing from the backend. +- **C (next): the generic streaming driver moves into the executor as a + public API.** That is the streamed raw input, the per-window run holder, + the window-end math, and a state-to-ASAPv1 call. The backend keeps + interning, sharding and routing, watermark policy, commit, persistence, + the memory budget and metrics; the collector and the backend then share + one driver. +- **B (rejected): the collector depends on the backend's precompute + crate.** It needs about ten `pub(crate)` items made public, uses a + process-wide interner, pulls in storage, `tokio`, `clap` and the full + `asap-planner` with its solver, and makes the collector a git dependency + on the backend. + +**Spike.** A feasibility spike built option A's driver in the collector +and compared it with the `asap_sketches` processor. + +| Measure | Result | +|---|---| +| Lock file | only `asap-executor` added; 0 third-party crates (one `arrow` 58.4, one `asap_sketchlib`) | +| Clean build | +3% wall, +5% CPU | +| Binary size | +4.6% (stripped +4.7%) | +| CPU per sample, 5 samples per window | `asap_sketches` 1298 ns; executor DAG run per second 1546 ns (+19%); per window 1410 ns (+9%); kernel only 1113 ns (-14%) | +| State memory, 10,000 series | 20.8 MB (executor) vs 30.1 MB (`asap_sketches`) | + +Correctness, over 120,000 states: the executor's variants are byte-equal to +each other. Against `asap_sketches` the count and the quantiles are the +same, but the bytes differ, because the executor shrinks a sealed state +(typically 69 B against 188 B); shrinking and re-encoding the old +processor's state gives the executor's bytes. The payload is about 2.7x +smaller. The worst relative error is 0.0500, within the sketch's +alpha. + +v1 therefore uses option A; step 10 is its implementation, and the spike +is its measure-first part. Partial aggregation (a non-local mergeable +aggregate as collector partial state plus a backend `SummaryMerge`) is +future work on top of it. ## Code interface @@ -950,6 +988,8 @@ Pins (all three repositories): 1. Bump the ASAPPlanner and `asap_sketchlib` pins to the latest main (Decision 13), in the planner, then the backend, then the collector. + The pin alignment precedes any byte-for-byte comparison with the + deployed backend. Backend: @@ -998,14 +1038,21 @@ Collector (ASAPCollector-public): per-sketch fields when it is set. 8. The window boundary `(e − w, e]` in `SketchEnvelope` and the point times (window attributes removed), placement by sample timestamp with - drop-and-count after close, and matchers (§5). It lands before step 5, + drop-and-count after close, and matchers (§5). For planner views the + executor supplies the window boundary, the placement by timestamp and the + matchers (step 10); the processor-side changes in steps 7 and 8 remain + for legacy non-planner configurations only. It lands before step 5, which needs equal windows. 9. The raw-forward filter by `backend_reads_raw`. -10. Embed `asap-executor` (§7): run `compile` and `instantiate` on the - sub-DAG, print the executor's capabilities, and retire the processor's - own sketch code once answers match. Measure first: clean build time, - binary size, and resident memory per view and per series, against - the processor. +10. v1 approach (§7, option A): embed `asap-executor` through a thin + collector-side driver over its public APIs: run `compile` and + `instantiate` on the sub-DAG, drive the per-window runs from the raw + samples, encode each state as ASAPv1, and print the executor's + capabilities. The spike is its measure-first part (build time, binary + size, CPU and memory against the processor, and state correctness). The + processor's own sketch code is retired for planner views once answers + match. Next (option C): move the generic streaming driver into the + executor as a public API, so the collector and the backend share it. **Future work.** Partial aggregation (collector partial states of a non-local mergeable aggregate, merged by a backend `SummaryMerge`). Late merge into a committed window (a store `replace`, a @@ -1082,8 +1129,8 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 15. **Dependency weight on the collector build.** `asap-types` adds `serde_json` and `thiserror` 2; with one `asap_sketchlib` pin (Decision 13) it adds no second sketchlib. Accept it. Measure the collector's clean build - time before and after in step 7. The executor (decision 25) is measured - separately in step 10. + time before and after in step 7. The executor (decision 25) was measured + separately in the spike (§7). 16. **Transport: OTLP HTTP or OTAP Arrow.** V1 accepts OTLP HTTP. Next, an OTAP Arrow adapter fed by `urn:otel:exporter:otap`, decoding with the `arrow-ipc` and `tonic` the backend already builds, rather than the @@ -1128,11 +1175,21 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad predicate; `operators` are `OperatorKind`s with only their own limits; `placement` says how series are partitioned. A new collector operator is one line, not a backend change. -25. **Target: the collector embeds `asap-executor`.** It compiles and - instantiates its sub-DAG as the backend does, so its capabilities are - the executor's and both sides run the same code. v1 maps leaf views - onto the existing processor; the embedding is the next step, after its - dependency and memory cost is measured (step 10). +25. **v1 embeds `asap-executor` through a thin collector-side driver; the + shared driver is next; the backend's precompute crate is rejected.** + The collector compiles and instantiates its sub-DAG as the backend does, + so its capabilities are the executor's and both sides run the same code. + v1 (option A) writes a small driver over the executor's public APIs; a + spike measured +3% build wall time, +4.6% binary size, 0 new + third-party crates and a smaller state memory, with correct answers. + Next (option C), the generic streaming driver moves into the executor as + a public API; the backend keeps interning, sharding and routing, + watermark policy, commit, persistence, the memory budget and metrics. + Option B, depending on the backend's precompute crate, is rejected: it + needs about ten `pub(crate)` items made public, has a process-wide + interner, pulls in storage, `tokio`, `clap` and the full `asap-planner` + with its solver, and makes the collector a git dependency on the + backend. 26. **Partial aggregation is future work.** A non-local mergeable aggregate (a group spread over instances) would cross the cut as a partial state merged by a backend `SummaryMerge`; v1 keeps it, and every node above From daf3b489257a3c62793f8383dd08d306645a78d2 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sat, 28 Nov 2026 15:33:42 +0000 Subject: [PATCH 12/21] docs: fold the implementation's departures into the collector design Engine option for the precompute skip, window_start_ms, merge/key_mismatch/name rejections, request staging order, CollectorViewsFile in common, CommitGrace, collector processors, per-group lateness, and the label-input weight decision. --- docs/design/collector-sketch-ingest.md | 185 ++++++++++++++++--------- 1 file changed, 120 insertions(+), 65 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 3cdab15b9..6656c261e 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -81,35 +81,36 @@ Scope: branch), new `common` types, the collector-state ingest in precompute, and the control plane. - The collector changes in its own repository: a capabilities command, the - `asap-types` dependency and a sub-DAG loader (later `asap-executor`, §7), view identity in metric - metadata, the window-boundary, out-of-order and matcher fixes, and a - raw-forward filter. + `asap-types` dependency and a sub-DAG loader, a `collector_views` processor + that runs the views on the embedded `asap-executor` (§7), view identity in + metric metadata, the window-boundary, out-of-order and matcher fixes, and a + `raw_forward` processor. ## Components ```text ┌───────────────────────────────── collector ─────────────────────────────────┐ - application ─ OTLP ─▶│ receiver ─┬─▶ asap_sketches (planner_views) ───────────────────▶ OTLP exporter│─┐ sketch path - │ └─▶ raw forward (drops metrics with backend_reads_raw = false) ─▶ ...│─┤ raw path + application ─ OTLP ─▶│ receiver ─┬─▶ collector_views (planner_views) ─────────────────▶ OTLP exporter│─┐ sketch path + │ └─▶ raw_forward (drops metrics with backend_reads_raw = false) ─▶ ...│─┤ raw path └─────────────────────────────────────────────────────────────────────────────┘ │ - asap_sketches --print-capabilities ─▶ capabilities.json ▲ collector-views.json │ + collector --print-capabilities ─▶ capabilities.json ▲ collector-views.json │ │ │ ▼ workload ─▶ control-plane ─▶ InstallablePlan ─┼──────────────────────┼──────▶ data-plane POST /v1/metrics │ (asap-planner) ▼ │ otlp: one walk, Schema + Dictionary decoded once; branch at the Record: └─ collector view rule (reads capabilities.json) ───────┘ ├─ point without sketch.envelope ─▶ Point ─▶ PrecomputeEngine::try_ingest (same collector-views.json) ────────────────────────────▶ └─ point with sketch.envelope ─▶ ViewStateBatch - ─▶ PrecomputeEngine::ingest_collector_states ─▶ committer ─▶ storage::ViewStore + ─▶ InstalledPrecompute::ingest_collector_states ─▶ committer ─▶ storage::ViewStore ``` | Component | Crate or repository | Role | |---|---|---| | Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares, in the planner's vocabulary, what the collector can run and how series are placed on its instances (§1) | | Collector view rule | `crates/control-plane` | Assigns nodes of the installed plan to the collector bottom-up against the capabilities and cuts the collector sub-DAG; the only copy of the rule | -| Collector-views file | `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw, the commit grace | -| `asap_sketches` processor | ASAPCollector-public | Loads the file at start, runs the sub-DAG (v1: builds each leaf view's per-series states with the embedded executor), writes the view identity into metric metadata, exports summary points with `sketch.envelope` | -| Raw forward | ASAPCollector-public | Forwards raw samples to the backend, except metrics the file marks `false` | +| Collector-views file | `CollectorViewsFile` in `crates/common` (the data plane reads it); written by `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw, the commit grace | +| `collector_views` processor | ASAPCollector-public | Config `planner_views: `. Loads the file at start, runs the sub-DAG on the embedded executor (v1: each leaf view's per-series states), writes the view identity into metric metadata (`asap.plan_id`, `asap.node_id`, `asap.view_state_key`), exports summary points with `sketch.envelope` | +| `raw_forward` processor | ASAPCollector-public | Config `planner_views: `. Forwards raw samples to the backend, except metrics the file marks `backend_reads_raw: false` | | OTLP adapter | `crates/adapters/ingest/otlp` | Decodes Schema and Dictionary as for raw samples; a point with `sketch.envelope` becomes a `common::ViewStateBatch` record; never reads the sketch bytes | -| Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states | +| Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states. The precompute skip of collector views is an engine option (`PrecomputeOptions::collector`), set from the file by the data plane's `--collector-views` | **Raw path.** The raw path stays (decision 3) for every metric the backend still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` @@ -130,7 +131,8 @@ crate / repository depends on ------------------- ------------------------------------------------------ otlp + common (ViewStateBatch); adapters may depend on common only precompute + decoding ASAPv1 through storage's existing codec (persist.rs decode_sketch) -control-plane unchanged dependencies (asap-planner, common) +control-plane + asap-types (the IR the rule reads; asap-planner does not re-export it), + common (the file) +data-plane reads CollectorViewsFile from common, not from control-plane ASAPCollector-public + asap-types (ASAPPlanner's types crate), pinned git rev ``` @@ -189,7 +191,10 @@ lists operator kinds and the limits that belong to one operator. `DeploymentCapabilities` from their `summary` fields, and keeps `input` and `parameters` for the rule. `input: "value"`: the summary's `input` is `{"item": null, "weight": {"Column": "SampleValue"}}`; `input: "label"`: - `item` is one label column. `parameters` are the ranges the collector's + `item` is one label column, and the entry must state the weight + semantics (count, or the per-key sum of the sample value); until it does, + the collector view rule requires weight 1 (count) for a label-input sketch + (decision 27). `parameters` are the ranges the collector's config validation enforces; the command prints them from that code, so the two cannot drift. `readouts: []` because the collector reads no value from a sketch yet; a sketch's readouts are filled when `SummaryEstimate` @@ -288,6 +293,11 @@ against about 16 bytes for the raw sample). Step 5 of the plan measures where this happens. Cost-based choice of collector views is future work; it needs a general planner capability (costing where a view is built). +**Known limitation: a view that reads a collector view and a raw metric.** +A view that both reads a collector view and scans a raw metric keeps that +metric's raw samples until the collector's first state arrives; only then +does it start from the collector view's windows. + ### 2. The collector-views file (control plane) The control plane copies the collector sub-DAG from the installed `dag` @@ -313,16 +323,20 @@ own serde: The collector loads the file once at start (a plan change is a collector restart, decision 14). The data plane takes the same file with -`--collector-views` and refuses it, at start and on each install, when its -`plan_id` differs from the installed plan's. The precompute engine then -compiles each refresh group without the collector sub-DAG's nodes (and -without a `Scan` only they read). The query engine is unchanged; it reads a collector view +`--collector-views`: its `outputs` and `commit_grace_ms` become the +precompute engine's collector-view option (the skip lives in the ingest +engine, not in the data plane), and the engine refuses the file, at start and +on each install, when its `plan_id` differs from the installed plan's. The +engine then compiles each refresh group without the collector sub-DAG's nodes +(and without a `Scan` only they read). The data plane reads neither +`planner_wire_version` (the collector checks it) nor `backend_reads_raw` (the +collector's raw forward uses it). The query engine is unchanged; it reads a collector view from the store like any other. ### 3. The collector: load, check, build, stamp At start, with `planner_views: ` in its processor config, the -`asap_sketches` processor: +`collector_views` processor: 1. **Loads** the file into the planner types. A `planner_wire_version` other than its pinned `asap-types` writes is a load error. @@ -337,8 +351,7 @@ At start, with `planner_views: ` in its processor config, the 3. **Reads each output's key** with `materialized_views()` on the sub-DAG and `view_state_key()`: the key depends only on the view node, so it equals the installed plan's. -4. **Builds** each view (v1: the executor through a thin driver; §7 for the - options): sketch and parameters from θ (an out-of-range +4. **Builds** each view on the embedded executor (§7): sketch and parameters from θ (an out-of-range value is a load error, never replaced by a default), window = `ViewWindow::Tumbling.width_ms`, matchers = `__name__ = metric` plus each `Scan`, `Filter` and chain-`filter` predicate, one state per series. A series is what it is for the @@ -353,14 +366,19 @@ At start, with `planner_views: ` in its processor config, the `MetricView::metadata` (empty today) and reads it back, and `window_merge` keys series by it. -With `planner_views` set, the per-sketch fields of the processor config -(`sketch_type`, `sketch_params`, `window_size`, `window_slide`, -`output_metric_name`, `agg_id`, `aggregate_by`, `omit_resource_attrs`, -`global_aggregation`, `emit_window_stats`, `transmit_sketch = false`) are a -config error: the file is the only source of truth. The pipeline YAML names -one `asap_sketches` node and does not change with the plan. +Lateness is tracked per run group, one group per (metric, window width), not +per view: a sample that a view's matchers exclude still moves its group's +watermark, and a sample of a window the group has closed is dropped and +counted. A value that one view's sketch refuses (for example a NaN, or a +value a DDSketch cannot index) is dropped for the whole group, so the views +of a group stay equal on the samples they fold. + +`asap_sketches` keeps serving hand-written configs only and does not take +`planner_views`; the file is the only source of truth for `collector_views`. +The pipeline YAML names one `collector_views` node and one `raw_forward` +node and does not change with the plan. -The collector's raw forward drops samples of every metric the file marks +The `raw_forward` processor drops samples of every metric the file marks `backend_reads_raw: false`, and forwards all others (including metrics the plan does not read). @@ -532,20 +550,31 @@ The ingest engine then, per view and record: 1. **View.** `plan_id` must be the installed plan's; otherwise rejected (`reason="other_plan"`). `node_id` must be a collector view of that plan whose `view_state_key()` equals the key and whose `Scan` metric and node - id give the Metric's name; otherwise rejected (`reason="unknown_view"`). -2. **Window.** `window_end_ms` must be a multiple of the key's width; - otherwise rejected (`reason="window"`). + id give the Metric's name; otherwise rejected (`reason="unknown_view"`, + or `reason="key_mismatch"` when the key differs from the node's, or + `reason="name"` when a series' `__name__` is not the view's `Scan` metric). +2. **Window.** `window_end_ms` must be a multiple of the key's width and + `window_start_ms` must be `window_end_ms − width`; otherwise rejected + (`reason="window"`). 3. **Series.** Interns the labels into the store's series table, as the raw path does, so the row's `$promql_series_identity` is the same canonical JSON a raw sample of that series gets. 4. **Decode.** Decodes the ASAPv1 bytes into the view's kernel; failure → - rejected (`reason="decode"`). + rejected (`reason="decode"`). A state that does not merge with the one + already staged is rejected (`reason="merge"`). 5. **Stage, dedup, merge, commit**, below. Every rejection increments `asap_collector_states_rejected_total{view, -reason}` and logs once per view and reason per minute; the request still +reason}` (a node id the plan has no collector view for is counted under +`view="unknown"`) and logs once per view and reason per minute; the request still returns 200 with the counts, as the raw OTLP route reports `rejected`. +**Request order.** `POST /v1/metrics` stages a request's states before it +ingests its samples. A request refused with 503 for either is retried whole; +its states are then duplicates and are ignored, so no sample is ingested +twice. States get 503 while the precompute backlog is full, as samples do +once the queues fill. + **Staging.** The view store appends a view's windows in order and each window once, so a collector view's window is committed once and whole. The engine stages states per `(view, window)` and commits through the precompute @@ -563,7 +592,9 @@ committer, the same path that commits a window it built (readers, States are full, not deltas, and each partial covers other samples. - **Commit time.** No raw samples of a collector view's metric need reach the backend, so the raw watermark cannot close its windows. A window commits - when the backend's wall clock passes `end + commit_grace_ms`, with + when the ingest engine's clock (the clock of the idle wall-clock close + feature; a manual clock in tests) passes `end + commit_grace_ms`. Collector + windows do not trigger that feature's idle flush. With `commit_grace_ms = window_close_delay_ms + export_interval_ms + clock_skew_allowance_ms` @@ -582,6 +613,12 @@ committer, the same path that commits a window it built (readers, A histogram of arrival delay (`end` to arrival) per view shows when the grace must grow. v1 has no late merge (decision 9). +A group of views that reads a collector view closes a window only behind +every group it reads; a view started by no metric starts with the collector +view, and one started earlier skips to the collector view's first window. +Windows skipped as past the view's retention are counted as `expired`, not +`late_dropped`. + **Envelope hash and implementation.** The envelope hash depends on which implementation produced the state: the executor shrinks sealed states, so an old-processor collector and an executor collector give different hashes, and @@ -599,8 +636,8 @@ builds is the state the backend would have built. **Options.** -- **A (v1): a thin collector-side driver over the executor's public APIs.** - The driver feeds each raw sample into the per-window run, closes a window +- **A (v1, implemented as the `collector_views` processor): a thin + collector-side driver over the executor's public APIs.** The driver feeds each raw sample into the per-window run, closes a window at its end, and encodes the resulting state as ASAPv1. It is small and needs nothing from the backend. - **C (next): the generic streaming driver moves into the executor as a @@ -648,7 +685,7 @@ use asap_types::plan::materialized_view::ViewStateKey; use asap_types::plan::PhysicalASAPNodeId; /// The collector states of one OTLP request: what the OTLP adapter hands -/// `PrecomputeEngine`. In `common` because the adapter depends only on +/// `InstalledPrecompute`. In `common` because the adapter depends only on /// `common` and must produce it. Nested as the OTAP tiers (Schema → /// Dictionary → Record). Never data between operators. #[derive(Debug, Clone, PartialEq, Default)] @@ -678,6 +715,8 @@ pub struct CollectorSeriesStates { /// One state in one window `(window_end_ms − width, window_end_ms]` (Record tier). #[derive(Debug, Clone, PartialEq)] pub struct ViewStateRecord { + /// A state whose start is not `window_end_ms − width` is rejected. + pub window_start_ms: i64, pub window_end_ms: i64, /// ASAPv1 bytes from `asap_sketchlib`: the full state. pub asapv1: Vec, @@ -692,19 +731,39 @@ pub struct CollectorStateIngestReport { pub duplicate: u64, pub merged: u64, pub late_dropped: u64, - /// By reason: `other_plan`, `unknown_view`, `window`, `decode`. + /// By reason: `other_plan`, `unknown_view`, `key_mismatch`, `name`, + /// `window`, `decode`, `merge`. pub rejected: BTreeMap<&'static str, u64>, } -impl PrecomputeEngine { - /// Checks, stages or merges each record; waits under backpressure as - /// `try_ingest` does. A method, not a trait: a trait is added with its - /// second implementation, and there is one. +impl InstalledPrecompute { + /// Checks, stages or merges each record; `Busy` (503) while the + /// precompute backlog is full. A method, not a trait: a trait is added + /// with its second implementation, and there is one. pub async fn ingest_collector_states(&self, batch: ViewStateBatch) -> Result; } ``` +```rust +/// The file the collector and the data plane load. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorViewsFile { + pub planner_wire_version: u32, + /// `PhysicalASAPDAG::plan_id()` of the installed plan. + pub plan_id: String, + pub commit_grace_ms: u64, + /// Per metric a `Scan` reads: whether a node off the collector, or a + /// query-time `Scan`, still reads its raw samples. + pub backend_reads_raw: BTreeMap, + /// The collector views: the cut nodes whose results the backend ingests. + pub outputs: Vec, + /// The collector sub-DAG; `roots = outputs`. + pub dag: PhysicalASAPDAG, +} +``` + `storage::ViewStore` is unchanged: every collector view window is written once, at commit. ### `crates/adapters/ingest/otlp` @@ -771,8 +830,8 @@ pub struct OperatorCapability { /// except `supported_summaries`, whose entries are `CollectorSummary`s. pub struct CollectorExecutor { pub supported_summaries: Vec, - #[serde(flatten)] - pub rest: DeploymentCapabilities, // its own `supported_summaries` stays `None` + pub rest: DeploymentCapabilities, // its own `supported_summaries` stays `None`; + // deserialized by hand, not `#[serde(flatten)]` } /// An entry of `executor.supported_summaries`: the planner's @@ -799,23 +858,6 @@ pub struct Placement { pub partitioned_by: PartitionedBy, } -/// The file the collector and the data plane load. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -#[serde(deny_unknown_fields)] -pub struct CollectorViewsFile { - pub planner_wire_version: u32, - /// `PhysicalASAPDAG::plan_id()` of the installed plan. - pub plan_id: String, - pub commit_grace_ms: u64, - /// Per metric a `Scan` reads: whether a node off the collector, or a - /// query-time `Scan`, still reads its raw samples. - pub backend_reads_raw: BTreeMap, - /// The collector views: the cut nodes whose results the backend ingests. - pub outputs: Vec, - /// The collector sub-DAG; `roots = outputs`. - pub dag: PhysicalASAPDAG, -} - /// Why a node is not on the collector, for the command's report. #[derive(Debug, Clone, PartialEq)] pub enum NotOnCollector { @@ -827,19 +869,26 @@ pub enum NotOnCollector { OutputNotAView, } -/// The installed plan's collector sub-DAG and why each other node is not on it. +/// The collector pipeline's export interval and the clock-skew allowance, +/// the two terms of `commit_grace_ms` that the collector's capabilities do +/// not give. Default 0 and 2 000. +pub struct CommitGrace { pub export_interval_ms: u64, pub clock_skew_allowance_ms: u64 } + +/// The installed plan's collector sub-DAG and why each other node is not on +/// it. An error when the plan's views do not derive or the cut does not +/// stand as a DAG. pub fn collector_sub_dag( plan: &InstallablePlan, capabilities: &CollectorCapabilities, - export_interval_ms: u64, -) -> (CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>); + grace: CommitGrace, +) -> Result<(CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>), InstallablePlanError>; ``` `DeploymentCapabilities`, `SupportedSummary`, `OperatorKind` and `CompareOpKind` are the planner's types, unchanged. CLI: `control_plane --plan --collector-capabilities [--collector-export-interval-ms ] ---emit-collector-views `; the data plane takes +[--collector-clock-skew-allowance-ms ] --emit-collector-views `; the data plane takes `--collector-views `. ## Worked example: q01 @@ -994,7 +1043,7 @@ Pins (all three repositories): Backend: 2. This document. -3. `ViewStateBatch` in `common`, `PrecomputeEngine::ingest_collector_states` and `CollectorStateIngestReport` in `precompute`; the +3. `ViewStateBatch` in `common`, `InstalledPrecompute::ingest_collector_states` and `CollectorStateIngestReport` in `precompute`; the `otlp` adapter's Record branch and the resource-attribute convention in its label function (raw path included); lookup by `(plan_id, node_id)` and key check, staging, the hash set, merge before commit, commit at @@ -1195,6 +1244,12 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad merged by a backend `SummaryMerge`; v1 keeps it, and every node above it, in the backend. +27. **Label-input sketches state their weight.** For `input: "label"`, the + capabilities entry must state the weight semantics (count, or the + per-key sum of the sample value). Until it does, the collector view rule + requires weight 1 (count) for a label-input sketch. Today's collector + loader refuses label-input sketches anyway, so no current cut changes. + ## Open questions None open. From 3f361a1588b261b642845b07a4fbcbd57854d376 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 00:23:33 +0000 Subject: [PATCH 13/21] docs(design): collector windows commit on arrival; later states merge within retention A request's states commit their windows when it ends, with no commit grace; states that come later for a committed window merge into it within the view's retention, through the raw path's late merge, and are dropped and counted beyond it. The hash set per (view, series, window) is kept while the window is within retention, so a resent state merges nothing twice. The commit grace, its file field and its CLI flags go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 113 +++++++++++-------------- 1 file changed, 51 insertions(+), 62 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 6656c261e..f5fd4c644 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -106,11 +106,11 @@ Scope: |---|---|---| | Capabilities | ASAPCollector-public (`asap_sketches --print-capabilities`) | Declares, in the planner's vocabulary, what the collector can run and how series are placed on its instances (§1) | | Collector view rule | `crates/control-plane` | Assigns nodes of the installed plan to the collector bottom-up against the capabilities and cuts the collector sub-DAG; the only copy of the rule | -| Collector-views file | `CollectorViewsFile` in `crates/common` (the data plane reads it); written by `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw, the commit grace | +| Collector-views file | `CollectorViewsFile` in `crates/common` (the data plane reads it); written by `crates/control-plane` (`--emit-collector-views`) | The collector sub-DAG, its outputs, the plan id, which metrics the backend still reads raw | | `collector_views` processor | ASAPCollector-public | Config `planner_views: `. Loads the file at start, runs the sub-DAG on the embedded executor (v1: each leaf view's per-series states), writes the view identity into metric metadata (`asap.plan_id`, `asap.node_id`, `asap.view_state_key`), exports summary points with `sketch.envelope` | | `raw_forward` processor | ASAPCollector-public | Config `planner_views: `. Forwards raw samples to the backend, except metrics the file marks `backend_reads_raw: false` | | OTLP adapter | `crates/adapters/ingest/otlp` | Decodes Schema and Dictionary as for raw samples; a point with `sketch.envelope` becomes a `common::ViewStateBatch` record; never reads the sketch bytes | -| Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges until commit, drops late states. The precompute skip of collector views is an engine option (`PrecomputeOptions::collector`), set from the file by the data plane's `--collector-views` | +| Collector-state ingest | `crates/precompute` | Finds the view by `(plan_id, node_id)`, checks the key, stages, deduplicates and merges a request's states, commits their windows when the request ends, and merges later states into committed windows within retention (beyond it, drops them). The precompute skip of collector views is an engine option (`PrecomputeOptions::collector`), set from the file by the data plane's `--collector-views` | **Raw path.** The raw path stays (decision 3) for every metric the backend still reads raw: a metric is marked `backend_reads_raw: true` when a `Scan` @@ -215,6 +215,8 @@ lists operator kinds and the limits that belong to one operator. reach one instance. - `window_close_delay_ms`: the longest time after a window's end before the collector emits it: the 5 s idle-close grace plus the 1 s timer period. + The backend commits a window when its states arrive (§6), so it does not + wait this long; the field stays the collector's declaration. The control plane reads the file with `--collector-capabilities ` and refuses a `capabilities_version` it does not know. It assigns nodes of @@ -309,7 +311,6 @@ own serde: ```json {"planner_wire_version": 16, "plan_id": "", - "commit_grace_ms": 8000, "backend_reads_raw": {"data": true, "data_total": true}, "outputs": [, ...], "dag": } @@ -319,11 +320,10 @@ own serde: to be a chain at the root: the backend ingests exactly these nodes' results, and nothing else in `dag` leaves the collector. - `backend_reads_raw` lists every metric a `Scan` of the plan reads. -- `commit_grace_ms` is computed as in §6. The collector loads the file once at start (a plan change is a collector restart, decision 14). The data plane takes the same file with -`--collector-views`: its `outputs` and `commit_grace_ms` become the +`--collector-views`: its `outputs` become the precompute engine's collector-view option (the skip lives in the ingest engine, not in the data plane), and the engine refuses the file, at start and on each install, when its `plan_id` differs from the installed plan's. The @@ -575,49 +575,45 @@ its states are then duplicates and are ignored, so no sample is ingested twice. States get 503 while the precompute backlog is full, as samples do once the queues fill. -**Staging.** The view store appends a view's windows in order and each -window once, so a collector view's window is committed once and whole. The engine -stages states per `(view, window)` and commits through the precompute -committer, the same path that commits a window it built (readers, -`RefreshTaskGraph` ordering, persistence and the memory budget all apply). - -- **Duplicates.** Until commit, the engine keeps the set of 64-bit envelope - hashes seen per `(view, series, window)`. A state whose hash is in the set - is ignored and counted (`duplicate`). A set, not the last hash, so that a - retry of one partial state after another partial was merged is still - caught. +**Staging and commit.** The engine stages a request's states per +`(view, window)` and, when the request ends, commits each window they +touch through the precompute committer, the same path that commits a +window it built (readers, `RefreshTaskGraph` ordering, persistence and the +memory budget all apply). The request is answered once those windows are +committed, so a window is queryable as soon as its first states arrive: +no commit grace (states arrive within a second of the window's end). + +- **Duplicates.** While a window is within its view's retention, committed + or not, the engine keeps the set of 64-bit envelope hashes seen per + `(view, series, window)`. A state whose hash is in the set is ignored and + counted (`duplicate`). A set, not the last hash, so that a retry of one + partial state after another partial was merged is still caught, and a + request sent twice merges nothing twice. - **Second states.** A state with a new hash for a `(view, series, window)` is merged into the staged one (sketch merge): a collector that restarted inside a window, or two collectors that each saw part of one series. States are full, not deltas, and each partial covers other samples. -- **Commit time.** No raw samples of a collector view's metric need reach the - backend, so the raw watermark cannot close its windows. A window commits - when the ingest engine's clock (the clock of the idle wall-clock close - feature; a manual clock in tests) passes `end + commit_grace_ms`. Collector - windows do not trigger that feature's idle flush. With - - `commit_grace_ms = window_close_delay_ms + export_interval_ms + clock_skew_allowance_ms` - - from the capabilities (6 s today), the collector pipeline's export - interval (`--collector-export-interval-ms`, default 0: today's pipelines - export each processor message at once), and an allowance for clock skew - (default 2 s). Default: 8 s. The control plane writes it into the file; - each collector view's retention must exceed it. -- **No states.** A window with no staged state at commit time is not - stored; a query that reads it gets `NotReady` and is forwarded to the - fallback (decision 20). -- **Late states.** A state that arrives after its window committed is - dropped and counted (`late_dropped`), whatever its reason: an export - slower than the grace, or a collector clock behind the backend's by more - than the allowance. The window then answers without that series' state. - A histogram of arrival delay (`end` to arrival) per view shows when the - grace must grow. v1 has no late merge (decision 9). +- **Later states of a committed window.** States that arrive in a later + request for a committed window (another series, another collector, or a + second partial of a series) take the late merge path of raw samples + (`docs/design/repo-layout.md`, Ingestion rules): within the view's + retention they are merged into the committed window, which is replaced + in the view store and in its file, the change is merged into the windows + of the groups reading the view, and cached query results that read it + become stale (`late_merged`). The window so converges to the state one + request with every state would give. +- **No states.** A window with no state is not stored; a query that reads + it gets `NotReady` and is forwarded to the fallback (decision 20). +- **Order.** A view's windows commit in window order. A window that gets + its first states after a later window of its view was committed is + behind the view's committed windows and is not stored: its states are + dropped and counted (`late_dropped`), as are states of a window past + the view's retention. A histogram of arrival delay (`end` to arrival) + per view shows how late states come. A group of views that reads a collector view closes a window only behind every group it reads; a view started by no metric starts with the collector view, and one started earlier skips to the collector view's first window. -Windows skipped as past the view's retention are counted as `expired`, not -`late_dropped`. **Envelope hash and implementation.** The envelope hash depends on which implementation produced the state: the executor shrinks sealed states, so an @@ -730,6 +726,7 @@ pub struct CollectorStateIngestReport { pub staged: u64, pub duplicate: u64, pub merged: u64, + pub late_merged: u64, pub late_dropped: u64, /// By reason: `other_plan`, `unknown_view`, `key_mismatch`, `name`, /// `window`, `decode`, `merge`. @@ -753,7 +750,6 @@ pub struct CollectorViewsFile { pub planner_wire_version: u32, /// `PhysicalASAPDAG::plan_id()` of the installed plan. pub plan_id: String, - pub commit_grace_ms: u64, /// Per metric a `Scan` reads: whether a node off the collector, or a /// query-time `Scan`, still reads its raw samples. pub backend_reads_raw: BTreeMap, @@ -869,26 +865,19 @@ pub enum NotOnCollector { OutputNotAView, } -/// The collector pipeline's export interval and the clock-skew allowance, -/// the two terms of `commit_grace_ms` that the collector's capabilities do -/// not give. Default 0 and 2 000. -pub struct CommitGrace { pub export_interval_ms: u64, pub clock_skew_allowance_ms: u64 } - /// The installed plan's collector sub-DAG and why each other node is not on /// it. An error when the plan's views do not derive or the cut does not /// stand as a DAG. pub fn collector_sub_dag( plan: &InstallablePlan, capabilities: &CollectorCapabilities, - grace: CommitGrace, ) -> Result<(CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>), InstallablePlanError>; ``` `DeploymentCapabilities`, `SupportedSummary`, `OperatorKind` and `CompareOpKind` are the planner's types, unchanged. CLI: `control_plane --plan --collector-capabilities - [--collector-export-interval-ms ] -[--collector-clock-skew-allowance-ms ] --emit-collector-views `; the data plane takes + --emit-collector-views `; the data plane takes `--collector-views `. ## Worked example: q01 @@ -914,7 +903,7 @@ too and `data` stays raw. The sub-DAG in `collector-views.json` (schemas shortened to their field names; the file carries them in full): ```json -{"planner_wire_version": 16, "plan_id": "…", "commit_grace_ms": 8000, +{"planner_wire_version": 16, "plan_id": "…", "backend_reads_raw": {"data": true, "data_total": true}, "outputs": [1], "dag": { @@ -1046,8 +1035,8 @@ Backend: 3. `ViewStateBatch` in `common`, `InstalledPrecompute::ingest_collector_states` and `CollectorStateIngestReport` in `precompute`; the `otlp` adapter's Record branch and the resource-attribute convention in its label function (raw path included); lookup by `(plan_id, node_id)` - and key check, staging, the hash set, merge before commit, commit at - grace, late drop. Test data: real ASAPv1 records the collector emits + and key check, staging, the hash set, merge before commit, commit on + arrival, late merge within retention. Test data: real ASAPv1 records the collector emits (captured OTLP bodies, checked in with the collector commit that wrote them), for each of the six sketch types, including two views over one metric, one key that differs from the node's (other θ), one state of @@ -1056,7 +1045,7 @@ Backend: 4. The control plane's bottom-up rule with `--collector-capabilities` (the four conditions, the cut, the view check on outputs), `--emit-collector-views` (sub-DAG, `outputs`, `plan_id`, - `backend_reads_raw`, `commit_grace_ms`); the data plane's + `backend_reads_raw`); the data plane's `--collector-views` with the plan-id check; precompute skips the collector sub-DAG. Tests: the benchmark plan gives exactly `outputs = [n1]` and marks both metrics raw; a q01-only plan marks `data` `false`; a @@ -1104,10 +1093,7 @@ Collector (ASAPCollector-public): executor as a public API, so the collector and the backend share it. **Future work.** Partial aggregation (collector partial states of a -non-local mergeable aggregate, merged by a backend `SummaryMerge`). Late merge into a committed window (a store `replace`, a -view-file rewrite and result-cache invalidation), only if step 5 or -production shows a late rate worth it, measured by `late_dropped` and the -arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow adapter. +non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based choice of collector views. The OTAP Arrow adapter. ## Decisions @@ -1141,8 +1127,9 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad 8. **The collector declares its capabilities** (`--print-capabilities`); the control plane's rule reads them. The rule exists once, in the control plane; the collector checks only that it can execute the sub-DAG. -9. **No late merge in v1.** A state after commit is dropped and counted. - The store's put-once contract is unchanged. +9. **Late merge within retention.** A state after its window committed is + merged into it while the window is within its view's retention, as a + late raw sample is; beyond it, it is dropped and counted. 10. **Raw forwarding follows the readers.** The file lists, per metric, whether the backend still reads it raw; the collector drops raw samples to the backend for metrics marked `false`. @@ -1202,9 +1189,11 @@ arrival-delay histogram. Cost-based choice of collector views. The OTAP Arrow ad down, or that no series had samples. Do not store it; queries over it are `NotReady` and forwarded to the fallback, which is correct in both cases. Revisit if idle views forward often. -21. **Clock-skew allowance.** 2 s by default (hosts run NTP, which keeps - them within milliseconds); raise it if the arrival-delay histogram or - `late_dropped` shows skew. +21. **Commit on arrival.** A window commits when the request carrying its + first states ends, not after a grace (6 s close delay plus 2 s skew + allowance cost every window about 6 s of freshness, while states + arrive within half a second of the window's end); later states merge + in (decision 9). 22. **One label function for both paths**, with Prometheus's convention for resource attributes: not copied into labels; `service.name` (with `service.namespace/`) → `job`, `service.instance.id` → `instance`; an From 7200ffd7f6f2cf7d5567f3a9176e7c6b41425ae0 Mon Sep 17 00:00:00 2001 From: zzylol Date: Sun, 29 Nov 2026 17:18:49 +0000 Subject: [PATCH 14/21] docs(design): a collector window whose first states come late is stored behind the newest Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index f5fd4c644..2f578475c 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -604,12 +604,14 @@ no commit grace (states arrive within a second of the window's end). request with every state would give. - **No states.** A window with no state is not stored; a query that reads it gets `NotReady` and is forwarded to the fallback (decision 20). -- **Order.** A view's windows commit in window order. A window that gets - its first states after a later window of its view was committed is - behind the view's committed windows and is not stored: its states are - dropped and counted (`late_dropped`), as are states of a window past - the view's retention. A histogram of arrival delay (`end` to arrival) - per view shows how late states come. +- **Order.** A window that gets its first states after a later window of + its view was committed (a collector lagging more than a window behind + another) is stored behind the newest, within the view's retention, and + the windows of the groups reading the view that cover it are computed + again from the views as they then stand (`late_merged`). States of a + window past the view's retention are dropped and counted + (`late_dropped`). A histogram of arrival delay (`end` to arrival) per + view shows how late states come. A group of views that reads a collector view closes a window only behind every group it reads; a view started by no metric starts with the collector From 674a05599b96e06b9f29d43b7ca38124115565a2 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 01:57:00 +0000 Subject: [PATCH 15/21] docs(design): collector corrections for late samples; order-sensitive views stay in the backend Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 2f578475c..69bddcb94 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -239,6 +239,12 @@ assigned if and only if all of these hold: `{"labels": L}`, `L ⊆ G`; with `"series"`, never. A non-local but mergeable aggregate is future work (partial aggregation: the collector sends a partial state, a backend `SummaryMerge` combines them). +5. **Not order-sensitive.** Its states do not depend on the order of their + samples. A counter's state (`rate`, `increase`) or an instant rate's + (`irate`) stays in the backend whatever the capabilities declare: the + backend computes such a window again from raw samples when a late one + comes, which a collector state cannot give. Its metric is read raw + (`backend_reads_raw: true`). The assigned nodes form the maximal collector sub-DAG. Each cut edge's producer is an output: a `Scan` output is the raw path (its metric is @@ -593,6 +599,13 @@ no commit grace (states arrive within a second of the window's end). is merged into the staged one (sketch merge): a collector that restarted inside a window, or two collectors that each saw part of one series. States are full, not deltas, and each partial covers other samples. +- **Corrections.** A collector that gets late samples of a window it + already emitted sends, while the window is within the view's retention, + a correction: a state built from the late samples alone, on the same + view metric, series and window (the wire format is unchanged). Its bytes + differ from the states already seen, so it is not a duplicate: it merges + into the window through the later-states path below, and the window + ends as if every sample had come on time. - **Later states of a committed window.** States that arrive in a later request for a committed window (another series, another collector, or a second partial of a series) take the late merge path of raw samples From 027e2a0ba22fe993dc62ee84e0c940f4db6624a1 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 02:30:27 +0000 Subject: [PATCH 16/21] docs(design): a collector window with no state is stored empty Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 69bddcb94..5519521dd 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -615,8 +615,10 @@ no commit grace (states arrive within a second of the window's end). of the groups reading the view, and cached query results that read it become stale (`late_merged`). The window so converges to the state one request with every state would give. -- **No states.** A window with no state is not stored; a query that reads - it gets `NotReady` and is forwarded to the fallback (decision 20). +- **No states.** A window that closes with no state (a feed gap) is stored + empty, as ASAPQuery-backend stores an idle window it builds itself, so a + query over the gap answers from the samples there were; states or + corrections coming later merge into it (decision 20). - **Order.** A window that gets its first states after a later window of its view was committed (a collector lagging more than a window behind another) is stored behind the newest, within the view's retention, and @@ -1201,9 +1203,11 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c node that builds every view in the file, keyed by (view, series); the pipeline YAML never changes with the plan. 20. **A window with no state at commit time.** It may mean the collector was - down, or that no series had samples. Do not store it; queries over it - are `NotReady` and forwarded to the fallback, which is correct in both - cases. Revisit if idle views forward often. + down, or that no series had samples. Store it empty, as a window built + from no samples is, so queries over it answer as the backend-only path + does; if the collector was down and later sends the window's states, + they merge in as late states. (Not storing it made every range over a + feed gap unanswerable.) 21. **Commit on arrival.** A window commits when the request carrying its first states ends, not after a grace (6 s close delay plus 2 s skew allowance cost every window about 6 s of freshness, while states From 29025e1a96c185bde5ad38de953466fef8e4b501 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 03:52:31 +0000 Subject: [PATCH 17/21] docs(design): a stopped collector's windows close on the monotonic clock Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 5519521dd..074ee8d0a 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -615,7 +615,15 @@ no commit grace (states arrive within a second of the window's end). of the groups reading the view, and cached query results that read it become stale (`late_merged`). The window so converges to the state one request with every state would give. -- **No states.** A window that closes with no state (a feed gap) is stored +- **Idle close.** While no state arrives, a view's windows also close on + the engine's monotonic clock, as decision 5 of the repo layout closes an + idle raw stream's: once the newest state's window end, plus the time + since it arrived, passes a window's end by the collector's + `window_close_delay_ms` and a skew allowance (6 s + 2 s today). So a + stopped collector's windows close too. Nothing closes this way before a + view's first states. +- **No states.** A window that closes with no state (a feed gap, or a + stopped collector) is stored empty, as ASAPQuery-backend stores an idle window it builds itself, so a query over the gap answers from the samples there were; states or corrections coming later merge into it (decision 20). From 2ad8cd5cc80ff3093991d79b3df8580d1c1221ed Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:28:17 +0000 Subject: [PATCH 18/21] docs(design): sequence numbers and delta transmission for collector views Maps ASAPCollector's transmission protocol onto collector views (new section 8): each record carries its producer epoch (Schema metadata) and its sequence, kind and base (Record attributes). A window's lineage starts with a full; later emissions (open-window emissions, the close after them, corrections) are deltas, the state of the samples since the base, merged by the view's kernel: bucket-count increments for DDSketch, a mergeable partial sketch for KLL. The backend applies a delta only on its exact base and marks the window incomplete on a gap, an unknown base or a new epoch without its full; queries reading it are forwarded. Resynchronization is a full at every window and every collector restart. The duplicate check reads (epoch, sequence) instead of envelope hashes, so two corrections with equal bytes are both applied. The collector-views file carries the collector's window_close_delay_ms, which the backend's idle close uses instead of a fixed 8 s. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 277 ++++++++++++++++++++++--- 1 file changed, 244 insertions(+), 33 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 074ee8d0a..2c7b2dce2 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -216,7 +216,9 @@ lists operator kinds and the limits that belong to one operator. - `window_close_delay_ms`: the longest time after a window's end before the collector emits it: the 5 s idle-close grace plus the 1 s timer period. The backend commits a window when its states arrive (§6), so it does not - wait this long; the field stays the collector's declaration. + wait this long to commit; it uses the delay, which the control plane + copies into the collector-views file, to close a stopped collector's + windows on its clock (§6, Idle close). The control plane reads the file with `--collector-capabilities ` and refuses a `capabilities_version` it does not know. It assigns nodes of @@ -318,6 +320,7 @@ own serde: {"planner_wire_version": 16, "plan_id": "", "backend_reads_raw": {"data": true, "data_total": true}, + "window_close_delay_ms": 6000, "outputs": [, ...], "dag": } ``` @@ -326,6 +329,10 @@ own serde: to be a chain at the root: the backend ingests exactly these nodes' results, and nothing else in `dag` leaves the collector. - `backend_reads_raw` lists every metric a `Scan` of the plan reads. +- `window_close_delay_ms` is the capabilities' value, copied unchanged. + The data plane closes a stopped collector's windows on its clock after + it plus a skew allowance (§6, Idle close); the collector accepts the + field and ignores it. The collector loads the file once at start (a plan change is a collector restart, decision 14). The data plane takes the same file with @@ -407,16 +414,17 @@ structure of raw samples; only the Record content differs: | Tier | Raw samples | Collector view states | `ViewStateBatch` | Backend handling | |---|---|---|---|---| -| Schema (per metric) | `Metric`: name, type, unit | the source metric's unit and description; name `.asap_view.`, type Summary; `metadata`: `asap.plan_id`, `asap.node_id`, `asap.view_state_key` | `views[]`: `plan_id`, `node_id`, `key` | Find the view, check the key and name | +| Schema (per metric) | `Metric`: name, type, unit | the source metric's unit and description; name `.asap_view.`, type Summary; `metadata`: `asap.plan_id`, `asap.node_id`, `asap.view_state_key`, `asap.producer_epoch` | `views[]`: `plan_id`, `node_id`, `key`, `producer_epoch` | Find the view, check the key and name | | Dictionary (per series) | Resource + Scope + point attributes → labels | identical: the source samples' Resource, Scope and point attributes, as received | `views[].series[].labels` | The raw path's label function; interned as the raw path interns | -| Record (per point) | `time_unix_nano` + value | window `(start_time_unix_nano, time_unix_nano]`; point attribute `sketch.envelope` (ASAPv1 bytes); `count` (samples) | `series[].records[]`: `window_end_ms`, `asapv1`, `sample_count` | Stage, dedup, merge, commit (§6) | +| Record (per point) | `time_unix_nano` + value | window `(start_time_unix_nano, time_unix_nano]`; point attributes `sketch.envelope` (ASAPv1 bytes), `asap.sequence`, `asap.state_kind`, `asap.base_sequence` (deltas only); `count` (samples) | `series[].records[]`: `window_end_ms`, `asapv1`, `sample_count`, `sequence`, `kind` | Stage, apply by lineage, merge, commit (§6, §8) | **Which view.** A record belongs to its Metric entry, whose metadata carries the view identity, so every record names its view through its metric, with no per-record identity attribute. Two views over one source metric (DDSketch α 0.05 and KLL, or two window widths) are two Metric -entries. `sketch.envelope` is the only attribute a state adds to its -point. +entries. A state adds to its point `sketch.envelope` and its place in its +lineage (`asap.sequence`, `asap.state_kind`, `asap.base_sequence`, §8); +none of them is a label. **Metric metadata survives the path.** OTLP `Metric.metadata` is `repeated KeyValue metadata = 12` in the protobuf both sides build @@ -474,6 +482,7 @@ erDiagram node_id PhysicalASAPNodeId "the output node (collector view)" key ViewStateKey "definition_id, window, logical_properties" name string "metric.asap_view.node_id" + producer_epoch u64 "asap.producer_epoch (section 8)" } KEY{ labels LabelSet "key columns of output_schema; per-series view: series labels, __name__ = Scan metric" @@ -482,6 +491,8 @@ erDiagram window_end_ms i64 "inclusive; start = end - width" asapv1 bytes "sketch.envelope: the full state (or an exact value)" sample_count u64 "count" + sequence u64 "asap.sequence; 0 for a full (section 8)" + kind StateKind "asap.state_kind, asap.base_sequence" } ``` @@ -590,22 +601,22 @@ committed, so a window is queryable as soon as its first states arrive: no commit grace (states arrive within a second of the window's end). - **Duplicates.** While a window is within its view's retention, committed - or not, the engine keeps the set of 64-bit envelope hashes seen per - `(view, series, window)`. A state whose hash is in the set is ignored and - counted (`duplicate`). A set, not the last hash, so that a retry of one - partial state after another partial was merged is still caught, and a - request sent twice merges nothing twice. -- **Second states.** A state with a new hash for a `(view, series, window)` + or not, the engine keeps, per `(view, series, window)`, each lineage's + producer epoch and last applied sequence (§8). A record whose + `(epoch, sequence)` was already applied is ignored and counted + (`duplicate`), so a request sent twice merges nothing twice. Two records + with equal bytes but different sequences are two records. +- **Second states.** A full of a new epoch for a `(view, series, window)` is merged into the staged one (sketch merge): a collector that restarted inside a window, or two collectors that each saw part of one series. - States are full, not deltas, and each partial covers other samples. + Each lineage covers other samples. A delta is merged only onto its base + (§8). - **Corrections.** A collector that gets late samples of a window it already emitted sends, while the window is within the view's retention, - a correction: a state built from the late samples alone, on the same - view metric, series and window (the wire format is unchanged). Its bytes - differ from the states already seen, so it is not a duplicate: it merges - into the window through the later-states path below, and the window - ends as if every sample had come on time. + a correction: a delta built from the late samples alone, on the same + view metric, series and window, with the lineage's next sequence (§8). + It merges into the window through the later-states path below, and the + window ends as if every sample had come on time. - **Later states of a committed window.** States that arrive in a later request for a committed window (another series, another collector, or a second partial of a series) take the late merge path of raw samples @@ -619,8 +630,9 @@ no commit grace (states arrive within a second of the window's end). the engine's monotonic clock, as decision 5 of the repo layout closes an idle raw stream's: once the newest state's window end, plus the time since it arrived, passes a window's end by the collector's - `window_close_delay_ms` and a skew allowance (6 s + 2 s today). So a - stopped collector's windows close too. Nothing closes this way before a + `window_close_delay_ms` from the collector-views file and a 2 s skew + allowance (6 s + 2 s with today's collector). So a stopped collector's + windows close too. Nothing closes this way before a view's first states. - **No states.** A window that closes with no state (a feed gap, or a stopped collector) is stored @@ -640,12 +652,11 @@ A group of views that reads a collector view closes a window only behind every group it reads; a view started by no metric starts with the collector view, and one started earlier skips to the collector view's first window. -**Envelope hash and implementation.** The envelope hash depends on which -implementation produced the state: the executor shrinks sealed states, so an -old-processor collector and an executor collector give different hashes, and -therefore different bytes, for equal states. In a mixed rollout the -duplicate check does not recognise such a pair as a duplicate, and the -second state takes the merge path, which handles it. +**Duplicates do not depend on bytes.** The duplicate check reads the +record's `(epoch, sequence)`, not its bytes: the executor shrinks sealed +states, so two implementations give different bytes for equal states, and +two different corrections can have equal bytes (two late samples of equal +value). Neither changes what is applied. ### 7. The collector runs `asap-executor` @@ -697,6 +708,146 @@ is its measure-first part. Partial aggregation (a non-local mergeable aggregate as collector partial state plus a backend `SummaryMerge`) is future work on top of it. +### 8. Delta transmission and sequence + +ASAPCollector's transmission protocol +(`docs/design_docs/asapcollector/collector-transmission-protocol.md` in +ASAPCollector) defines full and delta summaries, the sender and receiver +state they need, and what happens when a delta's base is missing. This +section maps it onto collector views. + +**Lineage.** A lineage is the sequence of records one collector instance +sends for one `(view, series, window)`. The instance is named by its +**producer epoch**, a random 64-bit number drawn when the collector starts; +a restarted collector has a new epoch and new lineages. Within a lineage +the records are numbered 0, 1, 2, …: record 0 is a **full** (the state of +the samples the instance had folded into that window when it sent it) and +every later record is a **delta** on the record before it. + +| Reference tier | Required information | Collector views | +|---|---|---| +| Schema | aggregation kind, parameters, encoding, policy | `asap.plan_id`, `asap.node_id`, `asap.view_state_key` (§4), and `asap.producer_epoch` (decimal text): one epoch per collector instance, so per view metric | +| Dictionary | series | the received Resource, Scope and point attributes (§4) | +| Record | window, full/delta, payload, producer/epoch, sequence, base for deltas | window times, `sketch.envelope`, `count`, and point attributes `asap.sequence` (int), `asap.state_kind` (`"full"` or `"delta"`), `asap.base_sequence` (int, deltas only) | + +A full has sequence 0 and no base; a delta has sequence `n ≥ 1` and base +`n − 1`. A record without the three attributes, or with a kind that does +not match its sequence and base, is refused with the request (400), as a +record without `sketch.envelope` is. + +**Example.** The collector, epoch `9241…`, emits the window `(0 s, 5 s]` of +series `{job="a"}` of view 1 three times: + +| Record | Kind | Sequence | Base | Payload | +|---|---|---|---|---| +| open-window emission at 2 s | full | 0 | – | state of the samples in `(0 s, 2 s]` | +| emission at close, 5 s | delta | 1 | 0 | state of the samples in `(2 s, 5 s]` | +| correction, 7 s (late sample at 4.5 s) | delta | 2 | 1 | state of that sample | + +**What a delta holds.** A delta is the state of the samples the lineage +folded since its previous record, in the view's own ASAPv1 encoding, and +the receiver applies it with the view kernel's merge. The collector keeps +no closed window's state to diff against: each emission seals the window's +current run, and the next sample starts a new one. + +- **DDSketch.** A DDSketch of the new samples is exactly their bucket-count + increments (the zero count included), and DDSketch merge adds bucket + counts. A full plus its deltas is therefore the DDSketch of all the + window's samples, byte-equal once encoded. +- **KLL.** The reference protocol sends KLL as full states in its MVP, + because KLL has no compact, order-independent diff. Collector views use + the other correct option: a KLL delta is a KLL sketch of the new samples + alone, and the receiver merges it. KLL is fully mergeable: the merge of + sketches of disjoint sample sets is a sketch of their union with the same + rank-error bound, whatever the order and shape of the merges. A full plus + its deltas is therefore not byte-equal to the KLL the collector would + have sent at close, but its quantiles are within the view's bound. The + alternative, a full KLL replacing the lineage at each emission, would + make the collector keep every closed window's KLL for the view's + retention (to resend it with a correction), and the backend keep each + lineage's state apart from the others of its series and window (to + replace one lineage when a series' window has states from several + epochs). Both cost memory on both sides for no accuracy gain, and the + receiver would need a second apply rule. + +**When the collector emits.** + +- **At close** (the default, as today): a window's first emission is at + its close, a full with sequence 0. With no late samples, every lineage is + that one full: the on-time records are today's, plus the three + attributes and the epoch. +- **Open windows** (collector option `open_window_emit_interval_ms`, off by + default): every interval, the collector also emits each open window that + folded samples since its last emission. A window's first emission is a + full, the later ones and the one at close are deltas. The backend commits + the window on the first record (§6), so a query sees the window's samples + up to the last emission; the final answer equals the one emission at + close would give (byte-equal for DDSketch, within the bound for KLL). +- **Corrections**: a late sample of a window still within retention is a + delta of that window's lineage, with its next sequence. The collector + keeps each window's next sequence per series while the window is within + the view's retention. + +**Receiver rules.** The backend keeps, per `(view, series, window)` while +the window is within retention, each lineage's epoch and last applied +sequence (12 bytes per lineage; the states themselves are only the window's +merged ones). For a record of epoch `e` and sequence `n`: + +| Record | Lineage `e` | Outcome | +|---|---|---| +| full, `n = 0` | none | a new lineage; merged into the window (staged, or the late merge path once committed) | +| any | last applied ≥ `n` | duplicate: ignored and counted (`duplicate`) | +| delta, base `n − 1` | last applied = `n − 1` | applied: merged into the window | +| delta | none (unknown base, a new epoch without its full, or a backend restart) | **incomplete** | +| delta | last applied < `n − 1` (a gap) | **incomplete** | + +A delta is never merged onto a plausible base of another epoch or sequence. +Records of one lineage are sent in order, one request at a time; one that +arrives before its base is a gap. + +**Incomplete windows.** A `(view, series, window)` whose lineage broke +makes the view's window **incomplete**: the backend marks it, and the +windows built from it (the windows of the groups reading the view that +cover it), in the view store. A query run reading an incomplete window +fails as one reading a window not stored (`NotReady`), so the dispatcher +forwards the query to the fallback store and no plausible result is +returned from the plan. Cached results that read the window become stale. +The mark stays until the window leaves the view's retention; records of +the window are still applied, but do not clear it. Each record that breaks +a lineage is counted (`incomplete`). + +**Resynchronization.** The reference protocol resynchronizes a broken +lineage with a full checkpoint. Collector views have no channel from the +backend back to the processor: `collector_views` acknowledges its input +upstream when it receives it and never sees the exporter's reply, and the +OTLP reply's partial success is not delivered to processors. So the +collector sends a full checkpoint at these points, and no other: + +1. **Every window.** Each window's lineage starts with a full, so a lost + record breaks at most one `(view, series, window)`; the next window is + complete again. +2. **Every restart.** A restarted collector has a new epoch, and its first + record of every window it emits is a full. Its lineages are new ones: + they merge with those of the previous epoch (each covers other samples), + and a delta of the new epoch whose full was lost is incomplete, never + applied to the previous epoch's state. + +A broken lineage is not repaired: the samples of the lost record are not +anywhere the backend can read. The window stays incomplete and its queries +are forwarded until it leaves retention. A feedback channel (the backend +asks for a full and the collector resends the window's whole state) would +need the collector to keep each window's state for the view's retention; +it is future work, as is a backend restart that keeps the marks (today a +restarted backend reads persisted windows back complete; deltas after the +restart have no known base and mark their windows incomplete again). + +**Composition with the other paths.** A full of a window the idle clock +closed empty (§6, No states) is a new lineage and merges in through the +late merge path; a delta for it has no known base and is incomplete. A +window stored behind the newest (§6, Order) keeps its lineages like any +other. States past retention are dropped (`late_dropped`) before any +lineage rule. + ## Code interface ### `crates/common` @@ -721,6 +872,8 @@ pub struct CollectorViewStates { pub plan_id: String, pub node_id: PhysicalASAPNodeId, pub key: ViewStateKey, + /// `asap.producer_epoch`: the collector instance that sent the states (§8). + pub producer_epoch: u64, pub series: Vec, } @@ -739,10 +892,24 @@ pub struct ViewStateRecord { /// A state whose start is not `window_end_ms − width` is rejected. pub window_start_ms: i64, pub window_end_ms: i64, - /// ASAPv1 bytes from `asap_sketchlib`: the full state. + /// ASAPv1 bytes from `asap_sketchlib`: a full state, or a delta's + /// state of the samples since its base (§8). pub asapv1: Vec, /// Samples folded into the state, as the collector counted them. pub sample_count: u64, + /// `asap.sequence`: its place in its lineage, 0 for a full. + pub sequence: u64, + /// `asap.state_kind` and `asap.base_sequence`. + pub kind: StateKind, +} + +/// Whether a record starts its lineage or applies onto its base. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum StateKind { + /// Sequence 0: the lineage's state so far. + Full, + /// The state of the samples since `base_sequence` (`sequence − 1`). + Delta { base_sequence: u64 }, } /// What happened to a batch's records. @@ -753,6 +920,9 @@ pub struct CollectorStateIngestReport { pub merged: u64, pub late_merged: u64, pub late_dropped: u64, + /// Deltas whose base was not the lineage's last applied record: their + /// windows are marked incomplete (§8). + pub incomplete: u64, /// By reason: `other_plan`, `unknown_view`, `key_mismatch`, `name`, /// `window`, `decode`, `merge`. pub rejected: BTreeMap<&'static str, u64>, @@ -778,6 +948,9 @@ pub struct CollectorViewsFile { /// Per metric a `Scan` reads: whether a node off the collector, or a /// query-time `Scan`, still reads its raw samples. pub backend_reads_raw: BTreeMap, + /// The capabilities' `window_close_delay_ms`, copied: the data plane + /// closes a stopped collector's windows after it plus a skew allowance. + pub window_close_delay_ms: u64, /// The collector views: the cut nodes whose results the backend ingests. pub outputs: Vec, /// The collector sub-DAG; `roots = outputs`. @@ -785,7 +958,9 @@ pub struct CollectorViewsFile { } ``` -`storage::ViewStore` is unchanged: every collector view window is written once, at commit. +`storage::ViewStore` gains the incomplete marks (§8): `mark_incomplete(view, +end_ms)`, and a read of a range holding a marked window fails as a read of a +missing window does. ### `crates/adapters/ingest/otlp` @@ -1117,6 +1292,23 @@ Collector (ASAPCollector-public): match. Next (option C): move the generic streaming driver into the executor as a public API, so the collector and the backend share it. +Both repositories: + +11. Sequence numbers and delta transmission (§8, decision 28), one change + in each repository. Collector: the producer epoch, per-lineage + sequences, corrections as deltas, and `open_window_emit_interval_ms`; + it accepts `window_close_delay_ms` in the file. Backend: the lineage + attributes in the `otlp` adapter, the receiver rules in place of the + hash set, the incomplete marks in the view store, and the idle close + from the file's `window_close_delay_ms` (decision 29). Tests: a full + and its deltas equal the full (DDSketch byte-equal, KLL within its + bound), a repeated sequence is a duplicate, two corrections with equal + bytes both apply, a gap leaves the window unanswered, a restart's full + starts a new lineage, open-window deltas answer and end at the + at-close answer, the delay round-trips through the file, and the + on-time states with open-window emission off are today's bytes apart + from the lineage attributes. + **Future work.** Partial aggregation (collector partial states of a non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based choice of collector views. The OTAP Arrow adapter. @@ -1129,18 +1321,20 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c selection is not sent: the node defines it. Which views the collector builds is a deployment decision the backend's control plane makes on the installed plan. -2. **The collector is ASAPCollector-public (OTAP), sending full ASAPv1 - states.** No deltas: each record holds the whole state of one series in - one window. +2. **The collector is ASAPCollector-public (OTAP), sending ASAPv1 + states.** A window's first record is its full state; later records of + the same window are deltas (decision 28). 3. **Two paths.** The raw path stays for every metric the backend still reads raw. The sketch path carries collector states on the same `/v1/metrics` route; a point with `sketch.envelope` takes it. 4. **Prometheus window semantics on both sides**: `(t − range, t]`. The backend already uses it; the collector changes in its own PR. The window travels as the OTLP point times; its width comes from the key. -5. **Dedup and merge before commit.** A state whose envelope hash was - already seen for its view, series and window is ignored and counted; a - state with a new hash is merged. +5. **Dedup and merge before commit.** A record whose `(epoch, sequence)` + was already applied for its view, series and window is ignored and + counted; a full of a new epoch, or a delta on its base, is merged + (decision 28). Bytes play no part: two corrections with equal bytes are + two records. 6. **Rule-based choice of collector views first**, against the collector's declared capabilities. No cost comparison. Exact aggregates stay in the backend until the collector declares them. @@ -1265,6 +1459,23 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c per-key sum of the sample value). Until it does, the collector view rule requires weight 1 (count) for a label-input sketch. Today's collector loader refuses label-input sketches anyway, so no current cut changes. +28. **Sequence numbers and delta transmission (§8).** Each record carries + its producer epoch (Schema metadata), sequence, kind and base (Record + attributes); a lineage is one instance's records of one + `(view, series, window)`, starting with a full. A delta is the state of + the samples since its base, merged by the view's kernel: bucket-count + increments for DDSketch (byte-equal to the full), a mergeable partial + sketch for KLL (within its rank-error bound). The backend applies a + delta only on its exact base; a gap, an unknown base or a new epoch + without its full marks the window incomplete, and queries reading it + are forwarded. Resynchronization is a full at every window and at + every collector restart; there is no backend-to-collector signal. Open + windows are emitted every `open_window_emit_interval_ms` when the + collector sets it (off by default). +29. **The backend closes idle collector windows after the collector's + declared delay.** The control plane copies `window_close_delay_ms` + from the capabilities into the collector-views file; the data plane + closes after it plus 2 s, instead of a fixed 8 s. ## Open questions From 691a47d4f0f2bf2097b302d103cf75b6e8a6028e Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 04:36:58 +0000 Subject: [PATCH 19/21] docs(design): an incomplete collector window takes no more records Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 2c7b2dce2..d4ec84acc 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -812,9 +812,10 @@ cover it), in the view store. A query run reading an incomplete window fails as one reading a window not stored (`NotReady`), so the dispatcher forwards the query to the fallback store and no plausible result is returned from the plan. Cached results that read the window become stale. -The mark stays until the window leaves the view's retention; records of -the window are still applied, but do not clear it. Each record that breaks -a lineage is counted (`incomplete`). +The mark stays until the window leaves the view's retention; later records +of the window are no longer applied, since none can clear it. Each record +that breaks a lineage, or comes for an incomplete window, is counted +(`incomplete`). **Resynchronization.** The reference protocol resynchronizes a broken lineage with a full checkpoint. Collector views have no channel from the From c97410e4748b19c6cc807e286ed82484ce1080b4 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 15:53:28 +0000 Subject: [PATCH 20/21] docs(design): reorder buffer, persisted incomplete marks, lineage frame Section 8 and decisions 30-34: - 30: incomplete marks are written to the view files beside the window records and survive a restart; FORMAT_VERSION 5 -> 6 (an older data plane sets the new segments aside instead of cutting them), version 5 segments still read. - 31: a receiver reorder buffer holds a delta that comes before its base; its window is incomplete only once the collector's declared window_close_delay_ms has passed with the base still missing. - 32: v1 delivery is at-least-once through the exporter's retry; the backend never asks the collector for a full (no resync request). - 33: a KLL delta is a partial sketch of the new samples, merged at the receiver; recorded as a departure from the reference protocol, whose document is unchanged. - 34: the lineage moves from three OTLP attributes into a versioned binary frame in sketch.envelope (0xA1, flags, uleb128 sequence and base); the producer epoch stays metric metadata. Measured: 48.7 -> 3.8 bytes of lineage per state on the golden on-time states. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 201 ++++++++++++++++++++----- 1 file changed, 162 insertions(+), 39 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index d4ec84acc..1c0b3bbe6 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -416,15 +416,15 @@ structure of raw samples; only the Record content differs: |---|---|---|---|---| | Schema (per metric) | `Metric`: name, type, unit | the source metric's unit and description; name `.asap_view.`, type Summary; `metadata`: `asap.plan_id`, `asap.node_id`, `asap.view_state_key`, `asap.producer_epoch` | `views[]`: `plan_id`, `node_id`, `key`, `producer_epoch` | Find the view, check the key and name | | Dictionary (per series) | Resource + Scope + point attributes → labels | identical: the source samples' Resource, Scope and point attributes, as received | `views[].series[].labels` | The raw path's label function; interned as the raw path interns | -| Record (per point) | `time_unix_nano` + value | window `(start_time_unix_nano, time_unix_nano]`; point attributes `sketch.envelope` (ASAPv1 bytes), `asap.sequence`, `asap.state_kind`, `asap.base_sequence` (deltas only); `count` (samples) | `series[].records[]`: `window_end_ms`, `asapv1`, `sample_count`, `sequence`, `kind` | Stage, apply by lineage, merge, commit (§6, §8) | +| Record (per point) | `time_unix_nano` + value | window `(start_time_unix_nano, time_unix_nano]`; point attribute `sketch.envelope` (the ASAPv1 bytes behind the record's lineage frame: sequence, full or delta, base); `count` (samples) | `series[].records[]`: `window_end_ms`, `asapv1`, `sample_count`, `sequence`, `kind` | Stage, apply by lineage, merge, commit (§6, §8) | **Which view.** A record belongs to its Metric entry, whose metadata carries the view identity, so every record names its view through its metric, with no per-record identity attribute. Two views over one source metric (DDSketch α 0.05 and KLL, or two window widths) are two Metric -entries. A state adds to its point `sketch.envelope` and its place in its -lineage (`asap.sequence`, `asap.state_kind`, `asap.base_sequence`, §8); -none of them is a label. +entries. A state adds to its point `sketch.envelope`, which holds its place +in its lineage in a binary frame in front of its ASAPv1 bytes (§8); it is +no label. **Metric metadata survives the path.** OTLP `Metric.metadata` is `repeated KeyValue metadata = 12` in the protobuf both sides build @@ -489,10 +489,10 @@ erDiagram } RECORD{ window_end_ms i64 "inclusive; start = end - width" - asapv1 bytes "sketch.envelope: the full state (or an exact value)" + asapv1 bytes "sketch.envelope behind its lineage frame: a full or a delta state" sample_count u64 "count" - sequence u64 "asap.sequence; 0 for a full (section 8)" - kind StateKind "asap.state_kind, asap.base_sequence" + sequence u64 "lineage frame; 0 for a full (section 8)" + kind StateKind "lineage frame: full, or delta with its base" } ``` @@ -728,12 +728,36 @@ every later record is a **delta** on the record before it. |---|---|---| | Schema | aggregation kind, parameters, encoding, policy | `asap.plan_id`, `asap.node_id`, `asap.view_state_key` (§4), and `asap.producer_epoch` (decimal text): one epoch per collector instance, so per view metric | | Dictionary | series | the received Resource, Scope and point attributes (§4) | -| Record | window, full/delta, payload, producer/epoch, sequence, base for deltas | window times, `sketch.envelope`, `count`, and point attributes `asap.sequence` (int), `asap.state_kind` (`"full"` or `"delta"`), `asap.base_sequence` (int, deltas only) | +| Record | window, full/delta, payload, producer/epoch, sequence, base for deltas | window times, `count`, and `sketch.envelope`: the lineage frame (kind, sequence, base for deltas) in front of the ASAPv1 bytes | A full has sequence 0 and no base; a delta has sequence `n ≥ 1` and base -`n − 1`. A record without the three attributes, or with a kind that does -not match its sequence and base, is refused with the request (400), as a -record without `sketch.envelope` is. +`n − 1`. + +**Lineage frame.** The kind, sequence and base travel in a binary frame in +front of the record's ASAPv1 bytes, in `sketch.envelope`: + +```text +[ 0xA1 | flags:u8 (bit 0: delta) | sequence:uleb128 + | base_sequence:uleb128 (deltas only) | ASAPv1 bytes ] +``` + +`0xA1` is the frame's marker (high nibble `0xA`) and version (low nibble, +1). An ASAPv1 envelope starts with `b'A'` (`0x41`), so a bare ASAPv1 state +is never read as a frame. A full costs 3 bytes (`A1 00 00`), a delta below +sequence 128 costs 4. The producer epoch stays metric metadata: it is the +same for every point of a metric, so it is sent once per metric (about 40 +bytes) rather than once per record (a random `u64` is a 10-byte varint); +the frame would be cheaper only for metrics of fewer than about four +records. A record whose `sketch.envelope` is a bare ASAPv1 state (a +collector from before the frame), a frame of another version, unknown +flags, or a kind that does not match its sequence and base, is refused with +the request (400), as a record without `sketch.envelope` is. A later frame +version is a new low nibble; a reader refuses versions it does not know. + +On the golden test's on-time states (three messages of 80 DDSketch states, +OTLP protobuf), the lineage as three point attributes cost 48.7 bytes per +state over no lineage (215.9 to 264.6 bytes, +22.6%); as the frame plus the +metric's epoch it costs 3.8 (219.7 bytes, +1.8%). **Example.** The collector, epoch `9241…`, emits the window `(0 s, 5 s]` of series `{job="a"}` of view 1 three times: @@ -755,9 +779,11 @@ current run, and the next sample starts a new one. counts. A full plus its deltas is therefore the DDSketch of all the window's samples, byte-equal once encoded. - **KLL.** The reference protocol sends KLL as full states in its MVP, - because KLL has no compact, order-independent diff. Collector views use - the other correct option: a KLL delta is a KLL sketch of the new samples - alone, and the receiver merges it. KLL is fully mergeable: the merge of + because KLL has no compact, order-independent diff. Collector views + depart from it here (decision 33): a KLL delta is a KLL sketch of the + new samples alone, a partial sketch, and the receiver merges it. The + reference protocol document is unchanged; this section records the + departure. KLL is fully mergeable: the merge of sketches of disjoint sample sets is a sketch of their union with the same rank-error bound, whatever the order and shape of the merges. A full plus its deltas is therefore not byte-equal to the KLL the collector would @@ -798,24 +824,40 @@ merged ones). For a record of epoch `e` and sequence `n`: | full, `n = 0` | none | a new lineage; merged into the window (staged, or the late merge path once committed) | | any | last applied ≥ `n` | duplicate: ignored and counted (`duplicate`) | | delta, base `n − 1` | last applied = `n − 1` | applied: merged into the window | -| delta | none (unknown base, a new epoch without its full, or a backend restart) | **incomplete** | -| delta | last applied < `n − 1` (a gap) | **incomplete** | +| delta | none (its full has not come: a new epoch, or a backend restart) | **held** for its base | +| delta | last applied < `n − 1` (its base has not come) | **held** for its base | +| held delta | its base not applied within the reorder wait | **incomplete** | A delta is never merged onto a plausible base of another epoch or sequence. -Records of one lineage are sent in order, one request at a time; one that -arrives before its base is a gap. + +**Reorder buffer.** A collector may export concurrently (several requests +in flight, and retries), so a lineage's records can arrive out of order. A +delta whose base has not been applied is held, per lineage and sequence, +and is applied as soon as its base is, followed by the records held after +it. A repeat of a held record is a duplicate. Only when one has been held +for the collector's declared `window_close_delay_ms` (copied into the +collector-views file, decision 29) on the data plane's monotonic clock with +its base still missing does its window become incomplete; the window's +other held records are then dropped. A record waits at most that long, +which bounds the buffer to the records of that long. While a record is +held, a query of its window answers from the records applied so far, as it +does for an open window. Held records live in memory only: after a backend +restart their lineages' bases are unknown, so the deltas that come next +are held and, with no full to apply, make their windows incomplete after +the wait. **Incomplete windows.** A `(view, series, window)` whose lineage broke makes the view's window **incomplete**: the backend marks it, and the windows built from it (the windows of the groups reading the view that -cover it), in the view store. A query run reading an incomplete window +cover it), in the view store, and writes the marks to the view files +(decision 30), so a restarted backend reads the window back incomplete. A query run reading an incomplete window fails as one reading a window not stored (`NotReady`), so the dispatcher forwards the query to the fallback store and no plausible result is returned from the plan. Cached results that read the window become stale. The mark stays until the window leaves the view's retention; later records of the window are no longer applied, since none can clear it. Each record that breaks a lineage, or comes for an incomplete window, is counted -(`incomplete`). +(`incomplete`); a record held is counted `held` when it is held. **Resynchronization.** The reference protocol resynchronizes a broken lineage with a full checkpoint. Collector views have no channel from the @@ -833,18 +875,23 @@ collector sends a full checkpoint at these points, and no other: and a delta of the new epoch whose full was lost is incomplete, never applied to the previous epoch's state. +**Delivery.** v1 delivery is at-least-once: the collector's OTLP exporter +retries a request that failed (a timeout, a 5xx or 429 reply) and the +backend drops the repeats by `(epoch, sequence)`; the reorder buffer holds +a retried request's successors until it arrives. The backend never asks +the collector for a full state: there is no resync request (decision 32). + A broken lineage is not repaired: the samples of the lost record are not anywhere the backend can read. The window stays incomplete and its queries -are forwarded until it leaves retention. A feedback channel (the backend -asks for a full and the collector resends the window's whole state) would -need the collector to keep each window's state for the view's retention; -it is future work, as is a backend restart that keeps the marks (today a -restarted backend reads persisted windows back complete; deltas after the -restart have no known base and mark their windows incomplete again). +are forwarded until it leaves retention, also across a backend restart. A +feedback channel (the backend asks for a full and the collector resends +the window's whole state) would need the collector to keep each window's +state for the view's retention; it is future work. **Composition with the other paths.** A full of a window the idle clock closed empty (§6, No states) is a new lineage and merges in through the -late merge path; a delta for it has no known base and is incomplete. A +late merge path; a delta for it with no full is held, and its window is +incomplete if no full comes within the reorder wait. A window stored behind the newest (§6, Order) keeps its lineages like any other. States past retention are dropped (`late_dropped`) before any lineage rule. @@ -898,9 +945,9 @@ pub struct ViewStateRecord { pub asapv1: Vec, /// Samples folded into the state, as the collector counted them. pub sample_count: u64, - /// `asap.sequence`: its place in its lineage, 0 for a full. + /// Its place in its lineage (lineage frame), 0 for a full. pub sequence: u64, - /// `asap.state_kind` and `asap.base_sequence`. + /// Full, or delta with its base (lineage frame). pub kind: StateKind, } @@ -921,8 +968,10 @@ pub struct CollectorStateIngestReport { pub merged: u64, pub late_merged: u64, pub late_dropped: u64, - /// Deltas whose base was not the lineage's last applied record: their - /// windows are marked incomplete (§8). + /// Deltas held for their base (§8, reorder buffer): applied when it + /// comes, or their window is marked incomplete after the reorder wait. + pub held: u64, + /// Records of a window already incomplete (§8). pub incomplete: u64, /// By reason: `other_plan`, `unknown_view`, `key_mismatch`, `name`, /// `window`, `decode`, `merge`. @@ -961,7 +1010,28 @@ pub struct CollectorViewsFile { `storage::ViewStore` gains the incomplete marks (§8): `mark_incomplete(view, end_ms)`, and a read of a range holding a marked window fails as a read of a -missing window does. +missing window does. The view files keep them (decision 30): a record head +lists the views whose window it marks incomplete, and a record may hold +marks alone; `ViewFiles::mark_incomplete(group, range_ms, views)` appends +one per retention, and `ViewFiles::index` collects them for the restarted +store. + +```rust +pub(crate) struct RecordHead { + // ... start_ms, end_ms, texts, grids, views, revision ... + /// Views whose window `(start_ms, end_ms]` is incomplete; version 5 + /// records read as none. + #[serde(default)] + pub incomplete: Vec, +} +/// 6: record heads carry incomplete marks; version 5 segments are read. +pub(crate) const FORMAT_VERSION: u32 = 6; +``` + +`common` gains the lineage frame's reader: `unframe_lineage(bytes) -> +Result<(sequence, StateKind, asapv1), String>` (and `frame_lineage` for +tests). `CollectorViewOptions` gains `reorder_wait_ms`, the file's +`window_close_delay_ms`. ### `crates/adapters/ingest/otlp` @@ -1300,7 +1370,8 @@ Both repositories: sequences, corrections as deltas, and `open_window_emit_interval_ms`; it accepts `window_close_delay_ms` in the file. Backend: the lineage attributes in the `otlp` adapter, the receiver rules in place of the - hash set, the incomplete marks in the view store, and the idle close + hash set, the incomplete marks in the view store and the view files, + the reorder buffer, the lineage frame, and the idle close from the file's `window_close_delay_ms` (decision 29). Tests: a full and its deltas equal the full (DDSketch byte-equal, KLL within its bound), a repeated sequence is a duplicate, two corrections with equal @@ -1308,7 +1379,10 @@ Both repositories: starts a new lineage, open-window deltas answer and end at the at-close answer, the delay round-trips through the file, and the on-time states with open-window emission off are today's bytes apart - from the lineage attributes. + from the epoch and the full's 3-byte lineage frame. Records out of + order in separate requests answer as in-order ones, a base still + missing after the reorder wait marks the window incomplete, and an + incomplete window stays incomplete after a backend restart. **Future work.** Partial aggregation (collector partial states of a non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based choice of collector views. The OTAP Arrow adapter. @@ -1461,15 +1535,15 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c requires weight 1 (count) for a label-input sketch. Today's collector loader refuses label-input sketches anyway, so no current cut changes. 28. **Sequence numbers and delta transmission (§8).** Each record carries - its producer epoch (Schema metadata), sequence, kind and base (Record - attributes); a lineage is one instance's records of one + its producer epoch (Schema metadata), sequence, kind and base (Record: + the lineage frame in `sketch.envelope`, decision 34); a lineage is one instance's records of one `(view, series, window)`, starting with a full. A delta is the state of the samples since its base, merged by the view's kernel: bucket-count increments for DDSketch (byte-equal to the full), a mergeable partial sketch for KLL (within its rank-error bound). The backend applies a - delta only on its exact base; a gap, an unknown base or a new epoch - without its full marks the window incomplete, and queries reading it - are forwarded. Resynchronization is a full at every window and at + delta only on its exact base, holding one that comes early (decision + 31); a base still missing after the reorder wait marks the window + incomplete, and queries reading it are forwarded. Resynchronization is a full at every window and at every collector restart; there is no backend-to-collector signal. Open windows are emitted every `open_window_emit_interval_ms` when the collector sets it (off by default). @@ -1477,6 +1551,55 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c declared delay.** The control plane copies `window_close_delay_ms` from the capabilities into the collector-views file; the data plane closes after it plus 2 s, instead of a fixed 8 s. +30. **Incomplete marks survive a restart.** The marks are written to the + view files next to the window records: a record head lists the views + whose window it marks, and a mark may be a record alone, so marking + never rewrites a window. They expire with their segments, like the + windows. Why: without them a restarted backend read an incomplete + window back complete and answered from it, a plausible but wrong + result; the reference protocol's rule is that a window whose lineage + broke is never answered. `FORMAT_VERSION` goes from 5 to 6: a version 5 + data plane cannot decode the new heads and would cut a segment at the + first one, so the bump makes it set version 6 segments aside instead. + Version 6 reads version 5 segments (their heads have no marks), so an + upgrade keeps its persisted windows. +31. **A receiver reorder buffer.** A delta that comes before its base is + held until the base comes, and its window is marked incomplete only + once the collector-declared close delay (`window_close_delay_ms`) has + passed with the base still missing. Why: a collector exporting + concurrently (several requests in flight, exporter retries) delivers a + lineage's records out of order; treating each early record as a gap + would make windows incomplete that every record of reaches. The close + delay is the longest the collector itself waits before it emits a + window, so it is the collector's own bound on its records' spread; the + buffer holds at most that long. +32. **v1 delivery is at-least-once, with no resync request.** The + collector's exporter retries failed requests; the backend drops repeats + by `(epoch, sequence)` and never asks the collector for a full state. + Why: the collector has no channel from the backend back to the + processor (§8, Resynchronization), and a resync would need it to keep + every window's state for the view's retention. A full at every window + and every restart bounds what a lost record breaks to one window. +33. **A KLL delta is a partial sketch of the new samples, merged at the + receiver.** This departs from the reference protocol, which sends KLL + as full states in its MVP; the reference document is not changed and + this decision records the departure. Why: KLL is fully mergeable, so + the merged lineage is within the sketch's rank-error bound, and full + KLL replacements would need the collector to keep every closed + window's KLL and the backend to keep each lineage's state apart (§8, + What a delta holds). +34. **The lineage travels in a binary frame in `sketch.envelope`, not in + OTLP string attributes.** Sequence and base are unsigned LEB128 + varints and the kind a flag bit, behind a version byte (`0xA1`); the + producer epoch stays metric metadata. Why: the three attributes cost + 48.7 bytes per state (+22.6%) on the golden on-time states, the frame + and epoch 3.8 bytes (+1.8%); the epoch is per collector instance, so + per metric it is sent once instead of per state. The version byte + makes a bare ASAPv1 state (a collector from before the frame) or an + unknown frame version an explicit refusal, not a misread. The frame is + not part of ASAPv1 itself: ASAPv1 encodes a sketch's state, which the + backend also stores and the collector also merges, while the lineage + belongs to one transmission. ## Open questions From 5a438d14a796290559ac90b46755617a530452e5 Mon Sep 17 00:00:00 2001 From: zzylol Date: Mon, 30 Nov 2026 16:24:24 +0000 Subject: [PATCH 21/21] docs(design): reorder wait adds the skew allowance; held records in memory; deploy together - Decision 31 and section 8: a held record's window is incomplete only after the declared window_close_delay_ms plus the same 2 s clock-skew allowance as the idle close. - Decision 31: v1 keeps held records in memory only; a backend restart drops them and their windows become incomplete after the wait. - Decision 34: the collector's lineage frame and the backend's decoder are deployed together. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf --- docs/design/collector-sketch-ingest.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md index 1c0b3bbe6..a27e824aa 100644 --- a/docs/design/collector-sketch-ingest.md +++ b/docs/design/collector-sketch-ingest.md @@ -836,8 +836,9 @@ delta whose base has not been applied is held, per lineage and sequence, and is applied as soon as its base is, followed by the records held after it. A repeat of a held record is a duplicate. Only when one has been held for the collector's declared `window_close_delay_ms` (copied into the -collector-views file, decision 29) on the data plane's monotonic clock with -its base still missing does its window become incomplete; the window's +collector-views file, decision 29) plus the same 2 s clock-skew allowance as +the idle close, on the data plane's monotonic clock, with its base still +missing does its window become incomplete; the window's other held records are then dropped. A record waits at most that long, which bounds the buffer to the records of that long. While a record is held, a query of its window answers from the records applied so far, as it @@ -1565,14 +1566,20 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c upgrade keeps its persisted windows. 31. **A receiver reorder buffer.** A delta that comes before its base is held until the base comes, and its window is marked incomplete only - once the collector-declared close delay (`window_close_delay_ms`) has - passed with the base still missing. Why: a collector exporting + once the collector-declared close delay (`window_close_delay_ms`) plus + the 2 s clock-skew allowance has passed with the base still missing + (the same wait as the idle close, decision 29). Why: a collector exporting concurrently (several requests in flight, exporter retries) delivers a lineage's records out of order; treating each early record as a gap would make windows incomplete that every record of reaches. The close delay is the longest the collector itself waits before it emits a window, so it is the collector's own bound on its records' spread; the - buffer holds at most that long. + skew allowance is added for consistency with the idle close, which + waits as long for a stopped collector's windows. The buffer holds a + record at most that long. In v1 held records live in memory only: a + backend restart drops them, and the deltas that follow have no known + base, so their windows become incomplete after the wait. Persisting the + buffer is not worth it for a wait of seconds. 32. **v1 delivery is at-least-once, with no resync request.** The collector's exporter retries failed requests; the backend drops repeats by `(epoch, sequence)` and never asks the collector for a full state. @@ -1600,6 +1607,9 @@ non-local mergeable aggregate, merged by a backend `SummaryMerge`). Cost-based c not part of ASAPv1 itself: ASAPv1 encodes a sketch's state, which the backend also stores and the collector also merges, while the lineage belongs to one transmission. + The collector's frame and the backend's decoder are deployed + together: a backend that reads the frame refuses an unframed state + under a producer epoch, and an older backend refuses framed states. ## Open questions