Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,9 @@
or globally rewritten scope indexes; uncached batches union in ranked the same
way. Windows within one minute read footer-pruned Parquet, and compaction
derives output lists from cached inputs. Body search matches redacted text.
Analytical service/edge watermark lag is separate. Completed-batch writes
Span, log, resource and service minute summaries share this batch lifecycle.
Fold counts, extrema and histogram bins over the pinned active IDs. Endpoint,
receiver and edge summaries retain their analytical watermarks. Completed-batch writes
have their own gate and write-pool slot; analytical writes use disjoint tables.
Maintenance must hold both gates for checkpointing.
- Batch format 6, including its physical schema and sidecars, is the only
Expand Down
152 changes: 55 additions & 97 deletions docs/proposals/0007-additive-rollup-aggregates.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
# Additive per-batch rollup aggregates

Status: Draft
Status: Phase 1 implemented
Date: 2026-11-14
Pull request: TBD
Related issues: #278 and #477

## 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.
Store span, log, resource and service minute summaries as per-batch partials in
the disposable read cache. Merge active partials at read time and fold them
during compaction. Endpoint, receiver and edge summaries retain their analytical
watermarks.

## 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
The previous `refreshServiceRollup` discovered the affected keys for a pass, derived one
event-time hull `[min(bucket), max(bucket)+1m)`, and re-scanned raw Parquet over
that hull once per key-chunk to rebuild every summary. This has three
structural costs, all surfaced by the engine audit:

Expand All @@ -34,9 +31,9 @@ structural costs, all surfaced by the engine audit:
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
The repository already runs the additive model for `read_trace_exemplars` and
`read_resource_seconds` via `read_batches` markers and
`transferBatchCacheLocked` (`internal/engine/batch_cache.go:555-589`). This
`transferBatchCacheLocked` (`internal/engine/batch_cache.go`). This
proposal generalizes that proven mechanism to the summary rollups.

## Goals and non-goals
Expand All @@ -58,28 +55,40 @@ Non-goals:
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.
## Phase 1 design

The cache writer groups each new immutable file by its batch ID and logical
minute key. It commits all four summaries and the `read_batches` marker in one
transaction. Span partials store counts, duration sums and extrema, and scale-3
histograms. Service counts combine span and log populations with zero-count
service-minutes from metric resources. Resource identities retain their projected
fields and exact first and last timestamps.

Every read pins the file catalog and reads markers and partials in one DuckDB
transaction. Only cached IDs in that catalog contribute. Uncached active files
supply the same aggregates from Parquet. Each public relation merges its complete
logical key, including histogram counts per bin. Fractions and averages are
computed from counts and sums after merging. The publication horizon supplies
additive ingest coverage and the last completed detector minute. Span and log
rates use the requested event-time interval.

Compaction folds the input partials before marking the output complete. A busy
cache writer defers the fold, so the published output can be read from Parquet
in the meantime. Readers on either side of the catalog swap see one generation.
The worker subsequently removes retired contributions.

The endpoint top-128 route fold depends on all routes in a service-minute.
Receiver summaries depend on retry winners and time-ordered counter changes,
and edges join spans across files. These stay on the analytical writer.
Endpoint and receiver discovery considers only routed spans and recognized
receiver metrics respectively. Their distinct keys are ordered by bucket,
namespace and service. Each chunk binds its own half-open minute range against
the captured catalog, using each signal's own footer bounds.

Phase 1 uses read-cache version 22 and rollup schema version 7. A mismatch
rebuilds the disposable partials from active files in bounded batches.
A future immutable sidecar could avoid this rebuild and would require a
canonical batch-format change.

## Alternatives

Expand All @@ -100,65 +109,14 @@ checkpoints for these tables entirely, at the cost of a batch-format bump.
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.

## 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.
## Prior art

ClickHouse's `AggregatingMergeTree` combines aggregate states at query time
and folds them during background merges. The compaction fold here serves the
same purpose. Apache Druid's ingestion-time rollup is also relevant to the
proposed immutable sidecar.

## Follow-up measurement

Measure read-time merging on representative 30-day panels and compare ingest,
rebuild and compaction costs before considering an immutable sidecar.
2 changes: 1 addition & 1 deletion docs/proposals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ 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 |
| 0007 | [Additive per-batch rollup aggregates](0007-additive-rollup-aggregates.md) | Phase 1 implemented |
| 0008 | [Mergeable latency sketch and derived service rollup](0008-mergeable-latency-sketch.md) | Implemented |
| 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) | Accepted |
Expand Down
6 changes: 3 additions & 3 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,14 +167,14 @@ used by the dashboard. Retain failures and timeout counts alongside latency; do
make a slow or failed run disappear by retrying until it passes. These targets
are acceptance criteria, not guarantees for arbitrary telemetry volumes.

The executor uses analytical minute summaries for supported span/log aggregates,
The executor uses per-batch minute summaries for supported span/log aggregates,
filters and dimensions; other shapes read raw telemetry. The disposable trace
read cache stores completed-batch candidates and parts. Service maps combine
analytical rollups with a raw client-span query for external peers. That query
materializes the filtered client projection once for reuse by peer and edge
aggregates; its child-span and observed-service checks also read spans. Health
panels use analytical rollups. Rollup data has separate watermark lag and approximate latency
semantics. Do not assume those rollups answer arbitrary raw counts,
panels read the published service and span summaries. Endpoint, receiver and
edge summaries have separate watermark lag. Histogram quantiles are approximate. Do not assume those rollups answer arbitrary raw counts,
rates or quantiles exactly, or report every dashboard query as cached.

