diff --git a/docs/operations.md b/docs/operations.md index 807e0960..fd99824d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -236,7 +236,10 @@ Diagnose slow trace drill-downs (`POST /api/queries/exemplars`) by stage: not covered yet. Ranking scans them raw, so a large value with slow `ranking` points at read-cache lag rather than retained data. - An exemplar run that takes a second or more logs `slow exemplar request` at - info level with the same stage breakdown in milliseconds. + info level with the same stage breakdown in milliseconds. It splits ranking + into the wait for a connection, snapshot binding and statement execution, and + reports its source: cached batches, raw tail batches and their spans, and + whether a cached threshold pruned the tail. Run Pitot under a supervisor that restarts it on exit: Docker or Compose with `restart: unless-stopped` (`--restart unless-stopped`), systemd with diff --git a/internal/engine/duck.go b/internal/engine/duck.go index b5f4b6c2..09bd698d 100644 --- a/internal/engine/duck.go +++ b/internal/engine/duck.go @@ -2507,7 +2507,14 @@ func (d *Duck) QueryContext(ctx context.Context, query string, args ...any) (que // The connection is taken explicitly and timed separately: DB.QueryContext // would fold the wait for a free connection into the statement's duration, // and telling queueing from execution is the whole reason this is measured. + var scratch queryrows.ReadProfile + profile := queryrows.ReadProfileFrom(ctx) + if profile == nil { + profile = &scratch + } + waited := time.Now() conn, pin, err := d.readConn(ctx) + profile.Wait = time.Since(waited) if err != nil { return nil, err } @@ -2561,11 +2568,13 @@ func (d *Duck) QueryContext(ctx context.Context, query string, args ...any) (que } } if windowed { + bound := time.Now() tx, err = beginRead(ctx, conn) if err == nil { db = tx query, err = d.bindSnapshot(ctx, tx, query, window) } + profile.Bind = time.Since(bound) if err != nil { return nil, err } @@ -2576,7 +2585,8 @@ func (d *Duck) QueryContext(ctx context.Context, query string, args ...any) (que done = d.begin(ctx, query) rows, err = db.QueryContext(ctx, query, args...) done(err) - metrics.DuckDBStatement.Observe(time.Since(started).Seconds()) + profile.Execute = time.Since(started) + metrics.DuckDBStatement.Observe(profile.Execute.Seconds()) if err != nil { return nil, err } diff --git a/internal/engine/trace_exemplars.go b/internal/engine/trace_exemplars.go index 6cf68868..7ea4b6ae 100644 --- a/internal/engine/trace_exemplars.go +++ b/internal/engine/trace_exemplars.go @@ -286,6 +286,15 @@ func (d *Duck) traceExemplarSource(ctx context.Context, db snapshotSQL, batches return `SELECT namespace,service,trace_id,start_time,start_unix_nano,duration,has_error FROM (SELECT coalesce(namespace,'') AS namespace,coalesce(service,'') AS service,trace_id,start_time,start_unix_nano,end_unix_nano-start_unix_nano AS duration, CASE WHEN status='STATUS_CODE_ERROR' THEN 1 ELSE 0 END AS has_error FROM (` + cleanSource("spans", d.snapshotSource("spans", raw, batches)) + `) WHERE ` + windowPredicate("start_time", w) + ` AND trace_id<>'') WHERE true` + scope.String() + threshold } + tailSpans := 0 + for _, b := range raw { + tailSpans += b.Spans + } + threshold := "" + if p := queryrows.ReadProfileFrom(ctx); p != nil { + p.CachedBatches, p.TailBatches, p.TailSpans = len(cachedIDs), len(raw), tailSpans + defer func() { p.Pruned = threshold != "" }() + } if len(cachedIDs) == 0 { return tail(""), nil } @@ -302,11 +311,6 @@ func (d *Duck) traceExemplarSource(ctx context.Context, db snapshotSQL, batches } cached := `SELECT namespace,service,trace_id,make_timestamp_ns(start_unix_nano)::TIMESTAMPTZ_NS AS start_time,start_unix_nano,duration,has_error FROM read_trace_exemplars WHERE batch_id IN (SELECT unnest([` + idsSQL(cachedIDs) + `]))` + fmt.Sprintf(" AND minute>=%d AND minute<=%d", startMinute, endMinute) + scope.String() + ` AND (` + strings.Join(ranges, " OR ") + `)` - tailSpans := 0 - for _, b := range raw { - tailSpans += b.Spans - } - threshold := "" if len(raw) > 0 && tailSpans >= d.tracePruneSpans { var traces, failed, duration int64 if err := db.QueryRowContext(ctx, fmt.Sprintf(`SELECT count(*),coalesce(min(score)[1],0),coalesce(min(score)[2],0) FROM (SELECT max([has_error::BIGINT,duration]) AS score FROM (%s) GROUP BY namespace,trace_id ORDER BY score DESC LIMIT %d)`, cached+" AND in_full", traceExemplarDepth)).Scan(&traces, &failed, &duration); err != nil { diff --git a/internal/engine/trace_exemplars_test.go b/internal/engine/trace_exemplars_test.go index fad66059..133b2ab1 100644 --- a/internal/engine/trace_exemplars_test.go +++ b/internal/engine/trace_exemplars_test.go @@ -522,8 +522,12 @@ func TestCompletedTraceQueryPrunesUncachedTailExactly(t *testing.T) { for i := range cachedTraces { cached = append(cached, span(fmt.Sprintf("t%02d", i), i%3, int64(cachedTraces-i)*ms, cachedFailed)) } - if err := commitRestoredFixture(repo, t.Context(), telemetrystore.Batch{ID: "cached", Spans: cached}); err != nil { - t.Fatal(err) + cachedBatches := 0 + if len(cached) > 0 { + cachedBatches = 1 + if err := commitRestoredFixture(repo, t.Context(), telemetrystore.Batch{ID: "cached", Spans: cached}); err != nil { + t.Fatal(err) + } } for { rows, err := d.RefreshReadCaches(t.Context()) @@ -544,6 +548,18 @@ func TestCompletedTraceQueryPrunesUncachedTailExactly(t *testing.T) { if got := boundTraceSource(t, d, w); got != pruned { t.Fatalf("window=%v tail pruned=%v want %v", bounds, got, pruned) } + // The slow drill-down log reports the same source shape. + var p queryrows.ReadProfile + pw := w + pw.Kind = queryrows.TraceCandidateRead + rows, err := d.QueryContext(queryrows.WithReadProfile(queryrows.WithWindow(t.Context(), pw), &p), queryrows.CompletedTraceQuery, w.Start, w.End, w.Namespace, w.Namespace, w.Service, w.Service, traceExemplarDepth) + if err != nil { + t.Fatal(err) + } + _ = rows.Close() + if p.CachedBatches != cachedBatches || p.TailBatches != 1 || p.TailSpans != len(tail) || p.Pruned != pruned || p.Execute <= 0 { + t.Fatalf("profile %+v, want %d cached, 1 tail of %d spans, pruned=%v", p, cachedBatches, len(tail), pruned) + } } for _, limit := range []int{1, 5, traceExemplarDepth} { got := completedTraces(t, d, w, limit) @@ -590,6 +606,9 @@ func TestCompletedTraceQueryPrunesUncachedTailExactly(t *testing.T) { } run(t, traceExemplarDepth-1, false, append(tail, span("t03", 2, 40*ms, false)), false) }) + t.Run("nothing cached", func(t *testing.T) { + run(t, 0, false, []telemetry.Span{span("only", 1, 5*ms, false), span("err", 2, ms, true)}, false) + }) } // Random tails against brute force: few traces and coarse durations force diff --git a/internal/query/exemplars.go b/internal/query/exemplars.go index 2887f8ab..7be1df7f 100644 --- a/internal/query/exemplars.go +++ b/internal/query/exemplars.go @@ -118,7 +118,11 @@ func (e *Executor) Exemplars(ctx context.Context, req ExemplarRequest) (Exemplar if total := time.Since(started); total >= slowDrilldown { slog.Info("slow exemplar request", "panel_id", req.PanelID, "kind", req.Kind, "indexed", stages.indexed, "total_ms", total.Milliseconds(), "admission_ms", stages.admission.Milliseconds(), - "ranking_ms", stages.ranking.Milliseconds(), "summaries_ms", stages.summaries.Milliseconds(), "error", err) + "ranking_ms", stages.ranking.Milliseconds(), "ranking_wait_ms", stages.read.Wait.Milliseconds(), + "ranking_bind_ms", stages.read.Bind.Milliseconds(), "ranking_execute_ms", stages.read.Execute.Milliseconds(), + "cached_batches", stages.read.CachedBatches, "tail_batches", stages.read.TailBatches, + "tail_spans", stages.read.TailSpans, "tail_pruned", stages.read.Pruned, + "summaries_ms", stages.summaries.Milliseconds(), "error", err) } }() if err != nil { @@ -411,6 +415,8 @@ const slowDrilldown = time.Second type drilldownStages struct { indexed bool admission, ranking, summaries time.Duration + // read profiles the ranking statement. + read queryrows.ReadProfile } type drilldownStagesKey struct{} @@ -442,7 +448,7 @@ func (e *Executor) indexedExemplars(ctx context.Context, w queryrows.Window, pan stages.indexed = true // Failed and timed-out rankings are recorded too: they are the slow ones. started := time.Now() - ids, err := e.rankTraces(ctx, w) + ids, err := e.rankTraces(queryrows.WithReadProfile(ctx, &stages.read), w) stages.ranking = time.Since(started) metrics.RecordDrilldownStage("ranking", stages.ranking.Seconds()) if err != nil { diff --git a/internal/queryrows/window.go b/internal/queryrows/window.go index b29c9414..64c6aa57 100644 --- a/internal/queryrows/window.go +++ b/internal/queryrows/window.go @@ -88,3 +88,25 @@ func RecordCoverage(ctx context.Context, fresh time.Time) { } } func (c *Coverage) FreshTo() time.Time { c.mu.Lock(); defer c.mu.Unlock(); return c.fresh } + +// ReadProfile carries one read's phase times, and for a trace ranking its +// source's shape, back to the caller's slow-request log. A context holds it +// for a single QueryContext call. +type ReadProfile struct { + Wait, Bind, Execute time.Duration + // Cached batches rank from read_trace_exemplars; tail batches and their + // spans are read raw, filtered when Pruned. + CachedBatches, TailBatches, TailSpans int + Pruned bool +} +type readProfileKey struct{} + +func WithReadProfile(ctx context.Context, p *ReadProfile) context.Context { + return context.WithValue(ctx, readProfileKey{}, p) +} + +// ReadProfileFrom returns the context's profile, or nil. +func ReadProfileFrom(ctx context.Context) *ReadProfile { + p, _ := ctx.Value(readProfileKey{}).(*ReadProfile) + return p +}