Skip to content

docs(design): plan sub-DAGs precomputed in the collector (v1: leaf sketch views) - #885

Draft
zzylol wants to merge 21 commits into
refactor/layout-eval-deployfrom
docs/collector-sketch-ingest
Draft

zzylol wants to merge 21 commits into
refactor/layout-eval-deployfrom
docs/collector-sketch-ingest

Conversation

@zzylol

@zzylol zzylol commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Problem: every sample goes raw to the backend, and the backend builds every leaf view itself. The collector (ASAPCollector-public, OTAP asap_sketches) could build the same per-series window states at the edge. Example: q01 quantile_over_time(0.99, data[1m]) at 10 samples/s folds 50 samples per series into one DDSketch state per 5 s window.
  • Change: a design doc, docs/design/collector-sketch-ingest.md. The collector declares its capabilities in the planner's vocabulary (DeploymentCapabilities, OperatorKinds with argument constraints, a series placement); the control plane assigns plan nodes to the collector bottom-up from the Scans, cuts the maximal collector sub-DAG, and writes collector-views.json (the sub-DAG, its outputs = collector views, the plan id, which metrics the backend still reads raw, the commit grace). With today's capabilities the rule gives exactly the leaf views, so v1 scope is unchanged; v1 embeds asap-executor in the collector through a thin collector-side driver over its public APIs (option A); next, the generic streaming driver moves into the executor (option C); depending on the backend's precompute crate (option B) is rejected. Collector view states use exactly the OTAP Schema / Dictionary / Record structure of raw samples; only the Record differs (window + ASAPv1 state). The view identity (plan_id, node_id, the planner's view state key from ASAPPlanner#1429) is metric-level metadata, so every state names its view through its metric; the backend stores it as if its own precompute had built it. The collector stops forwarding raw samples of metrics only collector views read.
  • Depends on: ASAPPlanner#1429 (ViewStateKey, MaterializedView::view_state_key(), PhysicalASAPDAG::plan_id()), closed by ASAPPlanner#1536 (merged); implementation PRs start after the pin bump (plan step 1).
  • Effect: none yet (doc only).

Review guide

  • Base: refactor/layout-eval-deploy (draft, layout step 9).
  • Read in this order: §1 (capabilities + rule), §2 (file), §4 (tier table, metadata survival, view metric name, labels), §6 (Record branch, lookup, dedup, commit grace, late drop), then the q01 example and Decisions 11, 12, 14, 17, 22.
  • Needs careful review:
    • View metric name <metric>.asap_view.<node_id> (Decision 17): OTLP metric metadata is non-identifying, so the name keeps views distinct for spec-following consumers.
    • Reinstall: states of the old plan_id are rejected until the collector restarts (Decision 14; previously unchanged views kept matching by key + selection).
    • Commit grace formula and its 2 s skew allowance (open question 8).
    • A window with no state at commit is not stored → NotReady → fallback (open question 7).

Before this PR → after this PR (the design)

Workload entry: q01 alone, quantile_over_time(0.99, data[1m]), every 5 s, 10 samples/s per series, 5 % relative error.

Before After
Control plane writes the plan + reads capabilities.json, writes collector-views.json: n1's sub-DAG, plan_id, backend_reads_raw: {"data": false}, commit_grace_ms: 8000
Collector forwards raw OTLP builds n1 (DDSketch α 0.05, 5 s windows); emits Metric data.asap_view.1 with metadata asap.plan_id / asap.node_id / asap.view_state_key under the raw samples' Resource, Scope and point attributes; one Summary point per series per window with sketch.envelope; drops raw data to the backend
Backend builds n1 from raw otlp decodes Schema/Dictionary as for raw, branches at the Record; finds n1 by (plan_id, node_id), checks key and name, labels from the raw path's function, stages, commits at end + 8 s; precompute skips n1
Query merge 12 windows → quantile unchanged

With the five-query benchmark set every metric still has a reader that is not a collector view, so expected benefit is about zero there; step 5 measures both workloads.