`just readbench-check` compiles the opt-in native read harness in CI without
Expand Down
15 changes: 8 additions & 7 deletions internal/agent/dashboard_eval_golden_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/labstack/pitot/internal/config"
"github.com/labstack/pitot/internal/dashboard"
"github.com/labstack/pitot/internal/engine"
"github.com/labstack/pitot/internal/engine/querytest"
pitotmcp "github.com/labstack/pitot/internal/mcp"
"github.com/labstack/pitot/internal/query"
controlstore "github.com/labstack/pitot/internal/store"
Expand All @@ -42,7 +41,7 @@ func TestDashboardEvalGoldensCurrent(t *testing.T) {
if err = repo.Commit(t.Context(), telemetrystore.Batch{ID: "eval_fixture", Spans: []telemetry.Span{{Namespace: "shop", ServiceName: "checkout", TraceID: "trace", SpanID: "span", Name: "request", Kind: "SPAN_KIND_SERVER", StartUnixNanos: from.UnixNano(), EndUnixNanos: from.Add(time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "STATUS_CODE_OK", IngestedAt: from.UnixNano()}}}); err != nil {
t.Fatal(err)
}
if err := querytest.RefreshSpanRollup(engine.DB); err != nil {
if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil {
t.Fatal(err)
}
executor := query.NewExecutor(engine, 30)
Expand Down Expand Up @@ -135,11 +134,13 @@ func TestDashboardEvalGoldensCurrent(t *testing.T) {
if err != nil {
t.Fatal(err)
}
for i := range results {
results[i].ElapsedMS = 0
}
for i := range addedResults {
addedResults[i].ElapsedMS = 0
for _, panels := range [][]query.Result{results, addedResults} {
for i := range panels {
panels[i].ElapsedMS = 0
if panels[i].FreshToMS != 0 {
panels[i].FreshToMS = to.UnixMilli()
}
}
}
if results[1].Status != "ok" || results[1].Frame != nil {
t.Fatalf("text shape: %#v", results[1])
Expand Down
1 change: 1 addition & 0 deletions internal/alert/engine_env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ func TestAlertRulesMeasureOnlyTheirNamespaceInTheCurrentWindow(t *testing.T) {
if err := engine.CreateCacheTables(db); err != nil {
t.Fatal(err)
}
querytest.CreateSummaryFixtures(t, db)
at := time.Now().UTC().Truncate(time.Minute).Add(-time.Minute)
querytest.SeedSpanRollup(t, db, at, "acme", "api", "", 100, 90, 20)
querytest.SeedSpanRollup(t, db, at.Add(-time.Minute), "globex", "api", "", 1000, 0, 200)
Expand Down
5 changes: 2 additions & 3 deletions internal/cmd/e2eseed/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
"github.com/labstack/pitot/internal/config"
"github.com/labstack/pitot/internal/dashboard"
"github.com/labstack/pitot/internal/engine"
"github.com/labstack/pitot/internal/engine/querytest"
"github.com/labstack/pitot/internal/ingest"
"github.com/labstack/pitot/internal/observability"
"github.com/labstack/pitot/internal/query"
Expand Down Expand Up @@ -81,7 +80,7 @@ func TestAllPanelsFixtureValidates(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { _ = engine.Close() })
if err := querytest.RefreshSpanRollup(engine.DB); err != nil {
if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil {
t.Fatal(err)
}
if _, problems, err := query.NewExecutor(engine, 30).Check(t.Context(), &spec); err != nil || len(problems) != 0 {
Expand Down Expand Up @@ -451,7 +450,7 @@ func TestPerformanceFixtureValidatesAndExecutes(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() { _ = engine.Close() })
if err := querytest.RefreshSpanRollup(engine.DB); err != nil {
if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil {
t.Fatal(err)
}
if _, problems, err := query.NewExecutor(engine, 30).Check(t.Context(), &spec); err != nil || len(problems) != 0 {
Expand Down
3 changes: 1 addition & 2 deletions internal/dashboard/defaults_sql.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,5 @@ func containerCapacitySQL() string {
FROM results ORDER BY (reporting<>'reporting') DESC,status DESC NULLS LAST,namespace,host,container`
}

// Selected resource tuples come from analytical minutes. No partial-second
// Parquet scan is needed; resource_inventory retains its separate exact contract.
// Resource summaries retain the first observation of each projected tuple per minute.
const versionObservationsSQL = `SELECT namespace,service,resource['service.version']::VARCHAR AS version,resource['process.runtime.name']::VARCHAR AS runtime_name,resource['process.runtime.version']::VARCHAR AS runtime_version,resource['telemetry.sdk.language']::VARCHAR AS sdk_language,resource['telemetry.sdk.version']::VARCHAR AS sdk_version,first_seen AS seen FROM resource_rollup WHERE $__window(bucket) AND $__window(first_seen) AND resource['service.version']::VARCHAR<>''`
2 changes: 1 addition & 1 deletion internal/dashboard/resource_inventory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func TestDefaultResourcePanelsAcrossCacheStates(t *testing.T) {
for _, state := range []string{"partial", "cold", "full"} {
t.Run(state, func(t *testing.T) {
if state == "cold" {
if _, err := d.DB.Exec(`DELETE FROM read_batches; DELETE FROM read_resource_inventory; DELETE FROM read_resource_seconds; DELETE FROM read_metric_names; DELETE FROM read_trace_exemplars`); err != nil {
if _, err := d.DB.Exec(`DELETE FROM read_span_rollup; DELETE FROM read_log_rollup; DELETE FROM read_resource_rollup; DELETE FROM read_service_rollup; DELETE FROM read_batches; DELETE FROM read_resource_inventory; DELETE FROM read_resource_seconds; DELETE FROM read_metric_names; DELETE FROM read_trace_exemplars`); err != nil {
t.Fatal(err)
}
if err := engine.CreateCacheTables(d.DB); err != nil {
Expand Down
Loading
Loading