diff --git a/AGENTS.md b/AGENTS.md index 270a1d0d..a4ecde2c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,7 +95,9 @@ or globally rewritten scope indexes; uncached batches union in ranked the same way. Windows within one minute read footer-pruned Parquet, and compaction derives output lists from cached inputs. Body search matches redacted text. - Analytical service/edge watermark lag is separate. Completed-batch writes + Span, log, resource and service minute summaries share this batch lifecycle. + Fold counts, extrema and histogram bins over the pinned active IDs. Endpoint, + receiver and edge summaries retain their analytical watermarks. Completed-batch writes have their own gate and write-pool slot; analytical writes use disjoint tables. Maintenance must hold both gates for checkpointing. - Batch format 6, including its physical schema and sidecars, is the only diff --git a/docs/proposals/0007-additive-rollup-aggregates.md b/docs/proposals/0007-additive-rollup-aggregates.md index 4a77e2e6..740c592d 100644 --- a/docs/proposals/0007-additive-rollup-aggregates.md +++ b/docs/proposals/0007-additive-rollup-aggregates.md @@ -1,23 +1,20 @@ # Additive per-batch rollup aggregates -Status: Draft +Status: Phase 1 implemented Date: 2026-11-14 -Pull request: TBD +Related issues: #278 and #477 ## Summary -Replace the raw re-aggregation rollup model for the scan summaries -(`span_rollup`, `log_rollup`, `endpoint_rollup`, and the resource/receiver -summaries) with additive per-batch partial aggregates that are merged at read -and folded during compaction. Cost becomes proportional to newly ingested rows -rather than to the event-time span touched by a pass. Keep watermark -re-aggregation only for the rollups whose output is not a simple additive -merge of per-batch partials. +Store span, log, resource and service minute summaries as per-batch partials in +the disposable read cache. Merge active partials at read time and fold them +during compaction. Endpoint, receiver and edge summaries retain their analytical +watermarks. ## Motivation -`refreshServiceRollup` discovers the affected keys for a pass, derives one -event-time hull `[min(bucket), max(bucket)+1m)`, and re-scans raw Parquet over +The previous `refreshServiceRollup` discovered the affected keys for a pass, derived one +event-time hull `[min(bucket), max(bucket)+1m)`, and re-scanned raw Parquet over that hull once per key-chunk to rebuild every summary. This has three structural costs, all surfaced by the engine audit: @@ -34,9 +31,9 @@ structural costs, all surfaced by the engine audit: its window and reinserts grouped rows, and correctness depends on every insert path keeping the delete-first/group-by discipline. -The repository already runs the additive model for `read_trace_parts` and +The repository already runs the additive model for `read_trace_exemplars` and `read_resource_seconds` via `read_batches` markers and -`transferBatchCacheLocked` (`internal/engine/batch_cache.go:555-589`). This +`transferBatchCacheLocked` (`internal/engine/batch_cache.go`). This proposal generalizes that proven mechanism to the summary rollups. ## Goals and non-goals @@ -58,28 +55,40 @@ Non-goals: which are join-shaped or order-dependent and stay on watermark re-aggregation. -## Design - -Each summary rollup becomes a set of per-batch partial aggregates keyed by the -summary's logical key plus the contributing batch ID, written once when a batch -first enters the read cache, exactly as `read_trace_parts` is today. A read or -a compaction merges the partials additively: - -- Counts and sums add directly. -- `min`/`max` take the extreme. -- Histograms merge by bin (the scale-3 layout already in `span_rollup.hist` - is mergeable). - -Because partials are additive, a duplicate per logical key is expected and -merges correctly, so the uniqueness invariant disappears for these tables and -the ART primary keys become unnecessary (already dropped; see the read-perf -work). A batch's partials are retired when the batch is compacted away, with the -compaction output contributing its own merged partials — the same lifecycle the -trace caches already follow. - -A later phase can compute the partials in Go at `Repository.Commit` and persist -them as an immutable per-batch sidecar, removing DuckDB writes, gates, WAL and -checkpoints for these tables entirely, at the cost of a batch-format bump. +## Phase 1 design + +The cache writer groups each new immutable file by its batch ID and logical +minute key. It commits all four summaries and the `read_batches` marker in one +transaction. Span partials store counts, duration sums and extrema, and scale-3 +histograms. Service counts combine span and log populations with zero-count +service-minutes from metric resources. Resource identities retain their projected +fields and exact first and last timestamps. + +Every read pins the file catalog and reads markers and partials in one DuckDB +transaction. Only cached IDs in that catalog contribute. Uncached active files +supply the same aggregates from Parquet. Each public relation merges its complete +logical key, including histogram counts per bin. Fractions and averages are +computed from counts and sums after merging. The publication horizon supplies +additive ingest coverage and the last completed detector minute. Span and log +rates use the requested event-time interval. + +Compaction folds the input partials before marking the output complete. A busy +cache writer defers the fold, so the published output can be read from Parquet +in the meantime. Readers on either side of the catalog swap see one generation. +The worker subsequently removes retired contributions. + +The endpoint top-128 route fold depends on all routes in a service-minute. +Receiver summaries depend on retry winners and time-ordered counter changes, +and edges join spans across files. These stay on the analytical writer. +Endpoint and receiver discovery considers only routed spans and recognized +receiver metrics respectively. Their distinct keys are ordered by bucket, +namespace and service. Each chunk binds its own half-open minute range against +the captured catalog, using each signal's own footer bounds. + +Phase 1 uses read-cache version 22 and rollup schema version 7. A mismatch +rebuilds the disposable partials from active files in bounded batches. +A future immutable sidecar could avoid this rebuild and would require a +canonical batch-format change. ## Alternatives @@ -100,65 +109,14 @@ checkpoints for these tables entirely, at the cost of a batch-format bump. during compaction so a read never merges more partials than live batches. - Cache-version and rebuild semantics must cover the new partial tables. -## Open questions - -- Which summaries move in phase one (proposal: span and log first, endpoint and - resource second)? -- Does the read-time merge stay within the panel latency budget at 30-day - windows, or does it force the compaction-fold step into phase one? -- Measurement: A/B the additive model against the current model on non-pico - data before committing. - -## Research validation (2026-11-15) - -A three-angle research pass (prior art, in-codebase fit, performance) was run -before build. Findings: - -**Prior art.** This design is ClickHouse's `AggregatingMergeTree` with the -`-State` / `-Merge` combinators: write a partial aggregate state per batch, -combine states at read, fold states during a background merge. Apache Druid's -ingestion-time rollup is the same idea for the phase-2 immutable sidecar. The -repository already runs this pattern for `read_trace_parts` via -`transferBatchCacheLocked`, so there is an in-repo precedent, not only external -ones. Keeping only associative/commutative stats on the additive model and -leaving non-additive ones (endpoint top-128 fold, joins) on re-aggregation -matches ClickHouse and Pinot guidance exactly. - -**Required revisions before build:** - -1. **Make the compaction fold mandatory in phase one, not an open question.** - ClickHouse's best-known production failure is "too many unmerged parts": a - read-time `-Merge` over thousands of per-batch states is slow, and the whole - design depends on background merges keeping the state count low. Phase one - without the fold reproduces that slowness at long windows. The in-repo - `transferBatchCacheLocked` already folds inputs into the compaction output, - so commit to it from the start. -2. **State the correctness invariants explicitly:** exactly-once contribution (a - batch's partial is counted once across retries via its `read_batches` marker, - and a compaction output *replaces* its inputs, never adds to them); store - `sum` + `count`, never `avg`, and divide at read for error rate and means; - every batch histogram is at the same scale-3 layout so bin-merge is exact - (reject or downscale-align anything else). -3. **Resolve the cross-gate snapshot design.** Moving span/log/endpoint rollups - onto per-batch partials moves them from the writeGate/watermark world to the - cacheGate/`read_batches` world, while `service_rollup` (0008) and - `edge_rollup` stay analytical. A consumer that reads a span partial *and* an - analytical rollup then spans two gates/snapshots and can see a torn view. - AGENTS.md requires maintenance to hold both gates for checkpointing; the - proposal must specify how a reader gets a consistent cross-gate snapshot. -4. **Name the residual.** Phase one keeps partials in the version-gated - disposable cache, so a cache-version bump re-derives all partials from raw - Parquet — the exact full-hull scan this removes, merely deferred to rebuild. - Only the phase-2 immutable Parquet sidecar removes that scan permanently. - -**Status confirmed.** The ART primary keys on `span`/`log`/`endpoint`/`service`/ -`edge_rollup` are already dropped on `main` (`rollup_schema_version` 5), so the -"already dropped" premise holds; the additive model's duplicate-per-batch rows -will not violate a PK. Versioning: a `readCacheVersion` + `rollup_schema_version` -bump (rebuildable, no format bump, no Goose) for phase one; a batch-format bump -only for the phase-2 sidecar. - -**Build readiness:** buildable after the cross-gate design (item 3) is specified -and the compaction fold is committed (item 1). Lower-risk fallback remains the -0007 "cliff fixes" (bucket-order affected keys, per-chunk bounds, key-filter the -log/metric aggregates) if the 30-day read-merge A/B blows the panel budget. +## Prior art + +ClickHouse's `AggregatingMergeTree` combines aggregate states at query time +and folds them during background merges. The compaction fold here serves the +same purpose. Apache Druid's ingestion-time rollup is also relevant to the +proposed immutable sidecar. + +## Follow-up measurement + +Measure read-time merging on representative 30-day panels and compare ingest, +rebuild and compaction costs before considering an immutable sidecar. diff --git a/docs/proposals/README.md b/docs/proposals/README.md index f667398d..74b37b19 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -38,7 +38,7 @@ Earlier proposals predate the template and keep their original structure. | 0004 | [Full UI without an LLM key, and PitotQL](0004-pitotql.md) | Accepted | | 0005 | [Dedicated attribute columns and batch format 5](0005-dedicated-attribute-columns.md) | Accepted | | 0006 | [Read performance under sustained ingest](0006-read-performance.md) | Draft | -| 0007 | [Additive per-batch rollup aggregates](0007-additive-rollup-aggregates.md) | Draft | +| 0007 | [Additive per-batch rollup aggregates](0007-additive-rollup-aggregates.md) | Phase 1 implemented | | 0008 | [Mergeable latency sketch and derived service rollup](0008-mergeable-latency-sketch.md) | Implemented | | 0009 | [Manifest catalog, write-ahead log, and parallel compaction](0009-manifest-catalog-wal-compaction.md) | Draft | | 0010 | [Result-cache key normalization and an extent cache](0010-result-cache-extent-key.md) | Accepted | diff --git a/docs/testing.md b/docs/testing.md index db058df0..f4b3c64b 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -167,14 +167,14 @@ used by the dashboard. Retain failures and timeout counts alongside latency; do make a slow or failed run disappear by retrying until it passes. These targets are acceptance criteria, not guarantees for arbitrary telemetry volumes. -The executor uses analytical minute summaries for supported span/log aggregates, +The executor uses per-batch minute summaries for supported span/log aggregates, filters and dimensions; other shapes read raw telemetry. The disposable trace read cache stores completed-batch candidates and parts. Service maps combine analytical rollups with a raw client-span query for external peers. That query materializes the filtered client projection once for reuse by peer and edge aggregates; its child-span and observed-service checks also read spans. Health -panels use analytical rollups. Rollup data has separate watermark lag and approximate latency -semantics. Do not assume those rollups answer arbitrary raw counts, +panels read the published service and span summaries. Endpoint, receiver and +edge summaries have separate watermark lag. Histogram quantiles are approximate. Do not assume those rollups answer arbitrary raw counts, rates or quantiles exactly, or report every dashboard query as cached. `just readbench-check` compiles the opt-in native read harness in CI without diff --git a/internal/agent/dashboard_eval_golden_test.go b/internal/agent/dashboard_eval_golden_test.go index df05b613..ab0bd852 100644 --- a/internal/agent/dashboard_eval_golden_test.go +++ b/internal/agent/dashboard_eval_golden_test.go @@ -15,7 +15,6 @@ import ( "github.com/labstack/pitot/internal/config" "github.com/labstack/pitot/internal/dashboard" "github.com/labstack/pitot/internal/engine" - "github.com/labstack/pitot/internal/engine/querytest" pitotmcp "github.com/labstack/pitot/internal/mcp" "github.com/labstack/pitot/internal/query" controlstore "github.com/labstack/pitot/internal/store" @@ -42,7 +41,7 @@ func TestDashboardEvalGoldensCurrent(t *testing.T) { if err = repo.Commit(t.Context(), telemetrystore.Batch{ID: "eval_fixture", Spans: []telemetry.Span{{Namespace: "shop", ServiceName: "checkout", TraceID: "trace", SpanID: "span", Name: "request", Kind: "SPAN_KIND_SERVER", StartUnixNanos: from.UnixNano(), EndUnixNanos: from.Add(time.Millisecond).UnixNano(), DurationMS: 1, StatusCode: "STATUS_CODE_OK", IngestedAt: from.UnixNano()}}}); err != nil { t.Fatal(err) } - if err := querytest.RefreshSpanRollup(engine.DB); err != nil { + if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil { t.Fatal(err) } executor := query.NewExecutor(engine, 30) @@ -135,11 +134,13 @@ func TestDashboardEvalGoldensCurrent(t *testing.T) { if err != nil { t.Fatal(err) } - for i := range results { - results[i].ElapsedMS = 0 - } - for i := range addedResults { - addedResults[i].ElapsedMS = 0 + for _, panels := range [][]query.Result{results, addedResults} { + for i := range panels { + panels[i].ElapsedMS = 0 + if panels[i].FreshToMS != 0 { + panels[i].FreshToMS = to.UnixMilli() + } + } } if results[1].Status != "ok" || results[1].Frame != nil { t.Fatalf("text shape: %#v", results[1]) diff --git a/internal/alert/engine_env_test.go b/internal/alert/engine_env_test.go index 05586aaa..2530f0c7 100644 --- a/internal/alert/engine_env_test.go +++ b/internal/alert/engine_env_test.go @@ -32,6 +32,7 @@ func TestAlertRulesMeasureOnlyTheirNamespaceInTheCurrentWindow(t *testing.T) { if err := engine.CreateCacheTables(db); err != nil { t.Fatal(err) } + querytest.CreateSummaryFixtures(t, db) at := time.Now().UTC().Truncate(time.Minute).Add(-time.Minute) querytest.SeedSpanRollup(t, db, at, "acme", "api", "", 100, 90, 20) querytest.SeedSpanRollup(t, db, at.Add(-time.Minute), "globex", "api", "", 1000, 0, 200) diff --git a/internal/cmd/e2eseed/main_test.go b/internal/cmd/e2eseed/main_test.go index 7986d84b..6ff22b86 100644 --- a/internal/cmd/e2eseed/main_test.go +++ b/internal/cmd/e2eseed/main_test.go @@ -17,7 +17,6 @@ import ( "github.com/labstack/pitot/internal/config" "github.com/labstack/pitot/internal/dashboard" "github.com/labstack/pitot/internal/engine" - "github.com/labstack/pitot/internal/engine/querytest" "github.com/labstack/pitot/internal/ingest" "github.com/labstack/pitot/internal/observability" "github.com/labstack/pitot/internal/query" @@ -81,7 +80,7 @@ func TestAllPanelsFixtureValidates(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = engine.Close() }) - if err := querytest.RefreshSpanRollup(engine.DB); err != nil { + if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil { t.Fatal(err) } if _, problems, err := query.NewExecutor(engine, 30).Check(t.Context(), &spec); err != nil || len(problems) != 0 { @@ -451,7 +450,7 @@ func TestPerformanceFixtureValidatesAndExecutes(t *testing.T) { t.Fatal(err) } t.Cleanup(func() { _ = engine.Close() }) - if err := querytest.RefreshSpanRollup(engine.DB); err != nil { + if _, err := engine.RefreshDashboardRollups(t.Context()); err != nil { t.Fatal(err) } if _, problems, err := query.NewExecutor(engine, 30).Check(t.Context(), &spec); err != nil || len(problems) != 0 { diff --git a/internal/dashboard/defaults_sql.go b/internal/dashboard/defaults_sql.go index 74b2fbd7..3043f60d 100644 --- a/internal/dashboard/defaults_sql.go +++ b/internal/dashboard/defaults_sql.go @@ -147,6 +147,5 @@ func containerCapacitySQL() string { FROM results ORDER BY (reporting<>'reporting') DESC,status DESC NULLS LAST,namespace,host,container` } -// Selected resource tuples come from analytical minutes. No partial-second -// Parquet scan is needed; resource_inventory retains its separate exact contract. +// Resource summaries retain the first observation of each projected tuple per minute. const versionObservationsSQL = `SELECT namespace,service,resource['service.version']::VARCHAR AS version,resource['process.runtime.name']::VARCHAR AS runtime_name,resource['process.runtime.version']::VARCHAR AS runtime_version,resource['telemetry.sdk.language']::VARCHAR AS sdk_language,resource['telemetry.sdk.version']::VARCHAR AS sdk_version,first_seen AS seen FROM resource_rollup WHERE $__window(bucket) AND $__window(first_seen) AND resource['service.version']::VARCHAR<>''` diff --git a/internal/dashboard/resource_inventory_test.go b/internal/dashboard/resource_inventory_test.go index 5c8542e3..66bebe45 100644 --- a/internal/dashboard/resource_inventory_test.go +++ b/internal/dashboard/resource_inventory_test.go @@ -103,7 +103,7 @@ func TestDefaultResourcePanelsAcrossCacheStates(t *testing.T) { for _, state := range []string{"partial", "cold", "full"} { t.Run(state, func(t *testing.T) { if state == "cold" { - if _, err := d.DB.Exec(`DELETE FROM read_batches; DELETE FROM read_resource_inventory; DELETE FROM read_resource_seconds; DELETE FROM read_metric_names; DELETE FROM read_trace_exemplars`); err != nil { + if _, err := d.DB.Exec(`DELETE FROM read_span_rollup; DELETE FROM read_log_rollup; DELETE FROM read_resource_rollup; DELETE FROM read_service_rollup; DELETE FROM read_batches; DELETE FROM read_resource_inventory; DELETE FROM read_resource_seconds; DELETE FROM read_metric_names; DELETE FROM read_trace_exemplars`); err != nil { t.Fatal(err) } if err := engine.CreateCacheTables(d.DB); err != nil { diff --git a/internal/engine/additive_rollup.go b/internal/engine/additive_rollup.go new file mode 100644 index 00000000..d3914e6d --- /dev/null +++ b/internal/engine/additive_rollup.go @@ -0,0 +1,249 @@ +package engine + +import ( + "fmt" + "strings" + "time" + + "github.com/labstack/pitot/internal/queryrows" + "github.com/labstack/pitot/internal/rollupsql" + "github.com/labstack/pitot/internal/telemetry" +) + +var additiveRollups = []string{"span_rollup", "log_rollup", "resource_rollup", "service_rollup"} + +// date_trunc coerces its timestamp argument to microseconds. Floor the signed +// nanoseconds first so a last-nanosecond event stays in its own minute. +func minuteBucketSQL(clock string) string { + return "make_timestamp_ns(" + minuteSQL("epoch_ns("+clock+")") + ")" +} + +func spanPartial(rows string) string { + return `SELECT batch_id,namespace,` + minuteBucketSQL("start_time") + ` 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,histogram(` + rollupsql.Bin("duration_ms") + `) hist + FROM (` + rows + `) s WHERE namespace IS NOT NULL AND service IS NOT NULL AND start_time IS NOT NULL GROUP BY ALL` +} + +func logPartial(rows string) string { + return `SELECT batch_id,namespace,` + minuteBucketSQL("time") + ` bucket,service,coalesce(severity,'') severity,count(*) logs + FROM (` + rows + `) l WHERE namespace IS NOT NULL AND service IS NOT NULL AND time IS NOT NULL GROUP BY ALL` +} + +func resourcePartial(signal, clock, rows string) string { + // Collapse repeated raw resources before extracting the inventory identity. + // Regroup after projection: resources that differ only in unrelated OTLP + // keys still describe one inventory population. Keep the converted version + // column authoritative and preserve exact event-time extrema. + return fmt.Sprintf(`WITH resources AS MATERIALIZED ( + SELECT batch_id,namespace,%[4]s bucket,service,resource,_r_service_version, + min(%[1]s) first_seen,max(%[1]s) last_seen + FROM (%[3]s) m WHERE namespace IS NOT NULL AND service IS NOT NULL AND %[1]s IS NOT NULL + GROUP BY batch_id,namespace,bucket,service,resource,_r_service_version), + projected AS (SELECT batch_id,namespace,bucket,service, + struct_pack("host.name" := resource['host.name']::VARCHAR,"service.version" := _r_service_version, + "process.runtime.name" := resource['process.runtime.name']::VARCHAR,"process.runtime.version" := resource['process.runtime.version']::VARCHAR, + "telemetry.sdk.language" := resource['telemetry.sdk.language']::VARCHAR,"telemetry.sdk.version" := resource['telemetry.sdk.version']::VARCHAR)::VARIANT identity,first_seen,last_seen + FROM resources) + SELECT batch_id,namespace,bucket,service,%[2]s AS signal,identity AS resource,min(first_seen) AS first_seen,max(last_seen) AS last_seen FROM projected GROUP BY batch_id,namespace,bucket,service,identity`, clock, sqlLiteral(signal), rows, minuteBucketSQL(clock)) +} + +// servicePartial includes metric-only service-minutes. The input relations carry +// batch_id so caching several files in one transaction preserves their ownership. +func servicePartial(spans, logs, metrics string) string { + var parts []string + if spans != "" { + parts = append(parts, `SELECT batch_id,namespace,bucket,service,spans, + CASE WHEN `+rollupsql.Served+` THEN spans ELSE 0 END served_spans, + CASE WHEN status='STATUS_CODE_ERROR' THEN spans ELSE 0 END error_spans,0 log_count FROM (`+spans+`) s`) + } + if logs != "" { + parts = append(parts, `SELECT batch_id,namespace,bucket,service,0 spans,0 served_spans,0 error_spans,logs log_count FROM (`+logs+`) l`) + } + if metrics != "" { + parts = append(parts, `SELECT DISTINCT batch_id,namespace,bucket,service,0 spans,0 served_spans,0 error_spans,0 log_count FROM (`+metrics+`) m WHERE signal='metrics'`) + } + return "SELECT batch_id,namespace,bucket,service," + serviceSums + " FROM (" + strings.Join(parts, " UNION ALL ") + ") p WHERE service<>'' GROUP BY batch_id,namespace,bucket,service" +} + +const serviceSums = "sum(spans)::BIGINT spans,sum(served_spans)::BIGINT served_spans,sum(error_spans)::BIGINT error_spans,sum(log_count)::BIGINT log_count" + +// Materialize only this pass's partials. The service counts reuse them without +// decoding the new files twice or searching retained tables for new batch IDs. +func insertBatchSummaries(sources map[string]string, exec func(string) error) error { + inputs := map[string]string{} + var temporary []string + for _, signal := range telemetry.Signals { + rows := sources[signal.Name] + if rows == "" { + continue + } + var name, partial string + switch signal.Name { + case "spans": + name, partial = "span_rollup", spanPartial(rows) + case "logs": + name, partial = "log_rollup", logPartial(rows) + case "metrics": + name, partial = "resource_rollup", resourcePartial(signal.Name, signal.Clock(), rows) + } + temp := "cache_new_" + name + if err := exec("CREATE TEMP TABLE " + temp + " AS " + partial); err != nil { + return err + } + temporary = append(temporary, temp) + inputs[signal.Name] = "SELECT * FROM " + temp + if err := exec("INSERT INTO read_" + name + " " + inputs[signal.Name]); err != nil { + return err + } + } + if len(inputs) == 0 { + return nil + } + if err := exec("INSERT INTO read_service_rollup " + servicePartial(inputs["spans"], inputs["logs"], inputs["metrics"])); err != nil { + return err + } + for _, table := range temporary { + if err := exec("DROP TABLE " + table); err != nil { + return err + } + } + return nil +} + +// mergeRollup is shared by snapshot reads and compaction. Its result has one +// row per logical key, independently of how the catalog partitions the input. +func mergeRollup(name, partials string) string { + src := " FROM (" + partials + ") p" + switch name { + case "service_rollup": + return "SELECT namespace,bucket,service," + serviceSums + src + " GROUP BY namespace,bucket,service" + case "log_rollup": + return "SELECT namespace,bucket,service,severity,sum(logs)::BIGINT logs" + src + " GROUP BY namespace,bucket,service,severity" + case "resource_rollup": + return "SELECT namespace,bucket,service,signal,resource,min(first_seen) first_seen,max(last_seen) last_seen" + src + " GROUP BY namespace,bucket,service,signal,resource" + case "span_rollup": + return `WITH partials AS NOT MATERIALIZED (` + partials + `), + totals AS (SELECT namespace,bucket,service,kind,status,sum(spans)::BIGINT spans,sum(duration_sum) duration_sum, + min(duration_min) duration_min,max(duration_max) duration_max FROM partials GROUP BY namespace,bucket,service,kind,status), + entries AS (SELECT namespace,bucket,service,kind,status,unnest(map_entries(hist)) e FROM partials), + bins AS (SELECT namespace,bucket,service,kind,status,e.key k,sum(e.value)::UBIGINT n FROM entries GROUP BY namespace,bucket,service,kind,status,k), + histograms AS (SELECT namespace,bucket,service,kind,status,map_from_entries(list(struct_pack(key := k,value := n) ORDER BY k)) hist + FROM bins GROUP BY namespace,bucket,service,kind,status) + SELECT totals.*,hist FROM totals JOIN histograms USING(namespace,bucket,service,kind,status)` + default: + panic("unknown additive rollup " + name) + } +} + +// batchSource reads only files carrying this signal and supplies their immutable IDs. +func (d *Duck) batchSource(signal string, batches []telemetry.BatchMetadata) string { + var selected []telemetry.BatchMetadata + for _, b := range batches { + if _, count := batchTime(b, signal); count > 0 { + selected = append(selected, b) + } + } + if len(selected) == 0 { + return "" + } + physical := strings.Replace(d.physicalSource(signal, selected), "SELECT ", "SELECT filename AS __pitot_filename,", 1) + return strings.Replace(cleanSource(signal, physical), "SELECT\n", "SELECT "+d.batchIDColumn(signal, "__pitot_filename")+" AS batch_id,\n", 1) +} + +// A minute summary needs every event in its boundary buckets. Clamp before +// converting to Unix nanoseconds, whose range is narrower than time.Time's. +func rollupMinuteWindow(w queryrows.Window) queryrows.Window { + nanos := func(t time.Time) int64 { + if t.Before(allTime.Start) { + return firstFiniteNanos + } + if t.After(allTime.End) { + return allTime.End.UnixNano() + } + return max(t.UnixNano(), firstFiniteNanos) + } + end := nanos(w.End) + hi := floorMinute(end) + if hi < end { + hi = nextMinute(hi) + } + return queryrows.Window{Start: time.Unix(0, floorMinute(nanos(w.Start))).UTC(), End: time.Unix(0, hi).UTC()} +} + +func (d *Duck) additiveSource(name string, batches []telemetry.BatchMetadata, markers map[string]bool, window queryrows.Window, now time.Time) string { + // Cached service/resource rows can combine signals. Include each active ID + // once if any contributing signal overlaps. Raw file lists are per signal. + var cached []string + raw := make(map[string][]telemetry.BatchMetadata) + for _, b := range batches { + for _, s := range telemetry.Signals { + if name == "span_rollup" && s.Name != "spans" || name == "log_rollup" && s.Name != "logs" { + continue + } + if !overlapping(b, s.Name, window) { + continue + } + if markers[b.ID] { + cached = append(cached, b.ID) + break + } + raw[s.Name] = append(raw[s.Name], b) + } + } + cachedRows := "SELECT * FROM read_" + name + " WHERE batch_id IN (" + idsSQL(cached) + ")" + if window != allTime { + cachedRows += " AND bucket>=" + timestampNSLiteral(window.Start) + " AND bucket<" + timestampNSLiteral(window.End) + } + parts := []string{cachedRows} + var spans, logs, metrics string + for _, s := range telemetry.Signals { + rows := d.batchSource(s.Name, raw[s.Name]) + if rows == "" { + continue + } + if window != allTime { + rows = "SELECT * FROM (" + rows + ") raw_rows WHERE " + windowPredicate(s.Clock(), window) + } + var partial string + switch { + case name == "resource_rollup": + partial = resourcePartial(s.Name, s.Clock(), rows) + case s.Name == "metrics": + metrics = "SELECT batch_id,namespace," + minuteBucketSQL("time") + " bucket,service,'metrics' signal FROM (" + rows + ") m WHERE namespace IS NOT NULL AND time IS NOT NULL" + case s.Name == "spans": + partial = spanPartial(rows) + spans = partial + case s.Name == "logs": + partial = logPartial(rows) + logs = partial + } + if name != "service_rollup" { + parts = append(parts, "("+partial+")") + } + } + if name == "service_rollup" && (spans != "" || logs != "" || metrics != "") { + parts = append(parts, servicePartial(spans, logs, metrics)) + } + partials := strings.Join(parts, " UNION ALL ") + var bounds []string + if cutoff, ok := d.cfg.RetentionCutoff(now); ok { + bounds = append(bounds, fmt.Sprintf("bucket>=make_timestamp_ns(%d)", floorMinute(cutoff))) + } + if d.cfg.IngestMaxFutureSkew > 0 { + bounds = append(bounds, fmt.Sprintf("bucket<=make_timestamp_ns(%d)", d.cfg.LatestEventTime(now).UnixNano())) + } + if len(bounds) > 0 { + partials = "SELECT * FROM (" + partials + ") retained WHERE " + strings.Join(bounds, " AND ") + } + return mergeRollup(name, partials) +} + +func usesAdditive(compiled compiledSnapshot) bool { + for _, name := range additiveRollups { + if _, ok := compiled.names[name]; ok { + return true + } + } + return false +} diff --git a/internal/engine/additive_rollup_test.go b/internal/engine/additive_rollup_test.go new file mode 100644 index 00000000..59d756f4 --- /dev/null +++ b/internal/engine/additive_rollup_test.go @@ -0,0 +1,384 @@ +package engine + +import ( + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "github.com/labstack/pitot/internal/engine/writegate" + "github.com/labstack/pitot/internal/queryrows" + "github.com/labstack/pitot/internal/telemetry" +) + +// Interpose only on the real catalog swap, after the synchronous fold or +// deferral decision. A read opened here remains pinned across publication. +type observingPublisher struct { + *Duck + observe func(context.Context, string, func(context.Context) error) error +} + +func (p observingPublisher) PublishParquetReplacement(ctx context.Context, output telemetry.BatchMetadata, inputs []string, swap func(context.Context) error) error { + return p.Duck.PublishParquetReplacement(ctx, output, inputs, func(ctx context.Context) error { return p.observe(ctx, output.ID, swap) }) +} + +func TestAdditiveRollupsAcrossCatalogSwap(t *testing.T) { + for _, busy := range []bool{false, true} { + t.Run(fmt.Sprintf("busy=%v", busy), func(t *testing.T) { + d, repo := newBatchCacheTest(t) + at := time.Now().UTC().Truncate(time.Minute).Add(-time.Hour) + const inputs = 8 + for i := range inputs { + b := rollupSnapshotBatch(fmt.Sprint("input-", i), at.Add(time.Duration(i)*time.Second), at.Add(time.Duration(i)*time.Second), 1) + b.Spans[0].StatusCode = "STATUS_CODE_ERROR" + b.Spans[0].DurationMS = []float64{1, 2, 4}[i%3] + b.Metrics[0].ServiceName = "metric-only" + if err := repo.Commit(t.Context(), b); err != nil { + t.Fatal(err) + } + if i == 3 { + if _, err := d.RefreshReadCaches(t.Context()); err != nil { + t.Fatal(err) + } + } + } + // One result per logical key. All files share the same projected identity. + // Bins 0, 8 and 16 represent 1, 2 and 4 ms, respectively. + const q = `SELECT (SELECT count(*) FROM span_rollup WHERE spans=8 AND duration_sum=17 AND duration_min=1 AND duration_max=4 AND hist=map([0,8,16],[3,3,2]::UBIGINT[])), + (SELECT count(*) FROM log_rollup WHERE logs=8), + (SELECT count(*) FROM resource_rollup WHERE epoch_ns(last_seen)-epoch_ns(first_seen)=7000000000), + (SELECT count(*) FROM service_rollup WHERE service='svc' AND spans=8 AND served_spans=8 AND error_spans=8 AND log_count=8), + (SELECT count(*) FROM service_rollup WHERE service='metric-only' AND spans=0 AND served_spans=0 AND error_spans=0 AND log_count=0)` + check := func(ctx context.Context) error { + var n [5]int + if err := d.QueryRowScan(ctx, []any{&n[0], &n[1], &n[2], &n[3], &n[4]}, q); err != nil { + return err + } + if n != [5]int{1, 1, 3, 1, 1} { + return fmt.Errorf("unexpected summary populations %v", n) + } + return nil + } + ctx := t.Context() + horizon, _, _ := repo.PublicationBounds() + completed, err := d.CompletedServiceRollupMinute(ctx) + if err != nil || !completed.Equal(time.Unix(0, horizon).UTC().Truncate(time.Minute)) { + t.Fatalf("completed service minute %v for publication horizon %d: %v", completed, horizon, err) + } + // The first half of the catalog is cached and the second half is raw. + if err := check(ctx); err != nil { + t.Fatal(err) + } + if _, err := d.RefreshReadCaches(ctx); err != nil { + t.Fatal(err) + } + if err := check(ctx); err != nil { + t.Fatal(err) + } + publisher := observingPublisher{d, func(ctx context.Context, id string, swap func(context.Context) error) error { + markers, err := batchMarkers(ctx, d.DB) + if err != nil { + return err + } + if markers[id] == busy { + return fmt.Errorf("replacement marker=%v before swap with busy=%v", markers[id], busy) + } + rows, err := d.QueryContext(ctx, q) + if err != nil { + return err + } + defer rows.Close() + if err := swap(ctx); err != nil { + return err + } + if !rows.Next() { + return fmt.Errorf("pinned read returned no result: %v", rows.Err()) + } + var n [5]int + if err := rows.Scan(&n[0], &n[1], &n[2], &n[3], &n[4]); err != nil { + return err + } + if n != [5]int{1, 1, 3, 1, 1} { + return fmt.Errorf("pinned read across swap: %v", n) + } + return check(ctx) + }} + func() { + if busy { + release := d.cacheGate.Lock(writegate.ReadCache) + defer release() + } + if n, err := repo.CompactParquet(ctx, publisher, inputs); err != nil || n != inputs { + t.Fatalf("compact %d: %v", n, err) + } + }() + if n, err := d.RefreshReadCaches(ctx); err != nil || n != 0 { + t.Fatalf("folded output rebuilt %d rows: %v", n, err) + } + if err := check(ctx); err != nil { + t.Fatal(err) + } + for _, name := range additiveRollups { + requireSnapshotCount(t, d, "SELECT count(DISTINCT batch_id) FROM read_"+name, 1) + } + }) + } +} + +func TestSpanRollupPredicatesReachCacheScans(t *testing.T) { + d, repo := newBatchCacheTest(t) + at := time.Now().UTC().Truncate(time.Minute).Add(-time.Hour) + for i := range 3 { + b := panelRollupKeyBatch(fmt.Sprint("batch-", i), at.Add(time.Duration(i)*time.Minute), 3, false) + b.Spans[0].Namespace = "other" + if err := repo.Commit(t.Context(), b); err != nil { + t.Fatal(err) + } + } + if _, err := d.RefreshReadCaches(t.Context()); err != nil { + t.Fatal(err) + } + tx, err := d.DB.BeginTx(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + defer tx.Rollback() + statement, err := d.bindSnapshot(t.Context(), tx, `SELECT * FROM span_rollup WHERE namespace=? AND service=? AND bucket>=?::TIMESTAMP_NS AND bucketcoalesce(r.spans,0) OR coalesce(e.logs,0)<>coalesce(r.log_count,0)`).Scan(&mismatches); err != nil || mismatches != 0 { +WHERE coalesce(e.spans,0)<>coalesce(r.spans,0) OR coalesce(e.logs,0)<>coalesce(r.log_count,0)`); err != nil || mismatches != 0 { t.Fatalf("raw/rollup bucket mismatches=%d err=%v", mismatches, err) } if n, err := d.refreshServiceRollup(ctx); err != nil || n != 0 { diff --git a/internal/engine/backlog_pressure_test.go b/internal/engine/backlog_pressure_test.go index 3e35e237..e9a40820 100644 --- a/internal/engine/backlog_pressure_test.go +++ b/internal/engine/backlog_pressure_test.go @@ -319,7 +319,7 @@ func TestBacklogPressureRecordsConcurrentStatementFailures(t *testing.T) { // Existing rollupOnce only labels the component, losing which of its two // expensive statements failed. Attribution must retain the native cause. func TestBacklogServiceFailuresIdentifyStatementAndPreserveCause(t *testing.T) { - for _, label := range []string{"service_rollup/delete", "service_rollup/insert"} { + for _, label := range []string{"endpoint_rollup/delete", "endpoint_rollup/insert"} { t.Run(label, func(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { @@ -332,16 +332,12 @@ func TestBacklogServiceFailuresIdentifyStatementAndPreserveCause(t *testing.T) { } mock.ExpectBegin() mock.ExpectExec("CREATE OR REPLACE TEMP TABLE service_pass_affected").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectQuery("SELECT epoch_ns").WillReturnRows(sqlmock.NewRows([]string{"lo", "hi"}).AddRow(0, 60_000_000_000)) - if label == "service_rollup/delete" { - mock.ExpectExec("DELETE FROM service_rollup").WillReturnError(cause) + mock.ExpectQuery("FROM service_pass_affected").WillReturnRows(sqlmock.NewRows([]string{"namespace", "bucket", "service"}).AddRow("ns", int64(0), "api")) + if label == "endpoint_rollup/delete" { + mock.ExpectExec("DELETE FROM endpoint_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("INSERT INTO span_rollup").WillReturnError(cause) + mock.ExpectExec("DELETE FROM endpoint_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO endpoint_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 8753b511..56199e3d 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 = 21 +const readCacheVersion = 22 const ( readCacheBatchLimit = 64 @@ -52,7 +52,16 @@ func CreateCacheTables(db *sql.DB) error { if err != nil { return err } - if version != readCacheVersion { + if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS rollup_schema_version (version INTEGER)`); err != nil { + return err + } + var rollupVersion int + if err := tx.QueryRow(`SELECT coalesce(max(version),0) FROM rollup_schema_version`).Scan(&rollupVersion); err != nil { + return err + } + if version != readCacheVersion || rollupVersion != rollup_schema_version { + // Enumerate physical tables first. Older caches used the public rollup + // names as tables. After their removal those names can only be views. rows, err := tx.Query(`SELECT table_name FROM duckdb_tables() WHERE database_name=current_database() AND schema_name='main' AND NOT temporary AND table_name NOT IN ('read_cache_version','anomaly_log')`) if err != nil { return err @@ -76,6 +85,17 @@ func CreateCacheTables(db *sql.DB) error { return err } } + for _, name := range additiveRollups { + if _, err := tx.Exec("DROP VIEW IF EXISTS " + name); err != nil { + return err + } + } + if _, err := tx.Exec(`CREATE TABLE rollup_schema_version (version INTEGER)`); err != nil { + return err + } + if _, err := tx.Exec(`INSERT INTO rollup_schema_version VALUES (?)`, rollup_schema_version); err != nil { + return err + } if _, err := tx.Exec(`DELETE FROM read_cache_version`); err != nil { return err } @@ -102,26 +122,6 @@ func CreateCacheTables(db *sql.DB) error { return err } } - if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS rollup_schema_version (version INTEGER)`); err != nil { - return err - } - var rollupVersion int - if err := tx.QueryRow(`SELECT coalesce(max(version),0) FROM rollup_schema_version`).Scan(&rollupVersion); err != nil { - return err - } - if rollupVersion != rollup_schema_version { - for _, stmt := range []string{`DROP TABLE service_rollup`, `DROP TABLE span_rollup`, `DROP TABLE log_rollup`, `DROP TABLE endpoint_rollup`, `DROP TABLE edge_rollup`, `DROP TABLE receiver_rollup`, `DROP TABLE resource_rollup`, `DROP TABLE receiver_entity_rollup`, createEdgeRollupTable, createServiceRollupTable, createSpanRollupTable, createLogRollupTable, createEndpointRollupTable, createReceiverRollupTable, createResourceRollupTable, createReceiverEntityRollupTable, - `DELETE FROM rollup_state WHERE cache_key = '` + serviceRollupStateKey + `'`, - `DELETE FROM rollup_state WHERE cache_key IN ('` + edgeRollupStateKey + `','` + edgeRollupSubCursorKey + `','` + edgeRollupSubWindowKey + `')`, - `DELETE FROM rollup_schema_version`} { - if _, err := tx.Exec(stmt); err != nil { - return err - } - } - if _, err := tx.Exec(`INSERT INTO rollup_schema_version VALUES (?)`, rollup_schema_version); err != nil { - return err - } - } if _, err := tx.Exec(createReceiverPointsView); err != nil { return err } @@ -413,46 +413,34 @@ func (d *Duck) cacheBatches(ctx context.Context, batches []telemetry.BatchMetada return err } if len(stale) > 0 { - for _, table := range []string{"read_resource_inventory", "read_resource_seconds", "read_metric_names", "read_trace_exemplars", "read_batches"} { + for _, table := range []string{"read_service_rollup", "read_resource_rollup", "read_span_rollup", "read_log_rollup", "read_resource_inventory", "read_resource_seconds", "read_metric_names", "read_trace_exemplars", "read_batches"} { if err := exec("DELETE FROM " + table + " WHERE batch_id IN (" + idsSQL(stale) + ")"); err != nil { return 0, err } } } // Each aggregation scans only the pass's new files. - source := func(signal string) string { - var selected []telemetry.BatchMetadata - for _, b := range batches { - _, count := batchTime(b, signal) - if count == 0 { - continue - } - selected = append(selected, b) - } - if len(selected) == 0 { - return "" - } - // One Parquet scan binds the pass's files. The virtual filename column - // identifies each contribution without a separate UNION branch per file. - physical := strings.Replace(d.physicalSource(signal, selected), "SELECT ", "SELECT filename AS __pitot_filename,", 1) - return strings.Replace(cleanSource(signal, physical), "SELECT\n", "SELECT "+d.batchIDColumn(signal, "__pitot_filename")+" AS batch_id,\n", 1) - } sources := make(map[string]string, len(telemetry.Signals)) for _, s := range telemetry.Signals { - rows := source(s.Name) + rows := d.batchSource(s.Name, batches) sources[s.Name] = rows if rows != "" { clock := s.Clock() + if s.Name != "metrics" { + if err := exec("INSERT INTO read_resource_rollup " + resourcePartial(s.Name, clock, rows)); err != nil { + return 0, err + } + } // Materialize only this pass's resource-seconds once. Inventory can // fold their exact extrema without decoding every raw point again. // The temporary table avoids scanning retained cache contributions. - if err := exec(`CREATE OR REPLACE TEMP TABLE cache_new_resource_seconds AS SELECT batch_id,` + sqlLiteral(s.Name) + ` AS signal,namespace,service,resource,date_trunc('second',` + clock + `::TIMESTAMP_NS) AS bucket,min(` + clock + `) AS first_seen,max(` + clock + `) AS last_seen FROM (` + rows + `) GROUP BY ALL`); err != nil { + if err := exec(`CREATE OR REPLACE TEMP TABLE cache_new_resource_seconds AS SELECT batch_id,` + sqlLiteral(s.Name) + ` AS signal,namespace,service,resource,date_trunc('second',` + clock + `::TIMESTAMP_NS) AS bucket,min(` + clock + `) AS first_seen,max(` + clock + `) AS last_seen FROM (` + rows + `) GROUP BY batch_id,namespace,service,resource,bucket`); err != nil { return 0, err } if err := exec(`INSERT INTO read_resource_seconds SELECT * FROM cache_new_resource_seconds`); err != nil { return 0, err } - if err := exec(`INSERT INTO read_resource_inventory SELECT batch_id,signal,namespace,service,resource,min(first_seen),max(last_seen) FROM cache_new_resource_seconds GROUP BY ALL`); err != nil { + if err := exec(`INSERT INTO read_resource_inventory SELECT batch_id,signal,namespace,service,resource,min(first_seen),max(last_seen) FROM cache_new_resource_seconds GROUP BY batch_id,signal,namespace,service,resource`); err != nil { return 0, err } if err := exec(`DROP TABLE cache_new_resource_seconds`); err != nil { @@ -482,6 +470,9 @@ func (d *Duck) cacheBatches(ctx context.Context, batches []telemetry.BatchMetada } } if len(batches) > 0 { + if err := insertBatchSummaries(sources, exec); err != nil { + return 0, err + } var values []string for _, b := range batches { values = append(values, "("+sqlLiteral(b.ID)+")") @@ -495,8 +486,21 @@ func (d *Duck) cacheBatches(ctx context.Context, batches []telemetry.BatchMetada } return written, nil } + +// The catalog uses the int64 endpoints as open bounds. DuckDB reserves +// those values, so spell infinity explicitly when constructing SQL. +func timestampNSLiteral(t time.Time) string { + switch { + case t.Equal(allTime.End): + return "'infinity'::TIMESTAMP_NS" + case t.Equal(allTime.Start): + return "'-infinity'::TIMESTAMP_NS" + default: + return "make_timestamp_ns(" + fmt.Sprint(t.UnixNano()) + ")" + } +} func timeLiteral(t time.Time) string { - return "make_timestamp_ns(" + fmt.Sprint(t.UnixNano()) + ")::TIMESTAMPTZ_NS" + return timestampNSLiteral(t) + "::TIMESTAMPTZ_NS" } func windowPredicate(column string, w queryrows.Window) string { return column + ">=" + timeLiteral(w.Start) + " AND " + column + "<" + timeLiteral(w.End) @@ -513,11 +517,25 @@ func scopePredicate(w queryrows.Window) string { } return scope } -func (d *Duck) aggregateSources(ctx context.Context, db snapshotSQL, batches []telemetry.BatchMetadata, w queryrows.Window, inventory, traces bool, sources map[string]string) error { +func (d *Duck) aggregateSources(ctx context.Context, db snapshotSQL, batches []telemetry.BatchMetadata, w queryrows.Window, inventory, traces bool, compiled compiledSnapshot, sources map[string]string) error { markers, err := batchMarkers(ctx, db) if err != nil { return err } + if usesAdditive(compiled) { + columns, scoped := queryrows.ReadWindowColumns(ctx) + now := time.Now() + for _, name := range additiveRollups { + if _, used := compiled.names[name]; !used { + continue + } + window := allTime + if w != allTime && (!scoped || windowBoundsColumn(columns, name, "bucket")) { + window = rollupMinuteWindow(w) + } + sources[name] = d.additiveSource(name, batches, markers, window, now) + } + } if inventory { window, ok := queryrows.ReadInventoryWindow(ctx) if !ok { @@ -651,6 +669,12 @@ func (d *Duck) transferBatchCacheLocked(ctx context.Context, output string, inpu return nil } where := " WHERE batch_id IN (" + idsSQL(inputs) + ")" + for _, name := range additiveRollups { + merged := mergeRollup(name, "SELECT * FROM read_"+name+where) + if _, err := tx.ExecContext(ctx, "INSERT INTO read_"+name+" SELECT "+sqlLiteral(output)+",* FROM ("+merged+") folded"); err != nil { + return err + } + } for _, stmt := range []string{ `INSERT INTO read_resource_inventory SELECT ` + sqlLiteral(output) + `,signal,namespace,service,resource,min(first_seen),max(last_seen) FROM read_resource_inventory` + where + ` GROUP BY signal,namespace,service,resource`, `INSERT INTO read_resource_seconds SELECT ` + sqlLiteral(output) + `,signal,namespace,service,resource,bucket,min(first_seen),max(last_seen) FROM read_resource_seconds` + where + ` GROUP BY signal,namespace,service,resource,bucket`, @@ -658,7 +682,6 @@ func (d *Duck) transferBatchCacheLocked(ctx context.Context, output string, inpu // The inputs' rows hold every span the output's partitions keep, so // ranking their union again derives the output's rows exactly. `CREATE OR REPLACE TEMP TABLE cache_transfer_exemplar_spans AS SELECT row_number() OVER () AS id,` + sqlLiteral(output) + ` AS batch_id,namespace,service,minute,trace_id,start_unix_nano,duration,has_error FROM read_trace_exemplars` + where, - `INSERT INTO read_batches(batch_id) VALUES (` + sqlLiteral(output) + `)`, } { if _, err := tx.ExecContext(ctx, stmt); err != nil { return err @@ -670,6 +693,9 @@ func (d *Duck) transferBatchCacheLocked(ctx context.Context, output string, inpu if _, err := tx.ExecContext(ctx, `DROP TABLE cache_transfer_exemplar_spans`); err != nil { return err } + if _, err := tx.ExecContext(ctx, "INSERT INTO read_batches(batch_id) VALUES (?)", output); err != nil { + return err + } return tx.Commit() } diff --git a/internal/engine/committed_watermark_test.go b/internal/engine/committed_watermark_test.go index ce6e8585..90113119 100644 --- a/internal/engine/committed_watermark_test.go +++ b/internal/engine/committed_watermark_test.go @@ -69,7 +69,7 @@ func TestCommittedWatermarkPublishesOnlySuccessfulRefresh(t *testing.T) { t.Fatal(err) } commitWatermarkSpan(t, repo, "second") - if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE span_rollup ADD COLUMN incompatible BOOLEAN`); err != nil { + if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE endpoint_rollup ADD COLUMN incompatible BOOLEAN`); err != nil { t.Fatal(err) } if _, err := d.refreshServiceRollup(t.Context()); err == nil { @@ -78,7 +78,7 @@ func TestCommittedWatermarkPublishesOnlySuccessfulRefresh(t *testing.T) { if got := assertCommittedWatermarkParity(t, d); !got.Equal(before) { t.Fatalf("failed refresh changed watermark: %v -> %v", before, got) } - if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE span_rollup DROP COLUMN incompatible`); err != nil { + if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE endpoint_rollup DROP COLUMN incompatible`); err != nil { t.Fatal(err) } if _, err := d.refreshServiceRollup(t.Context()); err != nil { @@ -148,7 +148,7 @@ func TestCommittedWatermarkInitializesSkipToLatest(t *testing.T) { t.Fatalf("skip horizon=%v want=%d", got, horizon) } var rows int - if err := d.DB.QueryRowContext(t.Context(), `SELECT count(*) FROM span_rollup`).Scan(&rows); err != nil || rows != 0 { + if err := d.DB.QueryRowContext(t.Context(), `SELECT count(*) FROM read_span_rollup`).Scan(&rows); err != nil || rows != 0 { t.Fatalf("skip unexpectedly aggregated rows=%d: %v", rows, err) } } @@ -202,7 +202,7 @@ func TestCommittedWatermarkConcurrentReadersAndRefreshes(t *testing.T) { func commitWatermarkSpan(t *testing.T, repo *telemetrystore.Repository, id string) { t.Helper() at := time.Now().UTC().Truncate(time.Minute).Add(-time.Hour) - if err := repo.Commit(t.Context(), telemetrystore.Batch{ID: id, Spans: []telemetry.Span{{Namespace: "ns", ServiceName: "svc", TraceID: id, SpanID: id, StartUnixNanos: at.UnixNano(), EndUnixNanos: at.Add(time.Millisecond).UnixNano(), DurationMS: 1}}}); err != nil { + if err := repo.Commit(t.Context(), telemetrystore.Batch{ID: id, Spans: []telemetry.Span{{Namespace: "ns", ServiceName: "svc", TraceID: id, SpanID: id, StartUnixNanos: at.UnixNano(), EndUnixNanos: at.Add(time.Millisecond).UnixNano(), DurationMS: 1, Attributes: map[string]any{"http.route": "/route"}}}}); err != nil { t.Fatal(err) } } diff --git a/internal/engine/dashboard_rollup.go b/internal/engine/dashboard_rollup.go index b3cb23d9..5a7d41f0 100644 --- a/internal/engine/dashboard_rollup.go +++ b/internal/engine/dashboard_rollup.go @@ -2,22 +2,13 @@ package engine import ( "context" - "database/sql" "fmt" - "strings" "time" + "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/rollupsql" ) -func logRollupInsertSQL(keys string) string { - return `INSERT INTO log_rollup - SELECT l.namespace,date_trunc('minute',l.time::TIMESTAMP_NS),l.service,coalesce(l.severity,''),count(*) - FROM logs l WHERE ` + keys + ` - AND l.time >= ?::TIMESTAMP_NS::TIMESTAMPTZ_NS AND l.time < ?::TIMESTAMP_NS::TIMESTAMPTZ_NS - GROUP BY ALL` -} - // Read the canonical dedicated route column, including semconv conversion and // spill semantics. Its Parquet predicate also skips files without routes. // Rank route populations before building histograms, then fold the rest before @@ -27,7 +18,7 @@ func logRollupInsertSQL(keys string) string { func endpointRollupInsertSQL(keys string) string { return fmt.Sprintf(`INSERT INTO endpoint_rollup WITH eligible AS MATERIALIZED ( - SELECT s.namespace,date_trunc('minute',s.start_time::TIMESTAMP_NS) bucket,s.service, + SELECT s.namespace,%s bucket,s.service, coalesce(s.kind,'') kind,coalesce(s.status,'') status, s._a_http_route route,s.duration_ms FROM spans s WHERE %s @@ -40,39 +31,66 @@ func endpointRollupInsertSQL(keys string) string { 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(%s) - FROM folded GROUP BY namespace,bucket,service,kind,status,route,overflow`, keys, endpointRouteLimit, endpointRouteLimit, rollupsql.Bin("duration_ms")) + FROM folded GROUP BY namespace,bucket,service,kind,status,route,overflow`, minuteBucketSQL("s.start_time"), keys, endpointRouteLimit, endpointRouteLimit, rollupsql.Bin("duration_ms")) } -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"} { - clock := "m.time" - if signal == "spans" { - clock = "m.start_time" - } - 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 { - 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"))) +// The key cursor is ordered by bucket. Bind each chunk to the same pinned +// catalog, pruned to the first and last minute in that chunk. +func refreshDashboardRollups(ctx context.Context, tx rollupSQL, bind func(queryrows.Window) error) (int64, error) { + var affected int64 + for _, family := range []string{"endpoint", "receiver"} { + err := forAffectedKeys(ctx, tx, serviceRollupAffectedKeysSQL, []any{family}, + "", serviceRollupAffectedKeyExpr, func(in string, args []any) error { + key := func(bucket string) string { + return "struct_pack(namespace := namespace,bucket := " + bucket + ",service := service)" + in + } + keys := key("bucket") + lo := time.Unix(0, args[1].(int64)).UTC() + hi := time.Unix(0, args[len(args)-2].(int64)).UTC().Truncate(time.Minute).Add(time.Minute) + // The driver cannot bind a Go timestamp at DuckDB's finite + // limits. Pass UTC nanosecond text through the existing + // TIMESTAMP_NS parameters, including the terminal open bound. + upper := hi.Format(time.RFC3339Nano) + if hi.After(allTime.End) { + upper = "infinity" + hi = allTime.End + } + if err := bind(queryrows.Window{Start: lo, End: hi}); err != nil { + return err } - for _, statement := range statements { - if _, err := tx.ExecContext(ctx, statement, append(args, lo, hi)...); err != nil { + type target struct { + table string + insert string + } + var targets []target + if family == "endpoint" { + targets = []target{{"endpoint_rollup", endpointRollupInsertSQL(key(minuteBucketSQL("s.start_time")))}} + } else { + targets = []target{ + {"receiver_rollup", receiverRollupInsertSQL(key(minuteBucketSQL("m.time")))}, + {"receiver_entity_rollup", receiverEntityRollupInsertSQL(keys)}, + } + } + bounds := append(args, lo.Format(time.RFC3339Nano), upper) + for _, t := range targets { + if _, err := tx.ExecContext(ctx, "DELETE FROM "+t.table+" WHERE "+keys+" AND bucket>=?::TIMESTAMP_NS AND bucket ? - AND ingested_unix_nano <= ? - AND start_time IS NOT NULL - AND service IS NOT NULL - UNION - SELECT DISTINCT namespace, date_trunc('minute', time::TIMESTAMP_NS) AS bucket, service - FROM logs - WHERE ingested_unix_nano > ? - AND ingested_unix_nano <= ? - AND time IS NOT NULL - AND service IS NOT NULL - UNION - SELECT DISTINCT namespace, date_trunc('minute', time::TIMESTAMP_NS) AS bucket, service - FROM metrics - WHERE ingested_unix_nano > ? - AND ingested_unix_nano <= ? - AND time IS NOT NULL - AND service IS NOT NULL;` - -const serviceRollupDeleteSQL = ` -DELETE FROM service_rollup -WHERE bucket >= ?::TIMESTAMP_NS - AND bucket < ?::TIMESTAMP_NS - AND EXISTS ( - SELECT 1 FROM service_pass_affected a - WHERE a.namespace = service_rollup.namespace - AND a.bucket = service_rollup.bucket - AND a.service = service_rollup.service -);` - -// 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 { - bounds := append(args, lo, hi) - if _, err := tx.ExecContext(ctx, spanRollupInsertSQL(keys), bounds...); err != nil { - return err - } - logKeys := strings.NewReplacer("s.", "l.", "start_time", "time").Replace(keys) - _, err := tx.ExecContext(ctx, logRollupInsertSQL(logKeys), bounds...) - return err - }) -} - -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)` + SELECT DISTINCT namespace, ` + minuteBucketSQL("start_time") + ` AS bucket, service,'endpoint' family + FROM spans WHERE ingested_unix_nano > ? AND ingested_unix_nano <= ? + AND _a_http_route<>'' AND start_time IS NOT NULL AND namespace IS NOT NULL AND service IS NOT NULL + UNION ALL + SELECT DISTINCT namespace,` + minuteBucketSQL("time") + ` bucket,service,'receiver' family + FROM metrics WHERE ingested_unix_nano > ? AND ingested_unix_nano <= ? + AND name IN (` + receiverNames + `) AND time IS NOT NULL AND namespace IS NOT NULL AND service IS NOT NULL` // rollupSQL is a rollup pass's transaction, or a test's database. type rollupSQL interface { @@ -1937,29 +1858,9 @@ func forAffectedKeys(ctx context.Context, tx rollupSQL, query string, queryArgs return nil } -// serviceRollupAffectedKeysSQL lists the distinct affected service-minutes, and -// serviceRollupAffectedKeyExpr is the constant each scan probes against. Both -// are shared by the span, log and metric aggregates so every signal is filtered -// to the same keys. -const serviceRollupAffectedKeysSQL = `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` - +const serviceRollupAffectedKeysSQL = `SELECT namespace,epoch_ns(bucket),service FROM service_pass_affected WHERE family=? ORDER BY bucket,namespace,service` const serviceRollupAffectedKeyExpr = `struct_pack(namespace := ?::VARCHAR, bucket := make_timestamp_ns(?::BIGINT), service := ?::VARCHAR)` -// 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 { - return `INSERT INTO span_rollup - 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(` + 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, '')` -} - // edgeArrivalGap bounds recent-arrival repair behind the completed ingest // watermark. Older relationships are not guaranteed to be repaired. const edgeArrivalGap = 5 * time.Minute @@ -2377,13 +2278,17 @@ func (d *Duck) retirementWaiting(pin telemetry.SnapshotPin) bool { var allTime = queryrows.Window{Start: time.Unix(0, math.MinInt64).UTC(), End: time.Unix(0, math.MaxInt64).UTC()} // unboundTelemetry is a cheap filter before parsing a statement that carries -// no read window: only text naming resource_inventory can reference it, and -// only text naming a signal can need binding to the captured catalog. +// no read window. Signal and additive summary reads both need the catalog. func (d *Duck) unboundTelemetry(query string) bool { lower := strings.ToLower(query) if strings.Contains(lower, "resource_inventory") { return true } + for _, name := range additiveRollups { + if strings.Contains(lower, name) { + return d.repository != nil && d.repository.Parquet != nil + } + } for _, s := range telemetry.Signals { if strings.Contains(lower, s.Name) { return d.repository != nil && d.repository.Parquet != nil @@ -2449,13 +2354,8 @@ func (d *Duck) QueryContext(ctx context.Context, query string, args ...any) (que if compileErr != nil { return nil, compileErr } - for _, s := range telemetry.Signals { - _, raw := compiled.names["telemetry."+s.Name] - _, clean := compiled.names[s.Name] - if raw || clean { - window, windowed = allTime, true - break - } + if len(compiled.names) > 0 { + window, windowed = allTime, true } } if windowed { @@ -2644,9 +2544,9 @@ func (d *Duck) PublishParquet(ctx context.Context, publish func(context.Context) // ---- Queries for API ---- -// RollupWatermark is the committed ingest horizon shared by service_rollup and -// span_rollup. This standalone preflight precedes the panel's data snapshot; -// snapshot-bound coverage checks read persisted state in their own transaction. +// RollupWatermark reports the analytical endpoint/receiver ingest horizon. +// Panels use it for preflight. Snapshot-bound coverage reads persisted state +// in the query transaction. func (d *Duck) RollupWatermark(ctx context.Context) (time.Time, error) { if err := ctx.Err(); err != nil { return time.Time{}, err @@ -2659,16 +2559,17 @@ func (d *Duck) RollupWatermark(ctx context.Context) (time.Time, error) { } // CompletedServiceRollupMinute is the exclusive end of detector input. The -// minute containing the ingest watermark may still be incomplete. +// additive summaries include all published files, even before either worker runs. +// Stop at the publication horizon so an in-flight earlier ingest stays incomplete. func (d *Duck) CompletedServiceRollupMinute(ctx context.Context) (time.Time, error) { - var stamp int64 - if err := d.QueryRowScan(ctx, []any{&stamp}, `SELECT coalesce((SELECT last_ingested_unix_nano FROM rollup_state WHERE cache_key=?),0)`, serviceRollupStateKey); err != nil { + if err := ctx.Err(); err != nil { return time.Time{}, err } - if stamp == 0 { + horizon, published, _ := d.publicationBounds() + if published == 0 { return time.Time{}, nil } - return time.Unix(0, stamp).UTC().Truncate(time.Minute), nil + return time.Unix(0, horizon).UTC().Truncate(time.Minute), nil } // WithReadTransaction keeps derived annotation rows and completeness flags in diff --git a/internal/engine/duck_test.go b/internal/engine/duck_test.go index 0cbbb415..fe3e5df0 100644 --- a/internal/engine/duck_test.go +++ b/internal/engine/duck_test.go @@ -80,10 +80,10 @@ func TestNewDuckUsesUTCForEveryConnection(t *testing.T) { t.Fatalf("roll up timezone fixture: %v", err) } var spans int64 - if err := d.DB.QueryRowContext(ctx, ` + if err := d.QueryRowScan(ctx, []any{&spans}, ` SELECT COALESCE(SUM(spans), 0)::BIGINT FROM service_rollup -WHERE bucket >= ? AND bucket < ?`, eventTime.Add(-time.Minute), eventTime.Add(time.Minute)).Scan(&spans); err != nil { +WHERE bucket >= ? AND bucket < ?`, eventTime.Add(-time.Minute), eventTime.Add(time.Minute)); err != nil { t.Fatalf("query UTC rollup window: %v", err) } if spans != 1 { @@ -316,27 +316,10 @@ func TestRollupAdmissionDoesNotCancelAdmittedWork(t *testing.T) { WillReturnRows(sqlmock.NewRows([]string{"watermark"}).AddRow(100)) mock.ExpectBegin() mock.ExpectExec("CREATE OR REPLACE TEMP TABLE service_pass_affected").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectQuery("SELECT epoch_ns").WillReturnRows(sqlmock.NewRows([]string{"lo", "hi"}).AddRow(0, 60_000_000_000)) - mock.ExpectExec("DELETE FROM service_rollup").WillDelayFor(20 * time.Millisecond).WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DELETE FROM span_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DELETE FROM log_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DELETE FROM endpoint_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - 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.ExpectQuery("FROM service_pass_affected").WillReturnRows(sqlmock.NewRows([]string{"namespace", "bucket", "service"}).AddRow("ns", int64(0), "api")) - mock.ExpectExec("INSERT INTO span_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 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.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("DELETE FROM endpoint_rollup").WillDelayFor(20 * time.Millisecond).WillReturnResult(sqlmock.NewResult(0, 0)) + mock.ExpectExec("INSERT INTO endpoint_rollup").WillReturnResult(sqlmock.NewResult(0, 1)) + mock.ExpectQuery("FROM service_pass_affected").WillReturnRows(sqlmock.NewRows([]string{"namespace", "bucket", "service"})) 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() @@ -365,12 +348,8 @@ func TestRepositoryPublicationDoesNotWaitForReadersOrDuckDBWrites(t *testing.T) if err := commitRestoredFixture(repository, context.Background(), telemetrystore.Batch{ID: "expired", Spans: []telemetry.Span{{TraceID: "trace", IngestedAt: 1}}}); err != nil { t.Fatal(err) } - mock.ExpectExec("DELETE FROM service_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DELETE FROM span_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) - mock.ExpectExec("DELETE FROM log_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("DELETE FROM endpoint_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) 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("DELETE FROM edge_rollup").WillReturnResult(sqlmock.NewResult(0, 0)) mock.ExpectExec("CHECKPOINT").WillReturnResult(sqlmock.NewResult(0, 0)) @@ -472,12 +451,8 @@ func TestCheckpointTracksConsecutiveFailures(t *testing.T) { func TestRollupPruningHonorsPastAndFutureBoundsIndependently(t *testing.T) { tables := []struct{ name, dimensions string }{ - {"service_rollup", ", 'svc' AS service"}, - {"span_rollup", ", 'svc' AS service, 'server' AS kind, 'ok' AS status"}, - {"log_rollup", ", 'svc' AS service, 'info' AS severity"}, {"endpoint_rollup", ", 'svc' AS service, 'server' AS kind, 'ok' AS status, '/' AS route, false AS overflow"}, {"receiver_rollup", ""}, - {"resource_rollup", ""}, {"receiver_entity_rollup", ""}, {"edge_rollup", ", 'client' AS caller, 'svc' AS callee"}, } @@ -542,9 +517,9 @@ func TestRetentionFailureDegradesMaintenance(t *testing.T) { t.Fatal(err) } defer db.Close() - for _, table := range []string{"service_rollup", "span_rollup", "log_rollup", "endpoint_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup", "edge_rollup"} { + for _, table := range []string{"endpoint_rollup", "receiver_rollup", "receiver_entity_rollup", "edge_rollup"} { e := mock.ExpectExec("DELETE FROM " + table) - if table == "service_rollup" { + if table == "endpoint_rollup" { e.WillReturnError(errors.New("injected retention failure")) } else { e.WillReturnResult(sqlmock.NewResult(0, 0)) @@ -584,7 +559,7 @@ func TestMaintenanceRecoversCompactionBeforeRetention(t *testing.T) { defer repository.Close() db := openTestDuck(t) defer db.Close() - for _, table := range []string{"service_rollup", "span_rollup", "log_rollup", "endpoint_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup", "edge_rollup"} { + for _, table := range []string{"endpoint_rollup", "receiver_rollup", "receiver_entity_rollup", "edge_rollup"} { if _, err := db.Exec("CREATE TABLE " + table + " (bucket TIMESTAMP)"); err != nil { t.Fatal(err) } diff --git a/internal/engine/edge_parent_plan_test.go b/internal/engine/edge_parent_plan_test.go index c0f335e5..6d858579 100644 --- a/internal/engine/edge_parent_plan_test.go +++ b/internal/engine/edge_parent_plan_test.go @@ -261,8 +261,8 @@ func TestOtherRollupJoinsKeepHistoryOffHashBuildSide(t *testing.T) { t.Fatal(err) } requireRawScansNotHashed(t, plan(edgeRollupInsertSQL, lo, hi)) - requireRawScansNotHashed(t, plan(spanRollupInsertSQL("true"), lo, hi)) - requireRawScansNotHashed(t, plan(logRollupInsertSQL("true"), lo, hi)) + requireRawScansNotHashed(t, plan(spanPartial("SELECT 'batch' batch_id,* FROM spans"))) + requireRawScansNotHashed(t, plan(logPartial("SELECT 'batch' batch_id,* FROM logs"))) }) } } diff --git a/internal/engine/file_snapshot.go b/internal/engine/file_snapshot.go index d2a8d927..6ec1f7df 100644 --- a/internal/engine/file_snapshot.go +++ b/internal/engine/file_snapshot.go @@ -18,7 +18,7 @@ import ( ) // summaryRelations are the rollup summary tables a snapshot read can name. -var summaryRelations = []string{"receiver_rollup", "receiver_points", "resource_rollup", "receiver_entity_rollup"} +var summaryRelations = []string{"receiver_rollup", "receiver_points", "endpoint_rollup", "receiver_entity_rollup"} type snapshotSQL interface { QueryRowContext(context.Context, string, ...any) *sql.Row @@ -34,17 +34,12 @@ func overlapping(b telemetry.BatchMetadata, signal string, w queryrows.Window) b return count > 0 && (!bounds.Known || bounds.MaxNanos >= w.Start.UnixNano() && bounds.MinNanos < w.End.UnixNano()) } -// signalWindowBounded reports whether a windowed column from a trusted SQL -// panel bounds this signal's own event-time clock, so that pruning files to the -// read window is sound. A bare column must equal the clock; a qualified column -// must name the signal's own relation (alias qualifiers we cannot resolve stay -// unbounded, which binds every file — correct, if slower). Columns come only -// from the validated macro expansion, never from unvalidated statement text. -func signalWindowBounded(columns []string, s *telemetry.Signal) bool { - clock := s.Clock() +// windowBoundsColumn recognizes a trusted panel's window on a raw signal clock +// or a rollup bucket. Unresolved qualifiers keep the full catalog bound. +func windowBoundsColumn(columns []string, relation, clock string) bool { for _, column := range columns { if dot := strings.LastIndexByte(column, '.'); dot >= 0 { - if column[dot+1:] == clock && strings.EqualFold(column[:dot], s.Name) { + if column[dot+1:] == clock && strings.EqualFold(column[:dot], relation) { return true } continue @@ -147,6 +142,12 @@ func (d *Duck) bindSnapshot(ctx context.Context, db snapshotSQL, query string, w if err != nil { return "", err } + if usesAdditive(compiled) { + horizon, published, _ := d.publicationBounds() + if published != 0 { + queryrows.RecordCoverage(ctx, time.Unix(0, horizon)) + } + } batches := d.repository.Parquet.BatchMetadata() sources := map[string]string{} summaries := false @@ -185,7 +186,7 @@ func (d *Duck) bindSnapshot(ctx context.Context, db snapshotSQL, query string, w // on another column (or joins this signal unwindowed), pruning by the // clock would drop rows the statement keeps, so bind every captured file. selectWindow := w - if scopedColumns && !signalWindowBounded(windowColumns, s) { + if scopedColumns && !windowBoundsColumn(windowColumns, signal, s.Clock()) { selectWindow = allTime } selected := []telemetry.BatchMetadata{} @@ -212,8 +213,8 @@ func (d *Duck) bindSnapshot(ctx context.Context, db snapshotSQL, query string, w _, inventory := compiled.names["resource_inventory"] _, traces := compiled.names["trace_exemplars"] traces = traces && w.Kind != queryrows.RawRead - if traces || inventory { - if err := d.aggregateSources(ctx, db, batches, w, inventory, traces, sources); err != nil { + if traces || inventory || usesAdditive(compiled) { + if err := d.aggregateSources(ctx, db, batches, w, inventory, traces, compiled, sources); err != nil { return "", err } } @@ -434,6 +435,7 @@ func (d *Duck) compileSnapshot(ctx context.Context, db snapshotSQL, query string d.snapshotMisses.Add(1) aliases := map[string]string{} names := append([]string{"trace_exemplars", "resource_inventory"}, summaryRelations...) + names = append(names, additiveRollups...) for _, s := range telemetry.Signals { names = append(names, "telemetry."+s.Name, s.Name) } @@ -467,7 +469,7 @@ func bindCompiledSnapshot(compiled compiledSnapshot, sources map[string]string) return "", fmt.Errorf("missing snapshot relation %s", name) } materialization := " AS (" - if name == "trace_exemplars" || slices.Contains(summaryRelations, name) { + if name == "trace_exemplars" || slices.Contains(summaryRelations, name) || slices.Contains(additiveRollups, name) { // These sources can have several consumers. Inline them so their // time/key predicates reach scans instead of copying every retained // exemplar or receiver payload into a temporary relation. diff --git a/internal/engine/file_snapshot_test.go b/internal/engine/file_snapshot_test.go index f85fd4d8..4d2bc213 100644 --- a/internal/engine/file_snapshot_test.go +++ b/internal/engine/file_snapshot_test.go @@ -414,7 +414,7 @@ func TestReadCacheSemanticVersionRebuildsAllContributions(t *testing.T) { t.Fatal(err) } for _, stmt := range []string{`UPDATE read_trace_exemplars SET start_unix_nano=0`, `UPDATE read_resource_inventory SET first_seen=make_timestamp_ns(0)::TIMESTAMPTZ_NS`, `UPDATE read_cache_version SET version=5`, `INSERT INTO read_edge_buckets VALUES ('ns',now(),10)`, `INSERT INTO rollup_state VALUES ('edge_rollup_v2_substart',1,now()),('edge_rollup_v2_subwindow_end',2,now())`, `CREATE TABLE read_endpoints (value INTEGER)`, `CREATE TABLE read_logs (value INTEGER)`, `CREATE TABLE read_obsolete (value INTEGER)`, - `INSERT INTO service_rollup (namespace,bucket,service,spans) VALUES ('ns',now(),'svc',1)`, `INSERT INTO edge_rollup (namespace,bucket,caller,callee,calls) VALUES ('ns',now(),'a','b',1)`, + `INSERT INTO read_service_rollup (batch_id,namespace,bucket,service,spans) VALUES ('semantic','ns',now(),'svc',1)`, `INSERT INTO edge_rollup (namespace,bucket,caller,callee,calls) VALUES ('ns',now(),'a','b',1)`, `INSERT INTO version_rollup VALUES ('ns','svc','v1',now(),now())`, `INSERT INTO version_rollup_batches VALUES ('semantic',1)`, `INSERT INTO anomaly_log VALUES ('ns','svc','latency',now(),now(),'slow','bad')`, `INSERT INTO rollup_state VALUES ('service_rollup_v3',1,now())`} { if _, err := d.DB.Exec(stmt); err != nil { @@ -425,7 +425,7 @@ func TestReadCacheSemanticVersionRebuildsAllContributions(t *testing.T) { t.Fatal(err) } for _, table := range []string{"read_batches", "read_resource_inventory", "read_trace_exemplars", "read_edge_buckets", - "service_rollup", "edge_rollup", "rollup_state", "version_rollup", "version_rollup_batches"} { + "read_service_rollup", "edge_rollup", "rollup_state", "version_rollup", "version_rollup_batches"} { var count int if err := d.DB.QueryRow("SELECT count(*) FROM " + table).Scan(&count); err != nil || count != 0 { t.Fatalf("%s survived semantic change: %d %v", table, count, err) @@ -988,7 +988,7 @@ func TestReadCacheBudgetsAllSignalsAndReportsInventoryWork(t *testing.T) { t.Fatal(err) } markers, err := batchMarkers(t.Context(), d.DB) - if err != nil || len(markers) != 1 || !markers["log-only"] || written != 2 { + if err != nil || len(markers) != 1 || !markers["log-only"] || written != 4 { t.Fatalf("all-signal budget/work: %v written=%d err=%v", markers, written, err) } if got := metricFamily(t, "pitot_read_cache_pending_batches").Metric[0].GetGauge().GetValue(); got != 3 { @@ -1003,7 +1003,7 @@ func TestReadCacheBudgetsAllSignalsAndReportsInventoryWork(t *testing.T) { } // The oldest file left leads, beside the oversized newer one. markers, err = batchMarkers(t.Context(), d.DB) - if err != nil || len(markers) != 3 || written != 8 { + if err != nil || len(markers) != 3 || written != 14 { t.Fatalf("oversized mixed batch: %v written=%d err=%v", markers, written, err) } } diff --git a/internal/engine/metric_rollup_memory_test.go b/internal/engine/metric_rollup_memory_test.go index 5edf7905..d3facc56 100644 --- a/internal/engine/metric_rollup_memory_test.go +++ b/internal/engine/metric_rollup_memory_test.go @@ -1,9 +1,6 @@ package engine -import ( - "testing" - "time" -) +import "testing" func TestServiceCountsKeepMetricOnlyKeysWithoutScanningMetrics(t *testing.T) { db := openTestDuck(t) @@ -13,13 +10,6 @@ func TestServiceCountsKeepMetricOnlyKeysWithoutScanningMetrics(t *testing.T) { if err := CreateViews(db); err != nil { t.Fatal(err) } - 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) - } - lo := time.Unix(0, 0).UTC() - if _, err := insertServiceRollup(t.Context(), db, lo, lo.Add(time.Minute)); err != nil { - t.Fatal(err) - } - 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) + metrics := "SELECT 'b' batch_id,'ns' namespace,TIMESTAMP '1970-01-01' bucket,'metrics-only' service,'metrics' signal" + requireRowCount(t, db, "SELECT count(*) FROM ("+servicePartial("", "", metrics)+") 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 74219680..3d41201b 100644 --- a/internal/engine/panel_rollup_keys_test.go +++ b/internal/engine/panel_rollup_keys_test.go @@ -3,6 +3,7 @@ package engine import ( "fmt" "reflect" + "slices" "strings" "testing" "time" @@ -21,6 +22,13 @@ var panelRollupKeys = []struct { {"endpoint_rollup", "namespace,bucket,service,kind,status,route,overflow"}, } +func physicalRollup(table, keys string) (string, string) { + if slices.Contains(additiveRollups, table) { + return "read_" + table, "batch_id," + keys + } + return table, keys +} + // derivedRollupKeys also dropped their ART primary keys. Their INSERT SQL is // too complex to re-derive from raw rows here, so they are guarded for schema // shape (no index, NOT NULL keys) and for key uniqueness after each refresh, @@ -37,6 +45,7 @@ func TestPanelRollupKeysKeepNotNullWithoutIndexes(t *testing.T) { d, _ := newBatchCacheTest(t) for _, table := range panelRollupKeys { t.Run(table.table, func(t *testing.T) { + table.table, table.keys = physicalRollup(table.table, table.keys) var constraints, indexes int if err := d.DB.QueryRowContext(t.Context(), `SELECT count(*) FROM duckdb_constraints() WHERE table_name=? AND constraint_type IN ('PRIMARY KEY','UNIQUE')`, table.table).Scan(&constraints); err != nil { t.Fatal(err) @@ -72,6 +81,7 @@ func TestDerivedRollupKeysDropIndexesKeepNotNull(t *testing.T) { d, _ := newBatchCacheTest(t) for _, table := range derivedRollupKeys { t.Run(table.table, func(t *testing.T) { + table.table, table.keys = physicalRollup(table.table, table.keys) var constraints, indexes int if err := d.DB.QueryRowContext(t.Context(), `SELECT count(*) FROM duckdb_constraints() WHERE table_name=? AND constraint_type IN ('PRIMARY KEY','UNIQUE')`, table.table).Scan(&constraints); err != nil { t.Fatal(err) @@ -116,10 +126,8 @@ func TestPanelRollupKeysSurviveLateRepairRetryAndRollback(t *testing.T) { } refreshPanelRollupKeys(t, d) refreshPanelRollupKeys(t, d) - for _, table := range panelRollupKeys { - if _, err := d.DB.ExecContext(t.Context(), "CREATE TABLE before_"+table.table+" AS SELECT * FROM "+table.table); err != nil { - t.Fatal(err) - } + if _, err := d.DB.Exec("CREATE TABLE before_endpoint_rollup AS SELECT * FROM endpoint_rollup"); err != nil { + t.Fatal(err) } before, err := d.RollupWatermark(t.Context()) if err != nil { @@ -128,8 +136,7 @@ func TestPanelRollupKeysSurviveLateRepairRetryAndRollback(t *testing.T) { if err := repo.Commit(t.Context(), panelRollupKeyBatch("late", at.Add(20*time.Second), 1, true)); err != nil { t.Fatal(err) } - // Endpoint insertion follows the span aggregate insertion. Failure here - // must roll back the shared transaction, including all earlier deletions. + // An endpoint insertion failure must roll back the preceding deletions. if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE endpoint_rollup ADD COLUMN incompatible BOOLEAN`); err != nil { t.Fatal(err) } @@ -139,13 +146,7 @@ func TestPanelRollupKeysSurviveLateRepairRetryAndRollback(t *testing.T) { if _, err := d.DB.ExecContext(t.Context(), `ALTER TABLE endpoint_rollup DROP COLUMN incompatible`); err != nil { t.Fatal(err) } - for _, table := range panelRollupKeys { - var differences int - query := "SELECT count(*) FROM ((SELECT * FROM " + table.table + " EXCEPT ALL SELECT * FROM before_" + table.table + ") UNION ALL (SELECT * FROM before_" + table.table + " EXCEPT ALL SELECT * FROM " + table.table + "))" - if err := d.DB.QueryRowContext(t.Context(), query).Scan(&differences); err != nil || differences != 0 { - t.Fatalf("rollback changed %s: differences=%d err=%v", table.table, differences, err) - } - } + requireSnapshotCount(t, d, `SELECT count(*) FROM ((SELECT * FROM endpoint_rollup EXCEPT ALL SELECT * FROM before_endpoint_rollup) UNION ALL (SELECT * FROM before_endpoint_rollup EXCEPT ALL SELECT * FROM endpoint_rollup))`, 0) if got, err := d.RollupWatermark(t.Context()); err != nil || !got.Equal(before) { t.Fatalf("rollback changed watermark: %v -> %v: %v", before, got, err) } @@ -203,16 +204,15 @@ func TestPanelRollupKeysUpgradePreviousCacheOnReopen(t *testing.T) { t.Fatal("fixture did not warm analytical progress") } metadata := repo.Parquet.BatchMetadata() - for _, table := range append(append([]struct{ table, keys string }{}, panelRollupKeys...), derivedRollupKeys...) { - // Recreate the exact previous physical key design, rather than only - // changing a version number on an already unindexed cache. - if _, err := d.DB.ExecContext(t.Context(), "ALTER TABLE "+table.table+" ADD PRIMARY KEY ("+table.keys+")"); err != nil { + // Version 21 stored the public summaries as physical tables. + for _, name := range additiveRollups { + if _, err := d.DB.Exec("DROP VIEW " + name + "; CREATE TABLE " + name + " AS SELECT * EXCLUDE(batch_id) FROM read_" + name); err != nil { t.Fatal(err) } } for _, statement := range []string{ - `UPDATE read_cache_version SET version=19`, - `UPDATE rollup_schema_version SET version=4`, + `UPDATE read_cache_version SET version=21`, + `UPDATE rollup_schema_version SET version=6`, `INSERT INTO anomaly_log VALUES ('upgrade','svc','latency',now(),now(),'witness','preserve me')`, `INSERT INTO read_edge_buckets VALUES ('upgrade',now(),10)`, `INSERT INTO edge_rollup (namespace,bucket,caller,callee,calls) VALUES ('upgrade',now(),'a','b',1)`, @@ -244,13 +244,13 @@ func TestPanelRollupKeysUpgradePreviousCacheOnReopen(t *testing.T) { if err != nil { t.Fatal(err) } - for table, want := range map[string]int{"read_cache_version": 21, "rollup_schema_version": 6} { + for table, want := range map[string]int{"read_cache_version": 22, "rollup_schema_version": 7} { 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) } } - for _, table := range []string{"span_rollup", "log_rollup", "endpoint_rollup", "service_rollup", "edge_rollup", "receiver_rollup", "resource_rollup", "receiver_entity_rollup", "rollup_state", "version_rollup", "version_rollup_batches", "read_batches", "read_trace_exemplars", "read_resource_inventory", "read_resource_seconds", "read_metric_names", "read_edge_buckets"} { + for _, table := range []string{"read_span_rollup", "read_log_rollup", "endpoint_rollup", "read_service_rollup", "edge_rollup", "receiver_rollup", "read_resource_rollup", "receiver_entity_rollup", "rollup_state", "version_rollup", "version_rollup_batches", "read_batches", "read_trace_exemplars", "read_resource_inventory", "read_resource_seconds", "read_metric_names", "read_edge_buckets"} { var count int if err := d.DB.QueryRowContext(t.Context(), "SELECT count(*) FROM "+table).Scan(&count); err != nil || count != 0 { t.Fatalf("previous %s survived rebuild: count=%d: %v", table, count, err) @@ -271,6 +271,7 @@ func TestPanelRollupKeysUpgradePreviousCacheOnReopen(t *testing.T) { t.Fatalf("canonical rows after reopen=%d/%d: %v", spans, logs, err) } for _, table := range append(append([]struct{ table, keys string }{}, panelRollupKeys...), derivedRollupKeys...) { + table.table, table.keys = physicalRollup(table.table, table.keys) var indexes int if err := d.DB.QueryRowContext(t.Context(), `SELECT (SELECT count(*) FROM duckdb_constraints() WHERE table_name=? AND constraint_type IN ('PRIMARY KEY','UNIQUE'))+(SELECT count(*) FROM duckdb_indexes() WHERE table_name=?)`, table.table, table.table).Scan(&indexes); err != nil || indexes != 0 { t.Fatalf("reopened %s key indexes=%d: %v", table.table, indexes, err) @@ -324,13 +325,16 @@ func panelRollupKeyBatch(id string, at time.Time, services int, overflow bool) t func refreshPanelRollupKeys(t *testing.T, d *Duck) { t.Helper() + if _, err := d.RefreshReadCaches(t.Context()); err != nil { + t.Fatal(err) + } if _, err := d.refreshServiceRollup(t.Context()); err != nil { t.Fatal(err) } for _, table := range append(append([]struct{ table, keys string }{}, panelRollupKeys...), derivedRollupKeys...) { var duplicates int query := "SELECT count(*) FROM (SELECT " + table.keys + " FROM " + table.table + " GROUP BY " + table.keys + " HAVING count(*)<>1)" - if err := d.DB.QueryRowContext(t.Context(), query).Scan(&duplicates); err != nil || duplicates != 0 { + if err := d.QueryRowScan(t.Context(), []any{&duplicates}, query); err != nil || duplicates != 0 { t.Fatalf("%s duplicate complete keys=%d: %v", table.table, duplicates, err) } } diff --git a/internal/engine/querytest/tables.go b/internal/engine/querytest/tables.go index 5241e04f..ce7312a9 100644 --- a/internal/engine/querytest/tables.go +++ b/internal/engine/querytest/tables.go @@ -4,7 +4,9 @@ package querytest import ( "database/sql" "fmt" + telemetrystore "github.com/labstack/pitot/internal/telemetry/store" "strings" + "sync/atomic" "testing" "time" @@ -50,21 +52,14 @@ func CreateTables(db *sql.DB, createCaches func(*sql.DB) error) error { return createCaches(db) } -// RefreshSpanRollup publishes summaries for read-side fixtures that do not run -// the background engine loop. Engine write-path tests use the real rollup pass. -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(` + 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 +// CreateSummaryFixtures supplies mutable inputs for consumer-only SQL tests. +func CreateSummaryFixtures(t testing.TB, db *sql.DB) { + t.Helper() + for _, name := range []string{"span_rollup", "service_rollup", "log_rollup", "resource_rollup"} { + if _, err := db.Exec("CREATE TABLE " + name + " AS SELECT * EXCLUDE(batch_id) FROM read_" + name + " WHERE false"); err != nil { + t.Fatal(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(` + 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. @@ -84,3 +79,21 @@ func SeedSpanRollup(t testing.TB, db *sql.DB, at time.Time, namespace, service, } } } + +var spanBatchSequence atomic.Uint64 + +// CommitSpans publishes a constant-duration population for snapshot-backed readers. +func CommitSpans(t testing.TB, repo *telemetrystore.Repository, at time.Time, namespace, service, kind string, count, errors int, duration float64) { + t.Helper() + batch := telemetrystore.Batch{ID: fmt.Sprintf("spans-%d", spanBatchSequence.Add(1))} + for i := range count { + status := "STATUS_CODE_OK" + if i < errors { + status = "STATUS_CODE_ERROR" + } + batch.Spans = append(batch.Spans, telemetry.Span{Namespace: namespace, ServiceName: service, Kind: kind, StartUnixNanos: at.UnixNano(), EndUnixNanos: at.Add(time.Duration(duration * float64(time.Millisecond))).UnixNano(), DurationMS: duration, StatusCode: status}) + } + if err := repo.Commit(t.Context(), batch); err != nil { + t.Fatal(err) + } +} diff --git a/internal/engine/read_pressure_test.go b/internal/engine/read_pressure_test.go index b6fd42c5..24cf7421 100644 --- a/internal/engine/read_pressure_test.go +++ b/internal/engine/read_pressure_test.go @@ -61,7 +61,7 @@ func TestAffectedKeysYieldsEveryChunk(t *testing.T) { func TestBackgroundLanesAdmitIndependentWriters(t *testing.T) { d, repo := newBatchCacheTest(t) - commitCurrentBatches(t, repo, "input", 1, time.Now().Add(-time.Minute)) + commitWatermarkSpan(t, repo, "input") checkBlocked := func(t *testing.T, refresh func(context.Context) (int64, error)) { t.Helper() ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) @@ -142,9 +142,9 @@ func TestCacheTransferCommitsDuringServiceRollup(t *testing.T) { const inputs = 8 // Force a second affected-key chunk so the service pass yields with its // first chunk written and the transaction still open on the first connection. - logs := make([]telemetry.Log, affectedKeyChunkSize+1) - for i := range logs { - logs[i] = telemetry.Log{ServiceName: fmt.Sprintf("service-%d", i), TimeUnixNanos: at, IngestedAt: at} + points := make([]telemetry.Metric, affectedKeyChunkSize+1) + for i := range points { + points[i] = telemetry.Metric{Name: "system.memory.usage", Type: "gauge", ServiceName: fmt.Sprintf("service-%d", i), TimeUnixNanos: at, IngestedAt: at} } // All inputs belong to the same compaction hour. for i := range inputs { @@ -153,7 +153,7 @@ func TestCacheTransferCommitsDuringServiceRollup(t *testing.T) { TraceID: id, SpanID: id, ServiceName: "api", StartUnixNanos: at, EndUnixNanos: at + 1, IngestedAt: at, }}} if i == 0 { - batch.Logs = logs + batch.Metrics = points } if err := commitRestoredFixture(repo, t.Context(), batch); err != nil { t.Fatal(err) @@ -216,9 +216,9 @@ func TestCacheTransferCommitsDuringServiceRollup(t *testing.T) { if ok, _, failures, err := d.CheckpointHealth(); ok.IsZero() || failures != 0 || err != nil { t.Fatalf("checkpoint last success=%v failures=%d: %v", ok, failures, err) } - var spans, logCount, exemplars, owners, cached int - if err := d.DB.QueryRowContext(ctx, `SELECT sum(spans),sum(log_count) FROM service_rollup`).Scan(&spans, &logCount); err != nil || spans != inputs || logCount != len(logs) { - t.Fatalf("committed rollup spans=%d logs=%d: %v", spans, logCount, err) + var spans, metricOnly, exemplars, owners, cached int + if err := d.QueryRowScan(ctx, []any{&spans, &metricOnly}, `SELECT sum(spans),count(*) FILTER(WHERE spans=0) FROM service_rollup`); err != nil || spans != inputs || metricOnly != len(points) { + t.Fatalf("committed rollup spans=%d metric-only=%d: %v", spans, metricOnly, err) } if err := d.DB.QueryRowContext(ctx, exemplarOwnersQuery).Scan(&exemplars, &owners, &cached); err != nil || exemplars != inputs || owners != 1 || cached != 1 { t.Fatalf("committed cache exemplars=%d owners=%d markers=%d: %v", exemplars, owners, cached, err) diff --git a/internal/engine/receiver_rollup.go b/internal/engine/receiver_rollup.go index dd79dde9..ef85d175 100644 --- a/internal/engine/receiver_rollup.go +++ b/internal/engine/receiver_rollup.go @@ -18,15 +18,15 @@ const createReceiverRollupTable = `CREATE TABLE IF NOT EXISTS receiver_rollup ( counter_increase DOUBLE,counter_seconds DOUBLE )` -const createResourceRollupTable = `CREATE TABLE IF NOT EXISTS resource_rollup ( - namespace VARCHAR,bucket TIMESTAMP_NS,service VARCHAR,signal VARCHAR, - resource VARIANT,first_seen TIMESTAMPTZ_NS,last_seen TIMESTAMPTZ_NS +const createResourceRollupTable = `CREATE TABLE IF NOT EXISTS read_resource_rollup ( + batch_id VARCHAR NOT NULL,namespace VARCHAR NOT NULL,bucket TIMESTAMP_NS NOT NULL,service VARCHAR NOT NULL,signal VARCHAR NOT NULL, + resource VARIANT NOT NULL,first_seen TIMESTAMPTZ_NS,last_seen TIMESTAMPTZ_NS )` func receiverRollupInsertSQL(keys string) string { return fmt.Sprintf(`INSERT INTO receiver_rollup WITH projected AS ( - SELECT namespace,date_trunc('minute',time::TIMESTAMP_NS) bucket,service,name,type,temporality,unit,scope_name, + SELECT namespace,%s bucket,service,name,type,temporality,unit,scope_name, struct_pack("host.name" := resource['host.name']::VARCHAR,"container.id" := _r_container_id,"container.name" := resource['container.name']::VARCHAR)::VARIANT resource, struct_pack(state := attributes['state']::VARCHAR,cpu := attributes['cpu']::VARCHAR,mountpoint := attributes['mountpoint']::VARCHAR,device := attributes['device']::VARCHAR, "http.url" := attributes['http.url']::VARCHAR,"http.method" := attributes['http.method']::VARCHAR,"http.status_class" := attributes['http.status_class']::VARCHAR,"http.status_code" := attributes['http.status_code']::VARCHAR)::VARIANT attributes, @@ -50,26 +50,7 @@ func receiverRollupInsertSQL(keys string) string { sum(CASE WHEN isfinite(value) AND isfinite(previous_finite.value) THEN CASE WHEN temporality='delta' OR valueprevious_finite.start_time) THEN value ELSE value-previous_finite.value END END) counter_increase, sum(CASE WHEN isfinite(value) AND isfinite(previous_finite.value) THEN epoch_ns(time::TIMESTAMP_NS)::HUGEINT-epoch_ns(CASE WHEN temporality='delta' AND start_time