Changes in this revision (feasibility spike)

  • v1 = embedded asap-executor via a thin driver (option A); option C next (streamed raw input, per-window run holder, window-end math, state-to-ASAPv1 call move into the executor; the backend keeps interning, sharding/routing, watermark policy, commit, persistence, memory budget, metrics); option B rejected (about ten pub(crate) items made public, process-wide interner, pulls storage/tokio/clap/full asap-planner with solver, git dependency on the backend).
  • Spike (§7): only asap-executor added to the lock (0 third-party crates); build +3% wall / +5% CPU; binary +4.6%; per-sample CPU at 5 samples/window 1298 ns (asap_sketches) vs 1546 / 1410 / 1113 ns (executor per second / per window / kernel only); state memory 20.8 MB vs 30.1 MB for 10,000 series; 120,000 states: same count and quantiles, executor states about 2.7x smaller, worst relative error 0.0500 within alpha.
  • Plan step 10 is the v1 approach; steps 7-8 remain for legacy non-planner configs only; step 1 precedes any byte-for-byte comparison; §6 notes the envelope hash depends on the producing implementation; Decision 25 rewritten.

Changes in this revision (generic sub-DAG)

  1. Capabilities in the planner's vocabulary, each stated once (§1): {"capabilities_version", "executor": DeploymentCapabilities, "predicate_ops": [..], "operators": [{"kind": OperatorKind, ..own limits}], "placement": {"partitioned_by": "series" | {"labels": [..]}}, "window_close_delay_ms"}. Each sketch appears once, in executor.supported_summaries, with its parameter ranges, input kind and readouts (the planner's SupportedSummary, unchanged, wrapped by the collector's entry); predicate_ops (Eq/Ne) is shared by every operator that takes a predicate. Today: Scan (TimeSeries), Filter, SummaryTumblingWindowChain (PerEntity), six sketches, readouts: [] (the collector reads no value from a sketch yet), no raw retention, no counter functions. The doc has a worked example of one added operator line moving the cut, and of placement keeping sum by (region) in the backend.
  2. Generic collector-view rule (§1, Decision 23): a node is on the collector iff its operator+arguments are in the capabilities, every input is a raw Scan or an assigned node, it runs at ingestion, and it is correct on one instance's partition (per-series always; Reduce(G) only under {"labels": L} with L ⊆ G). The maximal sub-DAG is cut; a Scan output is the raw path, any other output must be a materialized view with a wire encoding (state or exact value). The leaf rule is the special case.
  3. File lists the cut (§2): outputs: [node_id] + one dag (roots = outputs), instead of one two-node sub-DAG per view.
  4. Tier mapping generalized (§4): Schema = the output's (plan_id, node_id, ViewStateKey); Dictionary = the output schema's key columns (series labels for per-series views, identical to raw); Record = window + state/value. ER diagram updated.
  5. Target design (§7, Decision 25): the collector embeds asap-executor (compile/instantiate on its sub-DAG), so its capabilities equal the executor's. v1 keeps mapping leaf views onto asap_sketches; new plan step 10 embeds the executor after measuring build time, binary size and memory. Partial aggregation is future work (Decision 26).

Earlier revision (OTAP structure): same Schema/Dictionary/Record as raw samples, view identity as Metric.metadata, no Resource-level sketch.* attributes, one walk in the otlp adapter branching at the Record, lookup by (plan_id, node_id) + key check, ViewStateBatch mirrors the tiers.

Verification behind the design (cited in §4):

  • Metric.metadata (repeated KeyValue metadata = 12) exists in opentelemetry-proto 0.28 (backend) and otel-arrow 3e85c34's pdata protos (collector).
  • OTAP Arrow keeps it: otel-arrow's encoder writes metric.metadata() to METRIC_ATTRS by metric id, and OTAP→OTLP writes it back as field 12.
  • Collector today: its codec's MetricView::metadata returns empty and window_merge re-encodes keyed by agg_id, so the collector changes carry the identity in SketchEnvelope.
  • The proto calls metadata "non-identifying"; hence the reserved view name (Decision 17).

Interfaces (proposed for later PRs)

