Skip to content
Open
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
59 changes: 35 additions & 24 deletions docs/proposals/0008-mergeable-latency-sketch.md
Original file line number Diff line number Diff line change
@@ -1,30 +1,29 @@
# Mergeable latency sketch and derived service rollup

Status: Draft
Status: Implemented
Date: 2026-11-14
Pull request: TBD
Pull request: [#527](https://github.com/labstack/pitot/pull/527)

## 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.
same number and any window is re-aggregable. The public `service_rollup`
relation retains additive counts for SQL consumers and service discovery.

## 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:
Before this change, `service_rollup` stored final per-minute t-digest results in
`p50_ms` and `p95_ms`. Consumers combined those results in different ways:

- Alerts take an unweighted `avg(p95_ms)` and `avg(error_rate)`
- Alerts took 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
- The overview took `MAX(p95_ms)` (`internal/observability/latency_sql.go:15`).
- Dashboards merged the `span_rollup` histogram correctly
(`internal/query/rollup_compile.go:75-81`).

The same service and window therefore reports three different p95 values. (See
The same service and window could therefore report 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
Expand All @@ -35,7 +34,7 @@ not used consistently.
Goals:

- One definition of service p50/p95/error rate, computed from mergeable inputs,
used by alerts, the overview, and dashboards.
used by alerts, the overview, anomaly detection, 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.
Expand All @@ -51,14 +50,13 @@ Non-goals:
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
span counts. Log counts come from `log_rollup`. Metric reporting resources come from
`resource_rollup`. Alerts, the overview, anomaly detection, and dashboards use one shared package
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.
The public `service_rollup` relation retains additive per-minute counts. The
disposable cache rebuilds them from the canonical span and log summaries.
The batch format stays at version 6.

## Alternatives

Expand All @@ -76,12 +74,25 @@ rebuildable disposable cache, so this needs no batch-format change.
- 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?
## Implementation decisions

- Keep `service_rollup` for public panel SQL and service discovery, including
metric-only service-minutes. Its additive columns are `spans`, `served_spans`,
`error_spans` and `log_count`. The writer joins affected keys to the canonical
span and log summaries in the same transaction. Cache versions 21 and 6
rebuild this schema without changing Parquet format 6.
- For service latency, merge served spans across the entire selected group.
Use all spans when the group contains only client or producer calls. Counts
and error fractions include every span. Both alert windows group across
namespaces by service. Detector baseline scatter still uses five-minute bins.
- Preserve Overview's `metric_count` field as a window count of distinct
reporting resource identities from the metrics rows of `resource_rollup`.
The batch-level metric-name cache cannot answer a service-scoped time query.
- Existing alert thresholds may change because a true window quantile weights
every observation. The scale-3 interpolation error is bounded by one bin
(about 9.05%) relative to the observation at the requested rank. The old
unweighted average can differ by more. Re-evaluate latency, error-rate and
delta thresholds against representative windows.

## Research validation (2026-11-15)

Expand Down
2 changes: 1 addition & 1 deletion docs/proposals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Earlier proposals predate the template and keep their original structure.
| 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 |
| 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) | Draft |
| 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Draft |
Expand Down
54 changes: 21 additions & 33 deletions internal/alert/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/labstack/pitot/internal/engine"
"github.com/labstack/pitot/internal/intelligence"
"github.com/labstack/pitot/internal/rollupsql"
)

const pruneHistDays = 7
Expand Down Expand Up @@ -503,6 +504,26 @@ func (e *Engine) fireWebhookAsync(rule Rule, alert Alert, env Env, event string)
}()
}

const currentAlertWindow = `bucket >= (SELECT bucket FROM latest) - INTERVAL '5 minutes' AND bucket <= now()::TIMESTAMP_NS`
const previousAlertWindow = `bucket >= (SELECT bucket FROM latest) - INTERVAL '10 minutes' AND bucket < (SELECT bucket FROM latest) - INTERVAL '5 minutes'`

var envSQL = `WITH latest AS (
SELECT max(bucket) AS bucket FROM (
SELECT max(bucket) AS bucket FROM span_rollup WHERE service<>'' AND bucket<=now()::TIMESTAMP_NS
UNION ALL SELECT max(bucket) FROM log_rollup WHERE service<>'' AND bucket<=now()::TIMESTAMP_NS)
), current_spans AS (` + rollupsql.ServiceWindow(currentAlertWindow, "") + `),
current_logs AS (SELECT service,sum(logs)::DOUBLE AS log_count FROM log_rollup
WHERE service<>'' AND ` + currentAlertWindow + ` GROUP BY service),
current AS (SELECT service,coalesce(error_rate,0) AS error_rate,coalesce(p50,0) AS p50,
coalesce(p95,0) AS p95,coalesce(spans,0)::DOUBLE AS throughput,coalesce(log_count,0) AS log_count
FROM current_spans FULL JOIN current_logs USING(service)),
previous AS (` + rollupsql.ServiceWindow(previousAlertWindow, "") + `)
SELECT c.service,c.error_rate,c.p50,c.p95,c.throughput,c.log_count,
coalesce((c.error_rate-p.error_rate)/nullif(p.error_rate,0)*100,0),
coalesce((c.p95-p.p95)/nullif(p.p95,0)*100,0),
coalesce((c.throughput-p.spans)/nullif(p.spans,0)*100,0)
FROM current c LEFT JOIN previous p USING(service)`

