Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions cmd/pitot/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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)
Expand Down
25 changes: 13 additions & 12 deletions docs/proposals/0011-engine-admission-classes.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand All @@ -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).
2 changes: 1 addition & 1 deletion docs/proposals/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
15 changes: 10 additions & 5 deletions internal/api/schema_busy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
22 changes: 18 additions & 4 deletions internal/engine/duck.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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()
}
Expand Down
20 changes: 20 additions & 0 deletions internal/engine/stall_instrumentation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions internal/mcp/panels.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
22 changes: 14 additions & 8 deletions internal/mcp/panels_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/metrics/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 15 additions & 0 deletions internal/metrics/metrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) },
Expand Down Expand Up @@ -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")
}
}
Loading
Loading