+ common::{ViewStateBatch { views }, CollectorViewStates { plan_id, node_id, key: ViewStateKey, series }, CollectorSeriesStates { labels, records }, ViewStateRecord { window_end_ms, asapv1, sample_count }}
- common::{ViewStateBatch { stream_id, views }, CollectorViewStates { key, selection, series: Vec<(u32, LabelSet)>, records }, ViewStateRecord { series_id, .. }}   (previous revision)
+ precompute::{CollectorStateIngestReport, PrecomputeEngine::ingest_collector_states(ViewStateBatch) -> Result<CollectorStateIngestReport, IngestError>}   (method, no trait)
- otlp::decode(..) -> Result<Vec<Point>, OtlpError>
+ otlp::decode(..) -> Result<Decoded { points, view_states: ViewStateBatch }, OtlpError>;  OtlpError::ViewIdentity
- asap_sketch_otlp::{is_sketch_point, decode_view_states, SketchOtlpError}   (previous revision)
+ control_plane::{CollectorCapabilities { capabilities_version, executor: CollectorExecutor, predicate_ops: Vec<CompareOpKind>, operators: Vec<OperatorCapability>, placement: Placement, window_close_delay_ms }, CollectorExecutor { supported_summaries: Vec<CollectorSummary>, ..DeploymentCapabilities }, CollectorSummary { summary: SupportedSummary, input, parameters }, OperatorCapability { kind: OperatorKind, sources, reductions }, Placement { partitioned_by: PartitionedBy { Series | Labels } }}
- control_plane::CollectorCapabilities { summaries, reductions, windows, predicate_ops, .. }   (earlier revision)
+ control_plane::{CollectorViewsFile { planner_wire_version, plan_id, commit_grace_ms, backend_reads_raw, outputs: Vec<PhysicalASAPNodeId>, dag: PhysicalASAPDAG }, NotOnCollector, collector_sub_dag(plan, capabilities, export_interval_ms)}
- control_plane::{CollectorViewsFile { .., views: Vec<PhysicalASAPDAG> }, NotCollectorView, collector_view_dags(..)}   (previous revision)
+ control_plane --collector-capabilities <f> [--collector-export-interval-ms <ms>] --emit-collector-views <f>; data plane --collector-views <f>
+ collector: asap_sketches --print-capabilities; config planner_views: <path>; Metric.metadata asap.plan_id, asap.node_id, asap.view_state_key; metric name <metric>.asap_view.<node_id>
- collector: Resource sketch.agg_id, sketch.type, sketch.schema_version; Scope sketch.series_id; point sketch.window_start_ms, sketch.window_end_ms

Changes in this revision (delta transmission: decisions 30–34)

§8 and five new decisions, each with its reason in the doc:

  • 30. Incomplete marks survive a restart. They are written to the view files beside the window records: a record head lists the views whose window it marks, and a mark can be a record on its own. FORMAT_VERSION goes from 5 to 6, so an older data plane sets new segments aside instead of truncating them at the first head it cannot decode. Version 6 still reads version 5 segments, so an upgrade keeps its windows. Why: a restarted backend used to read an incomplete window back as complete and answer from it.
  • 31. Receiver reorder buffer. A delta that arrives before its base is held. The window becomes incomplete only after the collector's declared window_close_delay_ms passes with the base still missing. Why: a collector that exports concurrently, or retries, delivers a lineage's records out of order.
  • 32. v1 delivery is at-least-once, through the exporter's retry, with no resync request. Why: the processor has no channel back from the backend, and a resync would require keeping every window's state.
  • 33. A KLL delta is a partial sketch of only the new samples, merged at the receiver. This is recorded as a departure from the reference protocol (which sends full KLL states). The reference document is unchanged. Why: KLL merges within its rank-error bound, and sending full replacements would cost memory on both sides.
  • 34. The lineage moves into a versioned binary frame in sketch.envelope (0xA1, a flags byte, then the sequence and base as uleb128 varints), in front of the ASAPv1 bytes. The producer epoch stays in the metric metadata. Why: on the golden on-time states the lineage cost drops from 48.7 B per state (+22.6 %, as attributes) to 3.8 B (+1.8 %). The epoch is per instance, so it is sent once per metric. The version byte turns a bare ASAPv1 state, or an unknown frame version, into an explicit refusal.

Decisions and open questions

Decisions 1–34 are in the doc. New in this revision: 23 (generic rule), 24 (planner-vocabulary capabilities), 25 (target: embed asap-executor), 26 (partial aggregation future); 7, 8, 15, 18 adjusted to one sub-DAG + outputs.

Decision 13 (former open questions 1 and 2): everything uses the latest ASAPPlanner and the latest asap_sketchlib, bumped together. Concrete revs at the time of writing:

  • ASAPPlanner: latest main daaa2a207 for the backend and the collector; moved to the newer rev once the planner's sketchlib bump lands.
  • asap_sketchlib: latest main a05b35c for the planner, the backend and the collector (previously 389530c, 355093f and 60101c6).
  • The collector refuses a collector-views.json with another planner_wire_version; the captured-record compatibility test stays the guard; HLL is no longer excluded on version grounds.

