diff --git a/docs/proposals/0008-mergeable-latency-sketch.md b/docs/proposals/0008-mergeable-latency-sketch.md index bd18ac3de..476f4d89c 100644 --- a/docs/proposals/0008-mergeable-latency-sketch.md +++ b/docs/proposals/0008-mergeable-latency-sketch.md @@ -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 @@ -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. @@ -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 @@ -76,12 +74,27 @@ 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 uses the whole baseline's + selected span population in each five-minute bin. Structured span queries + share the interpolation and apply the panel's explicit filters to every measure. +- 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) diff --git a/docs/proposals/README.md b/docs/proposals/README.md index 3698190e4..0a08cc153 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -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 | diff --git a/internal/alert/engine.go b/internal/alert/engine.go index cc2a946ae..7d10922e2 100644 --- a/internal/alert/engine.go +++ b/internal/alert/engine.go @@ -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 @@ -503,6 +504,24 @@ 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 service_rollup WHERE service<>'' AND bucket<=now()::TIMESTAMP_NS + ), current_spans AS (` + rollupsql.ServiceWindow(currentAlertWindow, "") + `), + current_services AS (SELECT service,coalesce(sum(log_count),0)::DOUBLE AS log_count FROM service_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,log_count + FROM current_services LEFT JOIN current_spans 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 { @@ -513,39 +532,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) diff --git a/internal/alert/engine_env_test.go b/internal/alert/engine_env_test.go index 0fbaa0cf2..248d88ceb 100644 --- a/internal/alert/engine_env_test.go +++ b/internal/alert/engine_env_test.go @@ -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 service and span 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, @@ -28,22 +29,25 @@ 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) + } + at := time.Now().UTC().Truncate(time.Minute).Add(-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) + querytest.SeedSpanRollup(t, db, at.Add(-5*time.Minute), "prod", "stale", "", 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) } - 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) + if _, err := db.Exec(`INSERT INTO service_rollup VALUES + ('prod',$1,'svc-a',100,100,0,10),('other',$1 - INTERVAL '1 minute','svc-a',100,100,0,0), + ('prod',$1 + INTERVAL '4 minutes','svc-a',999,999,0,0),('prod',$1 + INTERVAL '10 years','future-only',1,1,0,0), + ('prod',$1,'log-only',0,0,0,3),('prod',$1 + INTERVAL '1 minute','metric-only',0,0,0,0), + ('prod',$1 - INTERVAL '5 minutes','stale',1,1,0,0),('prod',$1 - INTERVAL '8 minutes','svc-a',50,50,0,0)`, at); err != nil { + t.Fatal(err) } eng := NewEngine(nil, &engine.Duck{DB: db}, nil, time.Minute, 7) @@ -56,6 +60,12 @@ 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 metric, ok := envs["metric-only"]; !ok || metric != (Env{Service: "metric-only"}) { + t.Fatalf("metric-only service missing or nonzero: %+v", envs) + } if env.ThroughputDelta != 300 { t.Errorf("ThroughputDelta = %v, want 300%% (50 to 200 spans)", env.ThroughputDelta) } @@ -65,7 +75,11 @@ 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) } + // The newest metric minute advances the anchor past the stale span service. + if _, ok := envs["stale"]; ok { + t.Fatalf("stale service included: %+v", envs) + } } diff --git a/internal/alert/types.go b/internal/alert/types.go index 5b6973225..6ff8330ce 100644 --- a/internal/alert/types.go +++ b/internal/alert/types.go @@ -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. diff --git a/internal/engine/backlog_pressure_test.go b/internal/engine/backlog_pressure_test.go index aae7b5a54..3e35e2373 100644 --- a/internal/engine/backlog_pressure_test.go +++ b/internal/engine/backlog_pressure_test.go @@ -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 }} diff --git a/internal/engine/batch_cache.go b/internal/engine/batch_cache.go index f67b6979b..453389441 100644 --- a/internal/engine/batch_cache.go +++ b/internal/engine/batch_cache.go @@ -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 diff --git a/internal/engine/dashboard_rollup.go b/internal/engine/dashboard_rollup.go index 385e9d182..b3cb23d9d 100644 --- a/internal/engine/dashboard_rollup.go +++ b/internal/engine/dashboard_rollup.go @@ -2,9 +2,12 @@ package engine import ( "context" + "database/sql" "fmt" "strings" "time" + + "github.com/labstack/pitot/internal/rollupsql" ) func logRollupInsertSQL(keys string) string { @@ -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) } diff --git a/internal/engine/duck.go b/internal/engine/duck.go index 46f9d3b86..ac04ce018 100644 --- a/internal/engine/duck.go +++ b/internal/engine/duck.go @@ -24,6 +24,7 @@ import ( "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/readpressure" + "github.com/labstack/pitot/internal/rollupsql" "github.com/labstack/pitot/internal/telemetry" telemetrystore "github.com/labstack/pitot/internal/telemetry/store" ) @@ -270,7 +271,7 @@ const ( // Rollup progress keys in rollup_state. readCacheVersion drops that table // with the rollups, so a version change also restarts their backfill; the // keys need no version of their own. - rollup_schema_version = 5 + rollup_schema_version = 6 serviceRollupStateKey = "service_rollup_v3" edgeRollupStateKey = "edge_rollup_v2" edgeRollupSubCursorKey = "edge_rollup_v2_substart" @@ -1331,17 +1332,14 @@ func (d *Duck) refreshServiceRollup(ctx context.Context) (affected int64, err er return 0, fmt.Errorf("service_rollup/delete: %w", err) } for _, table := range []string{"span_rollup", "log_rollup", "endpoint_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup"} { - if _, err := tx.ExecContext(ctx, strings.ReplaceAll(strings.ReplaceAll(serviceRollupDeleteSQL, "service_rollup", table), "?::TIMESTAMP_NS::TIMESTAMPTZ_NS", "?::TIMESTAMP_NS"), lo, hi); err != nil { + if _, err := tx.ExecContext(ctx, strings.ReplaceAll(serviceRollupDeleteSQL, "service_rollup", table), lo, hi); err != nil { return 0, fmt.Errorf("%s/delete: %w", table, err) } } - res, err := insertServiceRollup(ctx, tx, lo, hi) + res, err := insertDashboardRollups(ctx, tx, lo, hi) if err != nil { return 0, fmt.Errorf("service_rollup/insert: %w", err) } - if err := insertDashboardRollups(ctx, tx, lo, hi); err != nil { - return 0, fmt.Errorf("dashboard_rollup/insert: %w", err) - } rows, err = res.RowsAffected() if err != nil { slog.Warn("service rollup rows affected unavailable", "err", err) @@ -1769,35 +1767,6 @@ SET last_ingested_unix_nano = excluded.last_ingested_unix_nano, return err } -// serviceRollupP50SQL and serviceRollupP95SQL build the latency columns of a -// rollup pass. -// -// These are approximate on purpose. quantile_cont is holistic: it retains every -// value of every group in a vector on the raw allocator, so its cost grows with -// the rows a pass scans, and memory_limit does not bound it -- DuckDB reports -// zero usage while the process grows by gigabytes. A pass covering an hour of -// ingest at this product's certified rate scans tens of millions of spans, and -// that is how the process reached 11.5 GiB anon-rss on a box configured for a -// 4 GB limit. -// -// approx_quantile keeps a fixed-size t-digest per group instead. Measured on -// 30M rows: 861 MiB of untracked growth becomes 8 MiB. The error is a fraction -// of a percent on a latency percentile that already describes a one-minute -// bucket, which is not a figure anyone reads to three significant digits. -// -// The COALESCE keeps a service that only makes outbound calls -- a load -// generator, a cron worker -- measured on what it does have rather than -// silently reported as having no latency at all. -func serviceRollupP50SQL(alias string) string { return serviceRollupQuantileSQL(alias, 1, "p50_ms") } - -func serviceRollupP95SQL(alias string) string { return serviceRollupQuantileSQL(alias, 2, "p95_ms") } - -func serviceRollupQuantileSQL(alias string, index int, column string) string { - served := fmt.Sprintf("approx_quantile(%[1]s.duration_ms, [0.50, 0.95]) FILTER (WHERE COALESCE(%[1]s.kind, '') NOT IN ('SPAN_KIND_CLIENT', 'SPAN_KIND_PRODUCER'))", alias) - all := fmt.Sprintf("approx_quantile(%s.duration_ms, [0.50, 0.95])", alias) - return fmt.Sprintf("COALESCE(%s[%d], %s[%d]) AS %s", served, index, all, index, column) -} - const createServicePassAffectedSQL = ` CREATE OR REPLACE TEMP TABLE service_pass_affected AS SELECT DISTINCT namespace, date_trunc('minute', start_time::TIMESTAMP_NS) AS bucket, service @@ -1823,8 +1792,8 @@ CREATE OR REPLACE TEMP TABLE service_pass_affected AS const serviceRollupDeleteSQL = ` DELETE FROM service_rollup -WHERE bucket >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND bucket < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS +WHERE bucket >= ?::TIMESTAMP_NS + AND bucket < ?::TIMESTAMP_NS AND EXISTS ( SELECT 1 FROM service_pass_affected a WHERE a.namespace = service_rollup.namespace @@ -1832,79 +1801,35 @@ WHERE bucket >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS AND a.service = service_rollup.service );` -// Aggregate each bounded signal scan before the final affected-bucket joins. -// Schema-first Parquet scans can have a zero cardinality estimate in DuckDB 2; -// joining raw events to the affected table can then build a hash table of every -// event. Spans, logs and metrics are all filtered to the affected keys first, -// bound as a constant list rather than a semi-join against -// service_pass_affected, which reverses into a build of every raw event. A late -// or clock-skewed event pulls the event-time hull back by days; without the key -// filter the log and metric aggregates then scanned and grouped every -// service-minute of that whole hull, blowing memory and freezing the watermark. -// For spans each unaffected service-minute otherwise also allocates its own -// t-digest states. The final join only reads the materialized aggregates. -func insertServiceRollup(ctx context.Context, tx rollupSQL, lo, hi time.Time) (sql.Result, error) { - for _, create := range []string{ - `CREATE OR REPLACE TEMP TABLE service_pass_spans ( - namespace VARCHAR, bucket TIMESTAMP_NS, service VARCHAR, spans BIGINT, served_spans BIGINT, - p50_ms DOUBLE, p95_ms DOUBLE, error_rate DOUBLE)`, - `CREATE OR REPLACE TEMP TABLE service_pass_logs ( - namespace VARCHAR, bucket TIMESTAMP_NS, service VARCHAR, log_count BIGINT)`, - `CREATE OR REPLACE TEMP TABLE service_pass_metrics ( - namespace VARCHAR, bucket TIMESTAMP_NS, service VARCHAR, metric_count BIGINT)`, - } { - if _, err := tx.ExecContext(ctx, create); err != nil { - return nil, err - } - } - err := forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, nil, +// Build the canonical span and log summaries once per affected key. The public +// service counts join only those summaries, including zeroes for metric-only keys. +func insertSpanAndLogRollups(ctx context.Context, tx rollupSQL, lo, hi time.Time) error { + return forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, nil, `struct_pack(namespace := s.namespace, bucket := date_trunc('minute', s.start_time::TIMESTAMP_NS), service := s.service)`, - serviceRollupAffectedKeyExpr, - func(keys string, args []any) error { - _, err := tx.ExecContext(ctx, "INSERT INTO service_pass_spans "+serviceRollupSpanSQL(keys)+" SELECT * FROM span_agg", append(args, lo, hi)...) - if err != nil { + serviceRollupAffectedKeyExpr, func(keys string, args []any) error { + bounds := append(args, lo, hi) + if _, err := tx.ExecContext(ctx, spanRollupInsertSQL(keys), bounds...); err != nil { return err } - _, err = tx.ExecContext(ctx, spanRollupInsertSQL(keys), append(args, lo, hi)...) - return err - }) - if err != nil { - return nil, err - } - // Logs and metrics aggregate the same affected keys over the same bounded - // event-time range, so one old bucket cannot force a full-hull scan. - err = forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, nil, - `struct_pack(namespace := l.namespace, bucket := date_trunc('minute', l.time::TIMESTAMP_NS), service := l.service)`, - serviceRollupAffectedKeyExpr, - func(keys string, args []any) error { - _, err := tx.ExecContext(ctx, serviceRollupLogInsertSQL(keys), append(args, lo, hi)...) - return err - }) - if err != nil { - return nil, err - } - err = forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, nil, - `struct_pack(namespace := m.namespace, bucket := date_trunc('minute', m.time::TIMESTAMP_NS), service := m.service)`, - serviceRollupAffectedKeyExpr, - func(keys string, args []any) error { - _, err := tx.ExecContext(ctx, serviceRollupMetricInsertSQL(keys), append(args, lo, hi)...) + logKeys := strings.NewReplacer("s.", "l.", "start_time", "time").Replace(keys) + _, err := tx.ExecContext(ctx, logRollupInsertSQL(logKeys), bounds...) return err }) - if err != nil { - return nil, err - } - res, err := tx.ExecContext(ctx, serviceRollupJoinSQL) - if err != nil { - return nil, err - } - for _, table := range []string{"service_pass_spans", "service_pass_logs", "service_pass_metrics"} { - if _, err := tx.ExecContext(ctx, "DROP TABLE "+table); err != nil { - return nil, err - } - } - return res, nil } +const serviceRollupCountsSQL = `INSERT INTO service_rollup + WITH affected AS (SELECT * FROM service_pass_affected WHERE service<>'' AND bucket >= $1::TIMESTAMP_NS AND bucket < $2::TIMESTAMP_NS), + span_counts AS ( + SELECT namespace,bucket,service,sum(spans) spans,sum(spans) FILTER (WHERE ` + rollupsql.Served + `) served_spans, + ` + rollupsql.ErrorSpans + ` error_spans FROM span_rollup SEMI JOIN affected USING(namespace,bucket,service) + WHERE bucket >= $1::TIMESTAMP_NS AND bucket < $2::TIMESTAMP_NS GROUP BY ALL + ), log_counts AS ( + SELECT namespace,bucket,service,sum(logs) log_count FROM log_rollup SEMI JOIN affected USING(namespace,bucket,service) + WHERE bucket >= $1::TIMESTAMP_NS AND bucket < $2::TIMESTAMP_NS GROUP BY ALL + ) + SELECT namespace,bucket,service,coalesce(spans,0),coalesce(served_spans,0),coalesce(error_spans,0),coalesce(log_count,0) + FROM affected LEFT JOIN span_counts USING(namespace,bucket,service) LEFT JOIN log_counts USING(namespace,bucket,service)` + // rollupSQL is a rollup pass's transaction, or a test's database. type rollupSQL interface { QueryContext(context.Context, string, ...any) (*sql.Rows, error) @@ -1974,31 +1899,6 @@ const serviceRollupAffectedKeysSQL = `SELECT DISTINCT namespace, epoch_ns(bucket const serviceRollupAffectedKeyExpr = `struct_pack(namespace := ?::VARCHAR, bucket := make_timestamp_ns(?::BIGINT), service := ?::VARCHAR)` -// Log and metric aggregates probe the same constant affected-key list and the -// same bounded event-time range as the span path, so one old or clock-skewed -// bucket cannot widen them into a scan and group of the whole hull. Keys are -// distinct, so each affected service-minute lands in exactly one chunk and its -// COUNT and COUNT(DISTINCT name) are exact. -func serviceRollupLogInsertSQL(keys string) string { - return `INSERT INTO service_pass_logs - SELECT l.namespace, date_trunc('minute', l.time::TIMESTAMP_NS), l.service, COUNT(*) - FROM logs l - WHERE ` + keys + ` - AND l.time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND l.time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY l.namespace, date_trunc('minute', l.time::TIMESTAMP_NS), l.service` -} - -func serviceRollupMetricInsertSQL(keys string) string { - return `INSERT INTO service_pass_metrics - SELECT m.namespace, date_trunc('minute', m.time::TIMESTAMP_NS), m.service, COUNT(DISTINCT m.name) - FROM metrics m - WHERE ` + keys + ` - AND m.time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND m.time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY m.namespace, date_trunc('minute', m.time::TIMESTAMP_NS), m.service` -} - // Aggregate after probing the constant affected-key list, never by hashing raw // spans into a join against service_pass_affected. The histogram is O(buckets). func spanRollupInsertSQL(keys string) string { @@ -2006,89 +1906,13 @@ func spanRollupInsertSQL(keys string) string { SELECT s.namespace, date_trunc('minute', s.start_time::TIMESTAMP_NS), s.service, coalesce(s.kind, ''), coalesce(s.status, ''), count(*), sum(s.duration_ms), min(s.duration_ms), max(s.duration_ms), - histogram(CASE WHEN s.duration_ms > 0 THEN coalesce(try_cast(ceil(log2(s.duration_ms)*8) AS INTEGER),2147483647) ELSE ` + fmt.Sprint(spanHistogramZero) + ` END) + histogram(` + rollupsql.Bin("s.duration_ms") + `) FROM spans s WHERE ` + keys + ` AND s.start_time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS AND s.start_time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS GROUP BY s.namespace, date_trunc('minute', s.start_time::TIMESTAMP_NS), s.service, coalesce(s.kind, ''), coalesce(s.status, '')` } -func serviceRollupSpanSQL(keys string) string { - return ` -WITH span_agg AS ( - SELECT - s.namespace, - date_trunc('minute', s.start_time::TIMESTAMP_NS) AS bucket, - s.service, - COUNT(*) AS spans, - COUNT(*) FILTER (WHERE COALESCE(s.kind, '') NOT IN ('SPAN_KIND_CLIENT', 'SPAN_KIND_PRODUCER')) AS served_spans, - -- Latency describes the work a service performs, not the calls it waits - -- on. A CLIENT or PRODUCER span measures a dependency: a subscription held - -- open for ten minutes makes its subscriber look broken while saying - -- nothing about how that subscriber serves anyone. Grading on those is what - -- marked half the demo's services unhealthy for holding a flagd event - -- stream open. Error rate still counts every span, because a failing - -- outbound call is the caller's problem too. - -- - -- COALESCE keeps a service that only makes outbound calls — a load - -- generator, a cron worker — measured on what it does have rather than - -- silently reported as having no latency at all. - ` + serviceRollupP50SQL("s") + `, - ` + serviceRollupP95SQL("s") + `, - avg(CASE WHEN s.status = 'STATUS_CODE_ERROR' THEN 1.0 ELSE 0.0 END) AS error_rate - FROM spans s - WHERE ` + keys + ` - -- Bound the scan to the affected bucket range so Telemetry prunes parquet by - -- start_time stats instead of scanning all history. The final join on a - -- computed bucket alone does not prune. The range is a provable superset - -- of the affected buckets — every row in an affected bucket has start_time in - -- [MIN(bucket), MAX(bucket)+1min) — so it drops no rows. A late span with an - -- old start_time widens the range (and this scan) only for the pass that - -- ingests it, same trade-off as the edge rollup's parent bound. - AND s.start_time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND s.start_time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY s.namespace, date_trunc('minute', s.start_time::TIMESTAMP_NS), s.service -)` -} - -// serviceRollupJoinSQL reads the materialized span, log and metric aggregates, -// each already filtered to the affected keys, and joins them to every affected -// service-minute so empty signals still produce a zeroed row. -const serviceRollupJoinSQL = ` -WITH span_agg AS (SELECT * FROM service_pass_spans), -log_agg AS (SELECT * FROM service_pass_logs), -metric_agg AS (SELECT * FROM service_pass_metrics) -INSERT INTO service_rollup ( - namespace, - bucket, - service, - spans, - served_spans, - p50_ms, - p95_ms, - error_rate, - log_count, - metric_count -) -SELECT - a.namespace, - a.bucket, - a.service, - COALESCE(s.spans, 0), - COALESCE(s.served_spans, 0), - COALESCE(s.p50_ms, 0), - COALESCE(s.p95_ms, 0), - COALESCE(s.error_rate, 0), - COALESCE(l.log_count, 0), - COALESCE(m.metric_count, 0) -FROM service_pass_affected a -LEFT JOIN span_agg s USING (namespace, bucket, service) -LEFT JOIN log_agg l USING (namespace, bucket, service) -LEFT JOIN metric_agg m USING (namespace, bucket, service) --- Keep service health's existing nonempty-service population. Span panels also --- count spans whose resource omitted service.name. -WHERE a.service != '';` - // edgeArrivalGap bounds recent-arrival repair behind the completed ingest // watermark. Older relationships are not guaranteed to be repaired. const edgeArrivalGap = 5 * time.Minute diff --git a/internal/engine/duck_test.go b/internal/engine/duck_test.go index 05385e646..0cbbb4150 100644 --- a/internal/engine/duck_test.go +++ b/internal/engine/duck_test.go @@ -324,30 +324,19 @@ func TestRollupAdmissionDoesNotCancelAdmittedWork(t *testing.T) { mock.ExpectExec("DELETE FROM receiver_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("DELETE FROM resource_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("DELETE FROM receiver_entity_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("CREATE OR REPLACE TEMP TABLE service_pass_spans").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("CREATE OR REPLACE TEMP TABLE service_pass_logs").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("CREATE OR REPLACE TEMP TABLE service_pass_metrics").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("INSERT INTO service_pass_spans").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("INSERT INTO span_rollup").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("INSERT INTO service_pass_logs").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("INSERT INTO service_pass_metrics").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("WITH span_agg").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DROP TABLE service_pass_spans").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DROP TABLE service_pass_logs").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DROP TABLE service_pass_metrics").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO log_rollup").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("INSERT INTO resource_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("INSERT INTO endpoint_rollup").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("INSERT INTO resource_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("INSERT INTO log_rollup").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("INSERT INTO resource_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("INSERT INTO receiver_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("INSERT INTO receiver_entity_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO service_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("DROP TABLE service_pass_affected").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("INSERT INTO rollup_state").WillReturnResult(sqlmock.NewResult(0, 1)) mock.ExpectCommit() diff --git a/internal/engine/edge_parent_plan_test.go b/internal/engine/edge_parent_plan_test.go index 4e4c098de..c0f335e59 100644 --- a/internal/engine/edge_parent_plan_test.go +++ b/internal/engine/edge_parent_plan_test.go @@ -181,15 +181,15 @@ WHERE` // Audit the other raw-signal joins with both data-first and schema-first // estimates. Arrival repair must build incoming keys, messaging must aggregate -// before joining, and service rollups must aggregate logs and metrics first. +// before joining, and the canonical span and log aggregates must scan their inputs directly. func TestOtherRollupJoinsKeepHistoryOffHashBuildSide(t *testing.T) { db := openTestDuck(t) seedEdgeRollupFixture(t, db) dir := t.TempDir() - for _, signal := range []string{"spans", "logs", "metrics"} { + for _, signal := range []string{"spans", "logs"} { query := "SELECT * FROM spans" if signal != "spans" { - query = "SELECT namespace,service,start_time AS time,'requests' AS name FROM spans" + query = "SELECT namespace,service,start_time AS time,'INFO' AS severity FROM spans" } for _, empty := range []bool{false, true} { suffix := "data" @@ -202,12 +202,12 @@ func TestOtherRollupJoinsKeepHistoryOffHashBuildSide(t *testing.T) { } } } - if _, err := db.Exec(createServiceRollupTable); err != nil { + if _, err := db.Exec(createSpanRollupTable + createLogRollupTable); err != nil { t.Fatal(err) } for _, schemaFirst := range []bool{false, true} { t.Run(fmt.Sprint("schema first=", schemaFirst), func(t *testing.T) { - for _, signal := range []string{"spans", "logs", "metrics"} { + for _, signal := range []string{"spans", "logs"} { files := sqlLiteral(filepath.Join(dir, signal+"-data.parquet")) if schemaFirst { files = sqlLiteral(filepath.Join(dir, signal+"-schema.parquet")) + "," + files @@ -261,10 +261,8 @@ func TestOtherRollupJoinsKeepHistoryOffHashBuildSide(t *testing.T) { t.Fatal(err) } requireRawScansNotHashed(t, plan(edgeRollupInsertSQL, lo, hi)) - if _, err := tx.Exec("CREATE TEMP TABLE service_pass_affected AS SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS) bucket,service FROM spans GROUP BY ALL"); err != nil { - t.Fatal(err) - } - requireRawScansNotHashed(t, plan(serviceRollupInsertSQL("true"), lo, hi, lo, hi, lo, hi)) + requireRawScansNotHashed(t, plan(spanRollupInsertSQL("true"), lo, hi)) + requireRawScansNotHashed(t, plan(logRollupInsertSQL("true"), lo, hi)) }) } } diff --git a/internal/engine/metric_rollup_memory_test.go b/internal/engine/metric_rollup_memory_test.go index 7b124f4a6..5edf7905a 100644 --- a/internal/engine/metric_rollup_memory_test.go +++ b/internal/engine/metric_rollup_memory_test.go @@ -1,15 +1,11 @@ package engine import ( - "encoding/json" - "fmt" - "os" - "path/filepath" "testing" "time" ) -func TestServiceMetricRollupAggregatesBeforeJoiningAffectedBuckets(t *testing.T) { +func TestServiceCountsKeepMetricOnlyKeysWithoutScanningMetrics(t *testing.T) { db := openTestDuck(t) if err := CreateTables(db); err != nil { t.Fatal(err) @@ -17,72 +13,13 @@ func TestServiceMetricRollupAggregatesBeforeJoiningAffectedBuckets(t *testing.T) if err := CreateViews(db); err != nil { t.Fatal(err) } - dir := t.TempDir() - schema, data := filepath.Join(dir, "schema.parquet"), filepath.Join(dir, "data.parquet") - // Like the production schema-first snapshot, the first file is empty. DuckDB - // estimates this scan at zero rows and can choose it as a hash build side. - for _, q := range []string{ - "SET memory_limit='128MB'", "SET threads=4", - `CREATE VIEW metric_fixture AS SELECT - CASE WHEN i%5=0 THEN 'other' ELSE 'ns' END AS namespace, - CASE WHEN i%7=0 THEN 'unaffected' ELSE 'api' END AS service, - CASE WHEN i%11=0 THEN NULL ELSE 'metric-'||(i%4)::VARCHAR END AS name, - make_timestamp_ns(-120000000000+(i%3)*60000000000)::TIMESTAMPTZ_NS AS time - FROM range(1000000) t(i)`, - "COPY (SELECT * FROM metric_fixture WHERE false) TO " + sqlLiteral(schema) + " (FORMAT PARQUET)", - "COPY metric_fixture TO " + sqlLiteral(data) + " (FORMAT PARQUET)", - "CREATE OR REPLACE VIEW metrics AS SELECT * FROM read_parquet([" + sqlLiteral(schema) + "," + sqlLiteral(data) + "],union_by_name=false,hive_partitioning=false)", - `CREATE TEMP TABLE service_pass_affected AS SELECT 'ns' AS namespace, TIMESTAMP '1969-12-31 23:58:00' AS bucket, 'api' AS service - UNION ALL SELECT 'ns',TIMESTAMP '1970-01-01 00:00:00','api' - UNION ALL SELECT 'ns',TIMESTAMP '1969-12-31 23:58:00','missing'`, - "SET enable_profiling='json'", "SET profiling_output=" + sqlLiteral(filepath.Join(dir, "profile.json")), - } { - if _, err := db.Exec(q); err != nil { - t.Fatalf("fixture: %v", err) - } - } - lo, hi := time.Unix(-120, 0).UTC(), time.Unix(60, 0).UTC() - if _, err := insertServiceRollup(t.Context(), db, lo, hi); err != nil { - t.Fatal(err) - } - raw, err := os.ReadFile(filepath.Join(dir, "profile.json")) - if err != nil { + if _, err := db.Exec(`DROP VIEW metrics; + CREATE TEMP TABLE service_pass_affected AS SELECT 'ns' namespace, TIMESTAMP '1970-01-01' bucket, 'metrics-only' service`); err != nil { t.Fatal(err) } - var profile struct { - System struct { - PeakBufferMemory int64 `json:"peak_buffer_memory"` - } `json:"system"` - } - if err := json.Unmarshal(raw, &profile); err != nil { + lo := time.Unix(0, 0).UTC() + if _, err := insertServiceRollup(t.Context(), db, lo, lo.Add(time.Minute)); err != nil { t.Fatal(err) } - // One million repeated points describe only two affected service buckets. A hash build - // of the raw points used about 90 MiB; the distinct-name aggregation needs - // under 10 MiB. Keep this independent of host RSS and allocator reuse. - t.Logf("peak DuckDB buffer memory: %.1f MiB", float64(profile.System.PeakBufferMemory)/(1<<20)) - if peak := profile.System.PeakBufferMemory; peak == 0 || peak > 32<<20 { - t.Errorf("metric rollup peak buffer memory = %d, want 1..32 MiB", peak) - } - rows, err := db.Query("SELECT epoch_ns(bucket),service,metric_count FROM service_rollup ORDER BY bucket,service") - if err != nil { - t.Fatal(err) - } - defer rows.Close() - var got []string - for rows.Next() { - var bucket, count int64 - var service string - if err := rows.Scan(&bucket, &service, &count); err != nil { - t.Fatal(err) - } - got = append(got, fmt.Sprintf("%d/%s/%d", bucket, service, count)) - } - if err := rows.Err(); err != nil { - t.Fatal(err) - } - want := "[-120000000000/api/4 -120000000000/missing/0 0/api/4]" - if fmt.Sprint(got) != want { - t.Fatalf("rollups = %v, want %s", got, want) - } + requireRowCount(t, db, `SELECT count(*) FROM service_rollup WHERE service=? AND spans=0 AND served_spans=0 AND error_spans=0 AND log_count=0`, "metrics-only", 1) } diff --git a/internal/engine/panel_rollup_keys_test.go b/internal/engine/panel_rollup_keys_test.go index c590938a9..742196808 100644 --- a/internal/engine/panel_rollup_keys_test.go +++ b/internal/engine/panel_rollup_keys_test.go @@ -244,7 +244,7 @@ func TestPanelRollupKeysUpgradePreviousCacheOnReopen(t *testing.T) { if err != nil { t.Fatal(err) } - for table, want := range map[string]int{"read_cache_version": 20, "rollup_schema_version": 5} { + for table, want := range map[string]int{"read_cache_version": 21, "rollup_schema_version": 6} { var got int if err := d.DB.QueryRowContext(t.Context(), "SELECT version FROM "+table).Scan(&got); err != nil || got != want { t.Fatalf("reopened %s=%d want=%d: %v", table, got, want, err) @@ -336,7 +336,7 @@ func refreshPanelRollupKeys(t *testing.T, d *Duck) { } // Independent raw populations check all keys, counts, duration statistics // and every histogram bin, not only the number of persisted aggregates. - hist := `histogram(CASE WHEN duration_ms>0 THEN coalesce(try_cast(ceil(log2(duration_ms)*8) AS INTEGER),2147483647) ELSE -2147483648 END)` + hist := `histogram(CASE WHEN duration_ms>0 AND NOT isnan(duration_ms) THEN coalesce(try_cast(ceil(log2(duration_ms)*8) AS INTEGER),2147483647) ELSE -2147483648 END)` expected := map[string]string{ "span_rollup": `SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS) bucket,service,coalesce(kind,'') kind,coalesce(status,'') status,count(*) spans,sum(duration_ms) duration_sum,min(duration_ms) duration_min,max(duration_ms) duration_max,` + hist + ` hist FROM spans GROUP BY ALL`, "log_rollup": `SELECT namespace,date_trunc('minute',time::TIMESTAMP_NS) bucket,service,coalesce(severity,'') severity,count(*) logs FROM logs GROUP BY ALL`, diff --git a/internal/engine/querytest/tables.go b/internal/engine/querytest/tables.go index 273d9503f..5241e04fa 100644 --- a/internal/engine/querytest/tables.go +++ b/internal/engine/querytest/tables.go @@ -5,7 +5,10 @@ import ( "database/sql" "fmt" "strings" + "testing" + "time" + "github.com/labstack/pitot/internal/rollupsql" "github.com/labstack/pitot/internal/telemetry" ) @@ -53,13 +56,31 @@ func RefreshSpanRollup(db *sql.DB) error { if _, err := db.Exec(`DELETE FROM span_rollup`); err != nil { return err } - _, err := db.Exec(`INSERT INTO span_rollup SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS),service,coalesce(kind,''),coalesce(status,''),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 -2147483648 END) FROM spans WHERE service IS NOT NULL GROUP BY ALL`) + _, err := db.Exec(`INSERT INTO span_rollup SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS),service,coalesce(kind,''),coalesce(status,''),count(*),sum(duration_ms),min(duration_ms),max(duration_ms),histogram(` + rollupsql.Bin("duration_ms") + `) FROM spans WHERE service IS NOT NULL GROUP BY ALL`) if err != nil { return err } if _, err := db.Exec(`DELETE FROM log_rollup; INSERT INTO log_rollup SELECT namespace,date_trunc('minute',time::TIMESTAMP_NS),service,coalesce(severity,''),count(*) FROM logs WHERE service IS NOT NULL GROUP BY ALL`); err != nil { return err } - _, err = db.Exec(`DELETE FROM endpoint_rollup; INSERT INTO endpoint_rollup SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS),service,coalesce(kind,''),coalesce(status,''),_a_http_route,false,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 -2147483648 END) FROM spans WHERE service IS NOT NULL AND _a_http_route<>'' GROUP BY ALL`) + _, err = db.Exec(`DELETE FROM endpoint_rollup; INSERT INTO endpoint_rollup SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS),service,coalesce(kind,''),coalesce(status,''),_a_http_route,false,count(*),sum(duration_ms),min(duration_ms),max(duration_ms),histogram(` + rollupsql.Bin("duration_ms") + `) FROM spans WHERE service IS NOT NULL AND _a_http_route<>'' GROUP BY ALL`) return err } + +// SeedSpanRollup represents a minute of constant-duration spans split by status. +func SeedSpanRollup(t testing.TB, db *sql.DB, at time.Time, namespace, service, kind string, spans, errors int, duration float64) { + t.Helper() + for _, status := range []string{"STATUS_CODE_OK", "STATUS_CODE_ERROR"} { + n := spans - errors + if status == "STATUS_CODE_ERROR" { + n = errors + } + if n == 0 { + continue + } + _, err := db.Exec(`INSERT INTO span_rollup VALUES ($1,$2,$3,$4,$5,$6,$6*$7::DOUBLE,$7,$7,map([`+rollupsql.Bin("$7::DOUBLE")+`],[$6::UBIGINT]))`, namespace, at, service, kind, status, n, duration) + if err != nil { + t.Fatal(err) + } + } +} diff --git a/internal/engine/rollup_keys_test.go b/internal/engine/rollup_keys_test.go index 253ed7246..1ddc82964 100644 --- a/internal/engine/rollup_keys_test.go +++ b/internal/engine/rollup_keys_test.go @@ -101,8 +101,8 @@ func TestServiceRollupSpanScanIsNeverBuildSide(t *testing.T) { if _, err := insertServiceRollup(t.Context(), plan, lo, hi); err != nil { t.Fatal(err) } - if len(plan.plans) != 2 { - t.Fatalf("span scan plans=%d want 2", len(plan.plans)) + if len(plan.plans) != 1 { + t.Fatalf("span scan plans=%d want 1", len(plan.plans)) } for _, scan := range plan.plans { requireProbedSpans(t, scan) @@ -303,17 +303,7 @@ func TestServiceRollupKeysMatchSemiJoin(t *testing.T) { if _, err := db.Exec("CREATE OR REPLACE TABLE new_rollup AS SELECT * FROM service_rollup; DELETE FROM service_rollup"); err != nil { t.Fatal(err) } - semi := strings.Replace(serviceRollupInsertSQL("true"), " FROM spans s\n WHERE true\n", ` FROM spans s - SEMI JOIN service_pass_affected a - ON a.namespace = s.namespace - AND a.bucket = date_trunc('minute', s.start_time::TIMESTAMP_NS) - AND a.service = s.service - WHERE true -`, 1) - if semi == serviceRollupInsertSQL("true") { - t.Fatal("span filter text not found") - } - if _, err := db.Exec(semi, lo, hi, lo, hi, lo, hi); err != nil { + if _, err := db.Exec(serviceCountsReferenceSQL, lo, hi); err != nil { t.Fatal(err) } var diff, n int @@ -408,63 +398,24 @@ func TestEdgeRollupKeysMatchConstantList(t *testing.T) { } } -// Unchunked, full-scan reference for differential tests of the bounded -// implementation. span_agg comes from one bounded span scan; log_agg and -// metric_agg scan logs and metrics directly over the same event-time range. -// Production insertServiceRollup instead materializes all three per -// affected-key chunk; these tests pin that both produce identical rows. -func serviceRollupInsertSQL(keys string) string { - return serviceRollupSpanSQL(keys) + serviceRollupReferenceJoinSQL +// Exercise the service-count portion of the analytical pass with sparse raw fixtures. +func insertServiceRollup(ctx context.Context, tx rollupSQL, lo, hi time.Time) (sql.Result, error) { + if err := insertSpanAndLogRollups(ctx, tx, lo, hi); err != nil { + return nil, err + } + return tx.ExecContext(ctx, serviceRollupCountsSQL, lo, hi) } -const serviceRollupReferenceJoinSQL = `, -log_agg AS ( - SELECT - l.namespace, - date_trunc('minute', l.time::TIMESTAMP_NS) AS bucket, - l.service, - COUNT(*) AS log_count - FROM logs l - WHERE l.time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND l.time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY l.namespace, date_trunc('minute', l.time::TIMESTAMP_NS), l.service -), -metric_agg AS ( - SELECT - m.namespace, - date_trunc('minute', m.time::TIMESTAMP_NS) AS bucket, - m.service, - COUNT(DISTINCT m.name) AS metric_count - FROM metrics m - WHERE m.time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - AND m.time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY m.namespace, date_trunc('minute', m.time::TIMESTAMP_NS), m.service -) -INSERT INTO service_rollup ( - namespace, - bucket, - service, - spans, - served_spans, - p50_ms, - p95_ms, - error_rate, - log_count, - metric_count -) -SELECT - a.namespace, - a.bucket, - a.service, - COALESCE(s.spans, 0), - COALESCE(s.served_spans, 0), - COALESCE(s.p50_ms, 0), - COALESCE(s.p95_ms, 0), - COALESCE(s.error_rate, 0), - COALESCE(l.log_count, 0), - COALESCE(m.metric_count, 0) -FROM service_pass_affected a -LEFT JOIN span_agg s USING (namespace, bucket, service) -LEFT JOIN log_agg l USING (namespace, bucket, service) -LEFT JOIN metric_agg m USING (namespace, bucket, service) -WHERE a.service != '';` +// An independent raw-event oracle for the complete affected service-minute rows. +const serviceCountsReferenceSQL = `INSERT INTO service_rollup +WITH spans_by_key AS ( + SELECT namespace,date_trunc('minute',start_time::TIMESTAMP_NS) bucket,service,count(*) spans, + count(*) FILTER (WHERE coalesce(kind,'') NOT IN ('SPAN_KIND_CLIENT','SPAN_KIND_PRODUCER')) served_spans, + count(*) FILTER (WHERE status='STATUS_CODE_ERROR') error_spans FROM spans + WHERE start_time >= $1::TIMESTAMP_NS::TIMESTAMPTZ_NS AND start_time < $2::TIMESTAMP_NS::TIMESTAMPTZ_NS GROUP BY ALL +), logs_by_key AS ( + SELECT namespace,date_trunc('minute',time::TIMESTAMP_NS) bucket,service,count(*) logs FROM logs + WHERE time >= $1::TIMESTAMP_NS::TIMESTAMPTZ_NS AND time < $2::TIMESTAMP_NS::TIMESTAMPTZ_NS GROUP BY ALL +) SELECT namespace,bucket,service,coalesce(spans,0),coalesce(served_spans,0),coalesce(error_spans,0),coalesce(logs,0) +FROM service_pass_affected LEFT JOIN spans_by_key USING(namespace,bucket,service) +LEFT JOIN logs_by_key USING(namespace,bucket,service) WHERE service<>''` diff --git a/internal/engine/rollup_late_signal_memory_test.go b/internal/engine/rollup_late_signal_memory_test.go index f47c285ca..33d94b12b 100644 --- a/internal/engine/rollup_late_signal_memory_test.go +++ b/internal/engine/rollup_late_signal_memory_test.go @@ -37,8 +37,10 @@ func TestServiceLateSignalLogMetricMemory(t *testing.T) { UNION ALL SELECT 'ns',make_timestamp_ns(%d::BIGINT*60000000000)::TIMESTAMP_NS,'svc-0'`, recent, oldMinute) for _, q := range []string{ + "CREATE TEMP TABLE empty_logs AS SELECT * FROM logs LIMIT 0", + "CREATE TEMP TABLE empty_metrics AS SELECT * FROM metrics LIMIT 0", "SET memory_limit='2GB'", "SET threads=4", - fmt.Sprintf(`CREATE VIEW log_fixture AS SELECT 'ns' AS namespace,'svc-'||(i%%%d)::VARCHAR AS service, + fmt.Sprintf(`CREATE VIEW log_fixture AS SELECT 'ns' AS namespace,'svc-'||(i%%%d)::VARCHAR AS service,'' AS severity, make_timestamp_ns((i//%d)::BIGINT*60000000000)::TIMESTAMPTZ_NS AS time FROM range(%d) t(i)`, services, services, minutes*services), fmt.Sprintf(`CREATE VIEW metric_fixture AS SELECT 'ns' AS namespace,'svc-'||(i%%%d)::VARCHAR AS service, @@ -48,8 +50,8 @@ func TestServiceLateSignalLogMetricMemory(t *testing.T) { "COPY log_fixture TO " + sqlLiteral(logData) + " (FORMAT PARQUET)", "COPY (SELECT * FROM metric_fixture WHERE false) TO " + sqlLiteral(metricSchema) + " (FORMAT PARQUET)", "COPY metric_fixture TO " + sqlLiteral(metricData) + " (FORMAT PARQUET)", - "CREATE OR REPLACE VIEW logs AS SELECT * FROM read_parquet([" + sqlLiteral(logSchema) + "," + sqlLiteral(logData) + "],union_by_name=false,hive_partitioning=false)", - "CREATE OR REPLACE VIEW metrics AS SELECT * FROM read_parquet([" + sqlLiteral(metricSchema) + "," + sqlLiteral(metricData) + "],union_by_name=false,hive_partitioning=false)", + "CREATE OR REPLACE VIEW logs AS SELECT * FROM read_parquet([" + sqlLiteral(logSchema) + "," + sqlLiteral(logData) + "],union_by_name=false,hive_partitioning=false) UNION ALL BY NAME SELECT * FROM empty_logs", + "CREATE OR REPLACE VIEW metrics AS SELECT * FROM read_parquet([" + sqlLiteral(metricSchema) + "," + sqlLiteral(metricData) + "],union_by_name=false,hive_partitioning=false) UNION ALL BY NAME SELECT * FROM empty_metrics", "CREATE TEMP TABLE service_pass_affected AS " + affected, } { if _, err := db.Exec(q); err != nil { @@ -60,7 +62,7 @@ func TestServiceLateSignalLogMetricMemory(t *testing.T) { before := peakRSS(t) started := time.Now() lo, hi := time.Unix(0, 0).UTC(), time.Unix(int64(minutes*60), 0).UTC() - if _, err := insertServiceRollup(t.Context(), db, lo, hi); err != nil { + if _, err := insertDashboardRollups(t.Context(), db, lo, hi); err != nil { t.Fatal(err) } growth := peakRSS(t) - before @@ -71,11 +73,12 @@ func TestServiceLateSignalLogMetricMemory(t *testing.T) { // Only the six affected service-minutes are summarized, each with its one // log and one metric. The dense history behind the hull is never counted. - var rows, logCount, metricCount int - if err := db.QueryRow("SELECT count(*),sum(log_count),sum(metric_count) FROM service_rollup").Scan(&rows, &logCount, &metricCount); err != nil { + requireRowCount(t, db, "SELECT count(*) FROM resource_rollup WHERE signal=?", "metrics", 6) + var rows, logCount int + if err := db.QueryRow("SELECT count(*),sum(log_count) FROM service_rollup").Scan(&rows, &logCount); err != nil { t.Fatal(err) } - if rows != 6 || logCount != 6 || metricCount != 6 { - t.Fatalf("service_rollup rows=%d log_count=%d metric_count=%d, want 6/6/6", rows, logCount, metricCount) + if rows != 6 || logCount != 6 { + t.Fatalf("service_rollup rows=%d log_count=%d, want 6/6", rows, logCount) } } diff --git a/internal/engine/rollup_memory_test.go b/internal/engine/rollup_memory_test.go index 03d6e1162..cce62f9b6 100644 --- a/internal/engine/rollup_memory_test.go +++ b/internal/engine/rollup_memory_test.go @@ -10,6 +10,8 @@ import ( "strconv" "strings" "testing" + + "github.com/labstack/pitot/internal/rollupsql" ) // rollupUntrackedLimitMiB is how far past DuckDB's configured memory_limit one @@ -70,14 +72,14 @@ func TestServiceRollupLatencyDoesNotAllocatePerRow(t *testing.T) { t.Skip("scans 30M rows") } baseline := processRSSMiB(t) - query := fmt.Sprintf(`SELECT service, %s, %s + query := fmt.Sprintf(`SELECT service,histogram(%s) FROM ( SELECT (i %% 20)::VARCHAR AS service, (i %% 1000)::DOUBLE AS duration_ms, CASE WHEN i %% 7 = 0 THEN 'SPAN_KIND_CLIENT' ELSE 'SPAN_KIND_SERVER' END AS kind FROM range(30000000) t(i) ) s - GROUP BY service`, serviceRollupP50SQL("s"), serviceRollupP95SQL("s")) + GROUP BY service`, rollupsql.Bin("duration_ms")) rows, err := db.Query(query) if err != nil { diff --git a/internal/engine/rollup_scale_test.go b/internal/engine/rollup_scale_test.go index e76a7f278..7478c4350 100644 --- a/internal/engine/rollup_scale_test.go +++ b/internal/engine/rollup_scale_test.go @@ -144,9 +144,6 @@ func measureRollupKeyScale(t *testing.T, n int, kind string, verify bool) { width = 2 } wantStatements := (n + affectedKeyChunkSize - 1) / affectedKeyChunkSize - if kind == "service" { - wantStatements *= 2 - } // Service quantiles and span histogram, both bounded. if p.maxArgs > width*affectedKeyChunkSize+2 || p.statements != wantStatements { t.Fatalf("unbounded pass: args=%d statements=%d", p.maxArgs, p.statements) } @@ -162,7 +159,7 @@ func measureRollupKeyScale(t *testing.T, n int, kind string, verify bool) { if _, err := tx.ExecContext(t.Context(), "CREATE TEMP TABLE actual AS SELECT * FROM service_rollup; DELETE FROM service_rollup"); err != nil { t.Fatal(err) } - if _, err := tx.ExecContext(t.Context(), serviceRollupInsertSQL("true"), lo, hi, lo, hi, lo, hi); err != nil { + if _, err := tx.ExecContext(t.Context(), serviceCountsReferenceSQL, lo, hi); err != nil { t.Fatal(err) } } diff --git a/internal/engine/rollup_snapshot_window_test.go b/internal/engine/rollup_snapshot_window_test.go index 8ad71b061..2e8ddae67 100644 --- a/internal/engine/rollup_snapshot_window_test.go +++ b/internal/engine/rollup_snapshot_window_test.go @@ -36,9 +36,9 @@ func TestRollupSnapshotWindowRepairsOldMinuteFromAllCapturedFiles(t *testing.T) if d.rollupWatermarks[serviceRollupStateKey] <= before { t.Fatal("late publication did not advance the analytical watermark") } - var spans, logs, names int - if err := d.DB.QueryRowContext(t.Context(), `SELECT spans,log_count,metric_count FROM service_rollup WHERE bucket=?::TIMESTAMP_NS AND service='svc'`, at).Scan(&spans, &logs, &names); err != nil || spans != 1 || logs != 2 || names != 1 { - t.Fatalf("repaired old minute spans/logs/metric names=%d/%d/%d: %v", spans, logs, names, err) + var spans, logs int + if err := d.DB.QueryRowContext(t.Context(), `SELECT spans,log_count FROM service_rollup WHERE bucket=?::TIMESTAMP_NS AND service='svc'`, at).Scan(&spans, &logs); err != nil || spans != 1 || logs != 2 { + t.Fatalf("repaired old minute spans/logs=%d/%d: %v", spans, logs, err) } var first, last, increase, seconds float64 if err := d.DB.QueryRowContext(t.Context(), `SELECT first_point.value,last_point.value,counter_increase,counter_seconds FROM receiver_rollup WHERE bucket=?::TIMESTAMP_NS`, at).Scan(&first, &last, &increase, &seconds); err != nil || first != 1 || last != 3 || increase != 2 || seconds != 20 { diff --git a/internal/engine/rollup_sparse_memory_test.go b/internal/engine/rollup_sparse_memory_test.go index 6d89ec1d4..a65f500b2 100644 --- a/internal/engine/rollup_sparse_memory_test.go +++ b/internal/engine/rollup_sparse_memory_test.go @@ -109,16 +109,16 @@ func serviceSpanRollupMemory(t *testing.T, late bool) { t.Errorf("quantiles for %d affected keys grew RSS by %d, want <=96 MiB", wantGroups, growth) } var count, spans, served int - var p50, p95, errorRate float64 - if err := db.QueryRow("SELECT count(*),sum(spans),sum(served_spans),sum(p50_ms),sum(p95_ms),sum(error_rate) FROM service_rollup").Scan(&count, &spans, &served, &p50, &p95, &errorRate); err != nil { + var errors int + if err := db.QueryRow("SELECT count(*),sum(spans),sum(served_spans),sum(error_spans) FROM service_rollup").Scan(&count, &spans, &served, &errors); err != nil { t.Fatal(err) } var histogramSpans int if err := db.QueryRow("SELECT sum(list_sum(map_values(hist))) FROM span_rollup").Scan(&histogramSpans); err != nil || histogramSpans != wantSpans { t.Fatalf("histogram spans=%d want=%d: %v", histogramSpans, wantSpans, err) } - if count != wantGroups || spans != wantSpans || served != wantSpans || p50 != float64(wantGroups*5) || p95 != float64(wantGroups*5) || errorRate != 0 { - t.Fatalf("rollup=%d %d %d %g %g %g", count, spans, served, p50, p95, errorRate) + if count != wantGroups || spans != wantSpans || served != wantSpans || errors != 0 { + t.Fatalf("rollup=%d %d %d %d", count, spans, served, errors) } } diff --git a/internal/engine/rollup_test.go b/internal/engine/rollup_test.go index 22cce6663..b734eb9dd 100644 --- a/internal/engine/rollup_test.go +++ b/internal/engine/rollup_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/labstack/pitot/internal/config" + "github.com/labstack/pitot/internal/rollupsql" ) func TestRollupOnceRebuildsAffectedServiceBuckets(t *testing.T) { @@ -115,7 +116,7 @@ func TestServiceRollupLatencyExcludesDependencyWaits(t *testing.T) { p95 := func(service string) float64 { t.Helper() var value float64 - if err := db.QueryRow(`SELECT p95_ms FROM service_rollup WHERE namespace = 'ns' AND bucket = ? AND service = ?`, bucket, service).Scan(&value); err != nil { + if err := db.QueryRow("SELECT p95 FROM ("+rollupsql.ServiceWindow("namespace='ns' AND bucket=? AND service=?", "")+")", bucket, service).Scan(&value); err != nil { t.Fatalf("query p95 for %s: %v", service, err) } return value diff --git a/internal/engine/span_rollup_test.go b/internal/engine/span_rollup_test.go index df74db49e..ccb036205 100644 --- a/internal/engine/span_rollup_test.go +++ b/internal/engine/span_rollup_test.go @@ -2,9 +2,11 @@ package engine import ( "fmt" + "math" "testing" "time" + "github.com/labstack/pitot/internal/rollupsql" "github.com/labstack/pitot/internal/telemetry" telemetrystore "github.com/labstack/pitot/internal/telemetry/store" ) @@ -158,3 +160,32 @@ func TestSpanRollupFailureRollsBackServiceAndWatermark(t *testing.T) { requireRowCount(t, d.DB, "SELECT count(*) FROM "+table+" WHERE spans=?", 2, 1) } } + +func TestSpanHistogramHandlesNonfiniteDurationsAndEmptyBins(t *testing.T) { + db := openTestDuck(t) + for _, tc := range []struct { + duration float64 + bin int + p95 float64 + }{ + {math.NaN(), math.MinInt32, 0}, {math.Inf(-1), math.MinInt32, 0}, + {math.MaxFloat64, 8192, math.MaxFloat64}, {math.Inf(1), math.MaxInt32, math.MaxFloat64}, + } { + var bin int + var p95 float64 + err := db.QueryRow("SELECT k,"+rollupsql.Interpolate(".95", "k", "1", "1", "1")+" FROM (SELECT "+rollupsql.Bin("$1::DOUBLE")+" AS k)", tc.duration).Scan(&bin, &p95) + if err != nil || bin != tc.bin || p95 != tc.p95 { + t.Fatalf("duration %g: bin=%d p95=%g err=%v", tc.duration, bin, p95, err) + } + } + if err := CreateCacheTables(db); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`INSERT INTO span_rollup VALUES ('ns',now(),'empty','','',0,0,0,0,map([8],[0::UBIGINT]))`); err != nil { + t.Fatal(err) + } + var p50, p95 float64 + if err := db.QueryRow("SELECT p50,p95 FROM ("+rollupsql.ServiceWindow("true", "")+")").Scan(&p50, &p95); err != nil || p50 != 0 || p95 != 0 { + t.Fatalf("empty bin returned p50=%g p95=%g err=%v", p50, p95, err) + } +} diff --git a/internal/engine/views.go b/internal/engine/views.go index 4d64165fe..73bda5fc5 100644 --- a/internal/engine/views.go +++ b/internal/engine/views.go @@ -10,29 +10,20 @@ import ( // service_rollup drops its compound ART primary key for the same reason as the // scan summaries below. refreshServiceRollup replaces each affected scope in one -// serialized transaction and its INSERT groups by the complete logical key, so +// serialized transaction and joins counts to the distinct affected keys, so // uniqueness holds without an index DuckDB would probe under the checkpoint // vacuum lock. Keep every key column NOT NULL. const createServiceRollupTable = ` CREATE TABLE IF NOT EXISTS service_rollup ( namespace TEXT NOT NULL, - bucket TIMESTAMP NOT NULL, + bucket TIMESTAMP_NS NOT NULL, service TEXT NOT NULL, spans BIGINT, - -- Spans that describe work this service performed, rather than a call it was - -- waiting on. A bucket with none of them has no latency of its own to report, - -- and readers prefer the buckets that do; see the rollup's span_agg. served_spans BIGINT DEFAULT 0, - p50_ms DOUBLE, - p95_ms DOUBLE, - error_rate DOUBLE, - log_count BIGINT DEFAULT 0, - metric_count BIGINT DEFAULT 0 + error_spans BIGINT DEFAULT 0, + log_count BIGINT DEFAULT 0 );` -// spanHistogramZero is outside the index range of positive finite durations. -const spanHistogramZero = -2147483648 - // These scan-oriented summaries intentionally have no ART primary key. // refreshServiceRollup serializes complete affected-scope replacement in one // transaction, and each INSERT groups by the complete logical key. Keep every diff --git a/internal/intelligence/detector.go b/internal/intelligence/detector.go index 508c60309..3120c25af 100644 --- a/internal/intelligence/detector.go +++ b/internal/intelligence/detector.go @@ -14,6 +14,7 @@ import ( "github.com/labstack/pitot/internal/annotations" "github.com/labstack/pitot/internal/queryrows" + "github.com/labstack/pitot/internal/rollupsql" ) // Engine is the read and annotation surface the detector uses; *engine.Duck @@ -339,50 +340,7 @@ const minVolumeStddev = 1.0 // keeps a single stray error in a few thousand spans below the threshold while // letting a real break through. func errorRateAnomalySQL(startNano, endNano int64, scope string) string { - return fmt.Sprintf(` - WITH current_period AS ( - SELECT - service_name, - AVG(bucket_rate) AS error_rate - FROM ( - SELECT - service as service_name, - (SUM(error_rate * spans) / SUM(spans)) AS bucket_rate - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 - %s - GROUP BY service, time_bucket(INTERVAL '5 minutes', bucket) - ) buckets - GROUP BY service_name - ), - baseline_period AS ( - SELECT - service_name, - AVG(bucket_rate) AS error_rate, - GREATEST(COALESCE(STDDEV(bucket_rate), 0.0), %f) AS error_stddev - FROM ( - SELECT - service as service_name, - (SUM(error_rate * spans) / SUM(spans)) AS bucket_rate - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 - %s - GROUP BY service, time_bucket(INTERVAL '5 minutes', bucket) - ) buckets - GROUP BY service_name - ) - SELECT - c.service_name, - c.error_rate AS current_rate, - COALESCE(b.error_rate, 0.0) AS baseline_rate, - CASE - WHEN b.error_stddev > 0 THEN (c.error_rate - b.error_rate) / b.error_stddev - ELSE 0.0 - END AS z_score - FROM current_period c - LEFT JOIN baseline_period b ON c.service_name = b.service_name - WHERE c.error_rate > 0 - `, startNano, endNano, scope, minErrorRateStddev, startNano-endNano+startNano, startNano, scope) + return anomalyWindowSQL(startNano, endNano, scope, "error_rate", minErrorRateStddev) + " WHERE c.error_rate>0" } // detectErrorRateAnomalies detects error rate spikes @@ -422,8 +380,6 @@ func (d *Detector) detectErrorRateAnomalies(ctx context.Context, start, end time // detectLatencyAnomalies detects latency degradation func (d *Detector) detectLatencyAnomalies(ctx context.Context, start, end time.Time) ([]Anomaly, error) { - // service_rollup grades served spans (with its outbound-only fallback). - // Weight minute p95 values by spans; do not recompute raw-span quantiles. rows, err := d.readWindowAnomalies(ctx, start, end, latencyAnomalySQL) if err != nil { return nil, fmt.Errorf("latency detection: %w", err) @@ -436,9 +392,7 @@ func (d *Detector) detectLatencyAnomalies(ctx context.Context, start, end time.T baselineP95 := row.baseline zScore := row.zScore - increase := currentP95 - baselineP95 - if zScore >= d.config.LatencyThreshold && - increase >= minLatencyIncreaseMS && increase >= baselineP95*minLatencyIncreaseRatio { + if qualifiesLatencyIncrease(currentP95, baselineP95, zScore, d.config.LatencyThreshold) { anomalies = append(anomalies, Anomaly{ Type: AnomalyLatencyDegradation, ServiceName: serviceName, @@ -458,6 +412,11 @@ func (d *Detector) detectLatencyAnomalies(ctx context.Context, start, end time.T return anomalies, nil } +func qualifiesLatencyIncrease(current, baseline, zScore, threshold float64) bool { + increase := current - baseline + return zScore >= threshold && increase >= minLatencyIncreaseMS && increase >= baseline*minLatencyIncreaseRatio +} + // volumeAnomalySQL compares span volume in [startNano, endNano) against the // window of equal length immediately before it. // @@ -480,8 +439,8 @@ func volumeAnomalySQL(startNano, endNano int64, scope string) string { SELECT service as service_name, SUM(spans) AS cnt - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 + FROM span_rollup + WHERE service<>'' AND bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 %s GROUP BY service, time_bucket(INTERVAL '5 minutes', bucket) ) subq @@ -496,8 +455,8 @@ func volumeAnomalySQL(startNano, endNano int64, scope string) string { SELECT service as service_name, SUM(spans) AS cnt - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 + FROM span_rollup + WHERE service<>'' AND bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 %s GROUP BY service, time_bucket(INTERVAL '5 minutes', bucket) ) subq @@ -551,49 +510,35 @@ func (d *Detector) detectVolumeAnomalies(ctx context.Context, start, end time.Ti return anomalies, nil } -// latencyAnomalySQL compares span-weighted minute p95 values. Baseline -// scatter remains the standard deviation of five-minute bucket values. +// Compare whole-window values. Five-minute baseline samples only estimate scatter. func latencyAnomalySQL(startNano, endNano int64, scope string) string { - return fmt.Sprintf(` - WITH current_period AS ( - SELECT - service as service_name, - SUM(p95_ms * spans) / SUM(spans) AS p95_latency - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 - %s - GROUP BY service - ), - baseline_buckets AS ( - SELECT - service as service_name, - time_bucket(INTERVAL '5 minutes', bucket) AS baseline_bucket, - SUM(p95_ms * spans) / SUM(spans) AS p95_latency - FROM service_rollup - WHERE bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans > 0 - %s - GROUP BY service, baseline_bucket - ), - baseline_period AS ( - SELECT - service_name, - AVG(p95_latency) AS avg_p95, - STDDEV(p95_latency) AS p95_stddev - FROM baseline_buckets - GROUP BY service_name - ) - SELECT - c.service_name, - c.p95_latency AS current_p95, - COALESCE(b.avg_p95, 0.0) AS baseline_p95, - CASE - WHEN b.avg_p95 IS NOT NULL THEN (c.p95_latency - b.avg_p95) / GREATEST(COALESCE(b.p95_stddev, 0.0), %f) - ELSE 0.0 - END AS z_score - FROM current_period c - LEFT JOIN baseline_period b ON c.service_name = b.service_name - `, startNano, endNano, scope, startNano-endNano+startNano, startNano, scope, minLatencyStddev) + return anomalyWindowSQL(startNano, endNano, scope, "p95", minLatencyStddev) +} +func anomalyWindowSQL(start, end int64, scope, metric string, floor float64) string { + window := func(lo, hi int64, bucket string) string { + where := fmt.Sprintf("bucket >= make_timestamp_ns(%d) AND bucket < make_timestamp_ns(%d) AND spans>0 %s", lo, hi, scope) + if metric == "p95" { + if bucket != "" { + // Use the same population as the whole baseline. Quiet outbound-only + // minutes of a serving service contribute no latency sample. + where += " AND (" + rollupsql.Served + " OR service IN (SELECT service FROM baseline_period WHERE served_spans=0))" + } + return rollupsql.ServiceWindow(where, bucket) + } + group := "service" + if bucket != "" { + group += "," + bucket + } + return "SELECT service," + rollupsql.ErrorRate + " AS error_rate FROM span_rollup WHERE service<>'' AND " + where + " GROUP BY " + group + } + baseline := start - (end - start) + return fmt.Sprintf(`WITH current_period AS (%s), baseline_period AS (%s), + baseline_buckets AS (%s), scatter AS (SELECT service,stddev(%[4]s) AS deviation FROM baseline_buckets GROUP BY service) + SELECT c.service,c.%[4]s AS current_%[4]s,coalesce(b.%[4]s,0), + coalesce((c.%[4]s-b.%[4]s)/greatest(coalesce(deviation,0),%[5]f),0) + FROM current_period c LEFT JOIN baseline_period b USING(service) LEFT JOIN scatter USING(service)`, + window(start, end, ""), window(baseline, start, ""), window(baseline, start, "time_bucket(INTERVAL '5 minutes',bucket)"), metric, floor) } type serviceAnomalyRow struct { diff --git a/internal/intelligence/detector_recovery_test.go b/internal/intelligence/detector_recovery_test.go index cb8ad7fa8..195edbd1f 100644 --- a/internal/intelligence/detector_recovery_test.go +++ b/internal/intelligence/detector_recovery_test.go @@ -10,6 +10,7 @@ import ( "github.com/labstack/pitot/internal/annotations" "github.com/labstack/pitot/internal/config" "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" "github.com/labstack/pitot/internal/engine/writegate" telemetrystore "github.com/labstack/pitot/internal/telemetry/store" ) @@ -21,9 +22,7 @@ func seedDetectorRecoveryRollup(t *testing.T, db *sql.DB, end time.Time) { if i >= 3 { rate, p95 = .5, 1000 } - if _, err := db.Exec(`INSERT INTO service_rollup(namespace,bucket,service,spans,served_spans,p95_ms,error_rate) VALUES ('default',?,'api',?,?,?,?)`, end.Add(time.Duration(i-6)*5*time.Minute), count, count, p95, rate); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, end.Add(time.Duration(i-6)*5*time.Minute), "default", "api", "", count, int(float64(count)*rate), p95) } if _, err := db.Exec(`INSERT INTO rollup_state VALUES ('service_rollup_v3',?,now())`, end.Add(30*time.Second).UnixNano()); err != nil { t.Fatal(err) @@ -31,7 +30,7 @@ func seedDetectorRecoveryRollup(t *testing.T, db *sql.DB, end time.Time) { } func TestDetectorRetriesFailedQueriesAtUnchangedWatermark(t *testing.T) { - for _, statement := range []string{"AS current_rate", "AS current_p95", "AS current_count"} { + for _, statement := range []string{"AS current_error_rate", "AS current_p95", "AS current_count"} { for _, withPrevious := range []bool{false, true} { name := statement + "/startup" if withPrevious { @@ -191,7 +190,7 @@ func TestDetectorRetriesPatternFailureWithoutPublishingHealthySnapshot(t *testin } // The anomaly evaluation completed even if patterns failed. Recover // patterns while refusing to re-run that completed anomaly query. - connector.fail = "AS current_rate" + connector.fail = "AS current_error_rate" d.runCheck(t.Context()) got := d.LatestSnapshot() if got == nil || got == previous || len(got.Patterns) != 1 || len(got.Anomalies) != 3 || got.HealthScore >= 100 { @@ -221,7 +220,7 @@ func TestDetectorKeepsUnpublishedFindingsWhenWatermarkAdvances(t *testing.T) { // Replace the failed-publication evaluation with a healthy, later window // while patterns still fail, then recover at that new watermark. advanced := end.Add(time.Minute) - if _, err := connector.DB.Exec(`UPDATE service_rollup SET error_rate=0,p95_ms=10,spans=100,served_spans=100`); err != nil { + if _, err := connector.DB.Exec(`DELETE FROM span_rollup WHERE status='STATUS_CODE_ERROR'; UPDATE span_rollup SET spans=100,hist=map([27],[100::UBIGINT])`); err != nil { t.Fatal(err) } if _, err := connector.DB.Exec(`UPDATE rollup_state SET last_ingested_unix_nano=? WHERE cache_key='service_rollup_v3'`, advanced.Add(30*time.Second).UnixNano()); err != nil { diff --git a/internal/intelligence/effect_size_test.go b/internal/intelligence/effect_size_test.go index ed20994cd..9d70abec4 100644 --- a/internal/intelligence/effect_size_test.go +++ b/internal/intelligence/effect_size_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" ) func TestLatencyAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T) { @@ -25,15 +26,13 @@ func TestLatencyAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T {"sub_millisecond_doubling", .3, .6, .001, false}, {"real_regression", 20, 60, 1, true}, {"flat_baseline_regression", 20, 60, 0, true}, - {"absolute_below", 10, 15 - 1e-6, .01, false}, - {"absolute_at", 10, 15, .01, true}, - {"absolute_above", 10, 15 + 1e-6, .01, true}, + {"absolute_below", 10, 14, .01, false}, + {"absolute_above", 10, 16, .01, true}, {"relative_below", 100, 120 - 1e-6, .01, false}, - {"relative_at", 100, 120, .01, true}, - {"relative_above", 100, 120 + 1e-6, .01, true}, + {"relative_above", 100, 130, .01, true}, {"noisy_baseline", 100, 125, 30, false}, {"statistical_below", 20, 30 - 1e-6, 5, false}, - {"statistical_at", 20, 30, 5, true}, + {"statistical_above", 20, 45, 5, true}, {"improvement", 60, 20, 1, false}, } for _, tt := range tests { @@ -42,9 +41,7 @@ func TestLatencyAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T if i < 3 { p95 = tt.baseline + float64(i-1)*tt.stddev } - if _, err := db.Exec(`INSERT INTO service_rollup VALUES (?, 'default', ?, 100, ?)`, tt.name, start.Add(time.Duration(i-3)*5*time.Minute), p95); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, start.Add(time.Duration(i-3)*5*time.Minute), "default", tt.name, "", 100, 0, p95) } } d := NewDetector(&engine.Duck{DB: db}, DefaultDetectorConfig()) @@ -59,6 +56,21 @@ func TestLatencyAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T } } +func TestLatencyIncreaseIncludesExactDecisionBoundaries(t *testing.T) { + for _, tc := range []struct { + current, baseline, z float64 + want bool + }{ + {15 - 1e-6, 10, 4, false}, {15, 10, 4, true}, {15 + 1e-6, 10, 4, true}, + {120 - 1e-6, 100, 4, false}, {120, 100, 4, true}, {120 + 1e-6, 100, 4, true}, + {30, 20, 2 - 1e-6, false}, {30, 20, 2, true}, + } { + if got := qualifiesLatencyIncrease(tc.current, tc.baseline, tc.z, 2); got != tc.want { + t.Errorf("current=%g baseline=%g z=%g: got %t", tc.current, tc.baseline, tc.z, got) + } + } +} + func TestVolumeAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T) { db := effectSizeDB(t) start := time.Date(2026, 10, 1, 12, 15, 0, 0, time.UTC) @@ -99,9 +111,7 @@ func TestVolumeAnomaliesRequireStatisticalAndPracticalSignificance(t *testing.T) if count == 0 { continue } - if _, err := db.Exec(`INSERT INTO service_rollup VALUES (?, 'default', ?, ?, 10)`, tt.name, start.Add(time.Duration(i-3)*5*time.Minute), count); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, start.Add(time.Duration(i-3)*5*time.Minute), "default", tt.name, "", count, 0, 10) } } d := NewDetector(&engine.Duck{DB: db}, DefaultDetectorConfig()) @@ -132,13 +142,9 @@ func TestAnomalyScatterFloorsRetainFlatAndSingleBucketBaselines(t *testing.T) { } else { spans = value } - if _, err := db.Exec(`INSERT INTO service_rollup VALUES ('api', 'default', ?, ?, ?)`, start.Add(time.Duration(i-3)*5*time.Minute), spans, p95); err != nil { - t.Fatal(err) - } - } - if _, err := db.Exec(`INSERT INTO service_rollup VALUES ('api', 'default', ?, 150, 150)`, start); err != nil { - t.Fatal(err) + querytest.SeedSpanRollup(t, db, start.Add(time.Duration(i-3)*5*time.Minute), "default", "api", "", spans, 0, float64(p95)) } + querytest.SeedSpanRollup(t, db, start, "default", "api", "", 150, 0, 150) statement := latencyAnomalySQL(start.UnixNano(), end.UnixNano(), "") if kind == "volume" { statement = volumeAnomalySQL(start.UnixNano(), end.UnixNano(), "") @@ -152,7 +158,24 @@ func TestAnomalyScatterFloorsRetainFlatAndSingleBucketBaselines(t *testing.T) { if buckets == 3 { denominator = math.Max(float64(scatter), 1) } - if want := 50 / denominator; math.Abs(z-want) > 1e-9 { + if kind == "latency" && buckets == 3 { + // Each five-minute sample is a single populated bin. + estimates := make([]float64, buckets) + var mean float64 + for i := range estimates { + k := math.Ceil(math.Log2(float64(100+(i-1)*scatter)) * 8) + upper := math.Exp2(k / 8) + lower := math.Exp2((k - 1) / 8) + estimates[i] = lower + .95*(upper-lower) + mean += estimates[i] / float64(buckets) + } + var variance float64 + for _, p := range estimates { + variance += (p - mean) * (p - mean) / float64(buckets-1) + } + denominator = math.Max(1, math.Sqrt(variance)) + } + if want := (current - baseline) / denominator; math.Abs(z-want) > 1e-9 { t.Fatalf("z=%g, want %g", z, want) } }) @@ -168,7 +191,7 @@ func effectSizeDB(t *testing.T) *sql.DB { t.Fatal(err) } t.Cleanup(func() { _ = db.Close() }) - if _, err := db.Exec(`CREATE TABLE service_rollup (service TEXT, namespace TEXT, bucket TIMESTAMP_NS, spans BIGINT, p95_ms DOUBLE)`); err != nil { + if err := engine.CreateCacheTables(db); err != nil { t.Fatal(err) } return db @@ -209,3 +232,35 @@ func assertEffectSizeFinding(t *testing.T, d *Detector, anomalies []Anomaly, ser t.Fatalf("qualified finding severity: %+v", annotations) } } + +func TestLatencyScatterUsesWholeBaselinePopulation(t *testing.T) { + db := effectSizeDB(t) + start := time.Date(2026, 10, 1, 12, 15, 0, 0, time.UTC) + end := start.Add(15 * time.Minute) + for _, service := range []string{"api", "outbound"} { + kind := "SPAN_KIND_SERVER" + if service == "outbound" { + kind = "SPAN_KIND_CLIENT" + } + querytest.SeedSpanRollup(t, db, start.Add(-15*time.Minute), "default", service, kind, 100, 0, 20) + querytest.SeedSpanRollup(t, db, start.Add(-10*time.Minute), "default", service, "SPAN_KIND_CLIENT", 1, 0, 600000) + querytest.SeedSpanRollup(t, db, start.Add(-5*time.Minute), "default", service, kind, 100, 0, 20) + querytest.SeedSpanRollup(t, db, start, "default", service, kind, 100, 0, 60) + } + d := NewDetector(&engine.Duck{DB: db}, DefaultDetectorConfig()) + rows, err := d.readWindowAnomalies(t.Context(), start, end, latencyAnomalySQL) + if err != nil || len(rows) != 2 { + t.Fatalf("rows=%+v err=%v", rows, err) + } + for _, row := range rows { + if row.baseline < 19 || row.baseline > 22 || row.current < 55 || row.current > 65 { + t.Fatalf("unexpected latency: %+v", row) + } + if row.service == "api" && math.Abs(row.zScore-(row.current-row.baseline)/minLatencyStddev) > 1e-9 { + t.Fatalf("client-only minute contributed to serving baseline scatter: %+v", row) + } + if row.service == "outbound" && !(row.zScore > 0 && row.zScore < .001) { + t.Fatalf("outbound-only baseline lost its slow sample: %+v", row) + } + } +} diff --git a/internal/intelligence/error_rate_sql_test.go b/internal/intelligence/error_rate_sql_test.go index 95e2126c4..5d389ca47 100644 --- a/internal/intelligence/error_rate_sql_test.go +++ b/internal/intelligence/error_rate_sql_test.go @@ -5,6 +5,9 @@ import ( "math" "testing" "time" + + "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" ) // errorRateFixture writes six 5-minute buckets: the first three are the @@ -12,17 +15,13 @@ import ( // error percentage, so a service's whole history is one readable slice. func errorRateFixture(t *testing.T, db *sql.DB, start time.Time, services map[string][]float64) { t.Helper() - if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS service_rollup ( - service VARCHAR, namespace VARCHAR, bucket TIMESTAMP_NS, spans BIGINT, error_rate DOUBLE - )`); err != nil { + if err := engine.CreateCacheTables(db); err != nil { t.Fatal(err) } for service, rates := range services { for bucket, rate := range rates { at := start.Add(time.Duration(bucket) * 5 * time.Minute) - if _, err := db.Exec(`INSERT INTO service_rollup VALUES (?,'default',?,1000,?)`, service, at, rate); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, at, "default", service, "", 1000, int(math.Round(1000*rate)), 10) } } diff --git a/internal/intelligence/pattern_recovery_test.go b/internal/intelligence/pattern_recovery_test.go index 159f1344a..555f4850e 100644 --- a/internal/intelligence/pattern_recovery_test.go +++ b/internal/intelligence/pattern_recovery_test.go @@ -123,7 +123,7 @@ func TestDetectorRefreshesPatternsAtStalledAndZeroWatermarks(t *testing.T) { at := time.Now().UTC().Add(-time.Minute) e.commitFailures(t, at) // Changing rollup data must not change the cached anomaly evaluation. - if _, err := e.DB.Exec(`UPDATE service_rollup SET error_rate=0,p95_ms=0,spans=1`); err != nil { + if _, err := e.DB.Exec(`DELETE FROM span_rollup`); err != nil { t.Fatal(err) } d.runCheck(t.Context()) diff --git a/internal/intelligence/rollup_detector_test.go b/internal/intelligence/rollup_detector_test.go index fd21d8105..e99896467 100644 --- a/internal/intelligence/rollup_detector_test.go +++ b/internal/intelligence/rollup_detector_test.go @@ -9,6 +9,7 @@ import ( "github.com/labstack/pitot/internal/annotations" "github.com/labstack/pitot/internal/config" "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" telemetrystore "github.com/labstack/pitot/internal/telemetry/store" ) @@ -30,9 +31,7 @@ func TestServiceDetectorsWeightMinutesBySpanCount(t *testing.T) { spans int rate, p95 float64 }{{0, 10, .9, 100}, {1, 90, .1, 10}} { - if _, err := db.Exec(`INSERT INTO service_rollup(namespace,bucket,service,spans,served_spans,p95_ms,error_rate) VALUES ('prod',?,'api',?,?,?,?)`, at.Add(time.Duration(v.offset)*time.Minute), v.spans, v.spans, v.p95+float64(bucket), v.rate); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, at.Add(time.Duration(v.offset)*time.Minute), "prod", "api", "", v.spans, int(math.Round(float64(v.spans)*v.rate)), v.p95+float64(bucket)) } } for _, test := range []struct { @@ -40,7 +39,7 @@ func TestServiceDetectorsWeightMinutesBySpanCount(t *testing.T) { want float64 }{ {"errors", errorRateAnomalySQL(start.UnixNano(), end.UnixNano(), "AND namespace='prod'"), .18}, - {"latency", latencyAnomalySQL(start.UnixNano(), end.UnixNano(), "AND namespace='prod'"), 23}, + {"latency", latencyAnomalySQL(start.UnixNano(), end.UnixNano(), "AND namespace='prod'"), (math.Exp2(53.0/8) + math.Exp2(54.0/8)) / 2}, {"volume", volumeAnomalySQL(start.UnixNano(), end.UnixNano(), "AND namespace='prod'"), 100}, } { var service string @@ -78,9 +77,7 @@ func TestDetectorsStopBeforeTheServiceWatermarkMinute(t *testing.T) { db := e.DB base := time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) for i, rate := range []float64{0, .5, 1} { - if _, err := db.Exec(`INSERT INTO service_rollup(namespace,bucket,service,spans,served_spans,p95_ms,error_rate) VALUES ('prod',?,'api',100,100,10,?)`, base.Add(time.Duration(i)*5*time.Minute), rate); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, db, base.Add(time.Duration(i)*5*time.Minute), "prod", "api", "", 100, int(100*rate), 10) } watermark := base.Add(10*time.Minute + 30*time.Second).UnixNano() if _, err := db.Exec(`INSERT INTO rollup_state VALUES ('service_rollup_v3',?,now())`, watermark); err != nil { @@ -124,9 +121,7 @@ func TestDetectorPersistsEvaluatedWindowWhilePatternsRefresh(t *testing.T) { if i >= 0 { rate = .5 } - if _, err := duck.DB.Exec(`INSERT INTO service_rollup(namespace,bucket,service,spans,served_spans,p95_ms,error_rate) VALUES ('default',?,'api',100,100,10,?)`, start.Add(time.Duration(i)*5*time.Minute), rate); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, duck.DB, start.Add(time.Duration(i)*5*time.Minute), "default", "api", "", 100, int(100*rate), 10) } watermark := end.Add(30 * time.Second).UnixNano() if _, err := duck.DB.Exec(`INSERT INTO rollup_state VALUES ('service_rollup_v3',?,now())`, watermark); err != nil { @@ -160,7 +155,7 @@ func TestDetectorPersistsEvaluatedWindowWhilePatternsRefresh(t *testing.T) { } // A recheck would see different values; an unchanged completed minute must // retain the anomaly evaluation while rebuilding the live snapshot. - if _, err := duck.DB.Exec(`UPDATE service_rollup SET error_rate=.9 WHERE bucket >= ?`, start); err != nil { + if _, err := duck.DB.Exec(`UPDATE span_rollup SET status='STATUS_CODE_ERROR' WHERE bucket >= ?`, start); err != nil { t.Fatal(err) } for range 2 { diff --git a/internal/intelligence/volume_sql_test.go b/internal/intelligence/volume_sql_test.go index c1729b4bf..a9afb41f8 100644 --- a/internal/intelligence/volume_sql_test.go +++ b/internal/intelligence/volume_sql_test.go @@ -22,7 +22,7 @@ func TestVolumeAnomalyComparesEqualWindows(t *testing.T) { t.Fatal(err) } defer db.Close() - if _, err := db.Exec(`CREATE TABLE service_rollup ( + if _, err := db.Exec(`CREATE TABLE span_rollup ( service TEXT, namespace TEXT, bucket TIMESTAMP_NS, spans BIGINT )`); err != nil { t.Fatal(err) @@ -38,7 +38,7 @@ func TestVolumeAnomalyComparesEqualWindows(t *testing.T) { for bucket, count := range perBucket { at := baselineStart.Add(time.Duration(bucket) * 5 * time.Minute) for _, service := range []string{"cart", "checkout", "frontend"} { - if _, err := db.Exec(`INSERT INTO service_rollup VALUES (?, 'default', ?, ?)`, service, at, count); err != nil { + if _, err := db.Exec(`INSERT INTO span_rollup VALUES (?, 'default', ?, ?)`, service, at, count); err != nil { t.Fatal(err) } } @@ -90,7 +90,7 @@ func TestVolumeAnomalyStillFiresOnARealDrop(t *testing.T) { t.Fatal(err) } defer db.Close() - if _, err := db.Exec(`CREATE TABLE service_rollup ( + if _, err := db.Exec(`CREATE TABLE span_rollup ( service TEXT, namespace TEXT, bucket TIMESTAMP_NS, spans BIGINT )`); err != nil { t.Fatal(err) @@ -108,7 +108,7 @@ func TestVolumeAnomalyStillFiresOnARealDrop(t *testing.T) { if service == "collapsing" && inCurrentWindow { count = count / 20 } - if _, err := db.Exec(`INSERT INTO service_rollup VALUES (?, 'default', ?, ?)`, service, at, count); err != nil { + if _, err := db.Exec(`INSERT INTO span_rollup VALUES (?, 'default', ?, ?)`, service, at, count); err != nil { t.Fatal(err) } count = perBucket[bucket] diff --git a/internal/mcp/panels.go b/internal/mcp/panels.go index 025fc4765..dd4c34cfa 100644 --- a/internal/mcp/panels.go +++ b/internal/mcp/panels.go @@ -44,7 +44,7 @@ type PreviewOutput struct { Problems []query.Problem `json:"problems,omitempty"` } -const baseSpecGuide = `A dashboard is {name, description, time:{range}, variables, panels}. Each panel: {id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: {field: duration_ms, buckets: log2} for spans or {field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: {from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Standard OpenTelemetry keys that get_telemetry_schema marks indexed, such as http.response.status_code and k8s.pod.name, read typed: ingest converts a value sent in another type, so "200" reads as the number 200, and they need no cast. Other keys read as sent. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', attributes['http.route'] IN $routes, attributes['http.response.status_code'] >= 500. Variables: {name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, span_rollup, edge_rollup or resource_inventory that filters time with $__window(column).` + " " + query.SQLTimestampGuide + ` Use values exactly as get_telemetry_schema lists them. Example panel: {"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[{"value":1500,"status":"bad"}]}.` + " Structured spans aggregate panels restricted to namespace/service/kind/status and count/rate/error_rate/share or duration aggregates use span_rollup at minute resolution. Percentiles are approximate (one exponential bucket, 9.05%); fresh_to_ms is the ingest horizon. Other structured queries stay raw." + " " + metricMeasureGuide + " " + resourceInventoryGuide +const baseSpecGuide = `A dashboard is {name, description, time:{range}, variables, panels}. Each panel: {id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: {field: duration_ms, buckets: log2} for spans or {field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: {from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Standard OpenTelemetry keys that get_telemetry_schema marks indexed, such as http.response.status_code and k8s.pod.name, read typed: ingest converts a value sent in another type, so "200" reads as the number 200, and they need no cast. Other keys read as sent. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', attributes['http.route'] IN $routes, attributes['http.response.status_code'] >= 500. Variables: {name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, span_rollup, edge_rollup or resource_inventory that filters time with $__window(column).` + " " + query.SQLTimestampGuide + ` Use values exactly as get_telemetry_schema lists them. Example panel: {"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[{"value":1500,"status":"bad"}]}.` + " Structured spans aggregate panels restricted to namespace/service/kind/status and count/rate/error_rate/share or duration aggregates use span_rollup at minute resolution. All measures use the spans matching the panel filters. To measure served latency, filter out client and producer kinds. Percentiles are approximate (one exponential bucket, 9.05%); fresh_to_ms is the ingest horizon. Other structured queries stay raw." + " " + metricMeasureGuide + " " + resourceInventoryGuide func (s *Server) registerPanelTools() { readOnly := &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: boolPtr(false)} diff --git a/internal/mcp/panels_test.go b/internal/mcp/panels_test.go index afc499e12..514da1288 100644 --- a/internal/mcp/panels_test.go +++ b/internal/mcp/panels_test.go @@ -81,7 +81,10 @@ func panelServerFixtureAt(t *testing.T, seed bool, now time.Time) *Server { if err := querytest.RefreshSpanRollup(duck.DB); err != nil { t.Fatal(err) } - if _, err := duck.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',30,30,100,100,.1,30,0)`, at); err != nil { + if _, err := duck.DB.Exec(`INSERT INTO rollup_state VALUES ('service_rollup_v3',?,now())`, now.UnixNano()); err != nil { + t.Fatal(err) + } + if _, err := duck.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',30,30,30,30)`, at); err != nil { t.Fatal(err) } if _, err := duck.DB.Exec(`INSERT INTO edge_rollup(namespace,bucket,caller,callee,calls,avg_ms,error_rate,edge_type) VALUES ('shop',?,'checkout','payment',30,100,.1,'call')`, at); err != nil { diff --git a/internal/mcp/service_input_test.go b/internal/mcp/service_input_test.go index c8d91898e..ed9e3fc28 100644 --- a/internal/mcp/service_input_test.go +++ b/internal/mcp/service_input_test.go @@ -403,7 +403,7 @@ func BenchmarkServiceInput(b *testing.B) { if err := repo.Commit(b.Context(), batch); err != nil { b.Fatal(err) } - if _, err := duck.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',6,6,1,1,0,0,0)`, from.Add(time.Minute)); err != nil { + if _, err := duck.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',6,6,0,0)`, from.Add(time.Minute)); err != nil { b.Fatal(err) } if _, err := duck.RefreshReadCaches(b.Context()); err != nil { diff --git a/internal/observability/contracts.go b/internal/observability/contracts.go index 1bfab156b..76c74ef51 100644 --- a/internal/observability/contracts.go +++ b/internal/observability/contracts.go @@ -45,14 +45,15 @@ const ( ) type ServiceHealth struct { - Service string `json:"service"` - Health Health `json:"health"` - Spans int64 `json:"spans"` - ErrorRate float64 `json:"error_rate"` - P50MS float64 `json:"p50_ms"` - P95MS float64 `json:"p95_ms"` - LogCount int64 `json:"log_count"` - MetricCount int64 `json:"metric_count"` + Service string `json:"service"` + Health Health `json:"health"` + Spans int64 `json:"spans"` + ErrorRate float64 `json:"error_rate"` + P50MS float64 `json:"p50_ms"` + P95MS float64 `json:"p95_ms"` + LogCount int64 `json:"log_count"` + // MetricCount counts distinct reporting metric resource identities in the window. + MetricCount int64 `json:"metric_count"` } type HealthCounts struct { diff --git a/internal/observability/health_trend.go b/internal/observability/health_trend.go index a0150cf61..be959b660 100644 --- a/internal/observability/health_trend.go +++ b/internal/observability/health_trend.go @@ -3,8 +3,10 @@ package observability import ( "context" "fmt" - "github.com/labstack/pitot/internal/queryrows" "time" + + "github.com/labstack/pitot/internal/queryrows" + "github.com/labstack/pitot/internal/rollupsql" ) type HealthTrend struct { @@ -19,8 +21,8 @@ func (s *Service) HealthErrorTrend(ctx context.Context, scope Scope) (HealthTren } ctx = queryrows.WithWindow(ctx, queryrows.Window{Start: scope.Start, End: scope.End, Namespace: scope.Namespace, Service: scope.Service}) sql := fmt.Sprintf(`SELECT time_bucket(INTERVAL '%s',bucket) AS point_time, - 100.0*COALESCE(SUM(error_rate*spans)/NULLIF(SUM(spans),0),0) - FROM service_rollup WHERE bucket>=? AND bucket'' AND bucket>=? AND bucket 1e-9 || len(trend.Times) != 1 || trend.Times[0] != at.UnixMilli() { @@ -36,9 +39,7 @@ func TestHealthErrorTrendRetainsSparseBucketTimes(t *testing.T) { d, _, svc := newCompletedReadTest(t) at := time.Date(2026, 10, 1, 12, 1, 17, 0, time.UTC) for i, offset := range []time.Duration{time.Minute, 23 * time.Minute} { - if _, err := d.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',10,10,50,100,?,0,0)`, at.Add(offset), float64(i)/10); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, d.DB, at.Add(offset), "shop", "checkout", "", 10, i, 100) } trend, err := svc.HealthErrorTrend(t.Context(), Scope{Namespace: "shop", Start: at, End: at.Add(time.Hour)}) if err != nil || len(trend.Times) != 2 || len(trend.Values) != 2 || trend.Times[0] != time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC).UnixMilli() || trend.Times[1] != time.Date(2026, 10, 1, 12, 20, 0, 0, time.UTC).UnixMilli() || trend.Values[0] != 0 || trend.Values[1] != 10 { diff --git a/internal/observability/latency_read_test.go b/internal/observability/latency_read_test.go index 4994aef34..3a8e86615 100644 --- a/internal/observability/latency_read_test.go +++ b/internal/observability/latency_read_test.go @@ -7,6 +7,9 @@ import ( "time" _ "github.com/duckdb/duckdb-go/v2" + + "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" ) // A bucket holding nothing but calls the service was waiting on must not decide @@ -20,23 +23,14 @@ func TestOverviewPrefersBucketsWhereTheServiceServedSomething(t *testing.T) { t.Fatalf("open duckdb: %v", err) } t.Cleanup(func() { _ = db.Close() }) - 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) } now := time.Now().UTC().Truncate(time.Minute) - if _, err := db.Exec(`INSERT INTO service_rollup VALUES - ('', ?, 'reviews', 1, 0, 0, 600000, 600000, 0, 0), - ('', ?, 'reviews', 20, 20, 0, 30, 40, 0, 0), - ('', ?, 'generator', 5, 0, 0, 250, 250, 0, 0)`, - now.Add(-3*time.Minute), now.Add(-time.Minute), now.Add(-time.Minute)); err != nil { - t.Fatalf("seed service_rollup: %v", err) - } + querytest.SeedSpanRollup(t, db, now.Add(-3*time.Minute), "", "reviews", "SPAN_KIND_CLIENT", 1, 0, 600000) + querytest.SeedSpanRollup(t, db, now.Add(-time.Minute), "", "reviews", "SPAN_KIND_SERVER", 20, 0, 40) + querytest.SeedSpanRollup(t, db, now.Add(-time.Minute), "", "generator", "SPAN_KIND_CLIENT", 5, 0, 250) svc := New(SQLDB(db), newTestRepository(t).Parquet, 30) result, err := svc.Overview(context.Background(), Scope{Start: now.Add(-time.Hour), End: now.Add(time.Minute)}, 50) @@ -54,7 +48,7 @@ CREATE TABLE service_rollup ( t.Fatalf("reviews health = %q, want healthy", got["reviews"].Health) } // A service that served nothing all window keeps the only number it has. - if p95 := got["generator"].P95MS; p95 != 250 { + if p95 := got["generator"].P95MS; p95 < 230 || p95 > 273 { t.Fatalf("generator p95 = %.0fms, want 250ms rather than a flat zero", p95) } } diff --git a/internal/observability/latency_sql.go b/internal/observability/latency_sql.go deleted file mode 100644 index 369106029..000000000 --- a/internal/observability/latency_sql.go +++ /dev/null @@ -1,25 +0,0 @@ -package observability - -// A service's latency is read from the buckets in which it actually served -// something. service_rollup stores percentiles that already exclude the calls a -// service was waiting on, but a bucket holding nothing except such calls has no -// served latency to report and falls back to them — a subscription held open -// for ten minutes would otherwise decide the service's whole window. -// -// Preferring served buckets keeps that bucket out of the answer while leaving a -// service that served nothing all window — a load generator, a cron worker — -// measured on what it does have instead of reporting a flat zero. -const ( - // windowP95SQL aggregates p95 across buckets. MAX, not an average: the - // worst bucket is the one worth knowing about. - windowP95SQL = `COALESCE(MAX(p95_ms) FILTER (WHERE served_spans > 0), MAX(p95_ms), 0)` - - // windowP50SQL weights each bucket by the spans the figure describes. A - // bucket's p50 is computed over served spans, so weighting it by the - // bucket's total would let one served request sitting beside a thousand - // outbound calls outweigh a bucket that served hundreds. - windowP50SQL = `COALESCE( - SUM(p50_ms * served_spans) FILTER (WHERE served_spans > 0) / NULLIF(SUM(served_spans) FILTER (WHERE served_spans > 0), 0), - SUM(p50_ms * spans) / NULLIF(SUM(spans), 0), - 0)` -) diff --git a/internal/observability/namespace_test.go b/internal/observability/namespace_test.go index 421f59b18..23e38debf 100644 --- a/internal/observability/namespace_test.go +++ b/internal/observability/namespace_test.go @@ -7,6 +7,9 @@ import ( "time" _ "github.com/duckdb/duckdb-go/v2" + + "github.com/labstack/pitot/internal/engine" + "github.com/labstack/pitot/internal/engine/querytest" ) func TestOverviewEmptyNamespaceIncludesAllNamespaces(t *testing.T) { @@ -16,28 +19,13 @@ func TestOverviewEmptyNamespaceIncludesAllNamespaces(t *testing.T) { } t.Cleanup(func() { _ = db.Close() }) - if _, err := db.Exec(` -CREATE TABLE service_rollup ( - bucket TIMESTAMP, - namespace VARCHAR, - 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) } stamp := time.Date(2026, 8, 23, 20, 0, 0, 0, time.UTC) - if _, err := db.Exec(`INSERT INTO service_rollup VALUES - (?, 'prod', 'checkout', 2, 2, 0, 10, 20, 1, 1), - (?, 'staging', 'catalog', 3, 3, 0, 10, 20, 1, 1)`, stamp, stamp); err != nil { - t.Fatalf("insert service rollups: %v", err) - } + querytest.SeedSpanRollup(t, db, stamp, "prod", "checkout", "", 2, 0, 20) + querytest.SeedSpanRollup(t, db, stamp, "staging", "catalog", "", 3, 0, 20) svc := New(SQLDB(db), newTestRepository(t).Parquet, 30) result, err := svc.Overview(context.Background(), Scope{Start: stamp.Add(-time.Minute), End: stamp.Add(time.Minute)}, 100) @@ -48,3 +36,39 @@ CREATE TABLE service_rollup ( t.Fatalf("overview = %#v, want both namespaces", result) } } + +func TestOverviewCountsDistinctMetricResourcesAcrossMinutes(t *testing.T) { + d, _, svc := newCompletedReadTest(t) + at := time.Now().UTC().Truncate(time.Minute).Add(-time.Hour) + if _, err := d.DB.Exec(`INSERT INTO resource_rollup (namespace,bucket,service,signal,resource) VALUES + ('ns',$1,'agent','metrics',{'host.name':'a'}),('ns',$2,'agent','metrics',{'host.name':'a'}), + ('ns',$2,'agent','metrics',{'host.name':'b'}),('ns',$2,'agent','logs',{'host.name':'c'}), + ('other',$2,'agent','metrics',{'host.name':'d'}),('ns',$3,'agent','metrics',{'host.name':'e'})`, at, at.Add(time.Minute), at.Add(2*time.Minute)); err != nil { + t.Fatal(err) + } + o, err := svc.Overview(t.Context(), Scope{Start: at, End: at.Add(2 * time.Minute), Namespace: "ns"}, 10) + if err != nil || len(o.Services) != 1 { + t.Fatalf("overview=%+v err=%v", o, err) + } + s := o.Services[0] + if s.Service != "agent" || s.MetricCount != 2 || s.Spans != 0 || s.P50MS != 0 || s.P95MS != 0 || s.ErrorRate != 0 { + t.Fatalf("metric-only service: %+v", s) + } +} + +func TestOverviewIncludesLogOnlyService(t *testing.T) { + d, _, svc := newCompletedReadTest(t) + at := time.Now().UTC().Truncate(time.Minute).Add(-time.Hour) + if _, err := d.DB.Exec(`INSERT INTO log_rollup VALUES + ('ns',$1,'collector','INFO',4),('ns',$1,'collector','WARN',2),('other',$1,'collector','INFO',10)`, at); err != nil { + t.Fatal(err) + } + o, err := svc.Overview(t.Context(), Scope{Start: at, End: at.Add(time.Minute), Namespace: "ns"}, 10) + if err != nil || len(o.Services) != 1 { + t.Fatalf("overview=%+v err=%v", o, err) + } + s := o.Services[0] + if s.Service != "collector" || s.LogCount != 6 || s.MetricCount != 0 || s.Spans != 0 || s.ErrorRate != 0 || s.P50MS != 0 || s.P95MS != 0 { + t.Fatalf("log-only service: %+v", s) + } +} diff --git a/internal/observability/overview.go b/internal/observability/overview.go index 1d6130d20..d905ebd30 100644 --- a/internal/observability/overview.go +++ b/internal/observability/overview.go @@ -3,22 +3,22 @@ package observability import ( "context" "fmt" + + "github.com/labstack/pitot/internal/rollupsql" ) -var overviewQuery = ` -SELECT - service, - CAST(SUM(spans) AS BIGINT) AS spans, - COALESCE(SUM(error_rate * spans) / NULLIF(SUM(spans), 0), 0) AS error_rate, - ` + windowP50SQL + ` AS p50_ms, - ` + windowP95SQL + ` AS p95_ms, - CAST(SUM(log_count) AS BIGINT) AS log_count, - CAST(SUM(metric_count) AS BIGINT) AS metric_count -FROM service_rollup -WHERE bucket >= ? AND bucket < ? AND (? = '' OR namespace = ?) AND (? = '' OR service = ?) -GROUP BY service -ORDER BY error_rate DESC, p95_ms DESC, spans DESC, service ASC -LIMIT ?` +const overviewScope = `bucket >= $1::TIMESTAMP_NS AND bucket < $2::TIMESTAMP_NS + AND ($3='' OR namespace=$3) AND ($4='' OR service=$4)` + +var overviewQuery = `WITH latency AS (` + rollupsql.ServiceWindow(overviewScope, "") + `), + log_counts AS (SELECT service,sum(logs)::BIGINT AS logs FROM log_rollup + WHERE service<>'' AND ` + overviewScope + ` GROUP BY service), + metric_resources AS (SELECT service,count(DISTINCT resource) AS resources FROM resource_rollup + WHERE signal='metrics' AND service<>'' AND ` + overviewScope + ` GROUP BY service) + SELECT service,coalesce(spans,0) AS spans,coalesce(error_rate,0) AS error_rate, + coalesce(p50,0),coalesce(p95,0) AS p95_ms,coalesce(logs,0),coalesce(resources,0),coalesce(error_spans,0) + FROM latency FULL JOIN log_counts USING(service) FULL JOIN metric_resources USING(service) + ORDER BY error_rate DESC,p95_ms DESC,spans DESC,service LIMIT $5` func (s *Service) Overview(ctx context.Context, scope Scope, limit int) (Overview, error) { scope, err := s.normalizeScope(scope) @@ -30,16 +30,14 @@ func (s *Service) Overview(ctx context.Context, scope Scope, limit int) (Overvie return Overview{}, err } - services, err := s.serviceHealth(ctx, scope, limit) + services, errors, err := s.serviceHealth(ctx, scope, limit) if err != nil { return Overview{}, err } data := Overview{Services: services, ServiceCount: len(services)} - var weightedErrors float64 for _, service := range services { data.TotalSpans += service.Spans - weightedErrors += service.ErrorRate * float64(service.Spans) switch service.Health { case HealthUnhealthy: data.Counts.Unhealthy++ @@ -50,23 +48,25 @@ func (s *Service) Overview(ctx context.Context, scope Scope, limit int) (Overvie } } if data.TotalSpans > 0 { - data.ErrorRate = weightedErrors / float64(data.TotalSpans) + data.ErrorRate = float64(errors) / float64(data.TotalSpans) } data.Health = overallHealth(data.Counts) return data, nil } -func (s *Service) serviceHealth(ctx context.Context, scope Scope, limit int) ([]ServiceHealth, error) { - rows, err := s.db.QueryContext(ctx, overviewQuery, scope.Start, scope.End, scope.Namespace, scope.Namespace, scope.Service, scope.Service, limit) +func (s *Service) serviceHealth(ctx context.Context, scope Scope, limit int) ([]ServiceHealth, int64, error) { + rows, err := s.db.QueryContext(ctx, overviewQuery, scope.Start, scope.End, scope.Namespace, scope.Service, limit) if err != nil { - return nil, fmt.Errorf("query service health: %w", err) + return nil, 0, fmt.Errorf("query service health: %w", err) } defer rows.Close() + var totalErrors int64 services := make([]ServiceHealth, 0) for rows.Next() { var service ServiceHealth + var errorSpans int64 if err := rows.Scan( &service.Service, &service.Spans, @@ -75,14 +75,16 @@ func (s *Service) serviceHealth(ctx context.Context, scope Scope, limit int) ([] &service.P95MS, &service.LogCount, &service.MetricCount, + &errorSpans, ); err != nil { - return nil, fmt.Errorf("scan service health: %w", err) + return nil, 0, fmt.Errorf("scan service health: %w", err) } + totalErrors += errorSpans service.Health = classify(service.ErrorRate, service.P95MS) services = append(services, service) } if err := rows.Err(); err != nil { - return nil, fmt.Errorf("iterate service health: %w", err) + return nil, 0, fmt.Errorf("iterate service health: %w", err) } - return services, nil + return services, totalErrors, nil } diff --git a/internal/observability/service_test.go b/internal/observability/service_test.go index 280618ca2..9ee864a3e 100644 --- a/internal/observability/service_test.go +++ b/internal/observability/service_test.go @@ -107,11 +107,11 @@ func TestOverviewReturnsServiceHealth(t *testing.T) { svc, mock, _ := newMockService(t) start := time.Date(2026, 7, 20, 11, 0, 0, 0, time.UTC) end := start.Add(time.Hour) - rows := sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count"}). - AddRow("checkout", int64(1000), 0.08, 80.0, 2200.0, int64(20), int64(10)). - AddRow("catalog", int64(500), 0.0, 25.0, 100.0, int64(4), int64(2)) + rows := sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count", "error_spans"}). + AddRow("checkout", int64(1000), 0.08, 80.0, 2200.0, int64(20), int64(10), int64(80)). + AddRow("catalog", int64(500), 0.0, 25.0, 100.0, int64(4), int64(2), int64(0)) mock.ExpectQuery(regexp.QuoteMeta(overviewQuery)). - WithArgs(start, end, "prod", "prod", "", "", 100). + WithArgs(start, end, "prod", "", 100). WillReturnRows(rows) result, err := svc.Overview(context.Background(), Scope{Namespace: "prod", Start: start, End: end}, 0) @@ -134,8 +134,8 @@ func TestOverviewReportsEmptyWindowAsUnknownNotHealthy(t *testing.T) { start := time.Date(2026, 7, 20, 11, 0, 0, 0, time.UTC) end := start.Add(time.Hour) mock.ExpectQuery(regexp.QuoteMeta(overviewQuery)). - WithArgs(start, end, "nonexistent", "nonexistent", "", "", 100). - WillReturnRows(sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count"})) + WithArgs(start, end, "nonexistent", "", 100). + WillReturnRows(sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count", "error_spans"})) result, err := svc.Overview(context.Background(), Scope{Namespace: "nonexistent", Start: start, End: end}, 0) if err != nil { @@ -157,10 +157,10 @@ func TestTopologyUsesSharedNodesAndTypedEdges(t *testing.T) { start := time.Date(2026, 7, 20, 11, 0, 0, 0, time.UTC) end := start.Add(time.Hour) mock.ExpectQuery(regexp.QuoteMeta(overviewQuery)). - WithArgs(start, end, "prod", "prod", "", "", 50). - WillReturnRows(sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count"}). - AddRow("checkout", int64(10), 0.0, 20.0, 40.0, int64(1), int64(1)). - AddRow("postgres", int64(10), 0.0, 10.0, 20.0, int64(0), int64(0))) + WithArgs(start, end, "prod", "", 50). + WillReturnRows(sqlmock.NewRows([]string{"service", "spans", "error_rate", "p50_ms", "p95_ms", "log_count", "metric_count", "error_spans"}). + AddRow("checkout", int64(10), 0.0, 20.0, 40.0, int64(1), int64(1), int64(0)). + AddRow("postgres", int64(10), 0.0, 10.0, 20.0, int64(0), int64(0), int64(0))) mock.ExpectQuery(regexp.QuoteMeta(topologyEdgesQuery)). WithArgs(start, end, "prod", "prod", "", "", "", 50). WillReturnRows(sqlmock.NewRows([]string{"caller", "callee", "edge_type", "calls", "average_ms", "error_rate"}). diff --git a/internal/observability/topology.go b/internal/observability/topology.go index 1e5a3399c..f6b244499 100644 --- a/internal/observability/topology.go +++ b/internal/observability/topology.go @@ -46,7 +46,7 @@ func (s *Service) Topology(ctx context.Context, scope Scope, limit int) (Topolog } ctx = queryrows.WithWindow(ctx, queryrows.Window{Start: scope.Start, End: scope.End, Namespace: scope.Namespace}) - nodes, err := s.serviceHealth(ctx, scope, limit) + nodes, _, err := s.serviceHealth(ctx, scope, limit) if err != nil { return Topology{}, err } diff --git a/internal/query/annotation_scope_test.go b/internal/query/annotation_scope_test.go index 1dde467de..d4ee0fdae 100644 --- a/internal/query/annotation_scope_test.go +++ b/internal/query/annotation_scope_test.go @@ -73,7 +73,7 @@ func projectedFilters(t *testing.T, parser Parser, sig *signal, vars map[string] func TestAnnotationScopeRunPanelAndAllSources(t *testing.T) { engine, _ := newTestEngine(t) at := fixtureStart - if _, err := engine.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',1,1,1,2,0,0,0)`, at); err != nil { + if _, err := engine.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',1,1,0,0)`, at); err != nil { t.Fatal(err) } if _, err := engine.DB.Exec(`INSERT INTO anomaly_log VALUES ('shop','anomalyonly','latency',?::TIMESTAMP_NS::TIMESTAMPTZ_NS,?::TIMESTAMP_NS::TIMESTAMPTZ_NS,'Slow','warn')`, at, at.Add(time.Minute)); err != nil { diff --git a/internal/query/histogram_compile.go b/internal/query/histogram_compile.go index 8d442f4a1..f512b152f 100644 --- a/internal/query/histogram_compile.go +++ b/internal/query/histogram_compile.go @@ -3,6 +3,8 @@ package query import ( "fmt" "strings" + + "github.com/labstack/pitot/internal/rollupsql" ) func histogramMeasure(m Measure) bool { @@ -50,13 +52,12 @@ func histogramAggregate(b *strings.Builder, prefix, from string, selects, aliase // Projection expansion avoids a correlated join over the complete map. fmt.Fprintf(b, ", %s_bins AS (SELECT %s,e.key AS __hist_k,sum(e.value)::DOUBLE AS __hist_n FROM (SELECT *,unnest(map_entries(hist)) AS e FROM %s) __hist_entries%s)", prefix, strings.Join(hidden, ","), from, grouping(true)) partition := strings.Join(keys, ",") - fmt.Fprintf(b, ", %s_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY %s ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY %s) AS __hist_total FROM %s_bins)", prefix, partition, partition, prefix) + fmt.Fprintf(b, ", %s_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY %s ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY %s) AS __hist_total FROM %s_bins WHERE __hist_n>0)", prefix, partition, partition, prefix) values := append([]string(nil), keys...) for i := range aliases { if m, ok := quantiles[i]; ok { q := sqlFloat(m.Q) - value := `CASE WHEN __hist_k=-2147483648 THEN 0.0 ELSE pow(2.0,(__hist_k-1)/8.0)+(pow(2.0,__hist_k/8.0)-pow(2.0,(__hist_k-1)/8.0))*greatest(0.0,least(1.0,(` + q + `*__hist_total-(__hist_cum-__hist_n))/__hist_n)) END` - values = append(values, "min(CASE WHEN __hist_cum >= "+q+"*__hist_total THEN "+value+" END) AS "+quoteIdent(aliases[i])) + values = append(values, rollupsql.Quantile(q, "__hist_k", "__hist_n", "__hist_cum", "__hist_total")+" AS "+quoteIdent(aliases[i])) } } fmt.Fprintf(b, ", %s_quantiles AS (SELECT %s FROM %s_cdf GROUP BY %s)", prefix, strings.Join(values, ","), prefix, partition) diff --git a/internal/query/rollup_compile.go b/internal/query/rollup_compile.go index 02b244097..49e699817 100644 --- a/internal/query/rollup_compile.go +++ b/internal/query/rollup_compile.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" "time" + + "github.com/labstack/pitot/internal/rollupsql" ) func rollupDimension(name string) bool { @@ -73,12 +75,10 @@ func compileRollupQuery(p *Panel, measures []Measure, filters []Filter, scope Sc // Positive bucket k covers (2^((k-1)/8), 2^(k/8)]; INT_MIN represents zero. // The estimate is approximate, bounded by one positive bucket (9.05%). func rollupQuantileSQL(q float64) string { - return fmt.Sprintf(`(SELECT CASE WHEN k=-2147483648 THEN 0.0 ELSE - pow(2.0,(k-1)/8.0)+(pow(2.0,k/8.0)-pow(2.0,(k-1)/8.0))*greatest(0.0,least(1.0,(%[1]s*total-(cum-n))/n)) END - FROM (SELECT k,n,sum(n) OVER (ORDER BY k) cum,sum(n) OVER () total + return fmt.Sprintf(`(SELECT %[2]s FROM (SELECT k,n,sum(n) OVER (ORDER BY k) cum,sum(n) OVER () total FROM (SELECT e.key k,sum(e.value)::DOUBLE n FROM unnest(flatten(list_transform(list(hist), lambda h: map_entries(h)))) entries(e) - GROUP BY e.key)) cumulative WHERE cum >= %[1]s*total ORDER BY k LIMIT 1)`, sqlFloat(q)) + GROUP BY e.key HAVING sum(e.value)>0)) cumulative WHERE cum >= %[1]s*total ORDER BY k LIMIT 1)`, sqlFloat(q), rollupsql.Interpolate(sqlFloat(q), "k", "n", "cum", "total")) } func rollupMeasureSQL(m Measure, seconds, partition string) string { @@ -88,7 +88,7 @@ func rollupMeasureSQL(m Measure, seconds, partition string) string { case "rate": return "coalesce(sum(spans),0) / nullif(" + seconds + ",0)" case "error_rate": - return "100.0 * coalesce(sum(spans) FILTER (WHERE status='STATUS_CODE_ERROR'),0) / nullif(sum(spans),0)" + return "100.0 * " + rollupsql.ErrorRate case "share": return "100.0 * sum(spans) / sum(sum(spans)) OVER (" + partition + ")" case "avg": @@ -107,7 +107,7 @@ func rollupMeasureSQL(m Measure, seconds, partition string) string { func rollupRankingSQL(extra string, m Measure, seconds float64) (string, string, string) { value := rollupMeasureSQL(m, sqlFloat(seconds), "") samples := "sum(spans)" - extra = strings.ReplaceAll(extra, "sum(CASE WHEN status = 'STATUS_CODE_ERROR' THEN 1.0 ELSE 0.0 END)", "coalesce(sum(spans) FILTER (WHERE status='STATUS_CODE_ERROR'),0)") + extra = strings.ReplaceAll(extra, "sum(CASE WHEN status = 'STATUS_CODE_ERROR' THEN 1.0 ELSE 0.0 END)", rollupsql.ErrorSpans) return value, samples, extra } diff --git a/internal/query/rollup_compile_test.go b/internal/query/rollup_compile_test.go index 6026c9c54..e213a619c 100644 --- a/internal/query/rollup_compile_test.go +++ b/internal/query/rollup_compile_test.go @@ -383,3 +383,65 @@ func TestHistogramPlanPreservesMultipleQuantilesTotalsAndFoldedGroups(t *testing } } } + +func TestStructuredSpanQuantilesMatchRawAcrossKinds(t *testing.T) { + d, repo := newTestEngine(t) + spans := shopSpans() + for i := range spans { + s := &spans[i] + s.Kind, s.DurationMS = "SPAN_KIND_CLIENT", 1000 + if i == 0 { + s.Kind, s.DurationMS = "SPAN_KIND_SERVER", 10 + } + if i == 3 { + s.Kind, s.DurationMS = "SPAN_KIND_INTERNAL", 20 + } + s.EndUnixNanos = s.StartUnixNanos + int64(s.DurationMS)*int64(time.Millisecond) + } + commit(t, repo, spans, nil) + scope := Scope{Start: fixtureStart, End: fixtureStart.Add(time.Hour), Interval: time.Minute} + panel := &Panel{Viz: "stat", Query: &Spec{From: "spans"}} + measures := measuresOf(t, "spans", "p95(duration_ms)", "count()") + for _, where := range []string{"", "kind IN ('SPAN_KIND_CLIENT','SPAN_KIND_INTERNAL')"} { + var filters []Filter + if where != "" { + f, err := checkFilter(t.Context(), d, signals["spans"], nil, where) + if err != nil { + t.Fatal(err) + } + filters = []Filter{f} + } + rolled, err := compileQuery(panel, measures, filters, scope) + if err != nil { + t.Fatal(err) + } + raw, err := compileAggregateQuery(panel, measures, filters, scope, false) + if err != nil { + t.Fatal(err) + } + got, want := readCompiledFrame(t, d, rolled, scope), readCompiledFrame(t, d, raw, scope) + if !strings.Contains(rolled.SQL, "FROM span_rollup") || got.Rows != 60 || want.Rows != got.Rows || len(got.Totals) != 3 || len(want.Totals) != 3 { + t.Fatalf("rows and totals for %q: rollup=%+v raw=%+v", where, got, want) + } + compare := func(p95, rawP95, count, rawCount any) { + t.Helper() + if math.Abs(p95.(float64)/rawP95.(float64)-1) > math.Exp2(1.0/8)-1 || count != rawCount { + t.Fatalf("filter %q: p95=%v raw=%v count=%v raw=%v", where, p95, rawP95, count, rawCount) + } + } + compare(got.Totals[1], want.Totals[1], got.Totals[2], want.Totals[2]) + // Top-N ranking computes a scalar quantile over this same population. + scalar := "SELECT " + rollupQuantileSQL(.95) + ",sum(spans)::DOUBLE FROM span_rollup" + if where != "" { + scalar += " WHERE " + where + } + var p95, count float64 + if err := d.DB.QueryRow(scalar).Scan(&p95, &count); err != nil { + t.Fatal(err) + } + compare(p95, want.Totals[1], count, want.Totals[2]) + for row := range got.Rows { + compare(got.Values[1][row], want.Values[1][row], got.Values[2][row], want.Values[2][row]) + } + } +} diff --git a/internal/query/rollup_panels_test.go b/internal/query/rollup_panels_test.go index ac1dfc1a3..3be7e1c8c 100644 --- a/internal/query/rollup_panels_test.go +++ b/internal/query/rollup_panels_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/labstack/pitot/internal/engine/querytest" "github.com/labstack/pitot/internal/observability" "github.com/labstack/pitot/internal/queryrows" ) @@ -15,11 +16,9 @@ import ( func TestRollupPanelsReuseServices(t *testing.T) { engine, _ := newTestEngine(t) at := fixtureStart - _, err := engine.DB.Exec(`INSERT INTO service_rollup(namespace,bucket,service,spans,served_spans,p50_ms,p95_ms,error_rate,log_count,metric_count) VALUES ('shop',?,'checkout',10,10,50,100,.1,2,3),('shop',?,'payment',20,20,20,40,0,1,1)`, at, at) - if err != nil { - t.Fatal(err) - } - _, err = engine.DB.Exec(`INSERT INTO edge_rollup(namespace,bucket,caller,callee,calls,avg_ms,error_rate,edge_type) VALUES ('shop',?,'checkout','payment',10,20,.1,'call')`, at) + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "checkout", "", 10, 1, 100) + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "payment", "", 20, 0, 40) + _, err := engine.DB.Exec(`INSERT INTO edge_rollup(namespace,bucket,caller,callee,calls,avg_ms,error_rate,edge_type) VALUES ('shop',?,'checkout','payment',10,20,.1,'call')`, at) if err != nil { t.Fatal(err) } @@ -45,7 +44,7 @@ func TestRollupPanelsReuseServices(t *testing.T) { if got[1].Status != "ok" || got[1].Frame.Rows != 3 || got[1].Frame.Values[7][2].(float64) != 10 { t.Fatalf("edges: %+v", got[1]) } - if got[1].Frame.Columns[9].Name != "p95_ms" || got[1].Frame.Values[9][0] != float64(100) || got[1].Frame.Values[6][0] != nil || got[1].Frame.Values[9][2] != nil || got[1].Frame.Values[6][2] != float64(20) { + if got[1].Frame.Columns[9].Name != "p95_ms" || got[1].Frame.Values[9][0] != overview.Services[0].P95MS || got[1].Frame.Values[6][0] != nil || got[1].Frame.Values[9][2] != nil || got[1].Frame.Values[6][2] != float64(20) { t.Fatalf("mixed node/edge latency semantics: %+v", got[1].Frame) } d.Panels[0].Query.Where = []string{"namespace = 'missing'"} @@ -59,10 +58,9 @@ func TestRollupPanelsReuseServices(t *testing.T) { func TestRollupPanelsAggregateContract(t *testing.T) { engine, _ := newTestEngine(t) at := fixtureStart - _, err := engine.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',10,10,50,100,.1,2,3),('shop',?,'checkout',30,30,70,200,0,4,5),('shop',?,'payment',20,20,20,40,0,1,1)`, at, at.Add(10*time.Minute), at) - if err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "checkout", "", 10, 1, 100) + querytest.SeedSpanRollup(t, engine.DB, at.Add(10*time.Minute), "shop", "checkout", "", 30, 0, 200) + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "payment", "", 20, 0, 40) reader := observability.New(engine, engine, 30) e := NewExecutor(engine, 30) e.SetRollupReader(reader) @@ -81,7 +79,7 @@ func TestRollupPanelsAggregateContract(t *testing.T) { if got[0].Frame == nil || !reflect.DeepEqual(got[0].Frame.Health, want) { t.Fatalf("health aggregate got %+v want %+v", got, want) } - if got[0].Frame.Rows != 1 || got[0].Frame.Values[5][0] != float64(200) { + if got[0].Frame.Rows != 1 || got[0].Frame.Values[5][0] != o.Services[0].P95MS { t.Fatalf("service p95: %+v", got[0]) } } @@ -149,11 +147,11 @@ func TestRollupPanelsValidateScopeOnly(t *testing.T) { func TestRollupPanelsApplyServiceBeforeLimit(t *testing.T) { engine, _ := newTestEngine(t) at := fixtureStart - _, err := engine.DB.Exec(`INSERT INTO service_rollup SELECT 'shop',?,'noisy-'||i,100,100,3000,4000,.5,0,0 FROM generate_series(1,500) AS t(i)`, at) + _, err := engine.DB.Exec(`INSERT INTO span_rollup SELECT 'shop',?,'noisy-'||i,'','STATUS_CODE_ERROR',100,400000,4000,4000,map([96],[100::UBIGINT]) FROM generate_series(1,500) AS t(i)`, at) if err != nil { t.Fatal(err) } - _, err = engine.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'quiet',1,1,1,2,0,0,0)`, at) + _, err = engine.DB.Exec(`INSERT INTO span_rollup VALUES ('shop',?,'quiet','','',1,2,2,2,map([8],[1::UBIGINT]))`, at) if err != nil { t.Fatal(err) } @@ -215,9 +213,10 @@ func (db *countingHealthReadDB) QueryContext(ctx context.Context, sql string, ar func TestHealthPanelReadsOnlySummaryAndTrendForScopedRollups(t *testing.T) { engine, _ := newTestEngine(t) at := fixtureStart - if _, err := engine.DB.Exec(`INSERT INTO service_rollup VALUES ('shop',?,'checkout',10,10,50,100,.1,2,3),('shop',?,'checkout',30,30,70,200,0,4,5),('other',?,'checkout',100,100,1,1,1,0,0),('shop',?,'payment',100,100,1,1,1,0,0)`, at, at.Add(10*time.Minute), at, at); err != nil { - t.Fatal(err) - } + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "checkout", "", 10, 1, 100) + querytest.SeedSpanRollup(t, engine.DB, at.Add(10*time.Minute), "shop", "checkout", "", 30, 0, 200) + querytest.SeedSpanRollup(t, engine.DB, at, "other", "checkout", "", 100, 100, 1) + querytest.SeedSpanRollup(t, engine.DB, at, "shop", "payment", "", 100, 100, 1) counter := &countingHealthReadDB{DB: engine} executor := NewExecutor(engine, 30) executor.SetRollupReader(observability.New(counter, engine, 30)) diff --git a/internal/query/service_agreement_test.go b/internal/query/service_agreement_test.go new file mode 100644 index 000000000..b76576a3e --- /dev/null +++ b/internal/query/service_agreement_test.go @@ -0,0 +1,154 @@ +package query + +import ( + "fmt" + "math" + "testing" + "time" + + "github.com/labstack/pitot/internal/alert" + "github.com/labstack/pitot/internal/intelligence" + "github.com/labstack/pitot/internal/observability" + "github.com/labstack/pitot/internal/telemetry" + telemetrystore "github.com/labstack/pitot/internal/telemetry/store" +) + +func TestServiceWindowAgreesAcrossOverviewAlertsDetectorAndDashboards(t *testing.T) { + d, repo := newTestEngine(t) + end := time.Now().UTC().Truncate(time.Minute) + start := end.Add(-6 * time.Minute) + var spans []telemetry.Span + add := func(service, kind string, minute, total, errors int, ms float64) { + for i := range total { + at := start.Add(time.Duration(minute)*time.Minute + time.Duration(i)*time.Millisecond) + id := fmt.Sprint(len(spans)) + status := "STATUS_CODE_OK" + if i < errors { + status = "STATUS_CODE_ERROR" + } + spans = append(spans, telemetry.Span{Namespace: "ns", ServiceName: service, Kind: kind, TraceID: id, SpanID: id, StatusCode: status, + StartUnixNanos: at.UnixNano(), EndUnixNanos: at.Add(time.Duration(ms) * time.Millisecond).UnixNano(), DurationMS: ms}) + } + } + for _, svc := range []string{"api", "load"} { + kind := "SPAN_KIND_SERVER" + if svc == "load" { + kind = "SPAN_KIND_CLIENT" + } + add(svc, kind, -3, 100, 10, 8) + add(svc, kind, 0, 90, 0, 100) + add(svc, kind, 5, 10, 0, 300) + } + // A client-only minute increases volume and errors, while served minutes + // determine the api latency. The load generator falls back across both minutes. + add("api", "SPAN_KIND_CLIENT", 2, 100, 50, 600000) + add("load", "SPAN_KIND_PRODUCER", 3, 100, 50, 320) + if err := repo.Commit(t.Context(), telemetrystore.Batch{ID: "agreement", Spans: spans}); err != nil { + t.Fatal(err) + } + if _, err := d.RefreshDashboardRollups(t.Context()); err != nil { + t.Fatal(err) + } + if _, err := d.DB.Exec(`UPDATE rollup_state SET last_ingested_unix_nano=? WHERE cache_key='service_rollup_v3'`, end.UnixNano()); err != nil { + t.Fatal(err) + } + overview, err := observability.New(d, d, 30).Overview(t.Context(), observability.Scope{Start: start, End: end}, 100) + if err != nil || len(overview.Services) != 2 { + t.Fatalf("overview: %+v %v", overview, err) + } + envs, err := alert.NewEngine(nil, d, nil, time.Minute, 7).Test(t.Context(), alert.Rule{Expression: "true"}) + if err != nil || len(envs) != 2 { + t.Fatalf("alert results: %+v %v", envs, err) + } + cfg := intelligence.DefaultDetectorConfig() + cfg.LookbackWindow = end.Sub(start) + snap, err := intelligence.NewDetector(d, cfg).GenerateSnapshot(t.Context()) + if err != nil { + t.Fatal(err) + } + for _, svc := range overview.Services { + t.Run(svc.Service, func(t *testing.T) { + if svc.Spans != 200 || svc.ErrorRate != .25 { + t.Fatalf("all-span counts: %+v", svc) + } + var env alert.Env + for _, result := range envs { + if result.Service == svc.Service { + env = result.Env + } + } + if env.P50 != svc.P50MS || env.P95 != svc.P95MS || env.ErrorRate != svc.ErrorRate || env.Throughput != 200 { + t.Fatalf("alert %+v differs from overview %+v", env, svc) + } + // The preceding window contains one 8ms population, with 10 errors in 100 spans. + var previous float64 + if err := d.DB.QueryRow("SELECT "+rollupQuantileSQL(.95)+" FROM span_rollup WHERE service=? AND bucket 1e-10 || math.Abs(env.ErrorRateDelta-150) > 1e-10 || env.ThroughputDelta != 100 { + t.Fatalf("previous window: %+v", env) + } + findings := map[intelligence.AnomalyType]float64{} + for _, a := range snap.Anomalies { + if a.ServiceName == svc.Service { + findings[a.Type] = a.Current + } + } + if findings[intelligence.AnomalyLatencyDegradation] != svc.P95MS || findings[intelligence.AnomalyErrorRateChange] != svc.ErrorRate*100 { + t.Fatalf("detector: %v, overview: %+v", findings, svc) + } + + panel := Panel{Viz: "table", Query: &Spec{From: "spans", By: []string{"service"}}} + scope := Scope{Start: start, End: end} + var filters []Filter + selectKinds := "" + if svc.Service == "api" { + const served = "kind NOT IN ('SPAN_KIND_CLIENT', 'SPAN_KIND_PRODUCER')" + f, err := checkFilter(t.Context(), d, signals["spans"], nil, served) + if err != nil { + t.Fatal(err) + } + filters = []Filter{f} + selectKinds = " AND " + served + } + dashboard := func(filters []Filter, measures []string, values ...any) { + t.Helper() + compiled, err := compileQuery(&panel, measuresOf(t, "spans", measures...), filters, scope) + if err != nil { + t.Fatal(err) + } + var service string + if err := d.DB.QueryRow("SELECT * FROM ("+compiled.SQL+") WHERE service=?", append(compiled.Args, svc.Service)...).Scan(append([]any{&service}, values...)...); err != nil { + t.Fatal(err) + } + } + var p50, p95, rate float64 + dashboard(filters, []string{"p50(duration_ms)", "p95(duration_ms)"}, &p50, &p95) + dashboard(nil, []string{"error_rate()"}, &rate) + if p50 != svc.P50MS || p95 != svc.P95MS || rate != svc.ErrorRate*100 { + t.Fatalf("dashboard %g/%g/%g, overview %+v", p50, p95, rate, svc) + } + if err := d.DB.QueryRow("SELECT "+rollupQuantileSQL(.5)+","+rollupQuantileSQL(.95)+" FROM span_rollup WHERE service=? AND bucket>=? AND bucket= $2::TIMESTAMP_NS::TIMESTAMPTZ_NS AND start_time < $3::TIMESTAMP_NS::TIMESTAMPTZ_NS + AND ($1='load' OR kind='SPAN_KIND_SERVER')`, svc.Service, start, end).Scan(&exact50, &exact95, &digest50, &digest95); err != nil { + t.Fatal(err) + } + t.Logf("window p50/p95 (ms): merged %.3f/%.3f, exact %.3f/%.3f, t-digest %.3f/%.3f; error fraction %.3f", + p50, p95, exact50, exact95, digest50, digest95, svc.ErrorRate) + for _, p := range [][2]float64{{p50, exact50}, {p95, exact95}, {p50, digest50}, {p95, digest95}} { + if math.Abs(p[0]/p[1]-1) > math.Exp2(1.0/8)-1 { + t.Fatalf("estimate %g, raw reference %g", p[0], p[1]) + } + } + }) + } +} diff --git a/internal/query/sql_relations.go b/internal/query/sql_relations.go index 190540dfd..b0435f789 100644 --- a/internal/query/sql_relations.go +++ b/internal/query/sql_relations.go @@ -19,19 +19,16 @@ func SQLRelations() map[string]SQLRelationSchema { Description: "Per-service analytical rollup by namespace and time bucket. Panel SQL only; filter bucket with $__window(bucket).", Columns: []SQLColumnSchema{ {Field: str("namespace", "OpenTelemetry service namespace"), SQLType: "VARCHAR"}, - {Field: ts("bucket", "Rollup time bucket"), SQLType: "TIMESTAMP"}, + {Field: ts("bucket", "Rollup time bucket"), SQLType: "TIMESTAMP_NS"}, {Field: str("service", "Service name"), SQLType: "VARCHAR"}, {Field: num("spans", "count", "Total spans"), SQLType: "BIGINT"}, {Field: num("served_spans", "count", "Spans describing work performed by this service"), SQLType: "BIGINT"}, - {Field: num("p50_ms", "ms", "Median service latency"), SQLType: "DOUBLE"}, - {Field: num("p95_ms", "ms", "95th percentile service latency"), SQLType: "DOUBLE"}, - {Field: num("error_rate", "percent", "Error rate"), SQLType: "DOUBLE"}, + {Field: num("error_spans", "count", "Spans with error status"), SQLType: "BIGINT"}, {Field: num("log_count", "count", "Log events"), SQLType: "BIGINT"}, - {Field: num("metric_count", "count", "Metric data points"), SQLType: "BIGINT"}, }, }, "span_rollup": { - Description: "Per-minute spans by namespace, service, kind and status. Panel SQL only; filter bucket with $__window(bucket). Counts and duration aggregates merge across rows. Percentiles interpolate merged fixed-scale-3 OpenTelemetry exponential histograms and are approximate within one positive bucket (9.05%). Structured RED panels route here at minute resolution; fresh_to_ms reports the ingest horizon, usually 1–1.5 minutes behind ingestion. Window boundaries have minute precision.", + Description: "Per-minute spans by namespace, service, kind and status. Panel SQL only; filter bucket with $__window(bucket). Counts and duration aggregates merge across rows. Percentiles prefer served spans within each group and fall back to all spans for outbound-only groups. Percentiles interpolate merged fixed-scale-3 OpenTelemetry exponential histograms and are approximate within one positive bucket (9.05%). Structured RED panels route here at minute resolution; fresh_to_ms reports the ingest horizon, usually 1–1.5 minutes behind ingestion. Window boundaries have minute precision.", Columns: []SQLColumnSchema{ {Field: str("namespace", "OpenTelemetry service namespace"), SQLType: "VARCHAR"}, {Field: ts("bucket", "UTC minute bucket"), SQLType: "TIMESTAMP_NS"}, diff --git a/internal/rollupsql/sql.go b/internal/rollupsql/sql.go new file mode 100644 index 000000000..ceb664776 --- /dev/null +++ b/internal/rollupsql/sql.go @@ -0,0 +1,69 @@ +// Package rollupsql builds DuckDB expressions over the analytical span cache. +// Its arguments are SQL fragments owned by the caller. +package rollupsql + +import "fmt" + +const ( + Served = "coalesce(kind,'') NOT IN ('SPAN_KIND_CLIENT','SPAN_KIND_PRODUCER')" + ErrorSpans = "coalesce(sum(spans) FILTER (WHERE status='STATUS_CODE_ERROR'),0)" + ErrorRate = "(" + ErrorSpans + "::DOUBLE / nullif(sum(spans),0))" +) + +// Bin maps a duration in milliseconds to a scale-3 exponential histogram key. +func Bin(duration string) string { + return fmt.Sprintf("CASE WHEN %[1]s>0 AND NOT isnan(%[1]s) THEN coalesce(try_cast(ceil(log2(%[1]s)*8) AS INTEGER),2147483647) ELSE -2147483648 END", duration) +} + +// Interpolate locates the rank linearly within (2^((k-1)/8), 2^(k/8)]. +// Zero has its own sentinel. At k >= 8192 the upper edge exceeds DOUBLE's +// finite range, so saturate before computing the width of that bin. +func Interpolate(q, k, n, cum, total string) string { + lower := "pow(2.0,(" + k + "-1)/8.0)" + upper := "pow(2.0," + k + "/8.0)" + fraction := fmt.Sprintf("greatest(0.0,least(1.0,(%s*%s-(%s-%s))/%s))", q, total, cum, n, n) + return fmt.Sprintf("CASE WHEN %s=-2147483648 THEN 0.0 WHEN %s>=8192 THEN 1.7976931348623157e308::DOUBLE ELSE %s+(%s-%s)*%s END", k, k, lower, upper, lower, fraction) +} + +// Quantile reduces cumulative, nonempty bins to one quantile per group. +func Quantile(q, k, n, cum, total string) string { + return "min(" + Interpolate(q, k, n, cum, total) + ") FILTER (WHERE " + cum + " >= " + q + "*" + total + ")" +} + +// ServiceWindow groups span_rollup by service and an optional bucket expression. +// Counts include all spans. Only latency prefers work performed by the service, +// falling back to outbound calls when they are its whole window. +func ServiceWindow(where, bucket string) string { + group, projection := "service", "" + if bucket != "" { + group += ",period" + projection = "," + bucket + " AS period" + } + return `WITH scoped AS ( + SELECT service` + projection + `, kind, status, spans, hist + FROM span_rollup WHERE service <> '' AND (` + where + `) +), counts AS ( + SELECT ` + group + `, sum(spans)::BIGINT AS spans, ` + ErrorSpans + `::BIGINT AS error_spans, + ` + ErrorRate + ` AS error_rate, + coalesce(sum(spans) FILTER (WHERE ` + Served + `), 0) AS served_spans + FROM scoped GROUP BY ` + group + ` +), entries AS ( + SELECT ` + group + `, unnest(map_entries(hist)) AS entry + FROM scoped JOIN counts USING (` + group + `) + WHERE counts.served_spans = 0 OR ` + Served + ` +), bins AS ( + SELECT ` + group + `, entry.key AS k, sum(entry.value)::DOUBLE AS n + FROM entries GROUP BY ` + group + `, k +), cdf AS ( + SELECT *, sum(n) OVER (PARTITION BY ` + group + ` ORDER BY k) AS cum, + sum(n) OVER (PARTITION BY ` + group + `) AS total + FROM bins WHERE n>0 +), latency AS ( + SELECT ` + group + `, ` + Quantile("0.5", "k", "n", "cum", "total") + ` AS p50, + ` + Quantile("0.95", "k", "n", "cum", "total") + ` AS p95 + FROM cdf GROUP BY ` + group + ` +) +SELECT ` + group + `, spans, served_spans, error_spans, coalesce(error_rate,0) AS error_rate, + coalesce(p50,0) AS p50, coalesce(p95,0) AS p95 +FROM counts LEFT JOIN latency USING (` + group + `)` +} diff --git a/scripts/dashboard-eval/testdata/server.json b/scripts/dashboard-eval/testdata/server.json index 93f13d6b1..d6bff193e 100644 --- a/scripts/dashboard-eval/testdata/server.json +++ b/scripts/dashboard-eval/testdata/server.json @@ -42,7 +42,7 @@ 0.9958502021602336 ] }, - "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((service = 'checkout')) AND ((namespace = 'shop'))), __panel_hist_aggregate AS (SELECT epoch_ms(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\",NULL::DOUBLE AS \"p95\",grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,count(*) AS __hist_rows FROM base GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)),())), __panel_hist_bins AS (SELECT grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,e.key AS __hist_k,sum(e.value)::DOUBLE AS __hist_n FROM (SELECT *,unnest(map_entries(hist)) AS e FROM base) __hist_entries GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS),e.key),(e.key))), __panel_hist_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0 ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0) AS __hist_total FROM __panel_hist_bins), __panel_hist_quantiles AS (SELECT __hist_group,__hist_key_0,min(CASE WHEN __hist_cum \u003e= 0.95*__hist_total THEN CASE WHEN __hist_k=-2147483648 THEN 0.0 ELSE pow(2.0,(__hist_k-1)/8.0)+(pow(2.0,__hist_k/8.0)-pow(2.0,(__hist_k-1)/8.0))*greatest(0.0,least(1.0,(0.95*__hist_total-(__hist_cum-__hist_n))/__hist_n)) END END) AS \"p95\" FROM __panel_hist_cdf GROUP BY __hist_group,__hist_key_0), __panel_hist AS (SELECT a.\"_t\" AS \"_t\",q.\"p95\" AS \"p95\" FROM __panel_hist_aggregate a LEFT JOIN __panel_hist_quantiles q ON a.__hist_group IS NOT DISTINCT FROM q.__hist_group AND a.__hist_key_0 IS NOT DISTINCT FROM q.__hist_key_0) SELECT \"_t\", \"p95\" FROM __panel_hist ORDER BY \"_t\" NULLS FIRST LIMIT 18000", + "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((service = 'checkout')) AND ((namespace = 'shop'))), __panel_hist_aggregate AS (SELECT epoch_ms(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\",NULL::DOUBLE AS \"p95\",grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,count(*) AS __hist_rows FROM base GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)),())), __panel_hist_bins AS (SELECT grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,e.key AS __hist_k,sum(e.value)::DOUBLE AS __hist_n FROM (SELECT *,unnest(map_entries(hist)) AS e FROM base) __hist_entries GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS),e.key),(e.key))), __panel_hist_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0 ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0) AS __hist_total FROM __panel_hist_bins WHERE __hist_n\u003e0), __panel_hist_quantiles AS (SELECT __hist_group,__hist_key_0,min(CASE WHEN __hist_k=-2147483648 THEN 0.0 WHEN __hist_k\u003e=8192 THEN 1.7976931348623157e308::DOUBLE ELSE pow(2.0,(__hist_k-1)/8.0)+(pow(2.0,__hist_k/8.0)-pow(2.0,(__hist_k-1)/8.0))*greatest(0.0,least(1.0,(0.95*__hist_total-(__hist_cum-__hist_n))/__hist_n)) END) FILTER (WHERE __hist_cum \u003e= 0.95*__hist_total) AS \"p95\" FROM __panel_hist_cdf GROUP BY __hist_group,__hist_key_0), __panel_hist AS (SELECT a.\"_t\" AS \"_t\",q.\"p95\" AS \"p95\" FROM __panel_hist_aggregate a LEFT JOIN __panel_hist_quantiles q ON a.__hist_group IS NOT DISTINCT FROM q.__hist_group AND a.__hist_key_0 IS NOT DISTINCT FROM q.__hist_key_0) SELECT \"_t\", \"p95\" FROM __panel_hist ORDER BY \"_t\" NULLS FIRST LIMIT 18000", "interval": "5m", "elapsed_ms": 0, "from_ms": 1790856000000, @@ -379,7 +379,7 @@ 0.9958502021602336 ] }, - "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((service = 'checkout')) AND ((namespace = 'shop'))), __panel_hist_aggregate AS (SELECT epoch_ms(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\",NULL::DOUBLE AS \"p95\",grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,count(*) AS __hist_rows FROM base GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)),())), __panel_hist_bins AS (SELECT grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,e.key AS __hist_k,sum(e.value)::DOUBLE AS __hist_n FROM (SELECT *,unnest(map_entries(hist)) AS e FROM base) __hist_entries GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS),e.key),(e.key))), __panel_hist_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0 ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0) AS __hist_total FROM __panel_hist_bins), __panel_hist_quantiles AS (SELECT __hist_group,__hist_key_0,min(CASE WHEN __hist_cum \u003e= 0.95*__hist_total THEN CASE WHEN __hist_k=-2147483648 THEN 0.0 ELSE pow(2.0,(__hist_k-1)/8.0)+(pow(2.0,__hist_k/8.0)-pow(2.0,(__hist_k-1)/8.0))*greatest(0.0,least(1.0,(0.95*__hist_total-(__hist_cum-__hist_n))/__hist_n)) END END) AS \"p95\" FROM __panel_hist_cdf GROUP BY __hist_group,__hist_key_0), __panel_hist AS (SELECT a.\"_t\" AS \"_t\",q.\"p95\" AS \"p95\" FROM __panel_hist_aggregate a LEFT JOIN __panel_hist_quantiles q ON a.__hist_group IS NOT DISTINCT FROM q.__hist_group AND a.__hist_key_0 IS NOT DISTINCT FROM q.__hist_key_0) SELECT \"_t\", \"p95\" FROM __panel_hist ORDER BY \"_t\" NULLS FIRST LIMIT 18000", + "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((service = 'checkout')) AND ((namespace = 'shop'))), __panel_hist_aggregate AS (SELECT epoch_ms(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\",NULL::DOUBLE AS \"p95\",grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,count(*) AS __hist_rows FROM base GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)),())), __panel_hist_bins AS (SELECT grouping(time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS)) AS __hist_group,time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS) AS __hist_key_0,e.key AS __hist_k,sum(e.value)::DOUBLE AS __hist_n FROM (SELECT *,unnest(map_entries(hist)) AS e FROM base) __hist_entries GROUP BY GROUPING SETS ((time_bucket(INTERVAL '300 seconds', \"bucket\"::TIMESTAMP_NS),e.key),(e.key))), __panel_hist_cdf AS (SELECT *,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0 ORDER BY __hist_k) AS __hist_cum,sum(__hist_n) OVER (PARTITION BY __hist_group,__hist_key_0) AS __hist_total FROM __panel_hist_bins WHERE __hist_n\u003e0), __panel_hist_quantiles AS (SELECT __hist_group,__hist_key_0,min(CASE WHEN __hist_k=-2147483648 THEN 0.0 WHEN __hist_k\u003e=8192 THEN 1.7976931348623157e308::DOUBLE ELSE pow(2.0,(__hist_k-1)/8.0)+(pow(2.0,__hist_k/8.0)-pow(2.0,(__hist_k-1)/8.0))*greatest(0.0,least(1.0,(0.95*__hist_total-(__hist_cum-__hist_n))/__hist_n)) END) FILTER (WHERE __hist_cum \u003e= 0.95*__hist_total) AS \"p95\" FROM __panel_hist_cdf GROUP BY __hist_group,__hist_key_0), __panel_hist AS (SELECT a.\"_t\" AS \"_t\",q.\"p95\" AS \"p95\" FROM __panel_hist_aggregate a LEFT JOIN __panel_hist_quantiles q ON a.__hist_group IS NOT DISTINCT FROM q.__hist_group AND a.__hist_key_0 IS NOT DISTINCT FROM q.__hist_key_0) SELECT \"_t\", \"p95\" FROM __panel_hist ORDER BY \"_t\" NULLS FIRST LIMIT 18000", "interval": "5m", "elapsed_ms": 0, "from_ms": 1790856000000, diff --git a/site/src/content/docs/docs/concepts/insights.mdx b/site/src/content/docs/docs/concepts/insights.mdx index dccba32b3..51e354454 100644 --- a/site/src/content/docs/docs/concepts/insights.mdx +++ b/site/src/content/docs/docs/concepts/insights.mdx @@ -23,8 +23,8 @@ Snapshots contain anomalies, repeated log patterns, derived insights, a summary, The detector checks service error-rate changes, latency degradation and span volume changes across all namespaces. Service checks use completed rollup minutes, ending before the service watermark. The baseline is the preceding -window of equal length. Latency uses the span-weighted mean of minute p95 -values. See [rollup timing](/docs/concepts/storage#rollups-follow-durable-publication). +window of equal length. Latency compares the p95 of the merged span histogram in each window. +Error rate divides the number of error spans by the total spans in each window. See [rollup timing](/docs/concepts/storage#rollups-follow-durable-publication). Scores compare current values with the baseline and apply signal-specific variance floors and change thresholds. The z-score thresholds are 2.0 for diff --git a/site/src/content/docs/docs/concepts/storage.mdx b/site/src/content/docs/docs/concepts/storage.mdx index 60698b20a..953b5ee3b 100644 --- a/site/src/content/docs/docs/concepts/storage.mdx +++ b/site/src/content/docs/docs/concepts/storage.mdx @@ -247,10 +247,28 @@ rollups process disjoint ingestion windows up to that horizon, recomputing each affected event-time bucket in full. Raw committed telemetry remains queryable before its next rollup pass. -Error-rate, latency, and volume detectors read service-rollup minutes through -the last completed minute before the service watermark. The baseline has the -same length as the current period. Latency uses the span-weighted mean of the -rollup's served-span minute p95 values; log-pattern detection still reads logs. +The service-minute SQL relation keeps additive span, served-span, error-span +and log counts. Overview, alerts and anomaly detection derive latency from merged +scale-3 histogram bins. They prefer served spans across the whole window and +use all spans for outbound-only services. The detector uses the same population +for its five-minute baseline samples. Error rates and volumes count all spans. +Structured span queries apply the panel filters to every measure, including +percentiles. A panel can filter out client and producer spans to measure served +latency. Overview's `metric_count` counts +distinct reporting resource identities in the selected service and time window. + +When updating a saved SQL panel that used `service_rollup.error_rate`, divide +`sum(error_spans)::DOUBLE` by `nullif(sum(spans), 0)` for the window. Use +structured `p50(duration_ms)` and `p95(duration_ms)` measures for the removed +latency columns. The former `service_rollup.metric_count` summed distinct +metric names per minute. To count reporting resources over the window, use +`count(DISTINCT resource)` on `resource_rollup` with `signal = 'metrics'`. + +Error-rate, latency and volume detectors read span-rollup minutes through the +last completed minute before the service watermark. Each baseline has the same +length as its current window. Latency compares the two whole-window p95s. +Error detection compares whole-window error fractions. Both estimate baseline +scatter from five-minute buckets. Log-pattern detection reads logs. Ingest admission starts adapting a rows-per-second cap at 512 batches of reclaimable generation-0 compaction debt. Rising debt decreases the cap by 15% diff --git a/site/src/content/docs/docs/guides/alerts.mdx b/site/src/content/docs/docs/guides/alerts.mdx index a845da47d..6fe4423cf 100644 --- a/site/src/content/docs/docs/guides/alerts.mdx +++ b/site/src/content/docs/docs/guides/alerts.mdx @@ -85,6 +85,19 @@ error_rate > 0.02 && throughput > 10 `throughput` is the total span count in the rollup window. A traffic floor prevents a single failure on a quiet service from triggering this rule. +Both evaluation windows use the same service definition. `error_rate` is the +fraction of all spans with error status. `p50` and `p95` merge latency bins +across the whole window. They use served spans (all kinds except client and +producer) when present, and use all spans for an outbound-only window. + +**Migrating existing thresholds.** Earlier versions averaged minute error rates +and minute percentiles with equal weight. A busy minute now contributes in +proportion to its traffic. Recheck latency, error-rate and delta rules against +representative traffic using **Test against current data**. Scale-3 histogram +interpolation can move a positive latency estimate by one bin width (about +9.05%). The change from averaging minute percentiles to a whole-window quantile +can be larger, especially when traffic volume varies. + ## The lifecycle An alert moves through three states: diff --git a/site/src/content/docs/docs/reference/alert-expressions.mdx b/site/src/content/docs/docs/reference/alert-expressions.mdx index 8dfee98dc..e09b73015 100644 --- a/site/src/content/docs/docs/reference/alert-expressions.mdx +++ b/site/src/content/docs/docs/reference/alert-expressions.mdx @@ -25,12 +25,12 @@ numeric comparisons let you compare them with integer literals, as in | Variable | Type | Means | |---|---|---| -| `error_rate` | number | Mean of minute-rollup span error proportions over the evaluation window, from 0 to 1; not a request-weighted whole-window error rate. | +| `error_rate` | number | Fraction of all spans in the current window with error status, from 0 to 1. | | `error_rate_delta` | number | Relative change in error rate against the preceding rollup window, as a percentage; zero when the baseline is missing or zero. | | `health_score` | number | The detector's instance-wide composite 0-100 health score. Every service receives the same score; it is not a per-service value. | | `log_count` | number | Log records recorded for the service over the window. | -| `p50` | number | Mean of approximate minute-rollup median span latencies in milliseconds. | -| `p95` | number | 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. | +| `p50` | number | Approximate whole-window median latency in milliseconds for served spans, or all spans if none were served. | +| `p95` | number | Approximate whole-window 95th percentile latency in milliseconds, using the same span population as p50. | | `p95_delta` | number | Relative change in p95 latency against the preceding rollup window, as a percentage; zero when the baseline is missing or zero. | | `service` | string | The service name being evaluated, as a string. Compare it when one rule needs to behave differently for one service. | | `throughput` | number | 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. | diff --git a/site/src/content/docs/docs/reference/mcp.mdx b/site/src/content/docs/docs/reference/mcp.mdx index c0173b425..79fb27573 100644 --- a/site/src/content/docs/docs/reference/mcp.mdx +++ b/site/src/content/docs/docs/reference/mcp.mdx @@ -64,7 +64,7 @@ AG-UI `mcp-app` activity content uses exactly `resource_uri`, `tool_name`, ## create_dashboard -**Create dashboard**: Create a dashboard for the authenticated user from a complete spec. Read get_telemetry_schema first and preview_panels until every non-text panel returns data. Empty or failing panels return error.code invalid_spec with their path, title and diagnosis, plus structured problems. Successful saves return a receipt for that committed version: base_version, version, changes, layout_changed, dashboard_fields and save_check. Changes describe authored panel fields and position_changed; physical packing is only layout_changed. Order chips mark the minimal moved set. save_check reports checked, reason when unchecked, total elapsed_ms and one status/rows result per saved panel with elapsed_ms when executed. checked means every panel was executed, not that error or empty panels are healthy. Text rows identify nonempty content, not telemetry. Use the structured receipt rather than prose warnings as check evidence. Create receipts list added panels without layout or dashboard edit chips. No-op saves still create a new version with no change chips. Per-panel elapsed_ms is omitted when the panel did not run. A dashboard is \{name, description, time:\{range}, variables, panels}. Each panel: \{id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: \{field: duration_ms, buckets: log2} for spans or \{field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: \{from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Standard OpenTelemetry keys that get_telemetry_schema marks indexed, such as http.response.status_code and k8s.pod.name, read typed: ingest converts a value sent in another type, so "200" reads as the number 200, and they need no cast. Other keys read as sent. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', attributes['http.route'] IN $routes, attributes['http.response.status_code'] >= 500. Variables: \{name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, span_rollup, edge_rollup or resource_inventory that filters time with $__window(column). Compare time columns with TIMESTAMP 'YYYY-MM-DD HH:MM:SS' (UTC), or cast TIMESTAMPTZ literals with ::TIMESTAMPTZ_NS. Use values exactly as get_telemetry_schema lists them. Example panel: \{"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":\{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[\{"value":1500,"status":"bad"}]}. Structured spans aggregate panels restricted to namespace/service/kind/status and count/rate/error_rate/share or duration aggregates use span_rollup at minute resolution. Percentiles are approximate (one exponential bucket, 9.05%); fresh_to_ms is the ingest horizon. Other structured queries stay raw. Metrics: gauge/updown | counter | histogram. count(): points; count_distinct(): distinct. rate(): undefined | series increase/elapsed summed | count rate summed. sum(value): series means summed | increases | sum increases. avg(value): mean series means | undefined | sum/count increases. Gauge/updown sum/avg carry earlier points within 5m. Deltas spread across covered buckets; rate alone carries within 5m. rate() is per-second increase over covered elapsed time; auto >=1m. min/max: points | points | undefined. last(value): latest strictly before bucket/window end, reported within 5m, summed | same | undefined. pNN/quantile: points | undefined | interpolated bucket increases. summary: no value aggregates. Undefined: NULL. Fix name in its own where entry: one literal or single-value variable without All or multi-value; or name in by. Read type/temporality from get_telemetry_schema. Panel SQL also supports resource_inventory: signal, namespace, service, full typed resource, first_seen and last_seen. One row per distinct full resource per signal/namespace/service observed inside the logical panel window; first_seen/last_seen are actual in-window event times. Select signal='spans', 'logs' or 'metrics' and use resource['key'] with literal dotted keys. count(*) counts resource identities per signal, not events or instances. Declare $__window(first_seen). This relation is SQL-only: query.from and variables remain spans|logs|metrics; unscoped SQL cannot read it. state_timeline needs at least one threshold marked warn or bad, rather than only ok. Annotations attach only to timeseries, heatmap and state_timeline panels, scoped by service and namespace filters. drill: logs needs query.from=logs. Drill is not available on metrics. Every table format's field must exist in the returned frame; formatting cannot reference an absent column. A structured-table sparkline field must be a measure alias from that table's query. service_link needs variable to name the query or custom variable selected by the link. highlight applies to logs and log_patterns, at most 200 characters. split: deploy needs a service equality filter, as a literal or a single-value variable; other filters are allowed. When the service is All, a split: deploy panel shows the plain bar with a note explaining the missing service scope. Use service_map for dependency context, health for service health; neither proves causality. Example 1: Reference shapes; use only the types the question needs. \{"name":"Investigation shapes","annotations":\{"deploys":true,"anomalies":true},"variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"latency_heat","title":"Latency over time","viz":"heatmap","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"bucket":"auto","histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"latency_hist","title":"Latency by operation","viz":"histogram","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"by":["operation"],"histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"items","title":"Calls versus tail latency","viz":"scatter","query":\{"from":"spans","where":["service = $service"],"measures":["count() as rows","p95(duration_ms) as tail_latency"],"by":["operation"]},"drill":"traces"},\{"id":"states","title":"Error states","viz":"state_timeline","query":\{"from":"spans","where":["service = $service"],"measures":["error_rate()"],"by":["operation"],"bucket":"auto"},"thresholds":[\{"value":5,"status":"bad"}],"drill":"traces"},\{"id":"log_rows","title":"Recent logs","viz":"logs","query":\{"from":"logs","where":["service = $service"],"sort":"time","limit":100},"drill":"logs"},\{"id":"patterns","title":"Repeated log patterns","viz":"log_patterns","query":\{"from":"logs","where":["service = $service"],"measures":["count()"],"by":["body_template"],"bucket":"auto","limit":50},"drill":"logs"},\{"id":"trace_rows","title":"Slow traces","viz":"traces","query":\{"from":"spans","where":["service = $service"],"sort":"duration_ms","limit":20},"drill":"traces"},\{"id":"map","title":"Service calls","viz":"service_map","query":\{"from":"spans"}},\{"id":"health","title":"Service health","viz":"health","query":\{"from":"spans"}}]} Example 2: Reference shapes; use only the types the question needs. \{"name":"Interaction shapes","variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"hist","title":"Metric distribution","viz":"histogram","query":\{"from":"metrics","where":["service = $service"],"measures":["count()"],"histogram":\{"field":"value","buckets":"explicit"}}},\{"id":"table","title":"Service calls and trends","viz":"table","query":\{"from":"spans","measures":["count() as calls"],"by":["service"]},"options":\{"columns":[\{"field":"service","format":"service_link","variable":"service"},\{"field":"calls","format":"sparkline"}]}},\{"id":"prior","title":"Service calls one day earlier","viz":"bar","query":\{"from":"spans","measures":["count()"],"by":["service"]},"click":\{"set_variable":"service"},"time":\{"shift":"1d"}}]} Metric examples; use when the discovered type fits. \{"name":"Metric measures","panels":[\{"id":"network","title":"Network bytes per second","viz":"timeseries","query":\{"from":"metrics","where":["name = 'system.network.io'"],"measures":["rate()"],"by":["attributes['direction']"],"bucket":"auto"}},\{"id":"duration","title":"Request duration p95","viz":"timeseries","query":\{"from":"metrics","where":["name = 'http.server.request.duration'"],"measures":["p95(value)"],"bucket":"auto"},"unit":"s"}]} Observed-resource SQL example. \{"name":"Observed resources","panels":[\{"id":"resources","title":"Span resources observed in this window","viz":"table","sql":"SELECT namespace,service,resource['service.version']::VARCHAR AS version,first_seen,last_seen FROM resource_inventory WHERE signal='spans' AND $__window(first_seen) ORDER BY namespace,service,version,first_seen,last_seen"}]} +**Create dashboard**: Create a dashboard for the authenticated user from a complete spec. Read get_telemetry_schema first and preview_panels until every non-text panel returns data. Empty or failing panels return error.code invalid_spec with their path, title and diagnosis, plus structured problems. Successful saves return a receipt for that committed version: base_version, version, changes, layout_changed, dashboard_fields and save_check. Changes describe authored panel fields and position_changed; physical packing is only layout_changed. Order chips mark the minimal moved set. save_check reports checked, reason when unchecked, total elapsed_ms and one status/rows result per saved panel with elapsed_ms when executed. checked means every panel was executed, not that error or empty panels are healthy. Text rows identify nonempty content, not telemetry. Use the structured receipt rather than prose warnings as check evidence. Create receipts list added panels without layout or dashboard edit chips. No-op saves still create a new version with no change chips. Per-panel elapsed_ms is omitted when the panel did not run. A dashboard is \{name, description, time:\{range}, variables, panels}. Each panel: \{id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: \{field: duration_ms, buckets: log2} for spans or \{field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: \{from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Standard OpenTelemetry keys that get_telemetry_schema marks indexed, such as http.response.status_code and k8s.pod.name, read typed: ingest converts a value sent in another type, so "200" reads as the number 200, and they need no cast. Other keys read as sent. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', attributes['http.route'] IN $routes, attributes['http.response.status_code'] >= 500. Variables: \{name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, span_rollup, edge_rollup or resource_inventory that filters time with $__window(column). Compare time columns with TIMESTAMP 'YYYY-MM-DD HH:MM:SS' (UTC), or cast TIMESTAMPTZ literals with ::TIMESTAMPTZ_NS. Use values exactly as get_telemetry_schema lists them. Example panel: \{"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":\{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[\{"value":1500,"status":"bad"}]}. Structured spans aggregate panels restricted to namespace/service/kind/status and count/rate/error_rate/share or duration aggregates use span_rollup at minute resolution. All measures use the spans matching the panel filters. To measure served latency, filter out client and producer kinds. Percentiles are approximate (one exponential bucket, 9.05%); fresh_to_ms is the ingest horizon. Other structured queries stay raw. Metrics: gauge/updown | counter | histogram. count(): points; count_distinct(): distinct. rate(): undefined | series increase/elapsed summed | count rate summed. sum(value): series means summed | increases | sum increases. avg(value): mean series means | undefined | sum/count increases. Gauge/updown sum/avg carry earlier points within 5m. Deltas spread across covered buckets; rate alone carries within 5m. rate() is per-second increase over covered elapsed time; auto >=1m. min/max: points | points | undefined. last(value): latest strictly before bucket/window end, reported within 5m, summed | same | undefined. pNN/quantile: points | undefined | interpolated bucket increases. summary: no value aggregates. Undefined: NULL. Fix name in its own where entry: one literal or single-value variable without All or multi-value; or name in by. Read type/temporality from get_telemetry_schema. Panel SQL also supports resource_inventory: signal, namespace, service, full typed resource, first_seen and last_seen. One row per distinct full resource per signal/namespace/service observed inside the logical panel window; first_seen/last_seen are actual in-window event times. Select signal='spans', 'logs' or 'metrics' and use resource['key'] with literal dotted keys. count(*) counts resource identities per signal, not events or instances. Declare $__window(first_seen). This relation is SQL-only: query.from and variables remain spans|logs|metrics; unscoped SQL cannot read it. state_timeline needs at least one threshold marked warn or bad, rather than only ok. Annotations attach only to timeseries, heatmap and state_timeline panels, scoped by service and namespace filters. drill: logs needs query.from=logs. Drill is not available on metrics. Every table format's field must exist in the returned frame; formatting cannot reference an absent column. A structured-table sparkline field must be a measure alias from that table's query. service_link needs variable to name the query or custom variable selected by the link. highlight applies to logs and log_patterns, at most 200 characters. split: deploy needs a service equality filter, as a literal or a single-value variable; other filters are allowed. When the service is All, a split: deploy panel shows the plain bar with a note explaining the missing service scope. Use service_map for dependency context, health for service health; neither proves causality. Example 1: Reference shapes; use only the types the question needs. \{"name":"Investigation shapes","annotations":\{"deploys":true,"anomalies":true},"variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"latency_heat","title":"Latency over time","viz":"heatmap","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"bucket":"auto","histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"latency_hist","title":"Latency by operation","viz":"histogram","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"by":["operation"],"histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"items","title":"Calls versus tail latency","viz":"scatter","query":\{"from":"spans","where":["service = $service"],"measures":["count() as rows","p95(duration_ms) as tail_latency"],"by":["operation"]},"drill":"traces"},\{"id":"states","title":"Error states","viz":"state_timeline","query":\{"from":"spans","where":["service = $service"],"measures":["error_rate()"],"by":["operation"],"bucket":"auto"},"thresholds":[\{"value":5,"status":"bad"}],"drill":"traces"},\{"id":"log_rows","title":"Recent logs","viz":"logs","query":\{"from":"logs","where":["service = $service"],"sort":"time","limit":100},"drill":"logs"},\{"id":"patterns","title":"Repeated log patterns","viz":"log_patterns","query":\{"from":"logs","where":["service = $service"],"measures":["count()"],"by":["body_template"],"bucket":"auto","limit":50},"drill":"logs"},\{"id":"trace_rows","title":"Slow traces","viz":"traces","query":\{"from":"spans","where":["service = $service"],"sort":"duration_ms","limit":20},"drill":"traces"},\{"id":"map","title":"Service calls","viz":"service_map","query":\{"from":"spans"}},\{"id":"health","title":"Service health","viz":"health","query":\{"from":"spans"}}]} Example 2: Reference shapes; use only the types the question needs. \{"name":"Interaction shapes","variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"hist","title":"Metric distribution","viz":"histogram","query":\{"from":"metrics","where":["service = $service"],"measures":["count()"],"histogram":\{"field":"value","buckets":"explicit"}}},\{"id":"table","title":"Service calls and trends","viz":"table","query":\{"from":"spans","measures":["count() as calls"],"by":["service"]},"options":\{"columns":[\{"field":"service","format":"service_link","variable":"service"},\{"field":"calls","format":"sparkline"}]}},\{"id":"prior","title":"Service calls one day earlier","viz":"bar","query":\{"from":"spans","measures":["count()"],"by":["service"]},"click":\{"set_variable":"service"},"time":\{"shift":"1d"}}]} Metric examples; use when the discovered type fits. \{"name":"Metric measures","panels":[\{"id":"network","title":"Network bytes per second","viz":"timeseries","query":\{"from":"metrics","where":["name = 'system.network.io'"],"measures":["rate()"],"by":["attributes['direction']"],"bucket":"auto"}},\{"id":"duration","title":"Request duration p95","viz":"timeseries","query":\{"from":"metrics","where":["name = 'http.server.request.duration'"],"measures":["p95(value)"],"bucket":"auto"},"unit":"s"}]} Observed-resource SQL example. \{"name":"Observed resources","panels":[\{"id":"resources","title":"Span resources observed in this window","viz":"table","sql":"SELECT namespace,service,resource['service.version']::VARCHAR AS version,first_seen,last_seen FROM resource_inventory WHERE signal='spans' AND $__window(first_seen) ORDER BY namespace,service,version,first_seen,last_seen"}]} **Additive.** It creates something new and alters nothing that exists. @@ -510,19 +510,16 @@ Per-service analytical rollup by namespace and time bucket. Panel SQL only; filt | Column | SQL type | Means | |---|---|---| | `namespace` | `VARCHAR` | OpenTelemetry service namespace | -| `bucket` | `TIMESTAMP` | Rollup time bucket | +| `bucket` | `TIMESTAMP_NS` | Rollup time bucket | | `service` | `VARCHAR` | Service name | | `spans` | `BIGINT` | Total spans | | `served_spans` | `BIGINT` | Spans describing work performed by this service | -| `p50_ms` | `DOUBLE` | Median service latency | -| `p95_ms` | `DOUBLE` | 95th percentile service latency | -| `error_rate` | `DOUBLE` | Error rate | +| `error_spans` | `BIGINT` | Spans with error status | | `log_count` | `BIGINT` | Log events | -| `metric_count` | `BIGINT` | Metric data points | ### span_rollup -Per-minute spans by namespace, service, kind and status. Panel SQL only; filter bucket with $__window(bucket). Counts and duration aggregates merge across rows. Percentiles interpolate merged fixed-scale-3 OpenTelemetry exponential histograms and are approximate within one positive bucket (9.05%). Structured RED panels route here at minute resolution; fresh_to_ms reports the ingest horizon, usually 1–1.5 minutes behind ingestion. Window boundaries have minute precision. +Per-minute spans by namespace, service, kind and status. Panel SQL only; filter bucket with $__window(bucket). Counts and duration aggregates merge across rows. Percentiles prefer served spans within each group and fall back to all spans for outbound-only groups. Percentiles interpolate merged fixed-scale-3 OpenTelemetry exponential histograms and are approximate within one positive bucket (9.05%). Structured RED panels route here at minute resolution; fresh_to_ms reports the ingest horizon, usually 1–1.5 minutes behind ingestion. Window boundaries have minute precision. | Column | SQL type | Means | |---|---|---| diff --git a/ui/host/src/sql-editor/sql-editor.test.tsx b/ui/host/src/sql-editor/sql-editor.test.tsx index 1894715a7..8de9a4cac 100644 --- a/ui/host/src/sql-editor/sql-editor.test.tsx +++ b/ui/host/src/sql-editor/sql-editor.test.tsx @@ -18,7 +18,7 @@ const schema: TelemetrySchema = { }, sql_relations: { resource_inventory: { columns: [{ name: "resource", type: "map", sql_type: "VARIANT" }] }, - service_rollup: { columns: [{ name: "p95_ms", type: "number", sql_type: "DOUBLE" }] }, + service_rollup: { columns: [{ name: "error_spans", type: "number", sql_type: "BIGINT" }] }, edge_rollup: { columns: [{ name: "caller", type: "string", sql_type: "VARCHAR" }] }, }, }; diff --git a/ui/host/tests/go-fragments/overview.json b/ui/host/tests/go-fragments/overview.json index 638d97f8c..6f998c053 100644 --- a/ui/host/tests/go-fragments/overview.json +++ b/ui/host/tests/go-fragments/overview.json @@ -50,13 +50,13 @@ "unhealthy": 1 }, "total_spans": 30, - "error_rate": 10, + "error_rate": 100, "service_count": 1, "error_trend_times": [ 1791400500000 ], "error_trend": [ - 10 + 100 ] }, "columns": [ @@ -118,13 +118,13 @@ 30 ], [ - 10 + 100 ], [ - 100 + 103.16811698929183 ], [ - 100 + 107.1880787361571 ], [ 30 @@ -138,7 +138,8 @@ "sql": "observability.Service.Overview", "elapsed_ms": 0, "from_ms": 1791398700000, - "to_ms": 1791402300000 + "to_ms": 1791402300000, + "fresh_to_ms": 1791402300000 } ] } diff --git a/ui/host/tests/go-fragments/overview.summary.txt b/ui/host/tests/go-fragments/overview.summary.txt index 57b6145e1..f6250b449 100644 --- a/ui/host/tests/go-fragments/overview.summary.txt +++ b/ui/host/tests/go-fragments/overview.summary.txt @@ -1,3 +1,3 @@ health: status=ok rows=1 truncated=false - health=unhealthy healthy=0 degraded=0 unhealthy=1 services=1 spans=30 error_rate=10% - service=checkout, health=unhealthy, spans=30 count, error_rate=10%, p50_ms=100 ms, p95_ms=100 ms, log_count=30 count, metric_count=0 count + health=unhealthy healthy=0 degraded=0 unhealthy=1 services=1 spans=30 error_rate=100% + service=checkout, health=unhealthy, spans=30 count, error_rate=100%, p50_ms=103.16811698929183 ms, p95_ms=107.1880787361571 ms, log_count=30 count, metric_count=0 count diff --git a/ui/host/tests/go-fragments/performance.json b/ui/host/tests/go-fragments/performance.json index 9a98d8382..80d1f79c8 100644 --- a/ui/host/tests/go-fragments/performance.json +++ b/ui/host/tests/go-fragments/performance.json @@ -177,7 +177,7 @@ ], "rows": 1 }, - "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((namespace = 'shop'))) SELECT epoch_ms(time_bucket(INTERVAL '60 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\", 100.0 * coalesce(sum(spans) FILTER (WHERE status='STATUS_CODE_ERROR'),0) / nullif(sum(spans),0) AS \"error_rate\" FROM base GROUP BY time_bucket(INTERVAL '60 seconds', \"bucket\"::TIMESTAMP_NS) ORDER BY \"_t\" LIMIT 14000", + "sql": "WITH base AS (SELECT * FROM span_rollup WHERE \"bucket\" \u003e= ?::TIMESTAMP_NS AND \"bucket\" \u003c ?::TIMESTAMP_NS AND ((namespace = 'shop'))) SELECT epoch_ms(time_bucket(INTERVAL '60 seconds', \"bucket\"::TIMESTAMP_NS))::BIGINT AS \"_t\", 100.0 * (coalesce(sum(spans) FILTER (WHERE status='STATUS_CODE_ERROR'),0)::DOUBLE / nullif(sum(spans),0)) AS \"error_rate\" FROM base GROUP BY time_bucket(INTERVAL '60 seconds', \"bucket\"::TIMESTAMP_NS) ORDER BY \"_t\" LIMIT 14000", "interval": "1m", "elapsed_ms": 0, "from_ms": 1791398700000, diff --git a/ui/host/tests/go-fragments/topology.json b/ui/host/tests/go-fragments/topology.json index 86ec6cb9a..2f7c0fd9f 100644 --- a/ui/host/tests/go-fragments/topology.json +++ b/ui/host/tests/go-fragments/topology.json @@ -1,7 +1,7 @@ { "view": { "kind": "preset", - "key": "0846eaf4f61296fe9f69480ca33825c793559cd8ea88426af183ae245646c9db" + "key": "94e1c24eb73eda10e09d381342ae019a0dcf9724ee5529ed7fc8148b459abf2c" }, "dashboard": { "version": 1, @@ -125,7 +125,7 @@ 100 ], [ - 10, + 100, 10 ], [ @@ -133,7 +133,7 @@ "" ], [ - 100, + 107.1880787361571, null ], [ @@ -146,7 +146,8 @@ "sql": "observability.Service.Topology", "elapsed_ms": 0, "from_ms": 1791398700000, - "to_ms": 1791402300000 + "to_ms": 1791402300000, + "fresh_to_ms": 1791402300000 } ] }