From eb124051d4bafe1afa11b329a648e668cc25ad7a Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sat, 14 Nov 2026 19:03:35 -0800 Subject: [PATCH 1/8] docs: draft engine redesign proposals from the storage audit Record three structural bets surfaced by the read-only engine audit as Draft proposals, so the reasoning and trade-offs are reviewable before any build: - 0007: additive per-batch rollup aggregates, generalizing the existing read_trace_parts model to the summary rollups so maintenance cost tracks new rows instead of the touched event-time span. - 0008: derive service percentiles from the mergeable span_rollup histogram so alerts, overview and dashboards stop disagreeing, and drop the stored t-digest result. - 0009: append-only manifest catalog, WAL with a head block, and parallel time-ordered compaction, with the freshness-guarantee decision called out as the gating question. Each proposal names the related audit issues and marks itself measurement-gated and incremental; the cheap in-place fixes ship first regardless. --- .../0007-additive-rollup-aggregates.md | 110 ++++++++++++++++++ .../0008-mergeable-latency-sketch.md | 84 +++++++++++++ .../0009-manifest-catalog-wal-compaction.md | 96 +++++++++++++++ 3 files changed, 290 insertions(+) create mode 100644 docs/proposals/0007-additive-rollup-aggregates.md create mode 100644 docs/proposals/0008-mergeable-latency-sketch.md create mode 100644 docs/proposals/0009-manifest-catalog-wal-compaction.md diff --git a/docs/proposals/0007-additive-rollup-aggregates.md b/docs/proposals/0007-additive-rollup-aggregates.md new file mode 100644 index 00000000..7c854a23 --- /dev/null +++ b/docs/proposals/0007-additive-rollup-aggregates.md @@ -0,0 +1,110 @@ +# Additive per-batch rollup aggregates + +Status: Draft +Date: 2026-11-14 +Pull request: TBD + +## Summary + +Replace the raw re-aggregation rollup model for the scan summaries +(`span_rollup`, `log_rollup`, `endpoint_rollup`, and the resource/receiver +summaries) with additive per-batch partial aggregates that are merged at read +and folded during compaction. Cost becomes proportional to newly ingested rows +rather than to the event-time span touched by a pass. Keep watermark +re-aggregation only for the rollups whose output is not a simple additive +merge of per-batch partials. + +## Motivation + +`refreshServiceRollup` discovers the affected keys for a pass, derives one +event-time hull `[min(bucket), max(bucket)+1m)`, and re-scans raw Parquet over +that hull once per key-chunk to rebuild every summary. This has three +structural costs, all surfaced by the engine audit: + +- **A poison pill.** One span with an old `start_time` widens the hull to days, + and the unfiltered `log_agg`/`metric_agg` statements then OOM or hold the + write gate, freezing the watermark for every service-derived rollup. + (See issue: "one late or clock-skewed span stalls every service-derived + rollup".) +- **Cost = chunks × hull.** Unordered affected keys reuse the global `[lo,hi)`, + and the `struct_pack(...) IN (...)` predicate does not push into the Parquet + scan, so each 1000-key chunk decodes the whole hull. A 60k-key backfill is + ~60 chunks × four full span scans. +- **Delete churn and a convention-only uniqueness invariant.** Each pass deletes + its window and reinserts grouped rows, and correctness depends on every + insert path keeping the delete-first/group-by discipline. + +The repository already runs the additive model for `read_trace_parts` and +`read_resource_seconds` via `read_batches` markers and +`transferBatchCacheLocked` (`internal/engine/batch_cache.go:555-589`). This +proposal generalizes that proven mechanism to the summary rollups. + +## Goals and non-goals + +Goals: + +- Make summary-rollup maintenance cost proportional to new rows. +- Remove the event-time hull, the IN-list chunking, the poison pill, and the + per-pass delete churn for the summaries moved onto the model. +- Preserve exact aggregates, histogram bins, NOT NULL keys, and the existing + read contracts. + +Non-goals: + +- No change to the canonical Parquet telemetry format in the first phase (the + partials live in the disposable DuckDB read cache, which is already + version-gated and rebuildable). +- No change to `edge_rollup`, `receiver_rollup`, or the top-128 route fold, + which are join-shaped or order-dependent and stay on watermark + re-aggregation. + +## Design + +Each summary rollup becomes a set of per-batch partial aggregates keyed by the +summary's logical key plus the contributing batch ID, written once when a batch +first enters the read cache, exactly as `read_trace_parts` is today. A read or +a compaction merges the partials additively: + +- Counts and sums add directly. +- `min`/`max` take the extreme. +- Histograms merge by bin (the scale-3 layout already in `span_rollup.hist` + is mergeable). + +Because partials are additive, a duplicate per logical key is expected and +merges correctly, so the uniqueness invariant disappears for these tables and +the ART primary keys become unnecessary (already dropped; see the read-perf +work). A batch's partials are retired when the batch is compacted away, with the +compaction output contributing its own merged partials — the same lifecycle the +trace caches already follow. + +A later phase can compute the partials in Go at `Repository.Commit` and persist +them as an immutable per-batch sidecar, removing DuckDB writes, gates, WAL and +checkpoints for these tables entirely, at the cost of a batch-format bump. + +## Alternatives + +- **Keep raw re-aggregation, fix the cliffs only.** Bucket-order the affected + keys with per-chunk bounds and key-filter the log/metric aggregates. Removes + the poison pill and most of the chunks × hull cost without a model change. + This is the lower-risk fallback if the additive model does not pay off, and + the two are not mutually exclusive — the cliff fixes can ship first. +- **Materialized views.** DuckDB has no incremental materialized views that fit + this ingest pattern; emulating them would reproduce the current rescan. + +## Risks + +- Correctness of additive merges for every statistic, especially histogram bin + alignment and the endpoint top-128 fold (which is why the fold stays on + re-aggregation). +- Read-time merge cost for very long windows; mitigated by folding partials + during compaction so a read never merges more partials than live batches. +- Cache-version and rebuild semantics must cover the new partial tables. + +## Open questions + +- Which summaries move in phase one (proposal: span and log first, endpoint and + resource second)? +- Does the read-time merge stay within the panel latency budget at 30-day + windows, or does it force the compaction-fold step into phase one? +- Measurement: A/B the additive model against the current model on non-pico + data before committing. diff --git a/docs/proposals/0008-mergeable-latency-sketch.md b/docs/proposals/0008-mergeable-latency-sketch.md new file mode 100644 index 00000000..edea9350 --- /dev/null +++ b/docs/proposals/0008-mergeable-latency-sketch.md @@ -0,0 +1,84 @@ +# Mergeable latency sketch and derived service rollup + +Status: Draft +Date: 2026-11-14 +Pull request: TBD + +## Summary + +Stop storing final, unmergeable p50/p95 values in `service_rollup`. Derive +service latency percentiles, error rate, and counts from the mergeable +`span_rollup` histogram and counts at read time, so every surface computes the +same number and any window is re-aggregable. `service_rollup` becomes a thin +derivation (or is removed) rather than an independent summary. + +## Motivation + +`service_rollup` stores a per-minute t-digest result as final `p50_ms`/`p95_ms` +columns. A t-digest result cannot be merged across minutes, so each consumer +invents its own cross-minute combination: + +- Alerts take an unweighted `avg(p95_ms)` and `avg(error_rate)` + (`internal/alert/engine.go:520-530`). +- The overview takes `MAX(p95_ms)` (`internal/observability/latency_sql.go:15`). +- Dashboards merge the `span_rollup` histogram correctly + (`internal/query/rollup_compile.go:75-81`). + +The same service and window therefore reports three different p95 values. (See +issue: "three percentile merges disagree for the same service and window".) +The `span_rollup` histogram is already a mergeable, OTel-style scale-3 +exponential histogram, so the correct value is already computable — it is simply +not used consistently. + +## Goals and non-goals + +Goals: + +- One definition of service p50/p95/error rate, computed from mergeable inputs, + used by alerts, the overview, and dashboards. +- Re-aggregable over any window without a stored final percentile. +- Remove the t-digest scan and the `COUNT(DISTINCT m.name)` aggregate from the + rollup pass. + +Non-goals: + +- No change to the histogram layout or its bin semantics. +- No new precision guarantee beyond what the existing scale-3 histogram gives; + this proposal makes the existing precision consistent, not finer. + +## Design + +Percentiles for a service over a window are read from the summed `span_rollup` +histogram for that service and window, using the same bin-interpolation the +dashboards already use. Error rate is `sum(error spans) / sum(spans)` from the +span counts. Log and metric counts come from `log_rollup` and +`read_metric_names`. Alerts, the overview, and dashboards call one shared helper +so the definition cannot drift again. + +`service_rollup` keeps only the genuinely additive per-minute columns it still +needs as a convenience (counts), or is dropped entirely if nothing needs a +pre-joined per-minute row once percentiles are derived. The rollup tables are a +rebuildable disposable cache, so this needs no batch-format change. + +## Alternatives + +- **Store a mergeable sketch state** (DDSketch or ClickHouse-style + `quantileState`) in `service_rollup` instead of deriving from the histogram. + More storage and a second sketch to maintain, when the span histogram already + carries the information. +- **Pick one of the three existing merges and apply it everywhere.** `avg` and + `MAX` are both wrong; standardizing on a wrong merge is not acceptable. + +## Risks + +- The histogram's bin resolution sets percentile accuracy; confirm it meets the + alerting and overview needs before removing the t-digest. +- Read-time percentile computation cost over long windows; bounded by the + rollup grain and mitigated by the additive-partials proposal (0007). + +## Open questions + +- Keep a slim `service_rollup` for counts, or remove it and read counts from + `span_rollup`/`log_rollup` directly? +- Does deriving percentiles change any alert threshold's observed behavior + enough to need a migration note for existing alert rules? diff --git a/docs/proposals/0009-manifest-catalog-wal-compaction.md b/docs/proposals/0009-manifest-catalog-wal-compaction.md new file mode 100644 index 00000000..90a9a85b --- /dev/null +++ b/docs/proposals/0009-manifest-catalog-wal-compaction.md @@ -0,0 +1,96 @@ +# Manifest catalog, write-ahead log, and parallel compaction + +Status: Draft +Date: 2026-11-14 +Pull request: TBD + +## Summary + +Replace the filesystem-as-catalog model with an append-only manifest, add a +write-ahead log with a queryable head block so an acknowledgement is not a full +Parquet publish, and run compaction in parallel lanes with time-leading span +order. These are coupled bets about the ingest and storage layer; this proposal +records them together and the trade-offs that gate them. + +## Motivation + +The engine audit found the ingest/storage layer correct and crash-safe but +structurally expensive: + +- **Filesystem as catalog.** Boot is proportional to stored data (per batch: + `metadata.json` read twice, three footers, the whole `trace.fidx`), and + `BatchMetadata()` copies and sorts the entire catalog under a lock on every + statement. (Issues: "BatchMetadata copies and sorts the whole catalog"; + startup cost.) +- **No WAL.** Every group commit is a sort, up to three wide Parquet encodes, + up to seven fsyncs, a rename, and a footer re-parse, and it creates a + generation-0 directory re-encoded at least twice. The debt limit, admission + bands, and pressure windows all exist to manage this flood. +- **Single compaction lane with discard-on-preempt**, and span files ordered + trace-hash-first so they have no time locality (day merges capped at 250k + rows, narrow-time queries decode whole files). + +## Goals and non-goals + +Goals: + +- Boot proportional to the manifest, not to stored data. +- One refcounted catalog snapshot per epoch, shared by all readers, replacing + the pin/epoch scheme and the per-statement catalog copy. +- Acknowledge ingest after a bounded append, not a full publish. +- Parallel compaction with no discarded work and time-prunable large files. + +Non-goals: + +- Not a move to an external catalog service or a second storage engine; the + manifest stays a plain local file so ingest fsyncs stay independent of control + state. +- Not a change to UTC `TIMESTAMPTZ_NS` instant semantics. + +## Design + +**Manifest.** An append-only log of edit records (add / replace / prune), each +fsynced, carrying per-batch row counts and event-time bounds, plus namespace and +service sets for pruning. It replaces `metadata.json` re-reads, `replaces.json`, +`pruned`, `COMPACTION.json`, the `.retired` renames, and the large-directory +fsync. Boot is a log replay; a snapshot is a refcounted manifest version, which +subsumes `pinMu`/epoch and lets `BatchMetadata()` become one immutable load. + +**WAL + head block.** Ingest appends group-committed rows to a WAL and +acknowledges after one `fdatasync`; a sorted Parquet batch is cut at a size or +time threshold (~200k–1M rows or a few seconds). This removes one compaction +generation and most of the debt and admission machinery. The head block must +stay queryable, or the product accepts a few seconds of freshness lag — this +conflicts with today's "immediately visible" behavior and must be decided first. + +**Parallel tiered compaction.** Two or more lanes over disjoint input groups, +with no discard-on-preempt. In a new batch-format version, order spans by time +bucket then trace hash, with `trace.fidx` mapping a hash to several ranges, so +large multi-day files stay prunable by row-group statistics and the 250k-row cap +can go. + +## Alternatives + +- **Incremental fixes without the manifest.** The atomic-snapshot fix for + `BatchMetadata()` (issue) and header-only boot loading recover much of the + per-statement and boot cost without the manifest. These should ship first + regardless; the manifest is justified only if those prove insufficient. +- **SQLite as the catalog.** Couples ingest durability to control-plane state + and adds a second fsync domain; rejected in favor of a plain append-only file. + +## Risks + +- The freshness-guarantee decision for the WAL head block is load-bearing and + product-visible. +- A format bump for span ordering must be validated on non-pico data before + adoption, per the no-curve-fitting rule. +- Manifest replay and compaction crash-recovery must match today's + fsync-before-rename durability exactly. + +## Open questions + +- Keep "immediately visible" by making the head block queryable, or accept a + bounded freshness lag? +- Can the manifest ship incrementally (catalog snapshot first, WAL second, + compaction/order third), and which steps need the format bump? +- What is the measured boot and ingest win versus the incremental fixes alone? From 796e4e0805a626ad1ce446a830e9208b97303644 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sun, 15 Nov 2026 08:25:30 -0800 Subject: [PATCH 2/8] docs(proposals): fold three-agent research validation into 0007/0008/0009 Add a dated research-validation section to each engine-redesign proposal, capturing a prior-art/best-in-class pass, an in-codebase correctness and crash-safety pass, and a performance/sequencing pass: - 0007: confirmed as ClickHouse AggregatingMergeTree (-State/-Merge); make the compaction fold mandatory in phase one, state the exactly-once and sum+count-not-avg invariants, and resolve the cross-gate snapshot design. - 0008: confirmed as the Prometheus/OTel exponential-histogram approach; the shared helper must apply the served-kind filter, replicate the served-vs-all choice, pin interpolation, and handle the zero bucket; state the 4.33% bound and add an alert-migration note. Lowest risk; ship first. - 0009: manifest/WAL/compaction each match best-in-class, but parallel compaction is not safe as drafted (single marker/attempt/recovery, overlapping input selection, and a one-merge memory budget all cause data loss or OOM); add manifest checkpointing and a WAL replay bound; incremental fixes ship first (BatchMetadata snapshot already landed in #488). Proposals stay Draft; no production code changed. --- .../0007-additive-rollup-aggregates.md | 54 ++++++++++++++ .../0008-mergeable-latency-sketch.md | 50 +++++++++++++ .../0009-manifest-catalog-wal-compaction.md | 72 +++++++++++++++++++ 3 files changed, 176 insertions(+) diff --git a/docs/proposals/0007-additive-rollup-aggregates.md b/docs/proposals/0007-additive-rollup-aggregates.md index 7c854a23..4a77e2e6 100644 --- a/docs/proposals/0007-additive-rollup-aggregates.md +++ b/docs/proposals/0007-additive-rollup-aggregates.md @@ -108,3 +108,57 @@ checkpoints for these tables entirely, at the cost of a batch-format bump. windows, or does it force the compaction-fold step into phase one? - Measurement: A/B the additive model against the current model on non-pico data before committing. + +## Research validation (2026-11-15) + +A three-angle research pass (prior art, in-codebase fit, performance) was run +before build. Findings: + +**Prior art.** This design is ClickHouse's `AggregatingMergeTree` with the +`-State` / `-Merge` combinators: write a partial aggregate state per batch, +combine states at read, fold states during a background merge. Apache Druid's +ingestion-time rollup is the same idea for the phase-2 immutable sidecar. The +repository already runs this pattern for `read_trace_parts` via +`transferBatchCacheLocked`, so there is an in-repo precedent, not only external +ones. Keeping only associative/commutative stats on the additive model and +leaving non-additive ones (endpoint top-128 fold, joins) on re-aggregation +matches ClickHouse and Pinot guidance exactly. + +**Required revisions before build:** + +1. **Make the compaction fold mandatory in phase one, not an open question.** + ClickHouse's best-known production failure is "too many unmerged parts": a + read-time `-Merge` over thousands of per-batch states is slow, and the whole + design depends on background merges keeping the state count low. Phase one + without the fold reproduces that slowness at long windows. The in-repo + `transferBatchCacheLocked` already folds inputs into the compaction output, + so commit to it from the start. +2. **State the correctness invariants explicitly:** exactly-once contribution (a + batch's partial is counted once across retries via its `read_batches` marker, + and a compaction output *replaces* its inputs, never adds to them); store + `sum` + `count`, never `avg`, and divide at read for error rate and means; + every batch histogram is at the same scale-3 layout so bin-merge is exact + (reject or downscale-align anything else). +3. **Resolve the cross-gate snapshot design.** Moving span/log/endpoint rollups + onto per-batch partials moves them from the writeGate/watermark world to the + cacheGate/`read_batches` world, while `service_rollup` (0008) and + `edge_rollup` stay analytical. A consumer that reads a span partial *and* an + analytical rollup then spans two gates/snapshots and can see a torn view. + AGENTS.md requires maintenance to hold both gates for checkpointing; the + proposal must specify how a reader gets a consistent cross-gate snapshot. +4. **Name the residual.** Phase one keeps partials in the version-gated + disposable cache, so a cache-version bump re-derives all partials from raw + Parquet — the exact full-hull scan this removes, merely deferred to rebuild. + Only the phase-2 immutable Parquet sidecar removes that scan permanently. + +**Status confirmed.** The ART primary keys on `span`/`log`/`endpoint`/`service`/ +`edge_rollup` are already dropped on `main` (`rollup_schema_version` 5), so the +"already dropped" premise holds; the additive model's duplicate-per-batch rows +will not violate a PK. Versioning: a `readCacheVersion` + `rollup_schema_version` +bump (rebuildable, no format bump, no Goose) for phase one; a batch-format bump +only for the phase-2 sidecar. + +**Build readiness:** buildable after the cross-gate design (item 3) is specified +and the compaction fold is committed (item 1). Lower-risk fallback remains the +0007 "cliff fixes" (bucket-order affected keys, per-chunk bounds, key-filter the +log/metric aggregates) if the 30-day read-merge A/B blows the panel budget. diff --git a/docs/proposals/0008-mergeable-latency-sketch.md b/docs/proposals/0008-mergeable-latency-sketch.md index edea9350..61a97be3 100644 --- a/docs/proposals/0008-mergeable-latency-sketch.md +++ b/docs/proposals/0008-mergeable-latency-sketch.md @@ -82,3 +82,53 @@ rebuildable disposable cache, so this needs no batch-format change. `span_rollup`/`log_rollup` directly? - Does deriving percentiles change any alert threshold's observed behavior enough to need a migration note for existing alert rules? + +## Research validation (2026-11-15) + +A three-angle research pass (prior art, in-codebase fit, performance) was run +before build. Findings: + +**Prior art.** Deriving percentiles at read from a summed, mergeable +exponential histogram is exactly how Prometheus native histograms +(`histogram_quantile`), Mimir, and the existing dashboards compute them. The +`span_rollup` histogram is already a scale-3 OTel exponential histogram, whose +relative error is a fixed `(base-1)/(base+1) ≈ 4.33%` per bucket that holds +*through merges* — i.e. it already has DDSketch-class guarantees, so adding a +separate DDSketch/`quantileState` structure buys no new information. Averaging +quantiles (`avg(p95)`, alerts) and `MAX(p95)` (overview) are textbook-wrong; the +fix direction is unambiguously correct. + +**Framing to tighten:** the bug is the stored *scalar* `p50_ms`/`p95_ms` (a +t-digest *result*), which is categorically non-mergeable. A t-digest *state* +would be mergeable but has no formal post-merge error bound (reported >100% tail +error after many merges), whereas the exponential histogram's bound holds through +merges — so "derive from the histogram" is the clearly superior option, not just +a convenient one. State the ±4.33% scale-3 bound in the proposal and use it to +answer the alert-migration question: a threshold near a bucket edge can flip, so +a migration note is required. + +**Required for the shared helper (all surfaces must use it):** + +1. **Apply the served-span kind filter** (`kind NOT IN CLIENT/PRODUCER`, with the + COALESCE-to-all fallback) before merging, or every latency number silently + changes and the "stream held open marks service unhealthy" fix regresses. +2. **Replicate the served-vs-all choice.** Today the overview prefers served + buckets *per bucket*; a window-summed histogram can only choose served-only or + all-span over the whole window. The helper needs both merges and a rule ("use + served if served count > 0 over the window, else all") — close but not + identical to today's per-bucket COALESCE. This is a deliberate, documented + behavior change; decide it before building. +3. **Pin the bin-interpolation method** (match the OTel/Prometheus convention). + Identical bins still disagree under different interpolation — this is the + likeliest way the three-way disagreement returns. +4. Handle the **zero/empty bucket** and gaps, and ensure the histogram's total + count equals the error-rate denominator (**count-base consistency**). + +Also move both alert windows (previous and current) to the helper, and grep for +any remaining reader of `service_rollup.metric_count` before dropping it. + +**Build readiness:** lowest risk of the three; read-side only, no format change, +a `rollup_schema_version` bump (rebuildable). Ship first — it also proves the +`span_rollup` histogram is the canonical input, de-risking 0007. Gate before +build: the item-2 behavior-change decision plus the accuracy A/B +(histogram-derived vs t-digest p95 on the same spans). diff --git a/docs/proposals/0009-manifest-catalog-wal-compaction.md b/docs/proposals/0009-manifest-catalog-wal-compaction.md index 90a9a85b..08301192 100644 --- a/docs/proposals/0009-manifest-catalog-wal-compaction.md +++ b/docs/proposals/0009-manifest-catalog-wal-compaction.md @@ -94,3 +94,75 @@ can go. - Can the manifest ship incrementally (catalog snapshot first, WAL second, compaction/order third), and which steps need the format bump? - What is the measured boot and ingest win versus the incremental fixes alone? + +## Research validation (2026-11-15) + +A three-angle research pass (prior art, in-codebase fit, performance) was run +before build. The direction of all three bets matches best-in-class systems, but +the parallel-compaction bet is **not safe to build as drafted**. Findings by bet: + +**Manifest catalog — strongest-grounded.** Append-only manifest + boot-as-replay ++ one refcounted immutable snapshot shared by all readers is Iceberg +(`metadata.json` → manifest list), Delta Lake (`_delta_log` + checkpoints), and +Lucene (`segments_N` commit points) — the last maps directly onto replacing the +`pinMu`/epoch scheme. **Missing piece (highest value): manifest +checkpointing.** An add/replace/prune log grows unbounded, so boot-replay cost +creeps back to O(history) — the problem relocated into the log. Add a periodic +manifest checkpoint/snapshot, old-record pruning, orphan-file cleanup, and +explicit tombstone / expire-before-delete crash semantics (Delta checkpoints +every ~10 commits; Iceberg has `rewrite_manifests` + snapshot expiry). The +manifest must preserve the pin/epoch guarantee exactly: no reader excluded or +waited for, directories survive until no pin ≤ epoch. + +**WAL + head block.** Ack-after-`fdatasync` + cut a batch at a size/time +threshold is RocksDB/Elasticsearch-standard; a queryable in-memory head is +Prometheus TSDB / Druid real-time / Lucene NRT. **Recommend the queryable-head +path** to preserve today's "immediately visible" contract (AGENTS.md); the +freshness-lag option is a genuine product regression, a fallback only. **Missing +piece: a WAL replay bound** — truncate/rotate/checkpoint the WAL once the head is +cut to Parquet, paired with the manifest checkpoint, or replay is unbounded. + +**Parallel tiered compaction — do NOT build as drafted.** Parallel lanes over +disjoint groups with no discard-on-preempt is RocksDB subcompactions / Lucene +CMS; time-leading span order with a trace-id→row-group index is Grafana Tempo's +vParquet. But against today's single-marker machinery it loses data: + +1. **Per-lane durable state.** There is one `COMPACTION.json`, one + `COMPACTION-ATTEMPT.json`, one staging root, and one `recoverCompaction` that + runs before any pass. Two lanes overwrite each other's marker → on crash the + other lane's already-retired inputs are orphaned with no rollback record + (data loss; the inputs hold the only copy). Needs per-lane markers + attempt + records + per-lane preempt size, and recovery that iterates *all* markers and + protects *both* outputs' `.retired-` sets in cleanup. +2. **Disjoint input partitioning is mandatory.** `selectCompactionBatchesWith- + HigherCap` is not lane-aware; two concurrent calls on the same snapshot can + select overlapping batches (a day group and an hour group both containing + batch X), double-retiring X. Lanes must claim non-overlapping batch sets + atomically under `compactionMu` before releasing to merge, each excluding the + other lane's claimed IDs. +3. **Split the memory budget.** `maxCompactionBytes` (768 MiB) is sized for ONE + merge against the 4 GB DuckDB budget; two concurrent merges double peak RSS + and can OOM. Removing `errCompactionPreempted` is safe **only after** disjoint + partitioning *and* a split/halved per-lane byte budget — otherwise a + preempt-and-retry is traded for an OOM. Reserve ≥1 lane for small/recent + parts so a multi-day merge cannot starve freshness-critical compactions + (ClickHouse/LSM lesson). +4. **Span reorder needs a format bump** (format 5 → 6; the offline sort-tuple + check updates with it), validated on non-pico data per the no-curve-fitting + rule. Accept and document the trace-by-id point-lookup regression: one hash + maps to several row-group ranges, so `trace.fidx` must store *all* ranges and + get-trace unions them (Tempo accepts this with bloom filters + index). + +**Incremental fixes ship first, regardless of the manifest.** The +`BatchMetadata()` atomic pre-sorted snapshot is **already done** (PR #488), so +the per-statement catalog-copy win is banked and the manifest is now justified +only by residual boot cost. Header-only boot loading is still to do and is the +next cheap, invariant-safe win. + +**Build sequence:** (1) decide the WAL freshness guarantee (product call, no +code); (2) header-only boot A/B to settle whether the manifest is even needed; +(3) manifest + checkpointing (no format bump, backfillable); (4) WAL + queryable +head (freshness-gated); (5) parallel compaction + span reorder (format bump, +per-lane durability + disjoint partition + split budget, validated on chip). +Steps 3–5 are each independently revertible pre-release except the format bump, +whose rollback is "rebuild," not "downgrade." From 81b30ffbfaa88d13e3af6fccba1740acc06b8d71 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Sun, 15 Nov 2026 17:49:53 -0800 Subject: [PATCH 3/8] docs(proposals): draft 0010 result-cache extent key and 0011 engine admission; index 0007-0011 0010 addresses the result-cache key fragmentation and sub-refresh TTL (issue #477) with a normalized key and a watermark-split extent cache. 0011 addresses partial, cost-unaware read admission (issue #480) with one admission layer and interactive/panel/background/agent classes. Both are drafts and still need the three-angle research pass before build. Also adds the missing index rows for 0007-0011. --- .../proposals/0010-result-cache-extent-key.md | 130 ++++++++++++++++++ .../0011-engine-admission-classes.md | 125 +++++++++++++++++ docs/proposals/README.md | 5 + 3 files changed, 260 insertions(+) create mode 100644 docs/proposals/0010-result-cache-extent-key.md create mode 100644 docs/proposals/0011-engine-admission-classes.md diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md new file mode 100644 index 00000000..fe6899b4 --- /dev/null +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -0,0 +1,130 @@ +# Result-cache key normalization and an extent cache + +Status: Draft +Date: 2026-11-15 +Pull request: TBD + +## Summary + +Rework the dashboard result cache so a panel's cache key depends only on what +actually changes its result, and so the stable, already-computed part of a +relative window is reused instead of recomputed every refresh. Key on a +normalized panel spec, the resolved bucket interval, and only the variables the +panel references; align relative windows to the resolved step; and cache the +closed buckets older than the rollup watermark with a long TTL, re-querying only +the moving tail. This follows the query-frontend extent cache in Mimir, Cortex, +and Loki, and Druid's per-segment result cache. + +## Motivation + +The result cache (`internal/query/exec.go`, `internal/query/result_cache.go`) +rarely hits, so a single viewer re-runs DuckDB for work it just did. The engine +audit found several independent reasons, all in how the key is built and how +windows are chosen: + +- **Raw pixel width in the key.** The key uses the raw viewport `Width` + (`exec.go:417,478`, `result_cache.go:445-452`) even though `AutoInterval` + (`bucket.go:40-52`) quantizes it to a handful of intervals. Every viewport + width therefore starts its own DuckDB run, although most resolve to the same + bucket grain. +- **Whole-dashboard hashing.** The key hashes the whole dashboard, so any edit + invalidates every panel, and two identical panels on different dashboards + never share a result. +- **All variables, not referenced ones.** The key includes every dashboard + variable rather than only those the panel's query references, so changing an + unrelated variable misses the cache. +- **TTL shorter than the refresh period.** The default TTL is 10s + (`config.go:101`) against a 30s refresh (`exec.go:167-168`), so an entry + expires before the next refresh reads it: a single viewer sees a 0% hit rate. +- **Unaligned relative windows.** Relative windows are not step-aligned, so no + two refreshes cover the same buckets and the cache cannot reuse a prior run. + +(See issue: "result-cache key fragments and TTL is shorter than the refresh +period".) + +## Goals and non-goals + +Goals: + +- A cache key that changes only when the panel's result would change: the + normalized panel spec, the resolved interval, and the referenced variables. +- Hits across refreshes of the same panel, across identical panels on different + dashboards, and across viewport widths that resolve to the same interval. +- Reuse of the stable, closed-bucket portion of a relative window, recomputing + only the tail that is still changing. + +Non-goals: + +- No change to what a panel computes or to the arbitrary-SQL safety boundary. + Normalization is for keying only; it never alters the statement sent to the + engine. +- No change to the rollup watermark or freshness semantics; the extent cache is + bounded by the existing watermark, not a new freshness guarantee. + +## Design + +**Normalized key.** Build the key from a canonical form of the single panel's +query (spec fields in a fixed order, with display-only fields such as raw pixel +width removed), the interval that `AutoInterval` resolves the width to, and only +the variables the panel's query references. Panels that produce the same +statement over the same interval and variables share one entry regardless of the +dashboard they live on or the exact viewport width. + +**Step-aligned relative windows.** Snap a relative window's start and end to the +resolved step before keying and querying, so successive refreshes of a "last 1h" +panel cover the same bucket boundaries and a refresh can reuse the previous +run's buckets. + +**Extent cache.** Split a window at the rollup watermark. Buckets older than the +watermark are closed: their result cannot change, so cache them with a long TTL +keyed by the aligned extent. Re-query only the open tail between the watermark +and now on each refresh, and stitch the cached closed extent to the fresh tail. +This is the query-frontend extent cache used by Mimir, Cortex, and Loki, and +Druid's per-segment result cache. The TTL question above disappears for the +closed portion, because a closed extent is immutable. + +**TTL.** Set the live (tail) TTL at least as long as the refresh period so a +single viewer's own refresh hits, while the closed extents carry their own long +TTL. + +## Alternatives + +- **Just raise the TTL.** Lengthening the TTL past the refresh period fixes the + single-viewer 0% hit rate but leaves the key fragmentation (pixel width, whole + dashboard, all variables, unaligned windows), so cross-panel and cross-refresh + reuse still miss. The TTL change is the cheapest first step and can ship alone, + but it is not sufficient. +- **Cache only whole-window results.** Simpler than an extent cache, but a + relative window never repeats exactly, so a whole-window entry for "last 1h" + is stale on the next refresh. Extents are what make a moving window reusable. + +## Risks + +- Normalization must be exact: two panels share an entry only if their + statements and results are truly identical, so the canonical form must capture + every field that affects the result and nothing that does not. A missed field + would serve a wrong result. +- Stitching a cached closed extent to a fresh tail must preserve the exact + bucket boundaries and any cross-bucket aggregation, or a boundary bucket could + be double-counted or dropped. +- The watermark split must use the same watermark the rollups use, or a closed + extent could cache a bucket that is still changing. + +## Open questions + +- Does the extent cache live at the result-cache layer (keyed extents of the + frame) or deeper, and how does it interact with the result cache's existing + single-flight coalescing? +- Which variables count as "referenced" — only those in the compiled statement, + or also those in filters that were dropped as All? +- What is the measured hit-rate and latency improvement versus the TTL-only + change alone, on non-pico data? + +## Research validation + +This proposal has not yet had the three-angle research pass (prior art, +in-codebase fit, performance) that precedes a build. The prior art named above +(Mimir/Cortex/Loki query-frontend extent cache, Druid per-segment cache) comes +from the audit; it must be validated against the current result-cache and +watermark code before implementation, and the TTL-only first step measured +separately. diff --git a/docs/proposals/0011-engine-admission-classes.md b/docs/proposals/0011-engine-admission-classes.md new file mode 100644 index 00000000..26d1869a --- /dev/null +++ b/docs/proposals/0011-engine-admission-classes.md @@ -0,0 +1,125 @@ +# One cost-aware admission layer at the engine boundary + +Status: Draft +Date: 2026-11-15 +Pull request: TBD + +## Summary + +Put every read through one admission layer at the engine boundary, with a small +set of classes (interactive, panel, background, agent) that shed by deadline +rather than by connection count, and give each panel run a single pinned +snapshot and connection shared by its sub-reads. Today only some readers are +admitted, a slot is just a connection with no notion of thread or memory cost, +and the single background slot lets one rollup pass block the read-cache +refresh. + +## Motivation + +Admission is partial and not cost-aware (`internal/query/exec.go:120-126` and the +engine's slot machinery). The engine audit found three structural problems: + +- **Admission is not global.** Only panels, exemplars, and trace detail pass + through admission. The observability readers + (`internal/observability/{overview,topology,dependencies,trace,health_trend}.go`), + annotations, and variable-option queries (`internal/query/variables.go:70-73,107`) + call the engine directly and compete for the two spare connections and all + DuckDB threads without being admitted or shed. (See issue: "read admission is + neither global nor cost-aware".) +- **A slot has no cost.** A slot is one connection, with no notion of the thread + or memory a statement will use, so a cheap point read and a wide multi-day scan + count the same against the pool. +- **The background slot is a single choke point.** `backgroundSlots` has + capacity 1 (`internal/engine/duck.go:540`), so a rollup pass blocks + `refreshReadCaches` for its full duration. This contradicts the stated intent + that completed-batch writes have their own gate and slot. + +## Goals and non-goals + +Goals: + +- Every read, whatever its entry point, passes through one admission layer, so + load is actually bounded and shedding is uniform. +- Classes with distinct policies: interactive and panel reads are latency-first + and shed by deadline; background and agent work yields to them. +- Admission that accounts for cost (threads, and a memory estimate) rather than + only a connection count. +- One pinned snapshot and one connection per panel run, shared by its sub-reads, + so a panel's several statements see one consistent catalog and do not each take + a separate slot. +- Background work (rollups, read-cache refresh) that no longer serializes behind + a single slot where the design calls for separate gates. + +Non-goals: + +- Not a general query scheduler or priority preemption of running statements in + the first phase; shedding is at admission (by deadline), not mid-flight + cancellation beyond what the existing deadlines already do. +- No change to the pinned-snapshot correctness contract or the write gates' + semantics; this reorganizes who waits, not what a reader sees. + +## Design + +**One admission layer.** Route every engine read — panels, exemplars, trace +detail, the observability readers, annotations, and variable options — through a +single admit call at the engine boundary. Nothing reaches a connection without +being admitted. + +**Classes.** Define a small set: interactive (health checks, variable options, +single-trace detail), panel (dashboard panel runs), background (rollups, +read-cache refresh, compaction-adjacent reads), and agent (LLM-driven queries). +Interactive and panel are latency-first and carry a deadline; admission sheds +them when the wait would exceed the deadline rather than queueing unboundedly. +Background and agent yield to interactive and panel. + +**Cost awareness.** Admit against thread and memory budgets, not only a +connection count, so one wide scan does not crowd out several cheap reads and +the pool reflects what statements actually consume. + +**One snapshot and connection per panel run.** A panel run pins one catalog +snapshot and takes one connection that all of its sub-reads share, so the run is +internally consistent and counts once against admission instead of once per +sub-read. + +**Separate background lanes.** Give the rollup pass and the read-cache refresh +their own admission so a long rollup does not block the read-cache refresh, +honoring the "completed-batch writes have their own gate and slot" intent. + +## Alternatives + +- **Widen the existing slot pool.** More connections without classes or cost + awareness defers the problem: a burst of wide scans still starves interactive + reads, and background work still competes directly. +- **Admit only at the HTTP layer.** Admitting requests before they reach the + engine misses the engine's own background work and the sub-reads a single + request fans out into, which is where the contention actually is. + +## Risks + +- A single admission layer is a central chokepoint; its own overhead and + fairness must be measured so it does not become the bottleneck it manages. +- Deadline-based shedding changes observed behavior: a read that used to queue + and eventually run may now be shed. The classes and deadlines must be chosen + so this only sheds work that would have missed its deadline anyway. +- A memory estimate per statement is approximate; a bad estimate could admit too + much (OOM) or too little (idle pool). Start from a coarse, conservative + estimate and measure. + +## Open questions + +- How is per-statement cost estimated before execution — from the compiled plan, + the file count and window, or a learned estimate? +- Do agent queries get their own class with a separate budget, or share the + panel class with a lower priority? +- How does this layer interact with the result cache's single-flight coalescing + and with the write gates, so a reader is not admitted twice or counted against + two budgets? + +## Research validation + +This proposal has not yet had the three-angle research pass (prior art, +in-codebase fit, performance) that precedes a build. Admission-control and +cost-based class scheduling have strong prior art (database workload management +and admission controllers) that must be surveyed and mapped onto the current +slot and gate machinery before implementation. This is a design-heavy change and +should not be built as a single pass without that validation. diff --git a/docs/proposals/README.md b/docs/proposals/README.md index 385fac3f..6579b786 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -38,5 +38,10 @@ Earlier proposals predate the template and keep their original structure. | 0004 | [Full UI without an LLM key, and PitotQL](0004-pitotql.md) | Accepted | | 0005 | [Dedicated attribute columns and batch format 5](0005-dedicated-attribute-columns.md) | Accepted | | 0006 | [Read performance under sustained ingest](0006-read-performance.md) | Draft | +| 0007 | [Additive per-batch rollup aggregates](0007-additive-rollup-aggregates.md) | Draft | +| 0008 | [Mergeable latency sketch and derived service rollup](0008-mergeable-latency-sketch.md) | Draft | +| 0009 | [Manifest catalog, write-ahead log, and parallel compaction](0009-manifest-catalog-wal-compaction.md) | Draft | +| 0010 | [Result-cache key normalization and an extent cache](0010-result-cache-extent-key.md) | Draft | +| 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Draft | Settled decisions that a proposal leads to are recorded in [../adr](../adr/README.md). From 23bcb290d71fcee1c1a09126178574050d6b6865 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 17 Nov 2026 20:58:05 -0800 Subject: [PATCH 4/8] docs(proposals): add 0011 research validation and phased build sequence Completes the three-angle research pass (prior art, in-codebase fit, performance) 0011 owed, grounded in the v2026.11.8-alpha ccx33 read-gate benchmark for #480. Records the key correction that admission is necessary but not sufficient for the 20 ops/s gate (that binds to 0007/0010 read-cost work), the required revisions, and a four-phase build sequence whose Phase 0 makes admission global by routing the bypass observability/annotations/ variable-option readers through the existing interactive lane. --- .../0011-engine-admission-classes.md | 161 +++++++++++++++++- 1 file changed, 153 insertions(+), 8 deletions(-) diff --git a/docs/proposals/0011-engine-admission-classes.md b/docs/proposals/0011-engine-admission-classes.md index 26d1869a..3133a248 100644 --- a/docs/proposals/0011-engine-admission-classes.md +++ b/docs/proposals/0011-engine-admission-classes.md @@ -115,11 +115,156 @@ honoring the "completed-batch writes have their own gate and slot" intent. and with the write gates, so a reader is not admitted twice or counted against two budgets? -## Research validation - -This proposal has not yet had the three-angle research pass (prior art, -in-codebase fit, performance) that precedes a build. Admission-control and -cost-based class scheduling have strong prior art (database workload management -and admission controllers) that must be surveyed and mapped onto the current -slot and gate machinery before implementation. This is a design-heavy change and -should not be built as a single pass without that validation. +## Research validation (2026-11-17) + +A three-angle research pass (prior art, in-codebase fit, performance) was run +before build, grounded in a fresh Hetzner `ccx33` benchmark of `v2026.11.8-alpha` +(`publish` preset, `--query-rate 20`) that reproduces #480: 3.0/20 ops/s +completed, 1546 errors, 3533 shed, p99 8644 ms; dashboard-refresh 837/1000, +drill-traces 19/1000, trace-detail 75/1000. + +**Headline correction — this proposal is necessary but not sufficient for the +read gate.** Admission bounds concurrency and sheds; it cannot make a scan +cheaper. In the benchmark the box is already at its configured caps (7.9/8 cores +from thread oversubscription — up to `slots`≈10 scans × 8 DuckDB threads on 8 +cores — and 19.4 GiB RSS, which is the `duckDBMemoryPercent=60` limit on 32 GiB +working as designed, not a leak). Reaching 20 ops/s needs ~6.7× more read +throughput, which scheduling cannot manufacture. dashboard-refresh is +rollup-backed and cheap (hence 837/1000); the hard failures are drill-traces and +trace-detail, which scan the **growing raw Parquet snapshot** and are cost-bound. +Those pass only once per-op read cost drops — i.e. **0010** (result-cache extent +reuse) and **0007** (additive rollups so drill/exemplar/trace reads hit an +aggregate instead of re-scanning). This proposal is the stability/fairness layer +that makes the box degrade gracefully while those land. Its own exit test is +**errors → ~0, no thrash pegging, dashboard-refresh goodput up, ingest flat** — +not 20 ops/s, which binds to 0007/0010. + +**Prior art.** The design maps onto established systems: CockroachDB elastic +admission control (Go; gate on runnable-goroutines/CPU and scheduler latency, not +connection count; a cooperatively-yielding elastic/background class), Druid query +laning + automatic prioritization (cost estimated from **segment count × +interval**, a file-count + window heuristic — no plan analysis — with interactive +capacity guaranteed and background lanes capped to spare %), Trino resource +groups (the `slot = 1 connection` model is a documented production bug: one query +spawning many drivers saturates the cluster, so admission must carry a per-query +cost and a bounded queue with explicit reject), Grafana Mimir/Loki query +scheduler (round-robin fairness across classes; isolate the untrusted/agent class +like a misbehaving tenant), and LinkedIn Bouncer / Facebook epoch-LIFO (deadline +admission needs an estimated-wait model and must not shed mid-work-sequence). + +**Current mechanics (in-codebase).** Two separate things exist. The only hard +engine-boundary bound is the read pool `SetMaxOpenConns` (`duck.go:552`), FIFO, +no classes, entered through `readConn`/`acquireRead` (`duck.go:2440-2455`). The +class-aware semaphore `readAdmission` (`admission.go`) lives only in +`query.Executor`, sized to `pool-2` (`sizing.go:56-73`), leaving two raw +connections for annotations and readiness. The collapse is structural: the +observability readers (`overview`/`topology`/`dependencies`/`trace`/ +`health_trend`), annotations, and variable-options call `Duck.QueryContext` +directly and **never pass through `readAdmission`**, so a saturating dashboard +oversubscribes the pool (admitted `pool-2` panels + unbounded observability reads +→ `DB.Conn` blocks), defeating deadline shedding and even starving the two +reserved connections. + +**Required revisions before build:** + +1. **Bind the success criterion.** 0011's exit test is errors→~0 / no thrash / + dashboard-refresh goodput up / ingest flat. The 20 ops/s gate binds to + 0007 + 0010 (read cost), not here. Do not benchmark 0011 against a target it + structurally cannot hit. +2. **Overload signal is measured, not connection count.** Gate on DuckDB + worker-thread saturation + measured admission queue-wait (+ runnable + goroutines/CPU, available cheaply in Go). Delete "2 spare connections" as the + control variable. **Under-admit relative to cores** (Cockroach #91536: even a + perfect layer loses isolation if it admits more concurrent work than the + thread pool runs without scheduler-latency blowup — do not admit 8 scans on 8 + cores). +3. **Cost estimate v1 = file-count-in-window × window-span** (Druid), bucketed + into coarse cost classes (cheap rollup read / single raw-scan / multi-statement + panel fan-out). Explicitly **not** a DuckDB plan (no reliable pre-exec memory + estimate). Keep DuckDB's own `memory_limit` as the hard backstop (AGENTS: keep + defaults). Compute the estimate from already-maintained catalog stats + (`updateParquetStats`) + footer bounds, **outside** the admission mutex. Peak + memory depends on query shape (GROUP BY / DISTINCT / VARIANT), not file bytes, + so charge a class, not a precise prediction, and feed observed cost back to + correct it (SQL Server grant-feedback). `applyMemoryHeadroom` already turns a + misgrant into a clean Retryable error, not a crash. +4. **Charge per-class thread + memory budget and a per-query thread cap** (Trino; + SQL Server `REQUEST_MAX_MEMORY_GRANT_PERCENT` analog) so one wide scan cannot + serialize the box inside a single slot. +5. **Bounded queue + explicit reject** per class (panels/dashboard-refresh → a + `ErrBusy` 503 + Retry-After the UI renders; agent → retriable). Never an + unbounded wait. +6. **Admit the panel run as a unit.** The one pinned snapshot+connection shared by + a panel's sub-reads is a work-sequence: grant admission once for the whole run + against its total estimated cost; sub-reads inherit it and never re-queue + (epoch-LIFO breaks sequences — a panel whose first sub-reads succeeded must not + have later ones shed). This is also the **only** part of 0011 that reduces + cost rather than bounding it (reuse one snapshot/scan across a panel's ~6-7 + serial statements — `runScope`, `totals`, previous-period, `attachTableTrends`, + `annotationScope`, `applyMetricUnit`, `diagnose`; a 15-panel refresh is ~90 + statements today), so measure it by statements-per-panel and snapshot-cache hit + rate. +7. **Deadline shedding must close long readers promptly.** A per-run shared read + transaction extends reader lifetime, and a non-FORCE `CHECKPOINT` refuses while + a reader that began before the last write commit is still open + (`duck.go:131-141,781`) → unbounded WAL growth on a busy instance. Keep readers + short or checkpointing starves. Capture the Parquet pin **and** the DuckDB MVCC + read tx once at run start, or sub-reads tear across a publish/commit boundary. +8. **Preserve the existing `panelBatchAdmission` invariants** (lifetime-bounded + `reserveBatch`, panels retain one progress slot, interactive borrows idle + slots). Extract the pure semaphore core into an engine-owned type the engine + gates on in `readConn`; keep the batch-ticket logic as a thin query-layer + wrapper. A full rewrite risks re-introducing solved bugs (panel starvation, + unbounded resume population, the #481 memory loop). +9. **Round-robin fairness across classes**; treat the agent/arbitrary-SQL class as + the untrusted tenant with the hardest caps, killable by deadline (poison query). +10. **Keep the admit decision O(1) and lock-free during execution** (admit → + release the admission lock → execute); per-class FIFO, not a global + priority-heap reorder churned by thousands of sheds — or the central layer + becomes the bottleneck it manages. + +**Phased build sequence** (each independently shippable; later phases gated on +earlier measurements, A/B on chip x86_64 / Hetzner, never pico): + +- **Phase 0 — make admission global (pure plumbing, no policy, ship first).** + Route every bypass reader (`observability.{overview,topology,dependencies, + trace,health_trend}`, annotations, `query.variables` options) through the + existing `readAdmission` interactive lane via an admitting + `queryrows.Queryer`/`ReadTransactioner` wrapper defined in package `query` + (`observability` must not import `query`; `query` already imports it) and passed + into `observability.New`/`annotations.New` at wiring time. The wrapper holds the + slot **across row iteration** (release on `Rows.Close`, mirroring the engine's + `lockedRows`) and admits via the caller's own deadline. This restores the pool + invariant (admitted ≤ `pool-2` < pool), so a saturating dashboard can no longer + starve `DB.Conn`; bypass reads are deadline-shed as `ErrBusy` instead of piling + up, and refusals feed the existing `interactiveRefusals` → ingest backpressure. + Wrapping the injected `db` fixes the MCP observability path too. Add the metrics + every later phase needs: per-path queue depth, wait, admit/reject counts, DuckDB + thread saturation, runnable-goroutines/CPU. `Duck.Trace` (snapshot-pinned, + index-bounded, takes no pool connection) stays raw for now. This directly + addresses the measured "unadmitted readers oversubscribe the pool" collapse and + yields the clean baseline that quantifies how much per-op cost 0007/0010 must + still remove. +- **Phase 1 — split the background choke.** `backgroundSlots` is one permit + (`duck.go:35/680/692`) shared by rollups and the read-cache refresh even though + they already write disjoint tables under disjoint gates (`writeGate` vs + `cacheGate`). Give the read-cache refresh its own lane so a rollup pass cannot + block it; maintenance/checkpoint must hold both lanes (as it already holds both + gates); watch the doubled concurrent background memory (#481). Secondary: + read-vs-background is not the primary bench contention (ingest is flat). +- **Phase 2 — classes + bounded queue + deadline shed.** Four classes + (interactive/panel/background/agent), round-robin, per-class `maxQueued`, + admit-time deadline shedding using the Phase-0 service-time EWMA; admit panels + as a unit (revision 6). +- **Phase 3 — cost-aware admission (highest uncertainty, last).** file-count × + window cost estimate, per-class thread+memory budgets and per-query thread cap, + observed-cost feedback. Ship behind the metrics proving Phases 0-2 recovered + most of the collapse. + +The per-run shared snapshot+connection (the one cost-reducing move) folds into +Phase 2/3 and carries the checkpoint-refusal hazard (revision 7), so it is not in +the Phase 0 slice. + +**Build readiness.** Phase 0 is buildable now: bounded, additive, no policy, no +engine/snapshot/sizing change. Phases 2-3 are gated on Phase-0 production metrics +and per-phase A/B. The 20 ops/s gate stays owned by 0007/0010. From d671c5f500b2c4f71c853c691490f879a415d030 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Wed, 18 Nov 2026 02:42:53 -0800 Subject: [PATCH 5/8] docs(proposals): add 0010 research validation and phased build sequence Completes the three-angle research pass 0010 owed. Records the key correction that the result/extent cache is a repeated-request and cross-viewer efficiency change, not a lever for the sustained read-rate gate (the failing drill-traces and trace-detail ops are a ranking scan and a trace_id point lookup that the extent cache cannot split; 0007 owns those). Splits the cheap key+TTL normalization from the extent cache, gates the extent cache behind 0007, pins the closed/open boundary to the snapshot-consistent coverage horizon with the rollup safety-lag, and sequences the build TTL -> normalized key -> step-aligned windows -> extent cache. --- .../proposals/0010-result-cache-extent-key.md | 142 +++++++++++++++++- 1 file changed, 136 insertions(+), 6 deletions(-) diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md index fe6899b4..06af21c4 100644 --- a/docs/proposals/0010-result-cache-extent-key.md +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -122,9 +122,139 @@ TTL. ## Research validation -This proposal has not yet had the three-angle research pass (prior art, -in-codebase fit, performance) that precedes a build. The prior art named above -(Mimir/Cortex/Loki query-frontend extent cache, Druid per-segment cache) comes -from the audit; it must be validated against the current result-cache and -watermark code before implementation, and the TTL-only first step measured -separately. +A three-angle research pass (prior art, in-codebase fit, performance) was run +before build, grounded in the current result-cache code and the +`v2026.11.8-alpha` read-gate benchmark. + +**Headline correction — 0010 is a repeated-request / cross-viewer efficiency +change, not a lever for the sustained read-rate gate.** The gate fails on +`drill-traces` (19/1000) and `trace-detail` (75/1000). Neither is a time-bucketed +additive aggregate the extent cache can split and stitch: `trace-detail` is a +point lookup by `trace_id` and is already whole-result-cached end to end +(`cachedTraces.Trace`), and `drill-traces` is a ranking/dedup scan over the +window that does not decompose over per-bucket partials. The one op the extent +cache fits — `dashboard-refresh`, which reads the bucketed `service_rollup` — is +the cheap, already-passing op (837/1000). And result caching only helps +*repeated* keys: a load that reads varied traces gets a ~0% hit rate whatever the +TTL or key shape. So **0007 owns the two failing ops** (make drill/aggregate reads +hit rollups instead of raw scans; a `trace_id` point lookup is cost-bound on the +trace index regardless), **0011 owns p99 under pressure**, and 0010 improves +multi-viewer and refresh-cadence efficiency on top. State this in the proposal: +do not credit 0010 with gate throughput. + +**Prior art.** The extent cache is the Grafana Mimir/Cortex/Thanos query-frontend +pattern: split a range query, cache answered extents, detect partial overlap, +re-query only the missing sub-range, stitch cached + fresh. Step alignment +(`align-queries-with-step`) is their precondition for caching a range at all. +Thanos `response-cache-max-freshness` (default 1m) is a time-based "do not cache +the moving tail" floor; pitot's rollup watermark is a better, data-driven version +of the same guard — keep both (`min(watermark, now − freshness)`). TimescaleDB +real-time continuous aggregates are the watermark split as a storage primitive +(`cagg_watermark`: read materialized below, compute live above) and carry the +late-data caution. Druid per-segment caching keys on an immutable boundary and +never caches the real-time segment. ClickHouse's query cache keys on the +canonical AST with display-only settings stripped and refuses non-deterministic +queries by default (the `now()` trap). Request coalescing +(`golang.org/x/sync/singleflight`) is the stampede guard — pitot already has an +equivalent (`cacheFlight`). + +**Current mechanics (in-codebase).** `panelCacheKey` +(`result_cache.go:456`) keys on `Spec` (a sha256 of the *whole* dashboard JSON — +any panel edit busts every panel), `Vars` (*all* resolved variables, not the +panel's referenced set), and `Width` (the *raw* pixel width), confirming audit +items (a)-(c). `QueryCacheTTL` defaults to `10s` (`config.go:101`) against the +~30s refresh, so a lone viewer's scheduled refresh always ages out → cold miss +(item d). `AutoInterval` (`bucket.go:40-52`) quantizes width over a fixed ladder, +so a wide band of pixel widths resolves to the same interval — the resolved +interval, not the raw width, is the only width-derived input that changes a +result. A per-panel referenced-variable set is cheaply derivable from +`checked.Filters[p.ID]` → `Filter.Params` (plus SQL-AST params for arbitrary-SQL +panels, plus any measure params). The single-flight (`cacheFlight`, +`result_cache.go:80`) and LRU bounds (1024 entries / 64 MiB, +`sizing.go:47-48`) already exist. `TestPanelCacheKeyCoversRequest` guards the key +shape and must be extended with any change. + +**Watermark — use the snapshot-consistent horizon.** The proposal says "the same +watermark the rollups use," but there are two: `RollupWatermark` +(`duck.go:2740`, an in-memory atomic resolved in a standalone preflight, *not* +tied to the panel's pinned Parquet snapshot) and `coverage.FreshTo()` +(`exec.go:751`, read inside the panel's read transaction). The extent split must +use the **snapshot-consistent** `coverage.FreshTo()`, or a closed extent can be +cached against a horizon the panel's own snapshot does not match. The freshness +signal is resolved today only for rollup-planned panels (`exec.go:731-749`); raw +spans/logs panels have no exposed ingest horizon, so for them the closed boundary +must come from footer event-time bounds or the split falls back to off. + +**Required revisions before build:** +1. **Reframe the contribution** (above): 0010 is cross-viewer/repeated-request + efficiency; the failing ops belong to 0007; measuring ~0 gate movement from + 0010 alone is the expected, confirming result. +2. **Split Feature 1 (key + TTL normalization) from Feature 2 (extent cache).** + Feature 1 is cheap and independently valuable. **Gate the extent cache behind + 0007** — it only pays off once there is an additive aggregate to split, and it + needs the watermark/safety-lag boundary to exist. +3. **Resolve and step-align the relative window before it touches the key or the + query** — one operation, not two. The key carries the resolved, + interval-aligned `[start, end)`, never the literal range or an unresolved + `now()` (the non-determinism trap). +4. **Closed/open boundary = `min(coverage.FreshTo(), now − safety_lag)`**, reusing + the rollup's existing safety-lag, never wall clock, with a `max-freshness` + floor as belt-and-suspenders against late data. +5. **Half-open `[start, end)` stitch at `floor(freshTo, interval)` on the + `1970-01-01` bucket grid**, so the boundary bucket is counted exactly once + (mirror the clip discipline in `limitBatchFrames`, `exec.go:619`); **recompute + Totals over the full window** rather than stitching them (Totals are a separate + no-bucket scan). +6. **Referenced-variable set must be the transitive closure** (a variable + expression can reference other variables); under-computing it serves a wrong + result. Keep and extend `TestPanelCacheKeyCoversRequest` with a property check + (same reduced key ⇒ identical result under perturbation of the dropped fields). +7. **Bounded memory for extent entries.** A long TTL does not protect an entry + from LRU eviction in the shared 64 MiB pool, and storing a whole-window result + per refresh explodes entry count; store the closed-prefix aggregate once per + `(panel, interval, referenced-vars)` and give extent entries a separate budget + or reservation. +8. **Subscribe the extent cache to compaction/retention invalidation** (the engine + already must invalidate retired contributions), or a closed extent will serve + data for files compacted away. +9. **Key normalization is key-only.** It never alters the statement sent to the + engine; arbitrary-SQL panels are key-normalization-only in the first phases and + opt out of the extent split (they carry a `metricLookback` back-scan the split + must respect). + +**Phased build sequence:** +- **Phase 1 — TTL ≥ refresh (one line).** Raise the `QueryCacheTTL` default past + the refresh period (`config.go:101`, e.g. `60s`); the stale-while-revalidate + path already serves one background refresh. Converts a lone viewer from ~0% to a + high hit rate. Zero code-path change. +- **Phase 2 — normalized key.** Replace `Width` with the resolved interval, scope + `Vars` to the panel's referenced set, and (last, largest) move from the + whole-dashboard hash to a per-panel spec hash. Pure key change; coarser keys + make more requests coalesce onto one flight. Update the covering test. +- **Phase 3 — step-aligned relative windows** (`resolveWindow`, + `timerange.go`), compatible with the `1970-01-01` grid and SQL `metricLookback`. + Makes consecutive refreshes target identical bucket ranges (precondition for any + extent reuse) and stabilizes the Phase-2 key across refreshes. +- **Phase 4 — extent cache (hardest, gated behind 0007).** Split at + `floor(coverage.FreshTo(), interval)`, cache the closed half under a + watermark-pinned long-TTL fixed-window flight, re-query only the tail, stitch + half-open. Highest correctness surface (watermark race, boundary bucket, + invalidation); gate on those tests and a measured long-window raw-aggregate cost. + +**Risks (ranked):** (1) a watermark race caches a still-changing bucket and the +long TTL serves it wrong for the whole TTL; (2) stitch-seam double-count or drop; +(3) the referenced-variable reduction drops a result-affecting field; (4) LRU +eviction defeats the long TTL, or extent entries blow the 64 MiB budget; (5) the +step-aligned window is a visible semantic change interacting with the existing +relative-vs-fixed stamp logic. + +**Measurement.** A/B one lever per branch against the same Hetzner ccx33 read +gate, never co-merged: 0007 should move `drill-traces`/`trace-detail`; 0010 +should move the multi-viewer hit rate and `dashboard-refresh` cost but **not** the +failing ops; 0011 changes p99. Add a multi-viewer test (a single stream cannot +exercise cross-viewer sharing) and report the cache hit rate so a gain is not +mis-attributed. + +**Build readiness.** Phases 1-2 are buildable now, cheap and low-risk, and ship +independently of 0007. Phases 3-4 follow, with Phase 4 gated behind 0007 and the +correctness tests above. From 04cf376386086643be43accf79c121b970d6e912 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 1 Dec 2026 12:22:44 -0800 Subject: [PATCH 6/8] docs(proposals): address review findings across 0008-0011 --- .../0008-mergeable-latency-sketch.md | 24 ++-- .../0009-manifest-catalog-wal-compaction.md | 26 +++-- .../proposals/0010-result-cache-extent-key.md | 110 +++++++++++------- .../0011-engine-admission-classes.md | 87 ++++++++------ 4 files changed, 148 insertions(+), 99 deletions(-) diff --git a/docs/proposals/0008-mergeable-latency-sketch.md b/docs/proposals/0008-mergeable-latency-sketch.md index 61a97be3..bd18ac3d 100644 --- a/docs/proposals/0008-mergeable-latency-sketch.md +++ b/docs/proposals/0008-mergeable-latency-sketch.md @@ -91,21 +91,27 @@ before build. Findings: **Prior art.** Deriving percentiles at read from a summed, mergeable exponential histogram is exactly how Prometheus native histograms (`histogram_quantile`), Mimir, and the existing dashboards compute them. The -`span_rollup` histogram is already a scale-3 OTel exponential histogram, whose -relative error is a fixed `(base-1)/(base+1) ≈ 4.33%` per bucket that holds -*through merges* — i.e. it already has DDSketch-class guarantees, so adding a -separate DDSketch/`quantileState` structure buys no new information. Averaging -quantiles (`avg(p95)`, alerts) and `MAX(p95)` (overview) are textbook-wrong; the -fix direction is unambiguously correct. +`span_rollup` histogram is already a scale-3 OTel exponential histogram +(`γ = 2^(1/8) ≈ 1.09051` per positive bucket; harmonic-midpoint bucket precision +`(γ-1)/(γ+1) ≈ 4.33%`). Under `rollupQuantileSQL`'s linear within-bucket +interpolation (`internal/query/rollup_compile.go:75-82`), positive quantile +estimates stay within the target rank's bucket `(L, γL]`, giving a worst-case +relative error of `[-8.30%, +9.05%]` (`1 - γ^-1` to `γ - 1`, bounded by +`γ - 1 ≈ 9.05%`) that holds *through merges* — i.e. it already has +DDSketch-class post-merge guarantees, so adding a separate +DDSketch/`quantileState` structure buys no new information. Averaging quantiles +(`avg(p95)`, alerts) and `MAX(p95)` (overview) are textbook-wrong; the fix +direction is unambiguously correct. **Framing to tighten:** the bug is the stored *scalar* `p50_ms`/`p95_ms` (a t-digest *result*), which is categorically non-mergeable. A t-digest *state* would be mergeable but has no formal post-merge error bound (reported >100% tail error after many merges), whereas the exponential histogram's bound holds through merges — so "derive from the histogram" is the clearly superior option, not just -a convenient one. State the ±4.33% scale-3 bound in the proposal and use it to -answer the alert-migration question: a threshold near a bucket edge can flip, so -a migration note is required. +a convenient one. State `rollupQuantileSQL`'s `≤ 9.05%` (`2^(1/8) - 1`) scale-3 +interpolation bound in the proposal and use it to answer the alert-migration +question: a threshold within one bucket width can flip, so a migration note is +required. **Required for the shared helper (all surfaces must use it):** diff --git a/docs/proposals/0009-manifest-catalog-wal-compaction.md b/docs/proposals/0009-manifest-catalog-wal-compaction.md index 08301192..b021891b 100644 --- a/docs/proposals/0009-manifest-catalog-wal-compaction.md +++ b/docs/proposals/0009-manifest-catalog-wal-compaction.md @@ -18,10 +18,11 @@ The engine audit found the ingest/storage layer correct and crash-safe but structurally expensive: - **Filesystem as catalog.** Boot is proportional to stored data (per batch: - `metadata.json` read twice, three footers, the whole `trace.fidx`), and - `BatchMetadata()` copies and sorts the entire catalog under a lock on every - statement. (Issues: "BatchMetadata copies and sorts the whole catalog"; - startup cost.) + `metadata.json` read twice, up to three footers, the whole `trace.fidx`, and + `logs.fidx` fences), and directory retirement (`pinMu`/epoch) plus indexed + batch capture (`catalog()`) remain separate from `BatchMetadata()`'s atomic + snapshot. (See startup-cost issue; the per-statement `BatchMetadata()` copy + and sort was already removed in PR #488.) - **No WAL.** Every group commit is a sort, up to three wide Parquet encodes, up to seven fsyncs, a rename, and a footer re-parse, and it creates a generation-0 directory re-encoded at least twice. The debt limit, admission @@ -35,8 +36,9 @@ structurally expensive: Goals: - Boot proportional to the manifest, not to stored data. -- One refcounted catalog snapshot per epoch, shared by all readers, replacing - the pin/epoch scheme and the per-statement catalog copy. +- One refcounted catalog snapshot per epoch, shared by all readers, unifying + `BatchMetadata()`'s immutable snapshot with indexed batch handles and + replacing the separate `pinMu`/epoch retirement scheme. - Acknowledge ingest after a bounded append, not a full publish. - Parallel compaction with no discarded work and time-prunable large files. @@ -54,7 +56,8 @@ fsynced, carrying per-batch row counts and event-time bounds, plus namespace and service sets for pruning. It replaces `metadata.json` re-reads, `replaces.json`, `pruned`, `COMPACTION.json`, the `.retired` renames, and the large-directory fsync. Boot is a log replay; a snapshot is a refcounted manifest version, which -subsumes `pinMu`/epoch and lets `BatchMetadata()` become one immutable load. +subsumes `pinMu`/epoch and backs `BatchMetadata()` and indexed readers from one +immutable version. **WAL + head block.** Ingest appends group-committed rows to a WAL and acknowledges after one `fdatasync`; a sorted Parquet batch is cut at a size or @@ -72,9 +75,10 @@ can go. ## Alternatives - **Incremental fixes without the manifest.** The atomic-snapshot fix for - `BatchMetadata()` (issue) and header-only boot loading recover much of the - per-statement and boot cost without the manifest. These should ship first - regardless; the manifest is justified only if those prove insufficient. + `BatchMetadata()` (shipped in PR #488) and header-only boot loading recover + the per-statement cost and much of the boot cost without the manifest. + Header-only boot loading should ship first regardless; the manifest is + justified only if residual boot and retirement cost still warrants it. - **SQLite as the catalog.** Couples ingest durability to control-plane state and adds a second fsync domain; rejected in favor of a plain append-only file. @@ -147,7 +151,7 @@ vParquet. But against today's single-marker machinery it loses data: preempt-and-retry is traded for an OOM. Reserve ≥1 lane for small/recent parts so a multi-day merge cannot starve freshness-critical compactions (ClickHouse/LSM lesson). -4. **Span reorder needs a format bump** (format 5 → 6; the offline sort-tuple +4. **Span reorder needs a format bump** (format 6 → 7; the offline sort-tuple check updates with it), validated on non-pico data per the no-curve-fitting rule. Accept and document the trace-by-id point-lookup regression: one hash maps to several row-group ranges, so `trace.fidx` must store *all* ranges and diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md index 06af21c4..3d9e287c 100644 --- a/docs/proposals/0010-result-cache-extent-key.md +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -55,11 +55,14 @@ Goals: Non-goals: -- No change to what a panel computes or to the arbitrary-SQL safety boundary. - Normalization is for keying only; it never alters the statement sent to the - engine. -- No change to the rollup watermark or freshness semantics; the extent cache is - bounded by the existing watermark, not a new freshness guarantee. +- No change to compiled SQL or to the arbitrary-SQL safety boundary. Key + normalization (Phase 2) is for keying only and never alters the statement or + parameters sent to the engine; only step-aligned relative windows (Phase 3) + change query inputs, by snapping bucketed relative `[start, end)` bounds to + the resolved step grid (which shifts edge-bucket membership; see Risks). +- No relaxation of freshness semantics; the extent split uses the existing + snapshot-consistent rollup horizon and invalidates closed extents when late + publications, compaction, or retention touch their event-time range. ## Design @@ -70,22 +73,32 @@ the variables the panel's query references. Panels that produce the same statement over the same interval and variables share one entry regardless of the dashboard they live on or the exact viewport width. -**Step-aligned relative windows.** Snap a relative window's start and end to the -resolved step before keying and querying, so successive refreshes of a "last 1h" -panel cover the same bucket boundaries and a refresh can reuse the previous -run's buckets. - -**Extent cache.** Split a window at the rollup watermark. Buckets older than the -watermark are closed: their result cannot change, so cache them with a long TTL -keyed by the aligned extent. Re-query only the open tail between the watermark -and now on each refresh, and stitch the cached closed extent to the fresh tail. -This is the query-frontend extent cache used by Mimir, Cortex, and Loki, and -Druid's per-segment result cache. The TTL question above disappears for the -closed portion, because a closed extent is immutable. - -**TTL.** Set the live (tail) TTL at least as long as the refresh period so a -single viewer's own refresh hits, while the closed extents carry their own long -TTL. +**Step-aligned relative windows.** For bucketed queries (`interval > 0`), snap a +relative window's start and end to the resolved step grid before keying and +querying (`ceil` on `end` so live sub-step events are not dropped), so +successive refreshes of a "last 1h" panel cover aligned bucket boundaries and a +refresh can reuse prior buckets. Unbucketed raw panels keep exact `[start, end)` +bounds. + +**Extent cache.** Split a bucketed window at the snapshot-consistent rollup +horizon (`min(coverage.FreshTo(), now - safety_lag)`). Buckets older than that +horizon are closed unless late-arriving data lands in their event-time range, so +cache them with a long TTL keyed by the aligned extent and re-query only the +open tail on each refresh, stitching the cached closed extent to the fresh tail +(following Mimir, Cortex, Loki, and Druid). Because `FreshTo` tracks ingest time +rather than event time, a later batch can still carry events inside `[start, +split)`: the extent cache subscribes to batch publication (using each batch's +`SpanTime`/`LogTime`/`MetricTime` footer bounds, treating unknown bounds as +overlapping; for rollup-backed extents, firing when the batch's rollup/partial +write commits) as well as compaction and retention retirement, immediately +evicting any overlapping closed extent. + +**TTL and revalidation.** Set the live (tail) TTL at least as long as the +refresh period and retain today's half-TTL background stale-while-revalidate on +the live tail (and on whole-window entries before Phase 4). Closed extents omit +periodic half-TTL background polling because overlapping publications and +retirements evict them directly; their long TTL acts only as a bounded expiry +backstop. ## Alternatives @@ -136,11 +149,13 @@ window that does not decompose over per-bucket partials. The one op the extent cache fits — `dashboard-refresh`, which reads the bucketed `service_rollup` — is the cheap, already-passing op (837/1000). And result caching only helps *repeated* keys: a load that reads varied traces gets a ~0% hit rate whatever the -TTL or key shape. So **0007 owns the two failing ops** (make drill/aggregate reads -hit rollups instead of raw scans; a `trace_id` point lookup is cost-bound on the -trace index regardless), **0011 owns p99 under pressure**, and 0010 improves -multi-viewer and refresh-cadence efficiency on top. State this in the proposal: -do not credit 0010 with gate throughput. +TTL or key shape. So dedicated trace proposals own the two failing ops — +**0012** (bounded per-minute span exemplars, #504) owns `drill-traces` and +**0013** (per-batch `logs.fidx` trace-log index and fenced index probes, #507) +owns `trace-detail`, while **0007** covers summary-rollup aggregates only — +**0011 owns p99 under pressure**, and 0010 improves multi-viewer and +refresh-cadence efficiency on top. State this in the proposal: do not credit +0010 (or 0007) with trace-read gate throughput. **Prior art.** The extent cache is the Grafana Mimir/Cortex/Thanos query-frontend pattern: split a range query, cache answered extents, detect partial overlap, @@ -187,8 +202,9 @@ must come from footer event-time bounds or the split falls back to off. **Required revisions before build:** 1. **Reframe the contribution** (above): 0010 is cross-viewer/repeated-request - efficiency; the failing ops belong to 0007; measuring ~0 gate movement from - 0010 alone is the expected, confirming result. + efficiency; the failing trace ops belong to 0012 and 0013 (while 0007 covers + summary-rollup aggregates); measuring ~0 gate movement from 0010 alone is the + expected, confirming result. 2. **Split Feature 1 (key + TTL normalization) from Feature 2 (extent cache).** Feature 1 is cheap and independently valuable. **Gate the extent cache behind 0007** — it only pays off once there is an additive aggregate to split, and it @@ -214,13 +230,19 @@ must come from footer event-time bounds or the split falls back to off. per refresh explodes entry count; store the closed-prefix aggregate once per `(panel, interval, referenced-vars)` and give extent entries a separate budget or reservation. -8. **Subscribe the extent cache to compaction/retention invalidation** (the engine - already must invalidate retired contributions), or a closed extent will serve - data for files compacted away. -9. **Key normalization is key-only.** It never alters the statement sent to the - engine; arbitrary-SQL panels are key-normalization-only in the first phases and - opt out of the extent split (they carry a `metricLookback` back-scan the split - must respect). +8. **Subscribe the extent cache to late-publication, compaction, and retention + invalidation.** `FreshTo` is an ingest-time horizon, so a newly published + batch (or its committed rollup/partial pass) whose signal event-time bounds + overlap `[start, split)` — or unknown footer bounds — must evict matching + closed extents alongside compaction/retention retirement; closed extents then + skip periodic half-TTL background polling and rely on long-TTL expiry as a + safety net, while the live tail retains half-TTL revalidation. +9. **Key normalization is key-only; step alignment is Phase 3 only.** Phase 2 + never alters the statement or bounds sent to the engine (only Phase 3 rounds + relative bucketed `[start, end)` bounds); arbitrary-SQL panels are + key-normalization-only in the first phases and opt out of both step alignment + and the extent split (they carry a `metricLookback` back-scan the split must + respect). **Phased build sequence:** - **Phase 1 — TTL ≥ refresh (one line).** Raise the `QueryCacheTTL` default past @@ -236,10 +258,13 @@ must come from footer event-time bounds or the split falls back to off. Makes consecutive refreshes target identical bucket ranges (precondition for any extent reuse) and stabilizes the Phase-2 key across refreshes. - **Phase 4 — extent cache (hardest, gated behind 0007).** Split at - `floor(coverage.FreshTo(), interval)`, cache the closed half under a - watermark-pinned long-TTL fixed-window flight, re-query only the tail, stitch - half-open. Highest correctness surface (watermark race, boundary bucket, - invalidation); gate on those tests and a measured long-window raw-aggregate cost. + `floor(min(coverage.FreshTo(), now - safety_lag), interval)`, cache the closed + half under an aligned `[start, split)` long-TTL flight evicted on overlapping + batch/rollup publication or retirement (no half-TTL timer polling on closed + extents), re-query only the tail with live-TTL + half-TTL revalidation, and + stitch half-open. Highest correctness surface (watermark race, late-data + invalidation, boundary bucket); gate on those tests and a measured long-window + raw-aggregate cost. **Risks (ranked):** (1) a watermark race caches a still-changing bucket and the long TTL serves it wrong for the whole TTL; (2) stitch-seam double-count or drop; @@ -249,9 +274,10 @@ step-aligned window is a visible semantic change interacting with the existing relative-vs-fixed stamp logic. **Measurement.** A/B one lever per branch against the same Hetzner ccx33 read -gate, never co-merged: 0007 should move `drill-traces`/`trace-detail`; 0010 -should move the multi-viewer hit rate and `dashboard-refresh` cost but **not** the -failing ops; 0011 changes p99. Add a multi-viewer test (a single stream cannot +gate, never co-merged: 0012 moves `drill-traces` and 0013 moves `trace-detail`, +while 0007 moves summary-rollup maintenance and rollup-backed aggregate panels; +0010 should move the multi-viewer hit rate and `dashboard-refresh` cost but +**not** the failing trace ops; 0011 changes p99. Add a multi-viewer test (a single stream cannot exercise cross-viewer sharing) and report the cache hit rate so a gain is not mis-attributed. diff --git a/docs/proposals/0011-engine-admission-classes.md b/docs/proposals/0011-engine-admission-classes.md index 3133a248..1ca60e0e 100644 --- a/docs/proposals/0011-engine-admission-classes.md +++ b/docs/proposals/0011-engine-admission-classes.md @@ -132,12 +132,15 @@ working as designed, not a leak). Reaching 20 ops/s needs ~6.7× more read throughput, which scheduling cannot manufacture. dashboard-refresh is rollup-backed and cheap (hence 837/1000); the hard failures are drill-traces and trace-detail, which scan the **growing raw Parquet snapshot** and are cost-bound. -Those pass only once per-op read cost drops — i.e. **0010** (result-cache extent -reuse) and **0007** (additive rollups so drill/exemplar/trace reads hit an -aggregate instead of re-scanning). This proposal is the stability/fairness layer -that makes the box degrade gracefully while those land. Its own exit test is +Those pass only once per-op read cost drops — **0012** (bounded per-minute span +exemplar ranking for `drill-traces`, #504), **0013** (per-batch `logs.fidx` and +fenced index probes for `trace-detail`, #507), and **0007** for summary-rollup +aggregate reads within its scope (not 0010, whose result/extent cache gets a ~0% +hit rate on varied trace reads and cannot split `drill-traces` or +`trace-detail`). This proposal is the stability/fairness layer that makes the box +degrade gracefully alongside those cost reductions. Its own exit test is **errors → ~0, no thrash pegging, dashboard-refresh goodput up, ingest flat** — -not 20 ops/s, which binds to 0007/0010. +not 20 ops/s, which binds to 0012/0013 (and 0007 for rollup-scoped aggregates). **Prior art.** The design maps onto established systems: CockroachDB elastic admission control (Go; gate on runnable-goroutines/CPU and scheduler latency, not @@ -156,21 +159,23 @@ admission needs an estimated-wait model and must not shed mid-work-sequence). engine-boundary bound is the read pool `SetMaxOpenConns` (`duck.go:552`), FIFO, no classes, entered through `readConn`/`acquireRead` (`duck.go:2440-2455`). The class-aware semaphore `readAdmission` (`admission.go`) lives only in -`query.Executor`, sized to `pool-2` (`sizing.go:56-73`), leaving two raw -connections for annotations and readiness. The collapse is structural: the -observability readers (`overview`/`topology`/`dependencies`/`trace`/ -`health_trend`), annotations, and variable-options call `Duck.QueryContext` -directly and **never pass through `readAdmission`**, so a saturating dashboard -oversubscribes the pool (admitted `pool-2` panels + unbounded observability reads -→ `DB.Conn` blocks), defeating deadline shedding and even starving the two -reserved connections. +`query.Executor`, sized to `pool-2` when `pool >= 4` (including all auto-sized +pools, `cores+4 ≥ 5`) and `max(1, pool)` when an operator pins `pool < 4` +(`sizing.go:58-75`), leaving two raw connections for readiness and nested reads +only when `pool >= 4`. Before #502/#507, the observability readers +(`overview`/`topology`/`dependencies`/`trace`/`health_trend`), annotations, and +variable-options called `Duck.QueryContext` (and `repository.TraceDetail`) +directly without `readAdmission`, so a saturating dashboard oversubscribed the +pool (admitted slots + unbounded direct reads → `DB.Conn` blocks), defeating +deadline shedding and starving the reserved connections. **Required revisions before build:** 1. **Bind the success criterion.** 0011's exit test is errors→~0 / no thrash / dashboard-refresh goodput up / ingest flat. The 20 ops/s gate binds to - 0007 + 0010 (read cost), not here. Do not benchmark 0011 against a target it - structurally cannot hit. + 0012 + 0013 (trace ranking and indexed trace-log reads) plus 0007 for + rollup-scoped aggregates — not here and not 0010. Do not benchmark 0011 + against a target it structurally cannot hit. 2. **Overload signal is measured, not connection count.** Gate on DuckDB worker-thread saturation + measured admission queue-wait (+ runnable goroutines/CPU, available cheaply in Go). Delete "2 spare connections" as the @@ -226,25 +231,31 @@ reserved connections. **Phased build sequence** (each independently shippable; later phases gated on earlier measurements, A/B on chip x86_64 / Hetzner, never pico): -- **Phase 0 — make admission global (pure plumbing, no policy, ship first).** - Route every bypass reader (`observability.{overview,topology,dependencies, - trace,health_trend}`, annotations, `query.variables` options) through the - existing `readAdmission` interactive lane via an admitting - `queryrows.Queryer`/`ReadTransactioner` wrapper defined in package `query` - (`observability` must not import `query`; `query` already imports it) and passed - into `observability.New`/`annotations.New` at wiring time. The wrapper holds the - slot **across row iteration** (release on `Rows.Close`, mirroring the engine's - `lockedRows`) and admits via the caller's own deadline. This restores the pool - invariant (admitted ≤ `pool-2` < pool), so a saturating dashboard can no longer - starve `DB.Conn`; bypass reads are deadline-shed as `ErrBusy` instead of piling - up, and refusals feed the existing `interactiveRefusals` → ingest backpressure. - Wrapping the injected `db` fixes the MCP observability path too. Add the metrics - every later phase needs: per-path queue depth, wait, admit/reject counts, DuckDB - thread saturation, runnable-goroutines/CPU. `Duck.Trace` (snapshot-pinned, - index-bounded, takes no pool connection) stays raw for now. This directly - addresses the measured "unadmitted readers oversubscribe the pool" collapse and - yields the clean baseline that quantifies how much per-op cost 0007/0010 must - still remove. +- **Phase 0 — make admission global (pure plumbing, no policy, ship first; + partially landed in #502 and #507).** Route every bypass reader + (`observability.{overview,topology,dependencies,trace,health_trend}`, + annotations, `query.variables` options) through the existing `readAdmission` + interactive lane via `Executor.AdmitReader` (`queryrows.Queryer`/ + `ReadTransactioner`) and `Executor.AdmitTraceDetail` (`internal/query/ + admit_reader.go`), passed into `observability.New` (for direct/MCP callers) and + `annotations.New` at wiring time. Wrapping `db` alone is not enough for + `observability.Trace`: when a caller supplies a `trace_id`, it skips + `db.QueryContext` and calls the separately injected `repository.TraceDetail`, so + `AdmitTraceDetail` wraps that reader as well (HTTP trace detail is already + admitted once by `CachedTraces`, and the panel-internal `rollupReader` stays raw + so nested reads inside a panel slot cannot deadlock). `AdmitReader` holds the + slot **across row iteration** (release once on `Rows.Close`) and bounds the + admission wait by `batchTimeout`. For `pool >= 4` (all auto-sized pools), this + restores `admitted ≤ pool-2 < pool` so admitted work cannot starve `DB.Conn` for + `/readyz` and nested `rollupReader` calls; when an operator pins `pool < 4` + (e.g. a 2-connection pool where `QueryAdmission` sets `slots = pool`), Phase 0 + still caps admitted concurrency at `pool` and stops unbounded oversubscription, + though admitted interactive reads can occupy every connection so direct `/readyz` + or nested reads may still wait on `DB.Conn` until Phase 2/3. Still open in + Phase 0: routing `query.variables` option queries (`variables.go:25,72,107`) + through admission and adding per-path queue depth, wait, admit/reject, DuckDB + thread saturation, and runnable-goroutines/CPU metrics. This yields the clean + baseline for the read-cost proposals (0012, 0013, and 0007). - **Phase 1 — split the background choke.** `backgroundSlots` is one permit (`duck.go:35/680/692`) shared by rollups and the read-cache refresh even though they already write disjoint tables under disjoint gates (`writeGate` vs @@ -265,6 +276,8 @@ The per-run shared snapshot+connection (the one cost-reducing move) folds into Phase 2/3 and carries the checkpoint-refusal hazard (revision 7), so it is not in the Phase 0 slice. -**Build readiness.** Phase 0 is buildable now: bounded, additive, no policy, no -engine/snapshot/sizing change. Phases 2-3 are gated on Phase-0 production metrics -and per-phase A/B. The 20 ops/s gate stays owned by 0007/0010. +**Build readiness.** Phase 0's `observability`, `TraceDetail`, and `annotations` +wrappers have landed (#502, #507); `query.variables` admission and the Phase-0 +metrics remain. Phases 2-3 are gated on Phase-0 production metrics and per-phase +A/B. The 20 ops/s gate stays owned by 0012/0013 (and 0007 for rollup-scoped +aggregates). From a9ae36f04b7fe3512df06335dcbc1616fd41705f Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 1 Dec 2026 12:38:47 -0800 Subject: [PATCH 7/8] docs(proposals): clarify live TTL lag, extent insert generation, and schema admission --- .../proposals/0010-result-cache-extent-key.md | 13 +++++++++--- .../0011-engine-admission-classes.md | 21 +++++++++++-------- 2 files changed, 22 insertions(+), 12 deletions(-) diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md index 3d9e287c..733f5820 100644 --- a/docs/proposals/0010-result-cache-extent-key.md +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -60,9 +60,12 @@ Non-goals: parameters sent to the engine; only step-aligned relative windows (Phase 3) change query inputs, by snapping bucketed relative `[start, end)` bounds to the resolved step grid (which shifts edge-bucket membership; see Risks). -- No relaxation of freshness semantics; the extent split uses the existing +- No new storage-level freshness horizon; the extent split uses the existing snapshot-consistent rollup horizon and invalidates closed extents when late - publications, compaction, or retention touch their event-time range. + publications, compaction, or retention touch their event-time range. Raising + the default live `QueryCacheTTL` (e.g. from `10s` to `60s`) intentionally + allows a scheduled 30s refresh to receive a cached result up to + `QueryCacheTTL` old while background stale-while-revalidate refreshes it. ## Design @@ -91,7 +94,11 @@ split)`: the extent cache subscribes to batch publication (using each batch's `SpanTime`/`LogTime`/`MetricTime` footer bounds, treating unknown bounds as overlapping; for rollup-backed extents, firing when the batch's rollup/partial write commits) as well as compaction and retention retirement, immediately -evicting any overlapping closed extent. +evicting any overlapping closed extent. To close the check-then-insert race +where an overlapping publication lands while an extent query is in flight, each +extent read records a monotonic invalidation generation before pinning its read +snapshot, and cache insertion under the extent mutex drops the result if an +overlapping invalidation advanced the generation since the snapshot was pinned. **TTL and revalidation.** Set the live (tail) TTL at least as long as the refresh period and retain today's half-TTL background stale-while-revalidate on diff --git a/docs/proposals/0011-engine-admission-classes.md b/docs/proposals/0011-engine-admission-classes.md index 1ca60e0e..b36b907e 100644 --- a/docs/proposals/0011-engine-admission-classes.md +++ b/docs/proposals/0011-engine-admission-classes.md @@ -234,7 +234,8 @@ earlier measurements, A/B on chip x86_64 / Hetzner, never pico): - **Phase 0 — make admission global (pure plumbing, no policy, ship first; partially landed in #502 and #507).** Route every bypass reader (`observability.{overview,topology,dependencies,trace,health_trend}`, - annotations, `query.variables` options) through the existing `readAdmission` + annotations, `query.variables` options, and `Executor.Schema` discoveries in + `schema.go`) through the existing `readAdmission` interactive lane via `Executor.AdmitReader` (`queryrows.Queryer`/ `ReadTransactioner`) and `Executor.AdmitTraceDetail` (`internal/query/ admit_reader.go`), passed into `observability.New` (for direct/MCP callers) and @@ -245,7 +246,8 @@ earlier measurements, A/B on chip x86_64 / Hetzner, never pico): admitted once by `CachedTraces`, and the panel-internal `rollupReader` stays raw so nested reads inside a panel slot cannot deadlock). `AdmitReader` holds the slot **across row iteration** (release once on `Rows.Close`) and bounds the - admission wait by `batchTimeout`. For `pool >= 4` (all auto-sized pools), this + admission wait by `batchTimeout`. Once `query.variables` and `Executor.Schema` + are also admitted, for `pool >= 4` (all auto-sized pools) this restores `admitted ≤ pool-2 < pool` so admitted work cannot starve `DB.Conn` for `/readyz` and nested `rollupReader` calls; when an operator pins `pool < 4` (e.g. a 2-connection pool where `QueryAdmission` sets `slots = pool`), Phase 0 @@ -253,9 +255,10 @@ earlier measurements, A/B on chip x86_64 / Hetzner, never pico): though admitted interactive reads can occupy every connection so direct `/readyz` or nested reads may still wait on `DB.Conn` until Phase 2/3. Still open in Phase 0: routing `query.variables` option queries (`variables.go:25,72,107`) - through admission and adding per-path queue depth, wait, admit/reject, DuckDB - thread saturation, and runnable-goroutines/CPU metrics. This yields the clean - baseline for the read-cost proposals (0012, 0013, and 0007). + and `Executor.Schema` discoveries (`schema.go`) through admission, and adding + per-path queue depth, wait, admit/reject, DuckDB thread saturation, and + runnable-goroutines/CPU metrics. This yields the clean baseline for the + read-cost proposals (0012, 0013, and 0007). - **Phase 1 — split the background choke.** `backgroundSlots` is one permit (`duck.go:35/680/692`) shared by rollups and the read-cache refresh even though they already write disjoint tables under disjoint gates (`writeGate` vs @@ -277,7 +280,7 @@ Phase 2/3 and carries the checkpoint-refusal hazard (revision 7), so it is not i the Phase 0 slice. **Build readiness.** Phase 0's `observability`, `TraceDetail`, and `annotations` -wrappers have landed (#502, #507); `query.variables` admission and the Phase-0 -metrics remain. Phases 2-3 are gated on Phase-0 production metrics and per-phase -A/B. The 20 ops/s gate stays owned by 0012/0013 (and 0007 for rollup-scoped -aggregates). +wrappers have landed (#502, #507); `query.variables` and `Executor.Schema` +admission plus the Phase-0 metrics remain. Phases 2-3 are gated on Phase-0 +production metrics and per-phase A/B. The 20 ops/s gate stays owned by 0012/0013 +(and 0007 for rollup-scoped aggregates). From 7e13ebf1320b21158ae7133ecd4ba844c06ab6ec Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Tue, 1 Dec 2026 13:04:36 -0800 Subject: [PATCH 8/8] docs(proposals): clamp aligned-window cache stamps and match extent snapshot generations --- .../proposals/0010-result-cache-extent-key.md | 41 ++++++++++++------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/docs/proposals/0010-result-cache-extent-key.md b/docs/proposals/0010-result-cache-extent-key.md index 733f5820..6bbcab1d 100644 --- a/docs/proposals/0010-result-cache-extent-key.md +++ b/docs/proposals/0010-result-cache-extent-key.md @@ -80,7 +80,11 @@ dashboard they live on or the exact viewport width. relative window's start and end to the resolved step grid before keying and querying (`ceil` on `end` so live sub-step events are not dropped), so successive refreshes of a "last 1h" panel cover aligned bucket boundaries and a -refresh can reuse prior buckets. Unbucketed raw panels keep exact `[start, end)` +refresh can reuse prior buckets. Because `ceil` can place `window.End` ahead of +the resolved query time (`result_cache.go` measures entry age from the stamp), +clamp each stored entry's stamp to `min(window.End, queryNow)` (or stamp with +computation time) so a future-rounded `end` never produces a negative entry age +that outlives `QueryCacheTTL`. Unbucketed raw panels keep exact `[start, end)` bounds. **Extent cache.** Split a bucketed window at the snapshot-consistent rollup @@ -94,11 +98,14 @@ split)`: the extent cache subscribes to batch publication (using each batch's `SpanTime`/`LogTime`/`MetricTime` footer bounds, treating unknown bounds as overlapping; for rollup-backed extents, firing when the batch's rollup/partial write commits) as well as compaction and retention retirement, immediately -evicting any overlapping closed extent. To close the check-then-insert race -where an overlapping publication lands while an extent query is in flight, each -extent read records a monotonic invalidation generation before pinning its read -snapshot, and cache insertion under the extent mutex drops the result if an -overlapping invalidation advanced the generation since the snapshot was pinned. +evicting any overlapping closed extent. To keep both hits and insertions +snapshot-consistent, each panel run pins one read snapshot together with the +monotonic invalidation generation: an extent lookup hits only when the cached +entry's recorded generation equals the caller's pinned generation (otherwise the +reader computes `[start, split)` from its own pinned snapshot rather than mixing +a newer cached extent with an older tail), and insertion under the extent mutex +drops the result if an overlapping invalidation advanced the generation after +the snapshot was pinned. **TTL and revalidation.** Set the live (tail) TTL at least as long as the refresh period and retain today's half-TTL background stale-while-revalidate on @@ -261,24 +268,28 @@ must come from footer event-time bounds or the split falls back to off. whole-dashboard hash to a per-panel spec hash. Pure key change; coarser keys make more requests coalesce onto one flight. Update the covering test. - **Phase 3 — step-aligned relative windows** (`resolveWindow`, - `timerange.go`), compatible with the `1970-01-01` grid and SQL `metricLookback`. + `timerange.go`), compatible with the `1970-01-01` grid and SQL `metricLookback`, + clamping stored cache stamps to `min(window.End, queryNow)` so `ceil`-aligned + windows never start with negative age and outlive `QueryCacheTTL`. Makes consecutive refreshes target identical bucket ranges (precondition for any extent reuse) and stabilizes the Phase-2 key across refreshes. - **Phase 4 — extent cache (hardest, gated behind 0007).** Split at `floor(min(coverage.FreshTo(), now - safety_lag), interval)`, cache the closed - half under an aligned `[start, split)` long-TTL flight evicted on overlapping - batch/rollup publication or retirement (no half-TTL timer polling on closed - extents), re-query only the tail with live-TTL + half-TTL revalidation, and - stitch half-open. Highest correctness surface (watermark race, late-data - invalidation, boundary bucket); gate on those tests and a measured long-window - raw-aggregate cost. + half under an aligned `[start, split)` long-TTL flight tagged with the pinned + invalidation generation (requiring `entry.gen == pinnedGen` on hit so closed + and tail halves never mix snapshots) and evicted on overlapping batch/rollup + publication or retirement (no half-TTL timer polling on closed extents), + re-query only the tail with live-TTL + half-TTL revalidation, and stitch + half-open. Highest correctness surface (watermark race, snapshot/generation + matching, late-data invalidation, boundary bucket); gate on those tests and a + measured long-window raw-aggregate cost. **Risks (ranked):** (1) a watermark race caches a still-changing bucket and the long TTL serves it wrong for the whole TTL; (2) stitch-seam double-count or drop; (3) the referenced-variable reduction drops a result-affecting field; (4) LRU eviction defeats the long TTL, or extent entries blow the 64 MiB budget; (5) the -step-aligned window is a visible semantic change interacting with the existing -relative-vs-fixed stamp logic. +step-aligned window is a visible semantic change whose `ceil`-rounded `end` must +not advance the cache entry stamp past `queryNow`. **Measurement.** A/B one lever per branch against the same Hetzner ccx33 read gate, never co-merged: 0012 moves `drill-traces` and 0013 moves `trace-detail`,