diff --git a/docs/design/collector-sketch-ingest.md b/docs/design/collector-sketch-ingest.md new file mode 100644 index 000000000..a27e824aa --- /dev/null +++ b/docs/design/collector-sketch-ingest.md @@ -0,0 +1,1616 @@ +# Design: plan sub-DAGs precomputed in the collector (v1: leaf sketch views) + +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 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 +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. 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: 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 +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`): + +- **Plan**: the `InstallablePlan` the control plane writes: `wire_version`, + `dag: PhysicalASAPDAG` (`nodes`, `edges`, `roots`, `scalar_roots`) and + `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}}} + } + ``` + + 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. +- **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**: 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: + +- 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: 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, 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 ─┬─▶ collector_views (planner_views) ─────────────────▶ OTLP exporter│─┐ sketch path + │ └─▶ raw_forward (drops metrics with backend_reads_raw = false) ─▶ ...│─┤ raw path + └─────────────────────────────────────────────────────────────────────────────┘ │ + 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 + ─▶ 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 | `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 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` +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 +own path, not through this forward. + +### Dependencies + +Following the layout rules (adapters see no engine and no store): + +```text +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 + 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 +``` + +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. + +`asap-types` brings `serde`, `serde_json`, `thiserror` 2 and +`asap_sketchlib` into the collector build; no frontend or solver +(decision 15). `asap-executor` adds no third-party crate to the lock (§7). + +## Algorithm + +### 1. Capabilities and the collector view rule (control plane) + +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, + "executor": { + "supported_summaries": [ + {"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"]}, + {"kind": "Filter"}, + {"kind": "SummaryTumblingWindowChain", "reductions": ["PerEntity"]}], + "placement": {"partitioned_by": "series"}, + "window_close_delay_ms": 6000} +``` + +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, 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` + 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). + `{"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 backend commits a window when its states arrive (§6), so it does not + 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 +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 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 + `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). +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 +`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 +(§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, +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` +(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": 16, + "plan_id": "", + "backend_reads_raw": {"data": true, "data_total": true}, + "window_close_delay_ms": 6000, + "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. +- `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 +`--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 +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 +`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. +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 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 + 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. + +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 `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). + +### 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). 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 | +|---|---|---|---|---| +| 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` (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`, 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 +(`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. +So the Record's window is exactly the time part the rows add, in +Prometheus's `(t − range, t]` form (§5). + +```mermaid +erDiagram + SCHEMA ||--o{ KEY : keys + KEY ||--o{ RECORD : records + SCHEMA{ + plan_id string "PhysicalASAPDAG::plan_id()" + 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" + } + RECORD{ + window_end_ms i64 "inclusive; start = end - width" + asapv1 bytes "sketch.envelope behind its lineage frame: a full or a delta state" + sample_count u64 "count" + sequence u64 "lineage frame; 0 for a full (section 8)" + kind StateKind "lineage frame: full, or delta with its base" + } +``` + +**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`); 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]` + +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"). 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 + `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. + +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 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 + +`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.** `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"`, + 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"`). 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}` (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 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, 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. + 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 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 + (`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. +- **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` 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 + 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 + 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 +view, and one started earlier skips to the collector view's first window. + +**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` + +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, 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 + 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. + +### 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, `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`. + +**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: + +| 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 + 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 + 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 (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. + +**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) 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 +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, 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`); 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 +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. + +**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, 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 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. + +## Code interface + +### `crates/common` + +```rust +use asap_types::plan::materialized_view::ViewStateKey; +use asap_types::plan::PhysicalASAPNodeId; + +/// The collector states of one OTLP request: what the OTLP adapter hands +/// `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)] +pub struct ViewStateBatch { + pub views: Vec, +} + +/// 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, + /// `asap.producer_epoch`: the collector instance that sent the states (§8). + pub producer_epoch: u64, + 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 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`: 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, + /// Its place in its lineage (lineage frame), 0 for a full. + pub sequence: u64, + /// Full, or delta with its base (lineage frame). + 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. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct CollectorStateIngestReport { + pub staged: u64, + pub duplicate: u64, + pub merged: u64, + pub late_merged: u64, + pub late_dropped: u64, + /// 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`. + pub rejected: BTreeMap<&'static str, u64>, +} + +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, + /// 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`. + pub dag: PhysicalASAPDAG, +} +``` + +`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. 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` + +```rust +/// A decoded request: raw samples and collector states, from one walk. +pub struct Decoded { + pub points: Vec, + pub view_states: ViewStateBatch, +} + +pub fn decode(body: &[u8], content_encoding: Option<&str>, limits: &Limits) + -> Result; // was -> Vec + +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 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` + +```rust +/// What `asap_sketches --print-capabilities` prints (§1). +#[derive(Debug, Clone, PartialEq, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct CollectorCapabilities { + pub capabilities_version: u32, + /// 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 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 { + pub kind: OperatorKind, + /// `Scan`: the source variants, e.g. `TimeSeries`. + #[serde(default)] + pub sources: Vec, + /// Chain: `Reduction` variant names, e.g. `PerEntity`. + #[serde(default)] + pub reductions: Vec, +} + +/// `executor`: every `DeploymentCapabilities` field with its planner serde, +/// except `supported_summaries`, whose entries are `CollectorSummary`s. +pub struct CollectorExecutor { + pub supported_summaries: Vec, + pub rest: DeploymentCapabilities, // its own `supported_summaries` stays `None`; + // deserialized by hand, not `#[serde(flatten)]` +} + +/// 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 CollectorSummary { + pub summary: SupportedSummary, // summary_type + readouts + pub input: SummaryInputKind, // Value | Label + 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, +} + +/// Why a node is not on the collector, for the command's report. +#[derive(Debug, Clone, PartialEq)] +pub enum NotOnCollector { + NotInCapabilities(String), + InputNotOnCollector, + NotAtIngestion, + NotLocalToPartition, + /// v1: a cut producer that is not a materialized view. + OutputNotAView, +} + +/// 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, +) -> Result<(CollectorViewsFile, Vec<(PhysicalASAPNodeId, NotOnCollector)>), InstallablePlanError>; +``` + +`DeploymentCapabilities`, `SupportedSummary`, `OperatorKind` and +`CompareOpKind` are the planner's types, unchanged. CLI: +`control_plane --plan --collector-capabilities + --emit-collector-views `; the data plane takes +`--collector-views `. + +## Worked example: 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 +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) +``` + +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": 16, "plan_id": "…", + "backend_reads_raw": {"data": true, "data_total": true}, + "outputs": [1], + "dag": { + "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": []}} +``` + +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: + type: urn:asap:processor:asap_sketches + config: + planner_views: /etc/asap/collector-views.json +``` + +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): + +```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 +`(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 + +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) | 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 | +| 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 +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. + +## Plan + +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): + +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: + +2. This document. +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 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 + 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 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`); 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 + 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): + +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; 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). 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. 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. + +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 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 + 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 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. + +## Decisions + +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 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 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. +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 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 the sub-DAG. +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`. +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` + 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`. Step 3's + captured records stay the compatibility test, one per sketch type, and + 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.** 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 + 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 + 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. **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 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` + 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. 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 + 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 + 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, 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. **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 + 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. +28. **Sequence numbers and delta transmission (§8).** Each record carries + 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, 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). +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. +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`) 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 + 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. + 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. + 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 + +None open.