// buildEnvs returns Env keyed by service name. If envOverride is set it
// is returned directly (for tests). Otherwise DuckDB is queried.
func (e *Engine) buildEnvs(ctx context.Context) map[string]Env {
Expand All @@ -513,39 +534,6 @@ func (e *Engine) buildEnvs(ctx context.Context) map[string]Env {
return map[string]Env{}
}

const envSQL = `
WITH latest AS (
SELECT max(bucket) AS bucket FROM service_rollup WHERE bucket <= now()::TIMESTAMP_NS
),
current AS (
SELECT service,
avg(error_rate) as error_rate,
COALESCE(avg(p50_ms) FILTER (WHERE served_spans > 0), avg(p50_ms)) as p50,
COALESCE(avg(p95_ms) FILTER (WHERE served_spans > 0), avg(p95_ms)) as p95,
sum(spans)::DOUBLE as throughput, sum(log_count)::DOUBLE as log_count
FROM service_rollup
WHERE bucket >= (SELECT bucket FROM latest) - INTERVAL '5 minutes'
AND bucket <= now()::TIMESTAMP_NS
GROUP BY service
),
previous AS (
SELECT service,
avg(error_rate) as error_rate,
COALESCE(avg(p95_ms) FILTER (WHERE served_spans > 0), avg(p95_ms)) as p95,
sum(spans)::DOUBLE as throughput
FROM service_rollup
WHERE bucket >= (SELECT bucket FROM latest) - INTERVAL '10 minutes'
AND bucket < (SELECT bucket FROM latest) - INTERVAL '5 minutes'
GROUP BY service
)
SELECT c.service, coalesce(c.error_rate, 0), coalesce(c.p50, 0), coalesce(c.p95, 0),
coalesce(c.throughput, 0), coalesce(c.log_count, 0),
coalesce(((c.error_rate - p.error_rate) / NULLIF(p.error_rate, 0)) * 100, 0),
coalesce(((c.p95 - p.p95) / NULLIF(p.p95, 0)) * 100, 0),
coalesce(((c.throughput - p.throughput) / NULLIF(p.throughput, 0)) * 100, 0)
FROM current c LEFT JOIN previous p ON c.service = p.service
WHERE c.service <> ''`

// A fixed statement over the rollup cache: the typed read path, not the
// untrusted-SQL one.
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
Expand Down
33 changes: 16 additions & 17 deletions internal/alert/engine_env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@ import (
_ "github.com/duckdb/duckdb-go/v2"

"github.com/labstack/pitot/internal/engine"
"github.com/labstack/pitot/internal/engine/querytest"
)

// buildEnvs feeds CEL rules from a SQL aggregate over service_rollup. DuckDB
// buildEnvs feeds CEL rules from a SQL aggregate over the span and log rollups. DuckDB
// widens SUM over integer columns to HUGEINT, which the driver scans as
// *big.Int, so the statement casts those sums to DOUBLE. Without that,
// throughput/log_count read 0 while the DOUBLE fields (error_rate, p50, p95,
Expand All @@ -28,22 +29,17 @@ func TestBuildEnvsUsesLatestNonfutureBucketForTotalsAndDeltas(t *testing.T) {
t.Fatal(err)
}

if _, err := db.Exec(`
CREATE TABLE service_rollup (
namespace VARCHAR, bucket TIMESTAMP, service VARCHAR,
spans BIGINT, served_spans BIGINT, error_rate DOUBLE, p50_ms DOUBLE, p95_ms DOUBLE,
log_count BIGINT, metric_count BIGINT
)`); err != nil {
t.Fatalf("create service_rollup: %v", err)
if err := engine.CreateCacheTables(db); err != nil {
t.Fatal(err)
}
if _, err := db.Exec(`
INSERT INTO service_rollup VALUES
('', now(), 'svc-a', 100, 100, 0.0, 10.0, 20.0, 5, 0),
('', now() - INTERVAL 1 MINUTE, 'svc-a', 100, 100, 0.0, 10.0, 20.0, 5, 0),
('', now() - INTERVAL 8 MINUTE, 'svc-a', 50, 50, 0.0, 10.0, 20.0, 5, 0),
('', now() + INTERVAL 4 MINUTE, 'svc-a', 999, 0, 0.0, 0.0, 0.0, 0, 0),
('', now() + INTERVAL 10 YEAR, 'future-only', 1, 0, 0.0, 0.0, 0.0, 0, 0)`); err != nil {
t.Fatalf("seed service_rollup: %v", err)
at := time.Now().UTC().Truncate(time.Minute)
querytest.SeedSpanRollup(t, db, at, "prod", "svc-a", "", 100, 0, 20)
querytest.SeedSpanRollup(t, db, at.Add(-time.Minute), "other", "svc-a", "", 100, 0, 20)
querytest.SeedSpanRollup(t, db, at.Add(-8*time.Minute), "prod", "svc-a", "", 50, 0, 20)
querytest.SeedSpanRollup(t, db, at.Add(4*time.Minute), "prod", "svc-a", "", 999, 0, 100)
querytest.SeedSpanRollup(t, db, at.AddDate(10, 0, 0), "prod", "future-only", "", 1, 0, 20)
if _, err := db.Exec(`INSERT INTO log_rollup VALUES ('prod',$1,'svc-a','INFO',10),('prod',$1,'log-only','INFO',3)`, at); err != nil {
t.Fatal(err)
}

eng := NewEngine(nil, &engine.Duck{DB: db}, nil, time.Minute, 7)
Expand All @@ -56,6 +52,9 @@ INSERT INTO service_rollup VALUES
if _, ok := envs["future-only"]; ok {
t.Error("future-only service appeared in alert environment")
}
if logs := envs["log-only"]; logs.LogCount != 3 || logs.Throughput != 0 || logs.P95 != 0 {
t.Fatalf("log-only: %+v", logs)
}
if env.ThroughputDelta != 300 {
t.Errorf("ThroughputDelta = %v, want 300%% (50 to 200 spans)", env.ThroughputDelta)
}
Expand All @@ -65,7 +64,7 @@ INSERT INTO service_rollup VALUES
if env.LogCount != 10 {
t.Errorf("LogCount = %v, want 10 (sum(log_count) is HUGEINT — lost in conversion?)", env.LogCount)
}
if env.P95 != 20 {
if env.P95 < 19 || env.P95 > 22 {
t.Errorf("P95 = %v, want 20", env.P95)
}
}
9 changes: 3 additions & 6 deletions internal/alert/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,11 @@ type Alert struct {
// field here adds a row to the reference; describe it in a sentence a rule
// author would find useful, not in terms of how it is computed.
type Env struct {
// Mean of minute-rollup span error proportions over the evaluation window,
// from 0 to 1; not a request-weighted whole-window error rate.
// Fraction of all spans in the current window with error status, from 0 to 1.
ErrorRate float64 `expr:"error_rate" json:"error_rate"`
// Mean of approximate minute-rollup median span latencies in milliseconds.
// Approximate whole-window median latency in milliseconds for served spans, or all spans if none were served.
P50 float64 `expr:"p50" json:"p50"`
// Mean of approximate minute-rollup 95th-percentile span latencies in
// milliseconds; not the whole-window p95. Latency prefers served work,
// falling back to outbound spans when no served work is available.
// Approximate whole-window 95th percentile latency in milliseconds, using the same span population as p50.
P95 float64 `expr:"p95" json:"p95"`
// Total span count over the current rollup window, not requests per second.
// Pair it with an error threshold to avoid firing on very little traffic.
Expand Down
5 changes: 4 additions & 1 deletion internal/engine/backlog_pressure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -337,8 +337,11 @@ func TestBacklogServiceFailuresIdentifyStatementAndPreserveCause(t *testing.T) {
mock.ExpectExec("DELETE FROM service_rollup").WillReturnError(cause)
} else {
mock.ExpectExec("DELETE FROM service_rollup").WillReturnResult(sqlmock.NewResult(0, 0))
for _, table := range []string{"span_rollup", "log_rollup", "endpoint_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup"} {
mock.ExpectExec("DELETE FROM " + table).WillReturnResult(sqlmock.NewResult(0, 0))
}
mock.ExpectQuery("FROM service_pass_affected").WillReturnRows(sqlmock.NewRows([]string{"namespace", "bucket", "service"}).AddRow("ns", int64(0), "api"))
mock.ExpectExec("WITH span_agg").WillReturnError(cause)
mock.ExpectExec("INSERT INTO span_rollup").WillReturnError(cause)
}
mock.ExpectRollback()
d := &Duck{DB: db, writeDB: db, publicationBounds: func() (int64, int64, int64) { return 2, 2, 1 }}
Expand Down
2 changes: 1 addition & 1 deletion internal/engine/batch_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
// anomaly_log is not one of them: it holds detector output that nothing can
// rebuild, so the drop keeps it. Its table is created once; any change to its
// schema must be a separate, explicit migration step.
const readCacheVersion = 20
const readCacheVersion = 21

const (
readCacheBatchLimit = 64
Expand Down
56 changes: 28 additions & 28 deletions internal/engine/dashboard_rollup.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package engine

import (
"context"
"database/sql"
"fmt"
"strings"
"time"

"github.com/labstack/pitot/internal/rollupsql"
)

func logRollupInsertSQL(keys string) string {
Expand Down Expand Up @@ -36,43 +39,40 @@ func endpointRollupInsertSQL(keys string) string {
folded AS (SELECT e.* EXCLUDE(route),CASE WHEN r.r<=%d THEN e.route ELSE 'Other routes (overflow)' END route,r.r>%d overflow
FROM eligible e JOIN routes r USING(namespace,bucket,service,route))
SELECT namespace,bucket,service,kind,status,route,overflow,count(*),sum(duration_ms),min(duration_ms),max(duration_ms),
histogram(CASE WHEN duration_ms>0 THEN coalesce(try_cast(ceil(log2(duration_ms)*8) AS INTEGER),2147483647) ELSE %d END)
FROM folded GROUP BY namespace,bucket,service,kind,status,route,overflow`, keys, endpointRouteLimit, endpointRouteLimit, spanHistogramZero)
histogram(%s)
FROM folded GROUP BY namespace,bucket,service,kind,status,route,overflow`, keys, endpointRouteLimit, endpointRouteLimit, rollupsql.Bin("duration_ms"))
}

func insertDashboardRollups(ctx context.Context, tx rollupSQL, lo, hi time.Time) error {
func insertDashboardRollups(ctx context.Context, tx rollupSQL, lo, hi time.Time) (sql.Result, error) {
if err := insertSpanAndLogRollups(ctx, tx, lo, hi); err != nil {
return nil, err
}
for _, signal := range []string{"spans", "logs", "metrics"} {
alias, clock := "m", "start_time"
if signal != "spans" {
alias, clock = "m", "time"
clock := "m.time"
if signal == "spans" {
clock = "m.start_time"
}
err := forAffectedKeys(ctx, tx,
`SELECT DISTINCT namespace,epoch_ns(bucket),service FROM service_pass_affected WHERE namespace IS NOT NULL AND bucket IS NOT NULL AND service IS NOT NULL`, nil,
fmt.Sprintf(`struct_pack(namespace := %[1]s.namespace,bucket := date_trunc('minute',%[1]s.%[2]s::TIMESTAMP_NS),service := %[1]s.service)`, alias, clock),
`struct_pack(namespace := ?::VARCHAR,bucket := make_timestamp_ns(?::BIGINT),service := ?::VARCHAR)`,
minute := "date_trunc('minute'," + clock + "::TIMESTAMP_NS)"
err := forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, nil,
"struct_pack(namespace := m.namespace,bucket := "+minute+",service := m.service)", serviceRollupAffectedKeyExpr,
func(keys string, args []any) error {
resourceKeys := keys
if _, err := tx.ExecContext(ctx, resourceRollupInsertSQL(signal, alias+"."+clock, resourceKeys), append(args, lo, hi)...); err != nil {
return err
}
query := endpointRollupInsertSQL(strings.ReplaceAll(keys, "m.", "s."))
if signal == "logs" {
query = logRollupInsertSQL(strings.ReplaceAll(keys, "m.", "l."))
}
if signal == "metrics" {
query = receiverRollupInsertSQL(keys)
statements := []string{resourceRollupInsertSQL(signal, clock, keys)}
switch signal {
case "spans":
statements = append(statements, endpointRollupInsertSQL(strings.ReplaceAll(keys, "m.", "s.")))
case "metrics":
statements = append(statements, receiverRollupInsertSQL(keys), receiverEntityRollupInsertSQL(strings.ReplaceAll(keys, minute, "m.bucket")))
}
_, err := tx.ExecContext(ctx, query, append(args, lo, hi)...)
if err != nil || signal != "metrics" {
return err
for _, statement := range statements {
if _, err := tx.ExecContext(ctx, statement, append(args, lo, hi)...); err != nil {
return err
}
}
entityKeys := strings.ReplaceAll(keys, "date_trunc('minute',m.time::TIMESTAMP_NS)", "m.bucket")
_, err = tx.ExecContext(ctx, receiverEntityRollupInsertSQL(entityKeys), append(args, lo, hi)...)
return err
return nil
})
if err != nil {
return err
return nil, err
}
}
return nil
return tx.ExecContext(ctx, serviceRollupCountsSQL, lo, hi)
}
Loading
Loading