Open questions: none.

Resolved and removed: sketchlib versions and planner pin/file format (now Decision 13), dedup vs merge, window encoding, commit time, result cache after late merge, selective raw forwarding, out-of-order samples, definition_id coverage, reading definition_id outside the planner.

Updated to match the implementation

The doc now follows what the collector-state ingest and the collector-views file/rule PRs did, and the collector side as built (collector_views and raw_forward processors on the embedded executor): the precompute skip is an engine option set by the file; ViewStateRecord carries window_start_ms; rejection reasons add key_mismatch, name and merge, with unknown node ids under view="unknown"; a request's states are staged before its samples (a retried 503 never ingests samples twice) and states get 503 while the precompute backlog is full; CollectorViewsFile lives in common; collector_sub_dag takes a CommitGrace and returns a Result; the control plane depends on asap-types and common; collector windows close by the idle wall-clock close feature's engine clock without triggering its idle flush; lateness is per (metric, window width) group and a value refused by one view's sketch is dropped for the group. Known limitation added: a view that reads a collector view and scans a raw metric keeps that metric's raw samples until the collector's first state arrives. New decision 27: a label-input sketch's capabilities entry states its weight semantics; until it does, the rule requires weight 1 (count).

Verification

Scope Result Notes
Docs only n/a No code changes.
Planner names checked at ASAPPlanner main DeploymentCapabilities fields (supported_summaries, raw_data_retained, query_time_results_retained, counter_semantics, state_not_mergeable_across_windows, excluded_candidates), SupportedSummary { summary_type: SketchAlgorithm, readouts }, OperatorKind, SketchAlgorithm names (DDSketch, KLL, HLL, CountSketch, CountMinSketch, CountMinSketchWithHeap), CompareOpKind, Reduction::PerEntity, materialized_views, ViewStateKey, plan_id(), INSTALLABLE_PLAN_WIRE_VERSION = 16, asap-executor deps and compile/instantiate.
Backend names checked storage::ViewStore (write-once), ViewInstanceKey, PrecomputeEngine::try_ingest, precompute::IngestError, LabelSet, decode_sketch, window_end, Prometheus fallback.
Collector names checked at ASAPCollector-public main 8b88156 IDLE_CLOSE_GRACE 5 s, timer period ≤ 1 s, MatchOp {Equal, NotEqual}, SketchType names, schema attribute keys, parameter validation (alpha in (0,1), positive ints; KLL k ≥ 8 per the config doc), no batch processor before the exporters.

Follow-ups

Pins PR 1 (ASAPPlanner daaa2a207 or newer, asap_sketchlib a05b35c; planner, then backend, then collector). Backend PR 3 (batch, otlp Record branch + label convention, ingest), PR 4 (capabilities input, file, plan-id check, precompute skip), PR 5 (end-to-end, two workloads). Collector: capabilities command; loader + view identity in metric metadata (codec, window_merge); window boundary/out-of-order/matchers; raw-forward filter. Collector step 10: embed asap-executor (measure first). Later: partial aggregation, late merge (if measured late rate warrants), cost-based choice of collector views, OTAP Arrow adapter.

🤖 Generated with Claude Code

https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf

@zzylol zzylol added documentation Improvements or additions to documentation area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior feature: PromQL PromQL compatibility and execution semantics labels Nov 27, 2026
@zzylol
zzylol force-pushed the docs/collector-sketch-ingest branch from d6a54f2 to 7eb216d Compare November 27, 2026 16:33
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.
…tion_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.
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.
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.
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.
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.
…t a trait

The layout stack deleted IngestEngine and the common ViewStore trait; a
trait is added with its second implementation.
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 <metric>.asap_view.<node_id>
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.
…bilities, 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.
@zzylol zzylol changed the title docs(design): leaf sketch views precomputed in the collector docs(design): plan sub-DAGs precomputed in the collector (v1: leaf sketch views) Nov 28, 2026
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.
zzylol and others added 2 commits November 28, 2026 15:33
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.
… 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
zzylol and others added 8 commits November 29, 2026 17:18
…ed behind the newest

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
… views stay in the backend

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
…iews

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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
…emory; 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K1M6bo8kYWd83zXwh2Nobf
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: data plane Runtime ingestion, storage, and query-serving data paths area: query engine PromQL lowering, execution, result shaping, and fallback behavior documentation Improvements or additions to documentation feature: PromQL PromQL compatibility and execution semantics

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant