diff --git a/cmd/pitot/main.go b/cmd/pitot/main.go index 23033ccf..0fdbf5f4 100644 --- a/cmd/pitot/main.go +++ b/cmd/pitot/main.go @@ -306,7 +306,7 @@ func main() { // observability tools, and the annotation route below) are admitted through // the interactive lane so they cannot oversubscribe the read pool. queries := observability.New(q, q, cfg.RetentionDays) - admittedQueries := observability.New(panels.AdmitReader(q), panels.AdmitTraceDetail(q), cfg.RetentionDays) + admittedQueries := observability.New(panels.AdmitReader(q, appmetrics.ReadObservability), panels.AdmitTraceDetail(q), cfg.RetentionDays) writer.SetAdmission(repository.CompactionDebt, panels.InteractiveRefusals) go func() { err := writer.Run(ctx) @@ -324,7 +324,7 @@ func main() { panels.SetCacheTTL(cfg.QueryCacheTTL) api.RegisterQueryRoutes(e, panels) api.RegisterPitotQLRoutes(e, q, panels) - api.RegisterAnnotationRoutes(e, annotations.New(panels.AdmitReader(q))) + api.RegisterAnnotationRoutes(e, annotations.New(panels.AdmitReader(q, appmetrics.ReadAnnotations))) api.RegisterTraceRoutes(e, panels.CachedTraces(queries), cfg.RetentionDays) api.RegisterIntelligenceRoutes(e, detector) dashboards := dashboard.New(sqlite.DB, panels) diff --git a/docs/proposals/0011-engine-admission-classes.md b/docs/proposals/0011-engine-admission-classes.md index b36b907e..e8648c29 100644 --- a/docs/proposals/0011-engine-admission-classes.md +++ b/docs/proposals/0011-engine-admission-classes.md @@ -1,8 +1,8 @@ # One cost-aware admission layer at the engine boundary -Status: Draft +Status: Accepted Date: 2026-11-15 -Pull request: TBD +Pull request: #530 (Phase 0); Phases 1–3 remain open on #480 ## Summary @@ -253,11 +253,13 @@ earlier measurements, A/B on chip x86_64 / Hetzner, never pico): (e.g. a 2-connection pool where `QueryAdmission` sets `slots = pool`), Phase 0 still caps admitted concurrency at `pool` and stops unbounded oversubscription, though admitted interactive reads can occupy every connection so direct `/readyz` - or nested reads may still wait on `DB.Conn` until Phase 2/3. Still open in - Phase 0: routing `query.variables` option queries (`variables.go:25,72,107`) - and `Executor.Schema` discoveries (`schema.go`) through admission, and adding - per-path queue depth, wait, admit/reject, DuckDB thread saturation, and - runnable-goroutines/CPU metrics. This yields the clean baseline for the + or nested reads may still wait on `DB.Conn` until Phase 2/3. Variable options + acquire a slot per statement. MCP empty-result guidance takes one slot for + its sequential reads and starts its execution timeout after admission. + Exemplar variable resolution reuses its run’s slot. Schema discovery retains its two-flight + cap and releases its interactive slot between statements. Per-path wait, + admission outcomes, queue depth and slot usage are available alongside + DuckDB thread, active statement, write-pool and Go scheduler gauges. This yields the clean baseline for the read-cost proposals (0012, 0013, and 0007). - **Phase 1 — split the background choke.** `backgroundSlots` is one permit (`duck.go:35/680/692`) shared by rollups and the read-cache refresh even though @@ -279,8 +281,7 @@ The per-run shared snapshot+connection (the one cost-reducing move) folds into Phase 2/3 and carries the checkpoint-refusal hazard (revision 7), so it is not in the Phase 0 slice. -**Build readiness.** Phase 0's `observability`, `TraceDetail`, and `annotations` -wrappers have landed (#502, #507); `query.variables` and `Executor.Schema` -admission plus the Phase-0 metrics remain. Phases 2-3 are gated on Phase-0 -production metrics and per-phase A/B. The 20 ops/s gate stays owned by 0012/0013 -(and 0007 for rollup-scoped aggregates). +**Build readiness.** Phase 0 completes the read admission and saturation baseline +started in #502 and #507. Phase 1 is the next independent change. +Phases 2–3 are gated on Phase-0 production metrics and per-phase A/B. The 20 ops/s +gate stays owned by 0012/0013 (and 0007 for rollup-scoped aggregates). diff --git a/docs/proposals/README.md b/docs/proposals/README.md index dcb28a0f..f667398d 100644 --- a/docs/proposals/README.md +++ b/docs/proposals/README.md @@ -42,7 +42,7 @@ Earlier proposals predate the template and keep their original structure. | 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 | -| 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Draft | +| 0011 | [One cost-aware admission layer at the engine boundary](0011-engine-admission-classes.md) | Accepted | | 0012 | [Bounded trace ranking for drill-down](0012-bounded-trace-ranking.md) | Implemented | | 0013 | [Indexed trace logs](0013-log-trace-lookup.md) | Implemented | | 0014 | [Bounds for OTLP client timestamps](0014-ingest-timestamp-bounds.md) | Implemented | diff --git a/internal/api/schema_busy_test.go b/internal/api/schema_busy_test.go index 72161b54..f2fb620f 100644 --- a/internal/api/schema_busy_test.go +++ b/internal/api/schema_busy_test.go @@ -11,14 +11,19 @@ import ( type busySchema struct{ fakePanels } -func (*busySchema) Schema(context.Context, query.SchemaRequest) (*query.Schema, error) { - return nil, query.ErrSchemaBusy +func (s *busySchema) Schema(context.Context, query.SchemaRequest) (*query.Schema, error) { + return nil, s.err } func TestTelemetrySchemaBusyIs503WithRetryAfter(t *testing.T) { - rec := servePanels(t, &busySchema{}, http.MethodGet, "/api/telemetry/schema?window=6h", "") - if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != "5" || !strings.Contains(rec.Body.String(), `"code":"schema_busy"`) || strings.Contains(rec.Body.String(), "Panels") { - t.Fatalf("busy schema: %d %v %s", rec.Code, rec.Header(), rec.Body) + for _, tc := range []struct { + err error + code, retry string + }{{query.ErrSchemaBusy, "schema_busy", "5"}, {query.ErrBusy, "busy", "2"}} { + rec := servePanels(t, &busySchema{fakePanels{err: tc.err}}, http.MethodGet, "/api/telemetry/schema?window=6h", "") + if rec.Code != http.StatusServiceUnavailable || rec.Header().Get("Retry-After") != tc.retry || !strings.Contains(rec.Body.String(), `"code":"`+tc.code+`"`) || strings.Contains(rec.Body.String(), "Panels") { + t.Fatalf("%v: %d %v %s", tc.err, rec.Code, rec.Header(), rec.Body) + } } } diff --git a/internal/engine/duck.go b/internal/engine/duck.go index ac04ce01..3b9e7e27 100644 --- a/internal/engine/duck.go +++ b/internal/engine/duck.go @@ -83,10 +83,11 @@ type Duck struct { closeErr error // releasePoolGauges stops the pool gauges reading this Duck's pool, and // only if they are still reading it. - releasePoolGauges func() - releaseMemoryGauges func() - stopMemorySampler context.CancelFunc - memorySamplerDone chan struct{} + releasePoolGauges func() + releaseMemoryGauges func() + releaseSaturationGauges func() + stopMemorySampler context.CancelFunc + memorySamplerDone chan struct{} // memoryDB has one borrowed connection so a blocked memory query cannot // occupy a request or write slot. The read pool owns the shared instance. memoryDB *sql.DB @@ -459,6 +460,16 @@ func NewDuck(ctx context.Context, cfg config.Config, repository *telemetrystore. slog.Info("rollup skip-to-latest: existing data marked already-rolled-up") } } + threads := cfg.DuckDBThreads + if threads <= 0 { + if err := db.QueryRowContext(ctx, "SELECT current_setting('threads')::BIGINT").Scan(&threads); err != nil { + _ = d.Close() + return nil, fmt.Errorf("read DuckDB worker thread count: %w", err) + } + } + d.releaseSaturationGauges = metrics.SetDuckDBSaturationSource(func() metrics.DuckDBSaturation { + return metrics.DuckDBSaturation{Threads: threads, ReadStatements: d.inFlight(), WriteInUse: writeDB.Stats().InUse} + }) d.startMemorySampler(duckDBMemorySampleInterval, d.sampleMemory) return d, nil } @@ -635,6 +646,9 @@ func (d *Duck) Close() error { if d.stopMemorySampler != nil { d.stopMemorySampler() } + if d.releaseSaturationGauges != nil { + d.releaseSaturationGauges() + } if d.releasePoolGauges != nil { d.releasePoolGauges() } diff --git a/internal/engine/stall_instrumentation_test.go b/internal/engine/stall_instrumentation_test.go index 8a9fb96e..d243e950 100644 --- a/internal/engine/stall_instrumentation_test.go +++ b/internal/engine/stall_instrumentation_test.go @@ -159,6 +159,26 @@ func TestClosingADisplacedDuckLeavesTheGaugeSourceAlone(t *testing.T) { if got := int(metricFamily(t, "pitot_duckdb_pool_max_open").Metric[0].GetGauge().GetValue()); got != 3 { t.Fatalf("pool gauges read MaxOpenConnections = %d after a displaced Duck closed, want the live pool's 3", got) } + var threads int + if err := second.DB.QueryRowContext(ctx, "SELECT current_setting('threads')::BIGINT").Scan(&threads); err != nil { + t.Fatal(err) + } + conn, err := second.writeDB.Conn(ctx) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + done := second.begin(ctx, "SELECT 1") + defer done(nil) + for name, want := range map[string]int{ + "pitot_duckdb_threads": threads, + "pitot_duckdb_read_statements_in_flight": 1, + "pitot_duckdb_write_pool_in_use": 1, + } { + if got := metricFamily(t, name).Metric[0].GetGauge().GetValue(); got != float64(want) { + t.Errorf("%s = %v, want %v", name, got, want) + } + } } // The statement histogram exists to separate execution from queueing, so the diff --git a/internal/mcp/panels.go b/internal/mcp/panels.go index dd4c34cf..1004cada 100644 --- a/internal/mcp/panels.go +++ b/internal/mcp/panels.go @@ -77,6 +77,9 @@ func (s *Server) telemetrySchema(ctx context.Context, _ *mcp.CallToolRequest, in if errors.Is(err, query.ErrSchemaBusy) { return nil, nil, guidanceError("schema_busy", "Schema discovery is busy. Try again in a few seconds.") } + if errors.Is(err, query.ErrBusy) { + return nil, nil, guidanceError("busy", query.BusyMessage) + } if err != nil { return nil, nil, safePanelToolError(err) } diff --git a/internal/mcp/panels_test.go b/internal/mcp/panels_test.go index 514da128..fa0ff97a 100644 --- a/internal/mcp/panels_test.go +++ b/internal/mcp/panels_test.go @@ -217,20 +217,26 @@ func TestConfidenceGuide(t *testing.T) { } } -type busySchema struct{ panelExecutor } +type busySchema struct { + panelExecutor + err error +} -func (busySchema) Schema(context.Context, query.SchemaRequest) (*query.Schema, error) { - return nil, query.ErrSchemaBusy +func (s busySchema) Schema(context.Context, query.SchemaRequest) (*query.Schema, error) { + return nil, s.err } // Busy discovery is retryable, like HTTP's 503, not a generic read failure. func TestTelemetrySchemaReportsBusy(t *testing.T) { s := newPanelServer(t) - s.panels = busySchema{s.panels} - _, _, err := s.telemetrySchema(t.Context(), nil, SchemaInput{}) - var failure toolerror.Result - if err == nil || json.Unmarshal([]byte(err.Error()), &failure) != nil || failure.Error == nil || failure.Error.Code != "schema_busy" || !strings.Contains(failure.Error.Message, "Try again") { - t.Fatalf("err=%v", err) + panels := s.panels + for cause, code := range map[error]string{query.ErrSchemaBusy: "schema_busy", query.ErrBusy: "busy"} { + s.panels = busySchema{panels, cause} + _, _, err := s.telemetrySchema(t.Context(), nil, SchemaInput{}) + var failure toolerror.Result + if err == nil || json.Unmarshal([]byte(err.Error()), &failure) != nil || failure.Error == nil || failure.Error.Code != code || !strings.Contains(failure.Error.Message, "Try again") { + t.Fatalf("%v: err=%v", cause, err) + } } } diff --git a/internal/metrics/metrics.go b/internal/metrics/metrics.go index e848e069..1d4993a5 100644 --- a/internal/metrics/metrics.go +++ b/internal/metrics/metrics.go @@ -407,7 +407,7 @@ func (duckDBMemoryCollector) Collect(ch chan<- prometheus.Metric) { } func init() { - prometheus.DefaultRegisterer.MustRegister(duckDBMemoryCollector{}) + prometheus.DefaultRegisterer.MustRegister(duckDBMemoryCollector{}, readSaturationCollector{}) } // SetDuckDBPoolSource reads database/sql bookkeeping on each scrape without diff --git a/internal/metrics/metrics_test.go b/internal/metrics/metrics_test.go index 121c5a94..1c931720 100644 --- a/internal/metrics/metrics_test.go +++ b/internal/metrics/metrics_test.go @@ -140,6 +140,8 @@ func TestRecordTelemetryOperationOutcomes(t *testing.T) { func TestBoundedMetricLabelsRejectUnknownValues(t *testing.T) { for name, call := range map[string]func(){ + "read path": func() { RecordReadAdmission(ReadPathCount, ReadAdmitted, 0) }, + "read outcome": func() { RecordReadAdmission(ReadPanel, "unknown", 0) }, "rollup component": func() { RecordRollupComponent(RollupComponent("tenant"), RollupSuccess, 0, 0) }, "rollup result": func() { RecordRollupComponent(RollupService, RollupResult("unknown"), 0, 0) }, "telemetry operation": func() { RecordTelemetryOperation(TelemetryOperation("query"), TelemetrySuccess, 0) }, @@ -263,3 +265,16 @@ func TestCompactionBacklogSourceTracksCountAndOwner(t *testing.T) { } } } + +func TestNilReadMetricSourcesPreserveTheCurrentOwner(t *testing.T) { + defer SetReadAdmissionSource(func() ReadAdmissionStats { return ReadAdmissionStats{Shared: 3} })() + defer SetDuckDBSaturationSource(func() DuckDBSaturation { return DuckDBSaturation{Threads: 4} })() + SetReadAdmissionSource(nil)() + SetDuckDBSaturationSource(nil)() + if src := admissionSource.Load(); src == nil || (*src)().Shared != 3 { + t.Fatal("nil read admission source displaced the executor") + } + if src := saturationSource.Load(); src == nil || (*src)().Threads != 4 { + t.Fatal("nil saturation source displaced DuckDB") + } +} diff --git a/internal/metrics/read_admission.go b/internal/metrics/read_admission.go new file mode 100644 index 00000000..18988f76 --- /dev/null +++ b/internal/metrics/read_admission.go @@ -0,0 +1,162 @@ +package metrics + +import ( + runtimemetrics "runtime/metrics" + "sync/atomic" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/client_golang/prometheus/promauto" +) + +// ReadAdmissionPath identifies the work that owns a slot. Dense indices let +// the scheduler maintain per-path counts without allocating under its lock. +type ReadAdmissionPath int + +const ( + ReadPanel ReadAdmissionPath = iota + ReadExemplars + ReadTraceDetail + ReadObservability + ReadAnnotations + ReadVariables + ReadSchema + ReadPathCount +) + +func (p ReadAdmissionPath) String() string { + switch p { + case ReadPanel: + return "panel" + case ReadExemplars: + return "exemplars" + case ReadTraceDetail: + return "trace_detail" + case ReadObservability: + return "observability" + case ReadAnnotations: + return "annotations" + case ReadVariables: + return "variables" + case ReadSchema: + return "schema" + default: + panic("unknown read admission path") + } +} + +type ReadAdmissionOutcome string + +const ( + ReadAdmitted ReadAdmissionOutcome = "admitted" + ReadRejected ReadAdmissionOutcome = "rejected" + ReadTimeout ReadAdmissionOutcome = "timeout" + ReadCanceled ReadAdmissionOutcome = "canceled" +) + +var ( + readAdmissionRequests = promauto.NewCounterVec(prometheus.CounterOpts{ + Name: "pitot_read_admission_requests_total", + Help: "Read admission attempts by path and outcome", + }, []string{"path", "status"}) + readAdmissionWait = promauto.NewHistogramVec(prometheus.HistogramOpts{ + Name: "pitot_read_admission_wait_seconds", + Help: "Time spent waiting for read admission by path and outcome", + Buckets: []float64{.0001, .0005, .001, .005, .01, .025, .05, .1, .25, .5, 1, 2.5, 5, 10, 15}, + }, []string{"path", "status"}) +) + +func RecordReadAdmission(path ReadAdmissionPath, status ReadAdmissionOutcome, seconds float64) { + switch status { + case ReadAdmitted, ReadRejected, ReadTimeout, ReadCanceled: + default: + panic("unknown read admission outcome") + } + label := path.String() + readAdmissionRequests.WithLabelValues(label, string(status)).Inc() + readAdmissionWait.WithLabelValues(label, string(status)).Observe(seconds) +} + +type ReadAdmissionStats struct { + Queued, InUse [ReadPathCount]int + Shared, Reserved int +} + +type DuckDBSaturation struct { + Threads, ReadStatements, WriteInUse int +} + +var admissionSource atomic.Pointer[func() ReadAdmissionStats] +var saturationSource atomic.Pointer[func() DuckDBSaturation] + +func SetReadAdmissionSource(stats func() ReadAdmissionStats) func() { + if stats == nil { + return func() {} + } + admissionSource.Store(&stats) + return func() { admissionSource.CompareAndSwap(&stats, nil) } +} + +func SetDuckDBSaturationSource(stats func() DuckDBSaturation) func() { + if stats == nil { + return func() {} + } + saturationSource.Store(&stats) + return func() { saturationSource.CompareAndSwap(&stats, nil) } +} + +var ( + readQueueDepth = prometheus.NewDesc("pitot_read_admission_queue_depth", "Callers currently waiting for a global read slot", []string{"path"}, nil) + readInUse = prometheus.NewDesc("pitot_read_admission_in_use", "Global read slots currently held", []string{"path"}, nil) + readSlots = prometheus.NewDesc("pitot_read_admission_slots", "Configured shared and reserved read slots", []string{"class"}, nil) + duckThreads = prometheus.NewDesc("pitot_duckdb_threads", "Effective DuckDB worker thread limit", nil, nil) + duckReadStatements = prometheus.NewDesc("pitot_duckdb_read_statements_in_flight", "Read statements currently executing in DuckDB", nil, nil) + duckWriteInUse = prometheus.NewDesc("pitot_duckdb_write_pool_in_use", "DuckDB write connections currently in use", nil, nil) + goRunnable = prometheus.NewDesc("pitot_go_sched_runnable_goroutines", "Runnable goroutines waiting to execute", nil, nil) + goRunnablePerCPU = prometheus.NewDesc("pitot_go_sched_runnable_per_cpu", "Runnable goroutines per GOMAXPROCS", nil, nil) + goNotInGo = prometheus.NewDesc("pitot_go_sched_not_in_go_goroutines", "Goroutines executing outside Go", nil, nil) +) + +type readSaturationCollector struct{} + +func (readSaturationCollector) Describe(ch chan<- *prometheus.Desc) { + for _, desc := range []*prometheus.Desc{readQueueDepth, readInUse, readSlots, duckThreads, duckReadStatements, duckWriteInUse, goRunnable, goRunnablePerCPU, goNotInGo} { + ch <- desc + } +} + +func (readSaturationCollector) Collect(ch chan<- prometheus.Metric) { + gauge := func(desc *prometheus.Desc, value float64, labels ...string) { + ch <- prometheus.MustNewConstMetric(desc, prometheus.GaugeValue, value, labels...) + } + if source := admissionSource.Load(); source != nil { + stats := (*source)() + for path := range ReadPathCount { + gauge(readQueueDepth, float64(stats.Queued[path]), path.String()) + gauge(readInUse, float64(stats.InUse[path]), path.String()) + } + gauge(readSlots, float64(stats.Shared), "shared") + gauge(readSlots, float64(stats.Reserved), "reserved") + } + if source := saturationSource.Load(); source != nil { + stats := (*source)() + gauge(duckThreads, float64(stats.Threads)) + gauge(duckReadStatements, float64(stats.ReadStatements)) + gauge(duckWriteInUse, float64(stats.WriteInUse)) + } + samples := []runtimemetrics.Sample{ + {Name: "/sched/goroutines/runnable:goroutines"}, + {Name: "/sched/goroutines/not-in-go:goroutines"}, + {Name: "/sched/gomaxprocs:threads"}, + } + runtimemetrics.Read(samples) + if samples[0].Value.Kind() == runtimemetrics.KindUint64 { + runnable := float64(samples[0].Value.Uint64()) + gauge(goRunnable, runnable) + if samples[2].Value.Kind() == runtimemetrics.KindUint64 { + gauge(goRunnablePerCPU, runnable/float64(max(1, samples[2].Value.Uint64()))) + } + } + if samples[1].Value.Kind() == runtimemetrics.KindUint64 { + gauge(goNotInGo, float64(samples[1].Value.Uint64())) + } +} diff --git a/internal/query/admission.go b/internal/query/admission.go index 6a299bc7..f512e5de 100644 --- a/internal/query/admission.go +++ b/internal/query/admission.go @@ -2,7 +2,11 @@ package query import ( "context" + "errors" "sync" + "time" + + "github.com/labstack/pitot/internal/metrics" ) type readClass int @@ -13,6 +17,7 @@ const ( ) type readWaiter struct { + path metrics.ReadAdmissionPath ready chan struct{} granted bool weight int @@ -30,10 +35,15 @@ type readAdmission struct { bounds [2]int batches int batchActive int + stats metrics.ReadAdmissionStats } func newReadAdmission(slots, reserved, panelQueue int) *readAdmission { - return &readAdmission{slots: slots, reserved: reserved, bounds: [2]int{panelQueue, 2 * slots}} + return &readAdmission{ + slots: slots, reserved: reserved, + bounds: [2]int{panelQueue, 2 * slots}, + stats: metrics.ReadAdmissionStats{Shared: slots - reserved, Reserved: reserved}, + } } func (a *readAdmission) availableN(class readClass, n int) bool { if a.active[0]+a.active[1]+n > a.slots { @@ -49,13 +59,37 @@ func (a *readAdmission) availableN(class readClass, n int) bool { panels := min(1, demand, a.slots-a.reserved, a.slots-1) return a.active[interactiveClass]+n <= a.slots-panels } -func (a *readAdmission) acquire(ctx context.Context, class readClass) error { - return a.acquireN(ctx, class, 1) +func (a *readAdmission) snapshot() metrics.ReadAdmissionStats { + a.mu.Lock() + defer a.mu.Unlock() + return a.stats } -func (a *readAdmission) acquireN(ctx context.Context, class readClass, n int) error { - return a.acquireWeighted(ctx, class, n, true) + +func admissionOutcome(err error) metrics.ReadAdmissionOutcome { + switch { + case err == nil: + return metrics.ReadAdmitted + case errors.Is(err, errQueueFull): + return metrics.ReadRejected + case errors.Is(err, context.Canceled): + return metrics.ReadCanceled + default: + return metrics.ReadTimeout + } } -func (a *readAdmission) acquireWeighted(ctx context.Context, class readClass, n int, bounded bool) error { + +func readClassFor(path metrics.ReadAdmissionPath) readClass { + if path == metrics.ReadPanel { + return panelClass + } + return interactiveClass +} + +func (a *readAdmission) acquire(ctx context.Context, path metrics.ReadAdmissionPath) error { + return a.acquireWeighted(ctx, path, 1, true) +} +func (a *readAdmission) acquireWeighted(ctx context.Context, path metrics.ReadAdmissionPath, n int, bounded bool) error { + class := readClassFor(path) if err := ctx.Err(); err != nil { return err } @@ -63,6 +97,7 @@ func (a *readAdmission) acquireWeighted(ctx context.Context, class readClass, n a.mu.Lock() if len(a.queues[class]) == 0 && a.availableN(class, n) && (class == interactiveClass || len(a.queues[interactiveClass]) == 0) { a.active[class] += n + a.stats.InUse[path] += n if owned { a.batchActive += n } @@ -73,8 +108,9 @@ func (a *readAdmission) acquireWeighted(ctx context.Context, class readClass, n a.mu.Unlock() return errQueueFull } - w := &readWaiter{ready: make(chan struct{}), weight: n, owned: owned} + w := &readWaiter{path: path, ready: make(chan struct{}), weight: n, owned: owned} a.queues[class] = append(a.queues[class], w) + a.stats.Queued[path]++ a.mu.Unlock() select { case <-w.ready: @@ -83,10 +119,12 @@ func (a *readAdmission) acquireWeighted(ctx context.Context, class readClass, n a.mu.Lock() if w.granted { a.active[class] -= w.weight + a.stats.InUse[path] -= w.weight if w.owned { a.batchActive -= w.weight } } else { + a.stats.Queued[path]-- for i, other := range a.queues[class] { if other == w { a.queues[class] = append(a.queues[class][:i], a.queues[class][i+1:]...) @@ -105,6 +143,8 @@ func (a *readAdmission) wake() { w := a.queues[class][0] a.queues[class] = a.queues[class][1:] a.active[class] += w.weight + a.stats.Queued[w.path]-- + a.stats.InUse[w.path] += w.weight if w.owned { a.batchActive += w.weight } @@ -113,17 +153,19 @@ func (a *readAdmission) wake() { } } } -func (a *readAdmission) release(class readClass) { a.releaseN(class, 1) } -func (a *readAdmission) releaseN(class readClass, n int) { +func (a *readAdmission) release(path metrics.ReadAdmissionPath) { a.releaseN(path, 1) } +func (a *readAdmission) releaseN(path metrics.ReadAdmissionPath, n int) { a.mu.Lock() defer a.mu.Unlock() - a.active[class] -= n + a.active[readClassFor(path)] -= n + a.stats.InUse[path] -= n a.wake() } func (a *readAdmission) releaseOwnedPanel() { a.mu.Lock() defer a.mu.Unlock() a.active[panelClass]-- + a.stats.InUse[metrics.ReadPanel]-- a.batchActive-- a.wake() } @@ -200,6 +242,15 @@ func (b *panelBatchAdmission) admit(ctx context.Context) error { return nil } +// Measure only global slot contention. The local sibling limit has its own +// wait, which is included in the end-to-end panel admission histogram. +func (a *readAdmission) acquirePanel(ctx context.Context, bounded bool) error { + started := time.Now() + err := a.acquireWeighted(ctx, metrics.ReadPanel, 1, bounded) + metrics.RecordReadAdmission(metrics.ReadPanel, admissionOutcome(err), time.Since(started).Seconds()) + return err +} + func (b *panelBatchAdmission) acquire(ctx context.Context) (func(), error) { select { case b.limit <- struct{}{}: @@ -209,12 +260,12 @@ func (b *panelBatchAdmission) acquire(ctx context.Context) (func(), error) { b.mu.Lock() if b.closed && ctx.Value(panelBatchKey{}) != b { b.mu.Unlock() - if err := b.admission.acquire(ctx, panelClass); err != nil { + if err := b.admission.acquirePanel(ctx, true); err != nil { <-b.limit return nil, err } markStarted(ctx) - return func() { b.admission.release(panelClass); <-b.limit }, nil + return func() { b.admission.release(metrics.ReadPanel); <-b.limit }, nil } if !b.ticket { if err := b.admission.reserveBatch(); err != nil { @@ -226,7 +277,7 @@ func (b *panelBatchAdmission) acquire(ctx context.Context) (func(), error) { } b.refs++ b.mu.Unlock() - if err := b.admission.acquireWeighted(ctx, panelClass, 1, false); err != nil { + if err := b.admission.acquirePanel(ctx, false); err != nil { b.mu.Lock() b.refs-- b.releaseTicket() diff --git a/internal/query/admission_test.go b/internal/query/admission_test.go index 70c2af9f..f99899d0 100644 --- a/internal/query/admission_test.go +++ b/internal/query/admission_test.go @@ -4,14 +4,18 @@ import ( "context" "errors" "fmt" + "math" "slices" "sync" "testing" + "testing/synctest" "time" "github.com/labstack/pitot/internal/config" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/observability" "github.com/labstack/pitot/internal/queryrows" + "github.com/prometheus/client_golang/prometheus" ) type pooledEngine struct { @@ -35,7 +39,7 @@ func TestPanelSlotsReserveTwoConnections(t *testing.T) { e := NewExecutor(pooledEngine{pool: 8}, 30) defer e.Close() for range 5 { - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } } @@ -56,7 +60,7 @@ func TestPanelsAreRefusedAtTheQueueBound(t *testing.T) { e.admission = newReadAdmission(1, 0, 8) e.admission.bounds[panelClass] = 1 e.admission.bounds[interactiveClass] = 1 - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } queued := make(chan []Result, 1) @@ -74,11 +78,16 @@ func TestPanelsAreRefusedAtTheQueueBound(t *testing.T) { other := cacheDashboard() other.Panels[0].ID = "other" other.Panels = append(other.Panels, Panel{ID: "third", Title: "Third", Viz: "table", Query: &Spec{From: "spans", Measures: []string{"count()"}}}) + labels := map[string]string{"path": "panel", "status": "rejected"} + before := readAdmissionMetric(t, "requests_total", labels) started := time.Now() _, err := e.Run(t.Context(), RunRequest{Dashboard: other}) if !errors.Is(err, ErrBusy) || time.Since(started) > time.Second { t.Fatalf("err=%v after %s", err, time.Since(started)) } + if got := readAdmissionMetric(t, "requests_total", labels) - before; got != 1 { + t.Errorf("upfront panel rejections = %v, want 1", got) + } // Even a text panel cannot turn a refused refresh into partial success. with := other with.Panels = append(append([]Panel(nil), other.Panels...), Panel{ID: "note", Title: "Note", Viz: "text", Content: "hi"}) @@ -86,7 +95,7 @@ func TestPanelsAreRefusedAtTheQueueBound(t *testing.T) { if !errors.Is(err, ErrBusy) || len(results) != 0 { t.Errorf("results=%+v err=%v", results, err) } - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) if r := <-queued; len(r) != 1 || r[0].Status != StatusOK { t.Fatalf("queued panel=%+v", r) } @@ -105,7 +114,7 @@ func TestExemplarsAndTracesShareAdmission(t *testing.T) { e.admission = newReadAdmission(1, 0, 8) e.admission.bounds[panelClass] = 0 e.admission.bounds[interactiveClass] = 0 - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } req := ExemplarRequest{Dashboard: shopDashboard(), PanelID: "by_route", From: fixtureStart.Add(30 * time.Minute), To: fixtureStart.Add(31 * time.Minute), Dimensions: map[string]string{"attributes['http.route']": "/cart"}} @@ -130,7 +139,7 @@ func TestExemplarsAndTracesShareAdmission(t *testing.T) { if len(e.cache.entries) != 0 { t.Fatal("a busy answer was stored") } - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) if out, err := e.Exemplars(t.Context(), req); err != nil || len(out.Traces) != 1 { t.Fatalf("admitted exemplars=%+v err=%v", out, err) } @@ -145,13 +154,13 @@ func TestExecutorPressureTracksWaitersAndCapacity(t *testing.T) { if e.Pressure() { t.Fatal("idle executor under pressure") } - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } if !e.Pressure() { t.Fatal("full shared executor reported no pressure") } - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) if e.Pressure() { t.Fatal("pressure did not clear") } @@ -160,30 +169,30 @@ func TestExecutorPressureTracksWaitersAndCapacity(t *testing.T) { func TestInteractiveReadsAreAdmittedAheadOfPanels(t *testing.T) { a := newReadAdmission(6, 1, 48) for range 5 { - if err := a.acquire(t.Context(), panelClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } } panels := make(chan struct{}, 48) for range 48 { go func() { - if err := a.acquire(t.Context(), panelClass); err == nil { + if err := a.acquire(t.Context(), metrics.ReadPanel); err == nil { panels <- struct{}{} } }() } waitForReadWaiters(t, a, 48) - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } interactive := make(chan struct{}) go func() { - if err := a.acquire(t.Context(), interactiveClass); err == nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err == nil { close(interactive) } }() waitForReadWaiters(t, a, 49) - a.release(panelClass) + a.release(metrics.ReadPanel) select { case <-interactive: case <-time.After(time.Second): @@ -194,14 +203,14 @@ func TestInteractiveReadsAreAdmittedAheadOfPanels(t *testing.T) { t.Fatal("panel woke before interactive waiter") default: } - a.release(interactiveClass) - a.release(interactiveClass) + a.release(metrics.ReadObservability) + a.release(metrics.ReadObservability) for range 4 { - a.release(panelClass) + a.release(metrics.ReadPanel) } for range 48 { <-panels - a.release(panelClass) + a.release(metrics.ReadPanel) } } @@ -219,14 +228,14 @@ func waitForReadWaiters(t *testing.T, a *readAdmission, n int) { func TestPanelsNeverTakeTheReservedSlot(t *testing.T) { a := newReadAdmission(6, 1, 0) for range 5 { - if err := a.acquire(t.Context(), panelClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } } - if err := a.acquire(t.Context(), panelClass); !errors.Is(err, errQueueFull) { + if err := a.acquire(t.Context(), metrics.ReadPanel); !errors.Is(err, errQueueFull) { t.Fatal(err) } - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } } @@ -234,17 +243,17 @@ func TestPanelsNeverTakeTheReservedSlot(t *testing.T) { func TestInteractiveQueueBoundRefusesFloods(t *testing.T) { a := newReadAdmission(2, 1, 16) for range 2 { - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } } ctx, cancel := context.WithCancel(t.Context()) done := make(chan error, 4) for range 4 { - go func() { done <- a.acquire(ctx, interactiveClass) }() + go func() { done <- a.acquire(ctx, metrics.ReadObservability) }() } waitForReadWaiters(t, a, 4) - if err := a.acquire(t.Context(), interactiveClass); !errors.Is(err, errQueueFull) { + if err := a.acquire(t.Context(), metrics.ReadObservability); !errors.Is(err, errQueueFull) { t.Fatal(err) } cancel() @@ -257,28 +266,42 @@ func TestInteractiveQueueBoundRefusesFloods(t *testing.T) { t.Fatal("canceled waiters leaked") } for range 2 { - a.release(interactiveClass) + a.release(metrics.ReadObservability) } if !a.tryShared() { t.Fatal("cancellation leaked capacity") } } -func TestInteractiveRefusalsIncludeTheExemplarWaitDeadline(t *testing.T) { +func TestCallerDeadlineDoesNotSignalInteractivePressure(t *testing.T) { e := newFixtureExecutor(t) defer e.Close() e.admission = newReadAdmission(1, 0, 8) - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } - defer e.admission.release(panelClass) + defer e.admission.release(metrics.ReadPanel) ctx, cancel := context.WithTimeout(t.Context(), time.Millisecond) defer cancel() - if _, err := e.admit(ctx); !errors.Is(err, context.DeadlineExceeded) { + if _, err := e.admitInteractive(ctx, metrics.ReadExemplars, e.batchTimeout); !errors.Is(err, context.DeadlineExceeded) { t.Fatal(err) } - if e.InteractiveRefusals() != 1 { - t.Fatal("caller-bounded interactive wait was not counted") + if got := e.InteractiveRefusals(); got != 0 { + t.Fatalf("caller deadline signaled %d refusals", got) + } + // Entering with an expired context, even one carrying a slot, makes no attempt. + labels := map[string]string{"path": "exemplars", "status": "canceled"} + before := readAdmissionMetric(t, "requests_total", labels) + for _, expired := range []context.Context{ctx, e.withInteractiveSlot(ctx)} { + if _, err := e.admitInteractive(expired, metrics.ReadExemplars, e.batchTimeout); err != context.DeadlineExceeded { + t.Fatalf("expired context: %v", err) + } + } + if got := readAdmissionMetric(t, "requests_total", labels); got != before || e.InteractiveRefusals() != 0 { + t.Fatal("expired contexts changed admission metrics") + } + if _, err := e.admitInteractive(t.Context(), metrics.ReadExemplars, time.Millisecond); err != ErrBusy || e.InteractiveRefusals() != 1 { + t.Fatalf("own wait deadline: err=%v, refusals=%d", err, e.InteractiveRefusals()) } } @@ -287,7 +310,7 @@ func TestInteractiveRefusalsIncludeTheExemplarWaitDeadline(t *testing.T) { func TestRefreshAdmissionIsAtomicAndLeavesCapacityForOtherReaders(t *testing.T) { a := newReadAdmission(6, 1, 1) for range 5 { - if err := a.acquire(t.Context(), panelClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } } @@ -313,7 +336,7 @@ func TestRefreshAdmissionIsAtomicAndLeavesCapacityForOtherReaders(t *testing.T) } } other.close() - a.releaseN(panelClass, 2) + a.releaseN(metrics.ReadPanel, 2) for range 2 { release := <-done if release == nil { @@ -321,10 +344,10 @@ func TestRefreshAdmissionIsAtomicAndLeavesCapacityForOtherReaders(t *testing.T) } release() } - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } - a.release(interactiveClass) + a.release(metrics.ReadObservability) for range 15 { release, err := b.acquire(t.Context()) if err != nil { @@ -333,7 +356,7 @@ func TestRefreshAdmissionIsAtomicAndLeavesCapacityForOtherReaders(t *testing.T) release() } b.close() - a.releaseN(panelClass, 3) + a.releaseN(metrics.ReadPanel, 3) if !a.tryShared() || a.batches != 0 { t.Fatal("batch leaked its reservation") } @@ -364,7 +387,7 @@ func TestRefreshAdmissionKeepsDetachedFlightsAndReleasesCanceledWaiters(t *testi } release() for range 5 { - if err := a.acquire(t.Context(), panelClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } } @@ -378,7 +401,7 @@ func TestRefreshAdmissionKeepsDetachedFlightsAndReleasesCanceledWaiters(t *testi t.Fatal(err) } c.close() - a.releaseN(panelClass, 5) + a.releaseN(metrics.ReadPanel, 5) if !a.tryShared() || a.batches != 0 { t.Fatal("canceled batch leaked slots or queue") } @@ -386,17 +409,17 @@ func TestRefreshAdmissionKeepsDetachedFlightsAndReleasesCanceledWaiters(t *testi func TestRefreshPressureUsesEveryAvailablePanelSlot(t *testing.T) { a := newReadAdmission(6, 1, 48) - if err := a.acquireN(t.Context(), panelClass, 4); err != nil { + if err := a.acquireWeighted(t.Context(), metrics.ReadPanel, 4, true); err != nil { t.Fatal(err) } if !a.tryShared() { t.Fatal("an available panel slot was stranded by a refresh budget") } - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } - a.release(interactiveClass) - a.releaseN(panelClass, 4) + a.release(metrics.ReadObservability) + a.releaseN(metrics.ReadPanel, 4) if !a.tryShared() { t.Fatal("pressure did not clear") } @@ -415,10 +438,10 @@ func TestRefusedRefreshEmitsNeitherCachedNorTextPanels(t *testing.T) { t.Fatal(err) } e.admission = newReadAdmission(1, 0, 0) - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } - defer e.admission.release(panelClass) + defer e.admission.release(metrics.ReadPanel) sent := 0 err := e.Stream(t.Context(), RunRequest{Dashboard: d}, func(Result) { sent++ }) if !errors.Is(err, ErrBusy) || sent != 0 { @@ -614,7 +637,7 @@ func TestFullRefreshCoalescesWithoutAnotherExecutionTicket(t *testing.T) { func TestRefreshUsesTheLastAvailableGlobalPanelSlot(t *testing.T) { a := newReadAdmission(6, 1, 4) - if err := a.acquireN(t.Context(), panelClass, 4); err != nil { + if err := a.acquireWeighted(t.Context(), metrics.ReadPanel, 4, true); err != nil { t.Fatal(err) } b := newPanelBatchAdmission(a, 2) @@ -630,13 +653,13 @@ func TestRefreshUsesTheLastAvailableGlobalPanelSlot(t *testing.T) { if a.active[panelClass] != 5 { t.Fatalf("active panels=%d", a.active[panelClass]) } - if err := a.acquire(ctx, interactiveClass); err != nil { + if err := a.acquire(ctx, metrics.ReadObservability); err != nil { t.Fatal(err) } - a.release(interactiveClass) + a.release(metrics.ReadObservability) release() b.close() - a.releaseN(panelClass, 4) + a.releaseN(metrics.ReadPanel, 4) if a.batchActive != 0 || a.batches != 0 || !a.tryShared() { t.Fatal("refresh leaked capacity") } @@ -645,7 +668,7 @@ func TestRefreshUsesTheLastAvailableGlobalPanelSlot(t *testing.T) { func TestInteractiveBorrowingRetainsPanelProgressAndLendsIdleSlots(t *testing.T) { a := newReadAdmission(6, 1, 4) for range 6 { - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } } @@ -667,14 +690,14 @@ func TestInteractiveBorrowingRetainsPanelProgressAndLendsIdleSlots(t *testing.T) } waitForReadWaiters(t, a, 2) interactive := make(chan error, 1) - go func() { interactive <- a.acquire(ctx, interactiveClass) }() + go func() { interactive <- a.acquire(ctx, metrics.ReadObservability) }() waitForReadWaiters(t, a, 3) - a.release(interactiveClass) + a.release(metrics.ReadObservability) first := <-panels if first == nil { t.Fatal("interactive borrowing stranded panels") } - a.release(interactiveClass) + a.release(metrics.ReadObservability) if err := <-interactive; err != nil { t.Fatal(err) } @@ -691,7 +714,7 @@ func TestInteractiveBorrowingRetainsPanelProgressAndLendsIdleSlots(t *testing.T) second() b.close() for range 5 { - a.release(interactiveClass) + a.release(metrics.ReadObservability) } if !a.tryShared() || a.batches != 0 || a.batchActive != 0 { t.Fatal("reservation leaked capacity") @@ -702,20 +725,20 @@ func TestInteractiveBorrowingRetainsPanelProgressAndLendsIdleSlots(t *testing.T) // queued drill-down from borrowing the next released connection. func TestPanelProgressDoesNotStarveInteractiveReplacement(t *testing.T) { a := newReadAdmission(3, 1, 4) - if err := a.acquireN(t.Context(), panelClass, 2); err != nil { + if err := a.acquireWeighted(t.Context(), metrics.ReadPanel, 2, true); err != nil { t.Fatal(err) } - if err := a.acquire(t.Context(), interactiveClass); err != nil { + if err := a.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } ctx, cancel := context.WithTimeout(t.Context(), time.Second) defer cancel() interactive := make(chan error, 1) panel := make(chan error, 1) - go func() { interactive <- a.acquire(ctx, interactiveClass) }() - go func() { panel <- a.acquire(ctx, panelClass) }() + go func() { interactive <- a.acquire(ctx, metrics.ReadObservability) }() + go func() { panel <- a.acquire(ctx, metrics.ReadPanel) }() waitForReadWaiters(t, a, 2) - a.release(panelClass) + a.release(metrics.ReadPanel) select { case err := <-interactive: if err != nil { @@ -729,10 +752,124 @@ func TestPanelProgressDoesNotStarveInteractiveReplacement(t *testing.T) { t.Fatal("panel displaced interactive read while another panel was running") default: } - a.release(panelClass) + a.release(metrics.ReadPanel) if err := <-panel; err != nil { t.Fatal(err) } - a.release(panelClass) - a.releaseN(interactiveClass, 2) + a.release(metrics.ReadPanel) + a.releaseN(metrics.ReadObservability, 2) +} + +// Collect through the process registry so these checks exercise production +// source installation, label spelling and the scheduler's own bookkeeping. +func readAdmissionMetric(t *testing.T, name string, labels map[string]string) float64 { + t.Helper() + families, err := prometheus.DefaultGatherer.Gather() + if err != nil { + t.Fatal(err) + } + for _, family := range families { + if family.GetName() != "pitot_read_admission_"+name { + continue + } + for _, sample := range family.Metric { + if len(sample.Label) != len(labels) { + continue + } + match := true + for _, l := range sample.Label { + if labels[l.GetName()] != l.GetValue() { + match = false + break + } + } + if match { + if sample.Counter != nil { + return sample.Counter.GetValue() + } + if sample.Histogram != nil { + return sample.Histogram.GetSampleSum() + } + return sample.Gauge.GetValue() + } + } + } + return 0 +} + +func TestReadAdmissionGaugesFollowQueuedAndHeldSlots(t *testing.T) { + old := NewExecutor(pooledEngine{pool: 8}, 30) + e := NewExecutor(pooledEngine{pool: 8}, 30) + e.admission = newReadAdmission(1, 0, 0) + defer e.Close() + old.Close() + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + release, err := e.admitInteractive(ctx, metrics.ReadSchema, e.batchTimeout) + if err != nil { + t.Fatal(err) + } + done := make(chan error, 1) + go func() { _, err := e.admitInteractive(ctx, metrics.ReadVariables, e.batchTimeout); done <- err }() + waitForReadWaiters(t, e.admission, 1) + check := func(name, key, value string, want float64) { + t.Helper() + if got := readAdmissionMetric(t, name, map[string]string{key: value}); got != want { + t.Errorf("%s{%s=%s} = %v, want %v", name, key, value, got, want) + } + } + check("slots", "class", "shared", 1) + check("in_use", "path", "schema", 1) + check("queue_depth", "path", "variables", 1) + cancel() + if err := <-done; err != context.Canceled { + t.Fatalf("canceled waiter: %v", err) + } + release() + check("queue_depth", "path", "variables", 0) + check("in_use", "path", "schema", 0) +} + +func TestPanelAdmissionWaitExcludesSiblingExecution(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + a := newReadAdmission(1, 0, 1) + b := newPanelBatchAdmission(a, 1) + if err := b.admit(t.Context()); err != nil { + t.Fatal(err) + } + defer b.close() + labels := map[string]string{"path": "panel", "status": "admitted"} + before := readAdmissionMetric(t, "wait_seconds", labels) + first, err := b.acquire(t.Context()) + if err != nil { + t.Fatal(err) + } + second := make(chan error, 1) + go func() { + release, err := b.acquire(t.Context()) + if err == nil { + release() + } + second <- err + }() + // The sibling waits locally for two seconds. Queue a competing read to + // occupy the global slot for one more second after the first panel. + time.Sleep(2 * time.Second) + click := make(chan error, 1) + go func() { click <- a.acquire(t.Context(), metrics.ReadObservability) }() + synctest.Wait() + first() + if err := <-click; err != nil { + t.Fatal(err) + } + synctest.Wait() + time.Sleep(time.Second) + a.release(metrics.ReadObservability) + if err := <-second; err != nil { + t.Fatal(err) + } + if got := readAdmissionMetric(t, "wait_seconds", labels) - before; math.Abs(got-1) > 1e-9 { + t.Fatalf("global panel wait = %gs, want 1s", got) + } + }) } diff --git a/internal/query/admit_reader.go b/internal/query/admit_reader.go index c8b27311..9fb93421 100644 --- a/internal/query/admit_reader.go +++ b/internal/query/admit_reader.go @@ -2,46 +2,51 @@ package query import ( "context" - "errors" "sync" + "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" ) -// AdmitReader wraps a read surface so every read it issues passes through the -// interactive admission lane. The observability readers, annotations, and -// variable-option queries otherwise call the engine directly and compete for -// the read pool without being admitted, so a saturating dashboard oversubscribes -// the pool, starves admitted panels, and defeats the deadline shedding the pool -// size is meant to enforce. Routing those reads through admission restores the -// invariant that no more reads run concurrently than the pool can serve, and -// turns excess load into a bounded ErrBusy shed rather than unbounded queueing -// inside the engine. -// -// The admission slot is held for the lifetime of the returned rows and released -// when they close, mirroring how the engine holds a pool connection until its -// rows close. Callers already close every result set before issuing the next -// read, so one interactive slot is never held across acquiring another. -func (e *Executor) AdmitReader(inner queryrows.Queryer) queryrows.Queryer { - return &admittingQueryer{inner: inner, exec: e} +// AdmitReader routes reads through the interactive lane. Each result holds its +// slot until the caller exhausts or closes its rows. +func (e *Executor) AdmitReader(inner queryrows.Queryer, path metrics.ReadAdmissionPath) queryrows.Queryer { + return &admittingQueryer{inner: inner, exec: e, path: path} } type admittingQueryer struct { + path metrics.ReadAdmissionPath inner queryrows.Queryer exec *Executor } +// Annotation reads carry a ten-second transaction deadline. Shed a queued +// request with time left for that deadline to distinguish execution failures. +func (a *admittingQueryer) waitBudget() time.Duration { + if a.path == metrics.ReadAnnotations { + return min(a.exec.batchTimeout, 5*time.Second) + } + return a.exec.batchTimeout +} + func (a *admittingQueryer) QueryContext(ctx context.Context, query string, args ...any) (queryrows.Rows, error) { - release, err := a.exec.admitInteractive(ctx) + release, err := a.exec.admitInteractive(ctx, a.path, a.waitBudget()) if err != nil { return nil, err } + handedOff := false + defer func() { + if !handedOff { + release() + } + }() rows, err := a.inner.QueryContext(ctx, query, args...) if err != nil { - release() return nil, err } + handedOff = true return &admittedRows{Rows: rows, release: release}, nil } @@ -56,12 +61,25 @@ func (a *admittingQueryer) WithReadTransaction(ctx context.Context, read func(qu if !ok { return read(a) } - release, err := a.exec.admitInteractive(ctx) + release, err := a.exec.admitInteractive(ctx, a.path, a.waitBudget()) if err != nil { return err } defer release() - return rt.WithReadTransaction(ctx, read) + return rt.WithReadTransaction(a.exec.withInteractiveSlot(ctx), func(db queryrows.Queryer) error { + return read(transactionReader{db: db, exec: a.exec}) + }) +} + +// The transaction callback supplies its own query contexts. Preserve their +// cancellation and values while forwarding the transaction's slot ownership. +type transactionReader struct { + db queryrows.Queryer + exec *Executor +} + +func (r transactionReader) QueryContext(ctx context.Context, query string, args ...any) (queryrows.Rows, error) { + return r.db.QueryContext(r.exec.withInteractiveSlot(ctx), query, args...) } // DefaultNamespace forwards to the wrapped surface when it exposes one, matching @@ -94,7 +112,7 @@ type admittingTraces struct { } func (a admittingTraces) TraceDetail(ctx context.Context, query telemetry.TraceQuery) (telemetry.TraceDetail, error) { - release, err := a.exec.admitInteractive(ctx) + release, err := a.exec.admitInteractive(ctx, metrics.ReadTraceDetail, a.exec.batchTimeout) if err != nil { return telemetry.TraceDetail{}, err } @@ -102,35 +120,42 @@ func (a admittingTraces) TraceDetail(ctx context.Context, query telemetry.TraceQ return a.inner.TraceDetail(ctx, query) } -// admitInteractive takes one interactive slot, bounding the wait by the batch -// timeout as the exemplar and trace-detail path does, so a deadline-less caller -// (a background or MCP read) cannot sit in the bounded queue indefinitely. A -// full queue or an expired wait is counted as an interactive refusal and -// returned as ErrBusy, except when the caller's own context ended first. These -// refusals share the executor's interactive-pressure counter, so a flood of -// routed observability or annotation reads also feeds ingest backpressure — -// intended, since interactive read starvation is exactly when ingest should -// yield. -func (e *Executor) admitInteractive(ctx context.Context) (func(), error) { - wait, cancel := context.WithTimeout(ctx, e.batchTimeout) +type interactiveSlotKey struct{} + +// Only sequential work within the owning executor may inherit its slot. +func (e *Executor) withInteractiveSlot(ctx context.Context) context.Context { + return context.WithValue(ctx, interactiveSlotKey{}, e) +} + +// Only a full queue or an exhausted admission budget signals read pressure +// to the ingest writer. A caller can run out of execution time on an idle pool. +func (e *Executor) admitInteractive(ctx context.Context, path metrics.ReadAdmissionPath, waitBudget time.Duration) (func(), error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if ctx.Value(interactiveSlotKey{}) == e { + return func() {}, nil + } + started := time.Now() + wait, cancel := context.WithTimeout(ctx, waitBudget) defer cancel() - err := e.acquireClass(wait, interactiveClass) - if errors.Is(err, errQueueFull) || errors.Is(err, context.DeadlineExceeded) { - e.interactiveRefusals.Add(1) + err := e.admission.acquire(wait, path) + elapsed := time.Since(started).Seconds() + if err == nil { + metrics.RecordReadAdmission(path, metrics.ReadAdmitted, elapsed) + markStarted(ctx) + return func() { e.admission.release(path) }, nil } - switch { - case err == nil: - return func() { e.admission.release(interactiveClass) }, nil - case ctx.Err() != nil: - return nil, ctx.Err() - default: - return nil, ErrBusy + if callerErr := ctx.Err(); callerErr != nil { + metrics.RecordReadAdmission(path, metrics.ReadCanceled, elapsed) + return nil, callerErr } + metrics.RecordReadAdmission(path, admissionOutcome(err), elapsed) + e.interactiveRefusals.Add(1) + return nil, ErrBusy } -// admittedRows releases the admission slot when the wrapped rows close. Close is -// idempotent, so a double close or a close after exhaustion releases the slot -// exactly once. +// admittedRows releases its slot once, at exhaustion or close. type admittedRows struct { queryrows.Rows release func() @@ -138,7 +163,14 @@ type admittedRows struct { } func (r *admittedRows) Close() error { - err := r.Rows.Close() - r.once.Do(r.release) - return err + defer r.once.Do(r.release) + return r.Rows.Close() +} + +func (r *admittedRows) Next() bool { + ok := r.Rows.Next() + if !ok { + r.once.Do(r.release) + } + return ok } diff --git a/internal/query/admit_reader_test.go b/internal/query/admit_reader_test.go index 047d581a..515e4ab6 100644 --- a/internal/query/admit_reader_test.go +++ b/internal/query/admit_reader_test.go @@ -4,8 +4,11 @@ import ( "context" "errors" "testing" + "testing/synctest" "time" + "github.com/labstack/pitot/internal/annotations" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" ) @@ -54,7 +57,7 @@ func newAdmissionFixture(t *testing.T, slots, reserved, queue int) *Executor { func TestAdmittedReaderHoldsItsSlotUntilRowsClose(t *testing.T) { e := newAdmissionFixture(t, 1, 0, 4) closed := false - reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: &closed}}) + reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: &closed}}, metrics.ReadObservability) rows, err := reader.QueryContext(t.Context(), "SELECT 1") if err != nil { t.Fatal(err) @@ -78,7 +81,7 @@ func TestAdmittedReaderHoldsItsSlotUntilRowsClose(t *testing.T) { func TestAdmittedReaderReleasesItsSlotOnceOnDoubleClose(t *testing.T) { e := newAdmissionFixture(t, 2, 0, 4) closed := false - reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: &closed}}) + reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: &closed}}, metrics.ReadObservability) rows, err := reader.QueryContext(t.Context(), "SELECT 1") if err != nil { t.Fatal(err) @@ -95,11 +98,11 @@ func TestAdmittedReaderReleasesItsSlotOnceOnDoubleClose(t *testing.T) { func TestAdmittedReaderShedsWhenTheLaneIsFull(t *testing.T) { e := newAdmissionFixture(t, 1, 0, 1) e.admission.bounds[interactiveClass] = 0 - if err := e.admission.acquire(t.Context(), interactiveClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } queried := false - reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: new(bool)}, queried: &queried}) + reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: new(bool)}, queried: &queried}, metrics.ReadObservability) ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond) defer cancel() rows, err := reader.QueryContext(ctx, "SELECT 1") @@ -123,7 +126,7 @@ func TestAdmittedReaderShedsWhenTheLaneIsFull(t *testing.T) { func TestAdmittedReadTransactionTakesOneSlotForTheWholeCallback(t *testing.T) { e := newAdmissionFixture(t, 1, 0, 4) ran := false - reader := e.AdmitReader(fakeReader{txRan: &ran}).(queryrows.ReadTransactioner) + reader := e.AdmitReader(fakeReader{txRan: &ran}, metrics.ReadObservability).(queryrows.ReadTransactioner) err := reader.WithReadTransaction(t.Context(), func(queryrows.Queryer) error { if e.admission.active[interactiveClass] != 1 { t.Fatalf("slot not held during the callback: active=%d", e.admission.active[interactiveClass]) @@ -145,7 +148,7 @@ func TestAdmittedReadTransactionTakesOneSlotForTheWholeCallback(t *testing.T) { // probe through an optional interface. func TestAdmittedReaderForwardsTheDefaultNamespace(t *testing.T) { e := newAdmissionFixture(t, 1, 0, 4) - reader := e.AdmitReader(fakeReader{namespace: "edge"}) + reader := e.AdmitReader(fakeReader{namespace: "edge"}, metrics.ReadObservability) ns, ok := reader.(interface{ DefaultNamespace() string }) if !ok { t.Fatal("wrapper does not expose DefaultNamespace") @@ -178,7 +181,7 @@ func TestAdmittedTraceDetailHoldsOneSlotAndSheds(t *testing.T) { t.Fatalf("slot not released: active=%d", e.admission.active[interactiveClass]) } e.admission.bounds[interactiveClass] = 0 - if err := e.admission.acquire(t.Context(), interactiveClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadObservability); err != nil { t.Fatal(err) } shed := e.AdmitTraceDetail(fakeTraceDetail{read: func() { t.Fatal("read ran on a shed trace") }}) @@ -188,3 +191,136 @@ func TestAdmittedTraceDetailHoldsOneSlotAndSheds(t *testing.T) { t.Fatalf("err=%v, want ErrBusy", err) } } + +func TestVariableOptionsAndServiceGuidanceShedWhenReadSlotsAreBusy(t *testing.T) { + fixture := newFixtureExecutor(t) + e := NewExecutor(pooledEngine{Engine: fixture.engine, pool: 1}, 30) + t.Cleanup(e.Close) + e.now = fixture.now + e.batchTimeout = 10 * time.Millisecond + release, err := e.admitInteractive(t.Context(), metrics.ReadAnnotations, e.batchTimeout) + if err != nil { + t.Fatal(err) + } + defer release() + d := shopDashboard() + d.Variables[0].Default = "" + for name, read := range map[string]func() error{ + "resolve variables": func() error { _, err := e.ResolveVariables(t.Context(), ResolveRequest{Dashboard: d}); return err }, + "panel variables": func() error { _, err := e.Run(t.Context(), RunRequest{Dashboard: d}); return err }, + "service guidance": func() error { + _, err := e.ServiceGuidance(t.Context(), fixtureStart, e.now(), "", "checkout") + return err + }, + } { + if err := read(); !errors.Is(err, ErrBusy) { + t.Errorf("%s: got %v, want ErrBusy", name, err) + } + } +} + +type queryFunc func(context.Context, string, ...any) (queryrows.Rows, error) + +func (q queryFunc) QueryContext(ctx context.Context, sql string, args ...any) (queryrows.Rows, error) { + return q(ctx, sql, args...) +} + +type panicCloseRows struct{ fakeRows } + +func (panicCloseRows) Close() error { panic("close") } + +func TestInteractiveSlotSurvivesSetupAndClosePanics(t *testing.T) { + e := newAdmissionFixture(t, 1, 0, 0) + for _, stage := range []string{"setup", "close"} { + func() { + defer func() { + if got := recover(); got != stage { + t.Fatalf("panic = %v, want %s", got, stage) + } + }() + reader := e.AdmitReader(queryFunc(func(context.Context, string, ...any) (queryrows.Rows, error) { + if stage == "setup" { + panic(stage) + } + return panicCloseRows{}, nil + }), metrics.ReadSchema) + rows, err := reader.QueryContext(t.Context(), "SELECT 1") + if err != nil { + t.Fatal(err) + } + _ = rows.Close() + }() + if got := e.admission.snapshot().InUse[metrics.ReadSchema]; got != 0 { + t.Fatalf("%s panic left %d slots in use", stage, got) + } + } +} + +func TestExhaustedRowsReleaseInteractiveSlotBeforeClose(t *testing.T) { + e := newAdmissionFixture(t, 1, 0, 0) + reader := e.AdmitReader(fakeReader{rows: fakeRows{closed: new(bool)}}, metrics.ReadVariables) + rows, err := reader.QueryContext(t.Context(), "SELECT 1") + if err != nil { + t.Fatal(err) + } + if rows.Next() || e.admission.snapshot().InUse[metrics.ReadVariables] != 0 { + t.Fatal("exhausted rows kept the slot") + } + _ = rows.Close() + if e.admission.snapshot().InUse[metrics.ReadVariables] != 0 { + t.Fatal("slot released twice") + } +} + +type nestedTransaction struct { + fakeReader + db queryrows.Queryer +} + +func (n nestedTransaction) WithReadTransaction(_ context.Context, read func(queryrows.Queryer) error) error { + return read(n.db) +} + +func TestTransactionQueriesInheritSlotWithCallerContext(t *testing.T) { + e := newAdmissionFixture(t, 1, 0, 0) + e.batchTimeout = 10 * time.Millisecond + q := e.AdmitReader(fakeReader{rows: fakeRows{closed: new(bool)}}, metrics.ReadAnnotations) + rt := e.AdmitReader(nestedTransaction{db: q}, metrics.ReadAnnotations).(queryrows.ReadTransactioner) + ctx := t.Context() + err := rt.WithReadTransaction(ctx, func(db queryrows.Queryer) error { + rows, err := db.QueryContext(ctx, "SELECT 1") + if err != nil { + return err + } + return rows.Close() + }) + if err != nil || e.InteractiveRefusals() != 0 { + t.Fatalf("nested statement: %v, refusals=%d", err, e.InteractiveRefusals()) + } +} + +func TestSaturatedGuidanceAndAnnotationsReturnBusyWithDefaultDeadlines(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + e := newAdmissionFixture(t, 1, 0, 0) + ctx := t.Context() + if err := e.admission.acquire(ctx, metrics.ReadPanel); err != nil { + t.Fatal(err) + } + defer e.admission.release(metrics.ReadPanel) + end := time.Now() + start := end.Add(-time.Hour) + reader := annotations.New(e.AdmitReader(fakeReader{}, metrics.ReadAnnotations)) + if _, err := reader.Read(ctx, annotations.Request{From: start, To: end}); err != ErrBusy { + t.Fatalf("annotations: %v", err) + } + if _, err := e.ServiceGuidance(ctx, start, end, "", "checkout"); err != ErrBusy { + t.Fatalf("service guidance: %v", err) + } + if _, _, err := e.EmptyGuidance(ctx, RunRequest{Dashboard: shopDashboard()}); err != ErrBusy { + t.Fatalf("empty guidance: %v", err) + } + if got := e.InteractiveRefusals(); got != 3 { + t.Fatalf("refusals=%d, want 3", got) + } + }) +} diff --git a/internal/query/check.go b/internal/query/check.go index 03210c23..fe1a7db8 100644 --- a/internal/query/check.go +++ b/internal/query/check.go @@ -46,7 +46,7 @@ type checkedPanelSQL struct { // (cancellation, deadline, interrupt, closed database) rather than a fault in // the spec. The engine reports a cancelled query as a bare interrupt. func isOperational(err error) bool { - if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || + if errors.Is(err, ErrBusy) || errors.Is(err, ErrSchemaBusy) || errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, sql.ErrConnDone) || (err != nil && strings.Contains(err.Error(), "database is closed")) { return true } diff --git a/internal/query/diagnose_admission_test.go b/internal/query/diagnose_admission_test.go index f8af31d8..f70a56d0 100644 --- a/internal/query/diagnose_admission_test.go +++ b/internal/query/diagnose_admission_test.go @@ -7,6 +7,7 @@ import ( "testing" "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" ) @@ -81,12 +82,12 @@ func TestDiagnosisPressureDecisionSurvivesQueueDraining(t *testing.T) { e.admission = newReadAdmission(1, 0, 8) ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() - if err := e.admission.acquire(ctx, panelClass); err != nil { + if err := e.admission.acquire(ctx, metrics.ReadPanel); err != nil { t.Fatal(err) } // Work from another request is already queued when this batch arrives. other := make(chan error, 1) - go func() { other <- e.admission.acquire(ctx, panelClass) }() + go func() { other <- e.admission.acquire(ctx, metrics.ReadPanel) }() waitForReadWaiters(t, e.admission, 1) done := make(chan []Result, 1) go func() { @@ -97,11 +98,11 @@ func TestDiagnosisPressureDecisionSurvivesQueueDraining(t *testing.T) { done <- results }() waitForReadWaiters(t, e.admission, 2) - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) if err := <-other; err != nil { t.Fatal(err) } - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) results := <-done if len(results) != 1 { t.Fatalf("results=%+v", results) diff --git a/internal/query/exec.go b/internal/query/exec.go index ab637f55..2b176a89 100644 --- a/internal/query/exec.go +++ b/internal/query/exec.go @@ -83,16 +83,17 @@ type Result struct { } type Executor struct { - engine Engine - sqlPanels map[string]sqlPanelPlan - rollups RollupReader - maxWindow time.Duration - now func() time.Time - timeout time.Duration - batchTimeout time.Duration - parallel int - admission *readAdmission - interactiveRefusals atomic.Uint64 + engine Engine + sqlPanels map[string]sqlPanelPlan + rollups RollupReader + maxWindow time.Duration + now func() time.Time + timeout time.Duration + batchTimeout time.Duration + parallel int + admission *readAdmission + interactiveRefusals atomic.Uint64 + releaseAdmissionSource func() memo checkMemo cache resultCache @@ -125,9 +126,12 @@ func NewExecutor(engine Engine, retentionDays int) *Executor { slots, reserved, queue = config.QueryAdmission(pool.ReadConnections()) } life, stop := context.WithCancel(context.Background()) - return &Executor{engine: engine, maxWindow: maxWindow, now: time.Now, timeout: defaultPanelTimeout, batchTimeout: defaultBatchTimeout, parallel: 4, - admission: newReadAdmission(slots, reserved, queue), cache: newResultCache(), checks: map[[32]byte]*Checked{}, schemas: map[string]schemaEntry{}, + e := &Executor{engine: engine, maxWindow: maxWindow, now: time.Now, timeout: defaultPanelTimeout, batchTimeout: defaultBatchTimeout, parallel: 4, + admission: newReadAdmission(slots, reserved, queue), + cache: newResultCache(), checks: map[[32]byte]*Checked{}, schemas: map[string]schemaEntry{}, life: life, stop: stop, discoveries: make(chan struct{}, 2), discoverWait: time.Minute, discoverRun: 25 * time.Second} + e.releaseAdmissionSource = metrics.SetReadAdmissionSource(func() metrics.ReadAdmissionStats { return e.admission.snapshot() }) + return e } // Close cancels the schema discoveries still running and waits for them to @@ -137,6 +141,7 @@ func (e *Executor) Close() { e.stop() e.mu.Unlock() e.running.Wait() + e.releaseAdmissionSource() } // Pressure reports queued reads or a fully occupied admission pool. @@ -353,7 +358,15 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul if err != nil { return Problems{{Path: "time", Message: err.Error()}} } - vars, err := e.values(ctx, &d, checked, start, end, req.Vars) + dataPanels := 0 + needed := map[string]bool{} + for _, p := range targets { + if len(invalid[p]) == 0 && p.Viz != "text" { + dataPanels++ + checked.addPanelVariables(p.ID, needed) + } + } + vars, err := e.values(ctx, &d, checked, start, end, req.Vars, needed) if err != nil { return batchError(err) } @@ -389,7 +402,10 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul deferDiagnosis := e.admission.waiting() > 0 var group errgroup.Group batch := newPanelBatchAdmission(e.admission, min(e.parallel, 2, validCount)) + started := time.Now() if err := batch.admit(ctx); err != nil { + waitSeconds := time.Since(started).Seconds() + missing := dataPanels batch.close() if errors.Is(err, errQueueFull) { // An entirely cached/text refresh needs no execution ticket. Pin all @@ -400,12 +416,11 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul continue } key, keyErr := e.buildPanelCacheKey(p, checked, t, now, vars, req.Widths[p.ID], compare) - if keyErr != nil { - return ErrBusy - } - lookups = append(lookups, panelCacheLookup{key: key, id: p.ID, fixedWindow: t.From != nil && t.To != nil}) + lookups = append(lookups, panelCacheLookup{key: key, id: p.ID, uncacheable: keyErr != nil, fixedWindow: t.From != nil && t.To != nil}) } - if results, available, snapshotErr := e.availablePanels(caller, lookups, now); available { + results, unavailable, snapshotErr := e.availablePanels(caller, lookups, now) + missing = unavailable + if missing == 0 { if snapshotErr != nil { return snapshotErr } @@ -428,6 +443,9 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul return nil } } + for range missing { + metrics.RecordReadAdmission(metrics.ReadPanel, admissionOutcome(err), waitSeconds) + } if errors.Is(err, errQueueFull) || errors.Is(err, context.DeadlineExceeded) { return ErrBusy } @@ -470,16 +488,9 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul // The refresh already owns its lease; siblings wait locally. admissionStarted := time.Now() release, admissionErr := batch.acquire(run) - admissionStatus := "admitted" - switch { - case errors.Is(admissionErr, errQueueFull): - admissionStatus = "rejected" - case errors.Is(admissionErr, context.Canceled): - admissionStatus = "canceled" - case admissionErr != nil: - admissionStatus = "timeout" - } - metrics.RecordPanelAdmission(p.ID, admissionStatus, time.Since(admissionStarted).Seconds()) + status := admissionOutcome(admissionErr) + wait := time.Since(admissionStarted).Seconds() + metrics.RecordPanelAdmission(p.ID, string(status), wait) if admissionErr != nil { return panelOutcome{}, 0, false, admissionErr } @@ -520,40 +531,11 @@ func (e *Executor) run(ctx context.Context, req RunRequest, emit func(int, Resul return nil } -func (e *Executor) acquireClass(ctx context.Context, class readClass) error { - if err := e.admission.acquire(ctx, class); err != nil { - return err - } - markStarted(ctx) - return nil -} - // InteractiveRefusals counts interactive requests refused before execution. func (e *Executor) InteractiveRefusals() uint64 { return e.interactiveRefusals.Load() } var errQueueFull = errors.New("panel queue is full") -// admit takes a read slot for an exemplar or trace-detail run, which waits -// in a reserved, priority lane, so a flood of them is turned away -// as busy instead of holding the engine. The wait is bounded by the batch -// deadline; a full queue or a wait that outlasts it is ErrBusy. -func (e *Executor) admit(ctx context.Context) (release func(), err error) { - wait, cancel := context.WithTimeout(ctx, e.batchTimeout) - defer cancel() - err = e.acquireClass(wait, interactiveClass) - if errors.Is(err, errQueueFull) || errors.Is(err, context.DeadlineExceeded) { - e.interactiveRefusals.Add(1) - } - switch { - case err == nil: - return func() { e.admission.release(interactiveClass) }, nil - case ctx.Err() != nil: - return nil, ctx.Err() - default: - return nil, ErrBusy - } -} - // ErrBusy answers a request turned away before it started: every panel of a // batch, an exemplar or a trace-detail read refused at the queue bound or // left waiting past the batch deadline. HTTP answers it 503 with diff --git a/internal/query/exemplars.go b/internal/query/exemplars.go index 9cf224af..58b48205 100644 --- a/internal/query/exemplars.go +++ b/internal/query/exemplars.go @@ -2,7 +2,6 @@ package query import ( "context" - "errors" "fmt" "log/slog" "math" @@ -100,15 +99,10 @@ func (e *Executor) Exemplars(ctx context.Context, req ExemplarRequest) (Exemplar Kind string `json:"kind"` Request ExemplarRequest `json:"request"` }{"exemplars", req}) - if err != nil { - return e.exemplars(ctx, req, now) - } - out, _, err := loadCached(e, ctx, key, now, func(run context.Context) (ExemplarResponse, int64, bool, error) { + read := func(run context.Context) (ExemplarResponse, int64, bool, error) { // Leave room for execution and the response inside the 15s client bound. started := time.Now() - wait, cancel := context.WithTimeout(run, 2*time.Second) - release, err := e.admit(wait) - cancel() + release, err := e.admitInteractive(run, metrics.ReadExemplars, 2*time.Second) stages := &drilldownStages{admission: time.Since(started)} metrics.RecordDrilldownStage("admission", stages.admission.Seconds()) // Slow requests are logged however they end, including a slow @@ -126,16 +120,18 @@ func (e *Executor) Exemplars(ctx context.Context, req ExemplarRequest) (Exemplar } }() if err != nil { - if run.Err() == nil && errors.Is(err, context.DeadlineExceeded) { - err = ErrBusy - } return ExemplarResponse{Traces: []Exemplar{}}, 0, false, err } defer release() - out, err = e.exemplars(context.WithValue(run, drilldownStagesKey{}, stages), req, now) + out, err = e.exemplars(context.WithValue(e.withInteractiveSlot(run), drilldownStagesKey{}, stages), req, now) size := int64(256+len(out.Traces)*256) + out.Logs.size() return out, size, err == nil, err - }) + } + if err != nil { + out, _, _, err := read(ctx) + return out, err + } + out, _, err := loadCached(e, ctx, key, now, read) if err != nil { return ExemplarResponse{Traces: []Exemplar{}}, err } @@ -196,7 +192,7 @@ func (e *Executor) exemplars(ctx context.Context, req ExemplarRequest, now time. if !lo.Before(hi) { return out, outsideSelection() } - vars, err := e.values(ctx, &d, checked, start, end, req.Vars) + vars, err := e.values(ctx, &d, checked, start, end, req.Vars, nil) if err != nil { return out, err } diff --git a/internal/query/exemplars_test.go b/internal/query/exemplars_test.go index 59ba9a44..3944f643 100644 --- a/internal/query/exemplars_test.go +++ b/internal/query/exemplars_test.go @@ -8,6 +8,27 @@ import ( "time" ) +func TestExemplarsResolveQueryVariablesWithOneSlot(t *testing.T) { + duck, repo := newTestEngineWithPool(t, 1) + commit(t, repo, shopSpans(), nil) + e := NewExecutor(duck, 30) + t.Cleanup(e.Close) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + e.batchTimeout = 100 * time.Millisecond + d := shopDashboard() + d.Variables[0].Default = "" + req := ExemplarRequest{Dashboard: d, PanelID: "by_route", From: fixtureStart, To: e.now()} + options := map[string]string{"path": "variables", "status": "admitted"} + before := readAdmissionMetric(t, "requests_total", options) + got, err := e.Exemplars(t.Context(), req) + if got := readAdmissionMetric(t, "requests_total", options) - before; got != 0 { + t.Errorf("nested variable admissions = %v, want 0", got) + } + if err != nil || len(got.Traces) == 0 { + t.Fatalf("exemplars with a resolved service: %v, %d traces", err, len(got.Traces)) + } +} + func TestExemplarsCheckedScope(t *testing.T) { e := newFixtureExecutor(t) req := ExemplarRequest{Dashboard: shopDashboard(), PanelID: "by_route", From: fixtureStart.Add(30 * time.Minute), To: fixtureStart.Add(31 * time.Minute), Dimensions: map[string]string{"attributes['http.route']": "/cart"}} diff --git a/internal/query/frame_semantics_test.go b/internal/query/frame_semantics_test.go index b1e5efcb..e0e3c0cc 100644 --- a/internal/query/frame_semantics_test.go +++ b/internal/query/frame_semantics_test.go @@ -139,7 +139,7 @@ func TestSingleEmptySelectionFallsBack(t *testing.T) { if err != nil { t.Fatal(err) } - values, err := e.values(t.Context(), &d, checked, fixtureStart, fixtureStart.Add(time.Hour), given) + values, err := e.values(t.Context(), &d, checked, fixtureStart, fixtureStart.Add(time.Hour), given, nil) if err != nil { t.Fatal(err) } diff --git a/internal/query/result_cache.go b/internal/query/result_cache.go index f7d71078..8496cf0a 100644 --- a/internal/query/result_cache.go +++ b/internal/query/result_cache.go @@ -257,13 +257,14 @@ func (c *resultCache) leave(flight *cacheFlight) { type panelCacheLookup struct { key cacheKey id string + uncacheable bool fixedWindow bool } // availablePanels pins a whole refresh's existing answers or flights. It adds // no execution work, so neither cache hits nor coalesced waiters need a ticket -// in an already full queue. Missing even one panel makes this path ineligible. -func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLookup, stamp time.Time) ([]Result, bool, error) { +// in an already full queue. The count is the number needing new execution. +func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLookup, stamp time.Time) ([]Result, int, error) { c := &e.cache c.mu.Lock() now := e.now() @@ -271,15 +272,20 @@ func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLook flights := make([]*cacheFlight, len(lookups)) outcomes := make([]string, len(lookups)) bypass := BypassesCache(ctx) + missing := 0 for i, lookup := range lookups { + if lookup.uncacheable { + missing++ + continue + } if element := c.entries[lookup.key]; element != nil && !bypass { entry := element.Value.(*cacheEntry) if c.ttl > 0 && now.Sub(entry.stamp) < c.ttl { var ok bool values[i], ok = entry.value.(panelOutcome) if !ok { - c.mu.Unlock() - return nil, false, nil + missing++ + continue } outcomes[i] = cacheHit if now.Sub(entry.stamp) >= c.ttl/2 { @@ -290,11 +296,15 @@ func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLook } flight := c.flights[lookup.key] if flight == nil || !e.joinable(flight, stamp, bypass, lookup.fixedWindow) { - c.mu.Unlock() - return nil, false, nil + missing++ + continue } flights[i], outcomes[i] = flight, cacheCoalesced } + if missing > 0 { + c.mu.Unlock() + return nil, missing, nil + } for i, lookup := range lookups { if flight := flights[i]; flight != nil { flight.waiters++ @@ -325,14 +335,14 @@ func (e *Executor) availablePanels(ctx context.Context, lookups []panelCacheLook } values[i] = flight.value.(panelOutcome) case <-ctx.Done(): - return nil, true, ctx.Err() + return nil, 0, ctx.Err() } } results[i] = values[i].Result.clone() results[i].ID = lookup.id results[i].Cached = outcomes[i] == cacheHit || outcomes[i] == cacheStale } - return results, true, nil + return results, 0, nil } // joinable reports whether a caller may take flight's answer. Non-bypass @@ -536,29 +546,13 @@ func (e *Executor) buildPanelCacheKey(p *Panel, checked *Checked, t Time, now ti func referencedPanelValues(id string, checked *Checked, vars map[string]Value) map[string]panelCacheValue { values := make(map[string]panelCacheValue) - if checked == nil { - return values - } - var visit func(string) - visit = func(name string) { - if _, seen := values[name]; seen { - return - } - values[name] = panelCacheValue(vars[name]) - for _, f := range checked.VarFilters[name] { - for _, param := range f.Params { - visit(param) - } - } - } - for _, f := range checked.Filters[id] { - for _, param := range f.Params { - visit(param) + if checked != nil { + names := map[string]bool{} + checked.addPanelVariables(id, names) + for name := range names { + values[name] = panelCacheValue(vars[name]) } } - for _, param := range checked.SQLParams[id] { - visit(param) - } return values } @@ -665,13 +659,11 @@ func (c cachedTraces) Trace(ctx context.Context, scope observability.Scope, trac Service string `json:"service"` Limit int `json:"limit"` }{"trace", scope, traceID, service, limit}) - if err != nil { - return c.reader.Trace(ctx, scope, traceID, service, limit) - } + // A trace read has no relative window: its data is as of the run's start. - out, _, err := loadCached(c.executor, ctx, key, c.executor.now(), func(run context.Context) (observability.Result[observability.TraceDetail], int64, bool, error) { + read := func(run context.Context) (observability.Result[observability.TraceDetail], int64, bool, error) { var out observability.Result[observability.TraceDetail] - release, err := c.executor.admit(run) + release, err := c.executor.admitInteractive(run, metrics.ReadTraceDetail, c.executor.batchTimeout) if err != nil { return out, 0, false, err } @@ -684,6 +676,11 @@ func (c cachedTraces) Trace(ctx context.Context, scope observability.Scope, trac } raw, err := json.Marshal(out) return out, int64(len(raw)), err == nil, nil - }) + } + if err != nil { + out, _, _, err := read(ctx) + return out, err + } + out, _, err := loadCached(c.executor, ctx, key, c.executor.now(), read) return out, err } diff --git a/internal/query/result_cache_test.go b/internal/query/result_cache_test.go index c8ecbbc5..35e1b2a8 100644 --- a/internal/query/result_cache_test.go +++ b/internal/query/result_cache_test.go @@ -13,6 +13,7 @@ import ( "time" "github.com/labstack/pitot/internal/config" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/observability" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" @@ -570,12 +571,12 @@ func TestResultCacheNeverStoresErrors(t *testing.T) { func TestResultCacheNeverStoresBusyResults(t *testing.T) { e, _, _ := cachedExecutor(t) e.admission = newReadAdmission(1, 0, 0) - if err := e.admission.acquire(t.Context(), panelClass); err != nil { + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { t.Fatal(err) } e.batchTimeout = 30 * time.Millisecond results, err := e.Run(t.Context(), RunRequest{Dashboard: cacheDashboard()}) - e.admission.release(panelClass) + e.admission.release(metrics.ReadPanel) if !errors.Is(err, ErrBusy) || len(results) != 0 || len(e.cache.entries) != 0 { t.Fatalf("results=%+v err=%v entries=%d", results, err, len(e.cache.entries)) } @@ -1345,3 +1346,54 @@ func TestResultCacheNeverStoresPartialResults(t *testing.T) { t.Fatalf("a complete result was not stored: %d entries", len(e.cache.entries)) } } + +func TestCachedAndTextRefreshSkipsUnreferencedVariablesWhenPoolIsFull(t *testing.T) { + e, _, _ := cachedExecutor(t) + e.admission = newReadAdmission(1, 0, 0) + e.admission.bounds[interactiveClass] = 0 + d := cacheDashboard() + d.Variables = []Variable{{Name: "svc", Kind: "query", From: "spans", Field: "service"}} + d.Panels = append(d.Panels, + Panel{ID: "unused", Title: "Filtered", Viz: "stat", Query: &Spec{From: "spans", Where: []string{"service = $svc"}, Measures: []string{"count()"}}}, + Panel{ID: "note", Title: "Note", Viz: "text", Content: "Hello"}, + ) + req := RunRequest{Dashboard: d, Panels: []string{d.Panels[0].ID}} + if r := runOne(t, e, req); r.Status != StatusOK { + t.Fatal(r) + } + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { + t.Fatal(err) + } + defer e.admission.release(metrics.ReadPanel) + labels := map[string]string{"path": "panel", "status": "rejected"} + before := readAdmissionMetric(t, "requests_total", labels) + req.Panels = append(req.Panels, "note") + got, err := e.Run(t.Context(), req) + if err != nil || len(got) != 2 || !got[0].Cached || got[1].Status != StatusOK { + t.Fatalf("cached refresh: %+v, %v", got, err) + } + if e.InteractiveRefusals() != 0 || readAdmissionMetric(t, "requests_total", labels) != before { + t.Fatal("cached refresh recorded a rejection") + } + req.Panels = []string{"unused"} + if _, err := e.Run(t.Context(), req); !errors.Is(err, ErrBusy) || e.InteractiveRefusals() != 1 { + t.Fatalf("referenced option query: %v, refusals=%d", err, e.InteractiveRefusals()) + } +} + +func TestSelectedPanelResolvesTransitiveQueryVariables(t *testing.T) { + e := newFixtureExecutor(t) + defer e.Close() + d := shopDashboard() + d.Variables[0].Default = "" + d.Variables[1].Default = "" + d.Variables[1].IncludeAll = false + d.Variables = append(d.Variables, Variable{Name: "unused", Kind: "query", From: "logs", Field: "service"}) + d.Panels[0].Query.Where = []string{"attributes['http.route'] = $route"} + labels := map[string]string{"path": "variables", "status": "admitted"} + before := readAdmissionMetric(t, "requests_total", labels) + r := runOne(t, e, RunRequest{Dashboard: d, Panels: []string{d.Panels[0].ID}}) + if r.Status != StatusOK || readAdmissionMetric(t, "requests_total", labels)-before != 2 { + t.Fatalf("expected the route and its service dependency, result=%+v", r) + } +} diff --git a/internal/query/schema.go b/internal/query/schema.go index 17eeee42..715a6222 100644 --- a/internal/query/schema.go +++ b/internal/query/schema.go @@ -8,9 +8,9 @@ import ( "slices" "sort" "strings" - "sync" "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" "github.com/labstack/pitot/internal/telemetry/semconv" @@ -83,9 +83,10 @@ type schemaEntry struct { } type schemaFlight struct { - done chan struct{} - schema *Schema - err error + done chan struct{} + schema *Schema + namespaces []string + err error } const ( @@ -95,9 +96,6 @@ const ( namespacesKey = "\x00namespaces" ) -// namespaceMu serializes the namespace listing so a burst runs it once. -var namespaceMu sync.Mutex - // ErrSchemaBusy answers a new window and namespace when the cache holds only // in-flight entries, and a caller whose deadline passes while its discovery // is still running. Cached keys are always served. @@ -152,75 +150,99 @@ func (e *Executor) Schema(ctx context.Context, req SchemaRequest) (*Schema, erro } } e.mu.Lock() - entry = e.schemas[key] - flight := entry.flight - if flight == nil { - if !e.makeSchemaRoom() { - e.mu.Unlock() - return nil, ErrSchemaBusy - } - flight = &schemaFlight{done: make(chan struct{})} - e.schemas[key] = schemaEntry{flight: flight} - e.startDiscovery(key, req, span, flight) + // Namespace validation can outlive another caller's entire discovery. + now = e.now() + if ready := e.schemas[key]; ready.schema != nil && now.Before(ready.expires) && now.Before(ready.stale) { + e.mu.Unlock() + return ready.schema, nil } + flight, err := e.coldDiscovery(key, req, span) e.mu.Unlock() + if err != nil { + return nil, err + } + if err := flight.wait(ctx); err != nil { + return nil, err + } + return flight.schema, nil +} + +// coldDiscovery joins or starts a detached lookup. The caller holds e.mu. +func (e *Executor) coldDiscovery(key string, req SchemaRequest, span time.Duration) (*schemaFlight, error) { + entry, exists := e.schemas[key] + if entry.flight != nil { + return entry.flight, nil + } + if !exists && !e.makeSchemaRoom() { + return nil, ErrSchemaBusy + } + flight := &schemaFlight{done: make(chan struct{})} + e.schemas[key] = schemaEntry{flight: flight} + e.startDiscovery(key, req, span, flight) + return flight, nil +} + +func (f *schemaFlight) wait(ctx context.Context) error { select { - case <-flight.done: - return flight.schema, flight.err + case <-f.done: + return f.err case <-ctx.Done(): - // The discovery runs on; a caller out of time is told to come back. if errors.Is(ctx.Err(), context.DeadlineExceeded) { - return nil, ErrSchemaBusy + return ErrSchemaBusy } - return nil, ctx.Err() + return ctx.Err() } } -// checkNamespace rejects a namespace without data in the last 24h, so junk -// namespaces never start a discovery or take a cache entry. +// checkNamespace shares the retained namespace listing across all namespace +// lookups on this executor. Each caller can leave the flight independently. func (e *Executor) checkNamespace(ctx context.Context, namespace string) error { - namespaceMu.Lock() - defer namespaceMu.Unlock() e.mu.Lock() - entry, ok := e.schemas[namespacesKey] - e.mu.Unlock() - if !ok || !e.now().Before(entry.expires) { - end := e.now().UTC() - var parts []string - var args []any - for _, name := range SignalNames() { - where, a := windowWhere(signals[name], end.Add(-24*time.Hour), end, "") - parts = append(parts, "SELECT DISTINCT namespace FROM "+name+" WHERE "+where) - args = append(args, a...) - } - rows, err := e.engine.QueryContext(ctx, "SELECT DISTINCT namespace FROM ("+strings.Join(parts, " UNION ALL ")+") WHERE namespace <> '' ORDER BY 1 LIMIT 1000", args...) + entry := e.schemas[namespacesKey] + names := entry.namespaces + if e.now().Before(entry.expires) { + e.mu.Unlock() + } else { + flight, err := e.coldDiscovery(namespacesKey, SchemaRequest{}, 24*time.Hour) + e.mu.Unlock() if err != nil { return err } - var names []string - for rows.Next() { - var n string - if err := rows.Scan(&n); err != nil { - rows.Close() - return err - } - names = append(names, n) - } - err = rows.Err() - rows.Close() - if err != nil { + if err := flight.wait(ctx); err != nil { return err } - entry = schemaEntry{namespaces: names, expires: e.now().Add(schemaTTL)} - e.mu.Lock() - e.schemas[namespacesKey] = entry - e.mu.Unlock() + names = flight.namespaces } - if slices.Contains(entry.namespaces, namespace) { + if slices.Contains(names, namespace) { return nil } return Problems{{Path: "namespace", Message: fmt.Sprintf("namespace %q has no data in the last 24h", namespace), - Hint: "use one of " + strings.Join(entry.namespaces[:min(len(entry.namespaces), 20)], ", ")}} + Hint: "use one of " + strings.Join(names[:min(len(names), 20)], ", ")}} +} + +func (e *Executor) discoverNamespaces(ctx context.Context, span time.Duration) ([]string, error) { + end := e.now().UTC() + var parts []string + var args []any + for _, name := range SignalNames() { + where, a := windowWhere(signals[name], end.Add(-span), end, "") + parts = append(parts, "SELECT DISTINCT namespace FROM "+name+" WHERE "+where) + args = append(args, a...) + } + rows, err := e.AdmitReader(e.engine, metrics.ReadSchema).QueryContext(ctx, "SELECT DISTINCT namespace FROM ("+strings.Join(parts, " UNION ALL ")+") WHERE namespace <> '' ORDER BY 1 LIMIT 1000", args...) + if err != nil { + return nil, err + } + defer rows.Close() + var names []string + for rows.Next() { + var n string + if err := rows.Scan(&n); err != nil { + return nil, err + } + names = append(names, n) + } + return names, rows.Err() } // makeSchemaRoom removes entries past their stale horizon, then, while the @@ -260,18 +282,22 @@ func (e *Executor) startDiscovery(key string, req SchemaRequest, span time.Durat e.running.Add(1) go func() { defer e.running.Done() - e.discoverFlight(req, span, flight) + e.discoverFlight(key, req, span, flight) e.settle(key, flight) }() } -func (e *Executor) discoverFlight(req SchemaRequest, span time.Duration, flight *schemaFlight) { +func (e *Executor) discoverFlight(key string, req SchemaRequest, span time.Duration, flight *schemaFlight) { wait := time.NewTimer(e.discoverWait) select { case e.discoveries <- struct{}{}: wait.Stop() ctx, cancel := context.WithTimeout(e.life, e.discoverRun) - flight.schema, flight.err = e.discover(ctx, req, span) + if key == namespacesKey { + flight.namespaces, flight.err = e.discoverNamespaces(ctx, span) + } else { + flight.schema, flight.err = e.discover(ctx, req, span) + } cancel() <-e.discoveries case <-wait.C: @@ -290,7 +316,7 @@ func (e *Executor) settle(key string, flight *schemaFlight) { switch { case flight.err == nil: now := e.now() - e.schemas[key] = schemaEntry{schema: flight.schema, expires: now.Add(schemaTTL), stale: now.Add(schemaTTL + schemaStale), used: now} + e.schemas[key] = schemaEntry{schema: flight.schema, namespaces: flight.namespaces, expires: now.Add(schemaTTL), stale: now.Add(schemaTTL + schemaStale), used: now} case entry.schema != nil: // A failed refresh keeps serving the stale schema until its // horizon and retries ten seconds later. @@ -400,7 +426,7 @@ func (e *Executor) lowCardinality(ctx context.Context, sig *signal, start, end t } query := "SELECT c, v, count(*) AS n FROM (UNPIVOT (SELECT " + strings.Join(projection, ", ") + " FROM " + sig.name + " WHERE " + where + ") ON COLUMNS(*) INTO NAME c VALUE v) WHERE v <> '' GROUP BY c, v" - rows, err := e.engine.QueryContext(ctx, query, args...) + rows, err := e.AdmitReader(e.engine, metrics.ReadSchema).QueryContext(ctx, query, args...) if err != nil { if isOperational(err) { return nil, err @@ -454,7 +480,7 @@ func (e *Executor) attributes(ctx context.Context, sig *signal, start, end time. ) SELECT keys.scope, keys.k, keys.t, keys.n, keys.services, keys.ts, top.vals FROM keys LEFT JOIN top USING (scope, k) ORDER BY keys.n DESC, keys.k` - rows, err := e.engine.QueryContext(ctx, query, args...) + rows, err := e.AdmitReader(e.engine, metrics.ReadSchema).QueryContext(ctx, query, args...) if err != nil { if isOperational(err) { return nil, err @@ -556,7 +582,7 @@ func attributeType(jsonType string) string { func (e *Executor) metricNames(ctx context.Context, start, end time.Time, namespace string) ([]MetricSchema, error) { where, args := windowWhere(signals["metrics"], start, end, namespace) - rows, err := e.engine.QueryContext(ctx, "SELECT name,coalesce(unit,''),type,coalesce(temporality,''),count(*) FROM metrics WHERE "+where+" GROUP BY name,unit,type,temporality ORDER BY 5 DESC,1,3,4 LIMIT 300", args...) + rows, err := e.AdmitReader(e.engine, metrics.ReadSchema).QueryContext(ctx, "SELECT name,coalesce(unit,''),type,coalesce(temporality,''),count(*) FROM metrics WHERE "+where+" GROUP BY name,unit,type,temporality ORDER BY 5 DESC,1,3,4 LIMIT 300", args...) if err != nil { if isOperational(err) { return nil, err diff --git a/internal/query/schema_discovery_test.go b/internal/query/schema_discovery_test.go index 57644e3d..d26533eb 100644 --- a/internal/query/schema_discovery_test.go +++ b/internal/query/schema_discovery_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" "github.com/labstack/pitot/internal/telemetry" ) @@ -385,3 +386,132 @@ func TestSchemaCachedLookupNeverWaits(t *testing.T) { t.Fatalf("warm cached lookup err=%v", err) } } + +// Both the namespace lookup and a cold discovery can be shed. Neither leaves a +// cached result or a detached flight after returning ErrBusy. +func TestColdSchemaShedsAtReadAdmission(t *testing.T) { + e := newAdmissionFixture(t, 1, 0, 4) + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { + t.Fatal(err) + } + defer e.admission.release(metrics.ReadPanel) + e.batchTimeout = 10 * time.Millisecond + for _, ns := range []string{"shop", ""} { + _, err := e.Schema(t.Context(), SchemaRequest{Namespace: ns}) + if err != ErrBusy || len(e.schemas) != 0 { + t.Fatalf("namespace %q: err=%v, entries=%d", ns, err, len(e.schemas)) + } + } + // If admission outlives the discovery budget, preserve the run deadline. + e.batchTimeout, e.discoverRun = time.Second, 10*time.Millisecond + if _, err := e.Schema(t.Context(), SchemaRequest{}); err != context.DeadlineExceeded { + t.Fatalf("discovery deadline while queued: %v", err) + } +} + +func TestShedSchemaRefreshServesStaleAndRetries(t *testing.T) { + e := newFixtureExecutor(t) + t.Cleanup(e.Close) + now := e.now() + e.now = func() time.Time { return now } + e.admission = newReadAdmission(1, 0, 0) + e.batchTimeout = 10 * time.Millisecond + if err := e.admission.acquire(t.Context(), metrics.ReadPanel); err != nil { + t.Fatal(err) + } + stale := &Schema{Window: "1h"} + e.schemas["1h|"] = schemaEntry{schema: stale, expires: now, stale: now.Add(time.Minute)} + lookup := func() *Schema { + t.Helper() + got, err := e.Schema(t.Context(), SchemaRequest{}) + if err != nil { + t.Fatal(err) + } + return got + } + if lookup() != stale { + t.Fatal("refresh did not serve the cached schema") + } + e.running.Wait() + e.admission.release(metrics.ReadPanel) + if e.InteractiveRefusals() != 1 || lookup() != stale || e.schemas["1h|"].flight != nil { + t.Fatal("shed refresh did not retain the stale schema for its retry interval") + } + now = now.Add(11 * time.Second) + if lookup() != stale { + t.Fatal("retry did not serve the cached schema") + } + e.running.Wait() + if got := lookup(); got == stale || len(got.Signals) == 0 { + t.Fatal("retry did not warm the schema cache") + } +} + +func TestSchemaYieldsItsSlotBetweenDiscoveryStatements(t *testing.T) { + fixture := newFixtureExecutor(t) + engine := &countingEngine{Engine: fixture.engine} + e := NewExecutor(pooledEngine{Engine: engine, pool: 1}, 30) + t.Cleanup(e.Close) + e.now = fixture.now + ctx := t.Context() + // Queue the discovery first and an interactive click second. + if err := e.admission.acquire(ctx, metrics.ReadPanel); err != nil { + t.Fatal(err) + } + discovered := make(chan error, 1) + go func() { _, err := e.Schema(ctx, SchemaRequest{}); discovered <- err }() + waitForReadWaiters(t, e.admission, 1) + click := make(chan error, 1) + go func() { + release, err := e.admitInteractive(ctx, metrics.ReadObservability, e.batchTimeout) + if err == nil { + defer release() + if engine.queries != 1 { + err = fmt.Errorf("click admitted after %d discovery statements, want 1", engine.queries) + } + } + click <- err + }() + waitForReadWaiters(t, e.admission, 2) + e.admission.release(metrics.ReadPanel) + if err := <-click; err != nil { + t.Fatal(err) + } + if err := <-discovered; err != nil { + t.Fatal(err) + } +} + +func TestNamespaceListingCoalescesAndLetsCallersLeaveIndependently(t *testing.T) { + fixture := newFixtureExecutor(t) + engine := &activeEngine{Engine: fixture.engine, gate: make(chan struct{})} + e := NewExecutor(engine, 30) + t.Cleanup(e.Close) + e.now = fixture.now + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond) + defer cancel() + if err := e.checkNamespace(ctx, "shop"); err != ErrSchemaBusy { + t.Fatalf("caller deadline: %v", err) + } + other, stop := context.WithCancel(t.Context()) + left := make(chan error, 1) + go func() { left <- e.checkNamespace(other, "another") }() + stop() + select { + case err := <-left: + if err != context.Canceled { + t.Fatalf("departing caller: %v", err) + } + case <-time.After(time.Second): + t.Fatal("cancelled caller blocked behind namespace listing") + } + // A separate executor can discover its own listing while the first is blocked. + if err := fixture.checkNamespace(t.Context(), "shop"); err != nil { + t.Fatal(err) + } + close(engine.gate) + e.running.Wait() + if err := e.checkNamespace(t.Context(), "shop"); err != nil || engine.peak.Load() != 1 { + t.Fatalf("shared listing: %v, peak=%d", err, engine.peak.Load()) + } +} diff --git a/internal/query/service_input.go b/internal/query/service_input.go index 518e7fa7..18ce11a1 100644 --- a/internal/query/service_input.go +++ b/internal/query/service_input.go @@ -6,6 +6,7 @@ import ( "strings" "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" ) @@ -14,11 +15,29 @@ import ( // Rollups are the common, cheap path; inventory covers publication/rollup lag // and services that emit only logs or metrics. Neither uses a capped name list. func (e *Executor) ServiceGuidance(ctx context.Context, start, end time.Time, namespace, service string) (string, error) { - ctx, cancel := context.WithTimeout(ctx, e.timeout) - defer cancel() if !start.Before(end) || end.Sub(start) > e.maxWindow { return "", Problems{{Path: "time", Message: "window must be positive and within retention"}} } + ctx, finish, err := e.admitGuidance(ctx) + if err != nil { + return "", err + } + defer finish() + return e.serviceGuidance(ctx, start, end, namespace, service) +} + +// Guidance executes sequential reads. Start the execution budget after it +// owns a slot, including when EmptyGuidance also needs variable options. +func (e *Executor) admitGuidance(ctx context.Context) (context.Context, func(), error) { + release, err := e.admitInteractive(ctx, metrics.ReadObservability, e.batchTimeout) + if err != nil { + return nil, nil, err + } + run, cancel := context.WithTimeout(e.withInteractiveSlot(ctx), e.timeout) + return run, func() { cancel(); release() }, nil +} + +func (e *Executor) serviceGuidance(ctx context.Context, start, end time.Time, namespace, service string) (string, error) { known, err := e.observedService(ctx, `SELECT EXISTS ( SELECT 1 FROM service_rollup WHERE service=? AND (?='' OR namespace=?) )`, service, namespace, namespace) @@ -145,8 +164,11 @@ ORDER BY kind,n DESC,namespace,service` // EmptyGuidance is used only after a complete fragment returned no matching // data. Reuse checked filters and resolved variables to find exact service scopes. func (e *Executor) EmptyGuidance(ctx context.Context, req RunRequest) (string, string, error) { - ctx, cancel := context.WithTimeout(ctx, e.timeout) - defer cancel() + ctx, finish, err := e.admitGuidance(ctx) + if err != nil { + return "", "", err + } + defer finish() d := req.Dashboard Normalize(&d) checked, invalid, err := e.checkRun(ctx, &d) @@ -161,7 +183,7 @@ func (e *Executor) EmptyGuidance(ctx context.Context, req RunRequest) (string, s if err != nil { return "", "", err } - vars, err := e.values(ctx, &d, checked, start, end, req.Vars) + vars, err := e.values(ctx, &d, checked, start, end, req.Vars, nil) if err != nil { return "", "", err } @@ -214,7 +236,7 @@ func (e *Executor) EmptyGuidance(ctx context.Context, req RunRequest) (string, s continue } seen[key] = true - message, err := e.ServiceGuidance(ctx, start, end, namespace, service) + message, err := e.serviceGuidance(ctx, start, end, namespace, service) if err != nil { return "", "", err } diff --git a/internal/query/testhelpers_test.go b/internal/query/testhelpers_test.go index 5e494d69..25d26dc5 100644 --- a/internal/query/testhelpers_test.go +++ b/internal/query/testhelpers_test.go @@ -25,7 +25,12 @@ var fixtureStart = time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) func newTestEngine(t *testing.T) (*engine.Duck, *telemetrystore.Repository) { t.Helper() - cfg := config.Config{DataDir: t.TempDir(), DuckDBMemory: "256MB", DuckDBThreads: 2, DuckDBMaxConns: 4, RollupInterval: time.Hour} + return newTestEngineWithPool(t, 4) +} + +func newTestEngineWithPool(t *testing.T, conns int) (*engine.Duck, *telemetrystore.Repository) { + t.Helper() + cfg := config.Config{DataDir: t.TempDir(), DuckDBMemory: "256MB", DuckDBThreads: 2, DuckDBMaxConns: conns, RollupInterval: time.Hour} repo, err := telemetrystore.Open(cfg.TelemetryDir()) if err != nil { t.Fatal(err) diff --git a/internal/query/variables.go b/internal/query/variables.go index 28da0165..106fc0bb 100644 --- a/internal/query/variables.go +++ b/internal/query/variables.go @@ -5,6 +5,7 @@ import ( "fmt" "time" + "github.com/labstack/pitot/internal/metrics" "github.com/labstack/pitot/internal/queryrows" ) @@ -56,12 +57,39 @@ func (e *Executor) ResolveVariables(ctx context.Context, req ResolveRequest) (ma return options, nil } -// values resolves the current value of every variable for a run. Options are +// addPanelVariables includes dependencies used by query variables' own filters. +func (checked *Checked) addPanelVariables(id string, names map[string]bool) { + var visit func(string) + visit = func(name string) { + if names[name] { + return + } + names[name] = true + for _, f := range checked.VarFilters[name] { + for _, param := range f.Params { + visit(param) + } + } + } + for _, f := range checked.Filters[id] { + for _, param := range f.Params { + visit(param) + } + } + for _, param := range checked.SQLParams[id] { + visit(param) + } +} + +// values resolves the needed variables in dashboard order (nil selects all). Options are // queried only for a query variable with no provided value, no default and no // All, which is the one case that needs them. -func (e *Executor) values(ctx context.Context, d *Dashboard, checked *Checked, start, end time.Time, provided map[string]Value) (map[string]Value, error) { +func (e *Executor) values(ctx context.Context, d *Dashboard, checked *Checked, start, end time.Time, provided map[string]Value, needed map[string]bool) (map[string]Value, error) { values := map[string]Value{} for _, v := range d.Variables { + if needed != nil && !needed[v.Name] { + continue + } given, ok := provided[v.Name] if ok && !v.Multi && !given.All && len(given.Values) == 0 { ok = false @@ -104,7 +132,7 @@ func (e *Executor) optionsFor(ctx context.Context, v Variable, checked *Checked, } expr := ref.stringSQL() ctx = queryrows.WithWindow(ctx, queryrows.Window{Start: start, End: end}) - rows, err := e.engine.QueryContext(ctx, fmt.Sprintf("SELECT %s AS v, count(*) AS n FROM %s WHERE %s AND %s IS NOT NULL AND %s <> '' GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 500", expr, structuredSource(sig.name), where, expr, expr), args...) + rows, err := e.AdmitReader(e.engine, metrics.ReadVariables).QueryContext(ctx, fmt.Sprintf("SELECT %s AS v, count(*) AS n FROM %s WHERE %s AND %s IS NOT NULL AND %s <> '' GROUP BY 1 ORDER BY 2 DESC, 1 LIMIT 500", expr, structuredSource(sig.name), where, expr, expr), args...) if err != nil { return nil, fmt.Errorf("list values for $%s: %w", v.Name, err) }