Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

chore(metrics): remove database-sampled metrics (#7819)

Multica Eve7c1d826a9851
diff --git a/deploy/helm/multica/templates/prometheusrule.yaml b/deploy/helm/multica/templates/prometheusrule.yaml
deleted file mode 100644
index 2cf6295e9b..0000000000
--- a/deploy/helm/multica/templates/prometheusrule.yaml
+++ /dev/null
@@ -1,62 +0,0 @@
-{{- if .Values.monitoring.prometheusRule.enabled }}
-{{- $samplerQueryNames := "task_queued|task_running|task_stuck|workspace_total" -}}
-{{- $samplerErrorNames := printf "acquire|%s" $samplerQueryNames -}}
-apiVersion: monitoring.coreos.com/v1
-kind: PrometheusRule
-metadata:
- name: {{ include "multica.backend.fullname" . }}-sampler
- labels:
- {{- include "multica.labels" . | nindent 4 }}
- app.kubernetes.io/component: backend
- {{- with .Values.monitoring.prometheusRule.additionalLabels }}
- {{- toYaml . | nindent 4 }}
- {{- end }}
-spec:
- groups:
- - name: multica-business-sampler
- rules:
- - alert: MulticaBusinessSamplerQueryErrors
- expr: |
- sum by (name) (
- rate(multica_business_sampler_query_errors_total{name=~"{{ $samplerErrorNames }}"}[10m])
- ) > 0
- for: {{ .Values.monitoring.prometheusRule.samplerQueryErrorsFor | quote }}
- labels:
- severity: {{ .Values.monitoring.prometheusRule.severity | quote }}
- annotations:
- summary: "Business sampler query errors"
- description: "Business sampler query {{ "{{ $labels.name }}" }} is returning errors. Metrics may go stale if the query keeps timing out."
- - alert: MulticaBusinessSamplerQueryLatencyHigh
- expr: |
- histogram_quantile(
- 0.95,
- sum by (le, name) (
- rate(multica_business_sampler_query_seconds_bucket{name=~"{{ $samplerQueryNames }}"}[10m])
- )
- ) > 0.3
- for: {{ .Values.monitoring.prometheusRule.samplerQueryLatencyFor | quote }}
- labels:
- severity: {{ .Values.monitoring.prometheusRule.severity | quote }}
- annotations:
- summary: "Business sampler query p95 is high"
- description: "Business sampler query {{ "{{ $labels.name }}" }} p95 is above 300ms, leaving little headroom before the 500ms statement_timeout."
- - alert: MulticaSeatCapacityOutboxDeadLettered
- expr: |
- sum by (action) (multica_seat_capacity_outbox_dead_lettered) > 0
- for: {{ .Values.monitoring.prometheusRule.seatCapacityDeadLetteredFor | quote }}
- labels:
- severity: {{ .Values.monitoring.prometheusRule.severity | quote }}
- annotations:
- summary: "Seat capacity intent requires repair"
- description: "At least one {{ "{{ $labels.action }}" }} seat capacity intent exhausted automatic retries and entered the dead-letter state."
- - alert: MulticaSeatCapacityOutboxStalled
- expr: |
- max by (action) (multica_seat_capacity_outbox_oldest_pending_age_seconds)
- > {{ .Values.monitoring.prometheusRule.seatCapacityPendingAgeSeconds }}
- for: {{ .Values.monitoring.prometheusRule.seatCapacityPendingFor | quote }}
- labels:
- severity: {{ .Values.monitoring.prometheusRule.severity | quote }}
- annotations:
- summary: "Seat capacity outbox is stalled"
- description: "The oldest {{ "{{ $labels.action }}" }} seat capacity intent has remained unsettled beyond the configured age threshold. Repeated Cloud or proxy 429 deferrals intentionally remain pending and surface here instead of in the dead-letter alert."
-{{- end }}
diff --git a/deploy/helm/multica/values.yaml b/deploy/helm/multica/values.yaml
index e0e5550626..a25fc500d1 100644
--- a/deploy/helm/multica/values.yaml
+++ b/deploy/helm/multica/values.yaml
@@ -205,20 +205,3 @@ ingress:
# tls:
# - hosts: [multica.dev.lan, api.multica.dev.lan]
# secretName: multica-tls
-
-# -----------------------------------------------------------------------------
-# Monitoring
-# -----------------------------------------------------------------------------
-monitoring:
- prometheusRule:
- # Requires the Prometheus Operator CRD (monitoring.coreos.com/v1). Kept
- # disabled by default so minimal self-host installs without that CRD still
- # render and install.
- enabled: false
- additionalLabels: {}
- samplerQueryErrorsFor: 5m
- samplerQueryLatencyFor: 10m
- seatCapacityDeadLetteredFor: 5m
- seatCapacityPendingAgeSeconds: 900
- seatCapacityPendingFor: 5m
- severity: warning
diff --git a/scripts/helm-config.test.sh b/scripts/helm-config.test.sh
index 88c9697af7..5e2b48a44b 100644
--- a/scripts/helm-config.test.sh
+++ b/scripts/helm-config.test.sh
@@ -60,13 +60,4 @@ capacity_config="$(
)"
require_rendered_value "$capacity_config" 'MULTICA_CLOUD_URL: "https://multica-cloud.internal"'
-capacity_alerts="$(
- helm template multica "$CHART_DIR" \
- --show-only templates/prometheusrule.yaml \
- --set monitoring.prometheusRule.enabled=true
-)"
-require_rendered_value "$capacity_alerts" 'alert: MulticaSeatCapacityOutboxDeadLettered'
-require_rendered_value "$capacity_alerts" 'alert: MulticaSeatCapacityOutboxStalled'
-require_rendered_value "$capacity_alerts" 'multica_seat_capacity_outbox_oldest_pending_age_seconds'
-
echo "helm config rendering ok"
diff --git a/server/cmd/migrate/migrate_concurrent_test.go b/server/cmd/migrate/migrate_concurrent_test.go
index c264354f70..ab127ec778 100644
--- a/server/cmd/migrate/migrate_concurrent_test.go
+++ b/server/cmd/migrate/migrate_concurrent_test.go
@@ -47,11 +47,9 @@ import (
// The test connects to whatever DATABASE_URL points at (default
// postgres://multica:multica@localhost:5432/multica?sslmode=disable),
// matching the harness pattern already used in
-// server/internal/handler/handler_test.go and
-// server/internal/metrics/business_sampler_pgsleep_test.go. If
-// Postgres is unreachable the suite skips cleanly, the same way every
-// other live-Postgres test in the repo skips, so CI without a database
-// sees SKIP rather than failure.
+// server/internal/handler/handler_test.go. If Postgres is unreachable the
+// suite skips cleanly, the same way every other live-Postgres test in the
+// repo skips, so CI without a database sees SKIP rather than failure.
//
// Each test isolates itself by creating a unique throwaway schema
// (migrate_test_<timestamp>_<rand>) and using a unique advisory-lock
diff --git a/server/cmd/server/dbstats.go b/server/cmd/server/dbstats.go
index 735af88d2d..5b5f82107d 100644
--- a/server/cmd/server/dbstats.go
+++ b/server/cmd/server/dbstats.go
@@ -2,7 +2,6 @@ package main
import (
"context"
- "fmt"
"log/slog"
"net/url"
"os"
@@ -192,33 +191,3 @@ func runDBStatsLogger(ctx context.Context, pool *pgxpool.Pool) {
lastCanceled = s.CanceledAcquireCount()
}
}
-
-// samplerMaxConns is the cap for the dedicated /metrics sampler pool. The
-// sampler issues at most one acquire per scrape and Prometheus typically
-// scrapes once per 15s — two connections is plenty for two replicas
-// scraping in parallel without ever competing with the main pool.
-const samplerMaxConns int32 = 2
-
-// newSamplerDBPool builds a tiny pgxpool aimed exclusively at the
-// BusinessSamplerCollector. Keeping it isolated from the main pool means a
-// stalled sampler scrape can never starve business traffic — the worst
-// case is the next /metrics returning stale numbers, which is exactly the
-// safety contract documented on BusinessSamplerOptions.
-//
-// The pool is built from the same DATABASE_URL as the main pool so it
-// hits the same database; the sizing knobs (DATABASE_MAX_CONNS et al.) on
-// the main pool are intentionally NOT honored here. A sampler that grew
-// to 25 connections per replica during an incident would defeat the
-// purpose of running it on a separate pool in the first place.
-func newSamplerDBPool(ctx context.Context, dbURL string) (*pgxpool.Pool, error) {
- cfg, err := pgxpool.ParseConfig(dbURL)
- if err != nil {
- return nil, fmt.Errorf("parse database url for sampler: %w", err)
- }
- cfg.MaxConns = samplerMaxConns
- cfg.MinConns = 0
- // A dedicated short-lived idle window — the sampler runs every
- // scrape (~15s) so connections shouldn't sit warm forever.
- cfg.MaxConnIdleTime = 5 * time.Minute
- return pgxpool.NewWithConfig(ctx, cfg)
-}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index db9cc15391..58cb13ed46 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -13,7 +13,6 @@ import (
"syscall"
"time"
- "github.com/jackc/pgx/v5/pgxpool"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/daemonws"
@@ -367,7 +366,6 @@ func main() {
stopStartup()
slog.Info("connected to database")
logPoolConfig(pool)
- ctx := context.Background()
bus := events.New()
hub := realtime.NewHub()
@@ -554,41 +552,21 @@ func main() {
var metricsServer *http.Server
var httpMetrics *obsmetrics.HTTPMetrics
var businessMetrics *obsmetrics.BusinessMetrics
- var samplerPool *pgxpool.Pool
var channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics
var channelLeaseMetrics *obsmetrics.ChannelLeaseMetrics
- var seatCapacityMetrics *obsmetrics.SeatCapacityMetrics
var wecomMetrics *obsmetrics.WecomMetrics
if metricsConfig.Enabled() {
- // Build a dedicated tiny pool for the BusinessSamplerCollector
- // so a stalled scrape can never starve business traffic. If the
- // pool fails to construct we log and continue without the
- // sampler — the rest of /metrics is still useful.
- var err error
- samplerPool, err = newSamplerDBPool(ctx, dbURL)
- if err != nil {
- slog.Warn("metrics: failed to build sampler pgxpool; sampler disabled", "error", err)
- samplerPool = nil
- }
-
metricsRegistry := obsmetrics.NewRegistry(obsmetrics.RegistryOptions{
Pool: pool,
Realtime: realtime.M,
DaemonWS: daemonws.M,
Version: version,
Commit: commit,
- BusinessSampler: func() *obsmetrics.BusinessSamplerOptions {
- if samplerPool == nil {
- return nil
- }
- return &obsmetrics.BusinessSamplerOptions{Pool: samplerPool}
- }(),
})
httpMetrics = metricsRegistry.HTTP
businessMetrics = metricsRegistry.Business
channelMediaMetrics = metricsRegistry.ChannelMedia
channelLeaseMetrics = metricsRegistry.ChannelLease
- seatCapacityMetrics = metricsRegistry.SeatCapacity
wecomMetrics = metricsRegistry.Wecom
// Forward inbound daemon WS frames into the per-kind counter so
// dashboards can split heartbeat / unknown / invalid traffic.
@@ -603,10 +581,6 @@ func main() {
)
}
}
- if samplerPool != nil {
- defer samplerPool.Close()
- }
-
// Construct the BatchedHeartbeatScheduler before the router so it can
// be injected into the Handler. The Run goroutine starts below
// alongside the sweeper, and Stop is called explicitly during graceful
@@ -626,7 +600,6 @@ func main() {
HTTPMetrics: httpMetrics,
BusinessMetrics: businessMetrics,
ChannelLeaseMetrics: channelLeaseMetrics,
- SeatCapacityMetrics: seatCapacityMetrics,
ChannelLeaseRedis: channelLeaseRedis,
WecomMetrics: wecomMetrics,
DaemonHub: daemonHub,
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index f044a832d8..9e6ce3d7f9 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -216,7 +216,6 @@ type RouterOptions struct {
HTTPMetrics *obsmetrics.HTTPMetrics
BusinessMetrics *obsmetrics.BusinessMetrics
ChannelLeaseMetrics *obsmetrics.ChannelLeaseMetrics
- SeatCapacityMetrics *obsmetrics.SeatCapacityMetrics
// ChannelLeaseRedis is a dedicated non-blocking Redis client/pool. It is
// required only when CHANNEL_WS_LEASE_BACKEND=redis.
ChannelLeaseRedis *redis.Client
@@ -470,9 +469,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
capacityLocker := seatcapacity.NewWorkspaceLocker(pool)
h.SeatCapacityLocker = capacityLocker
if seatcapacity.CanRunWorker(h.SeatCapacity) {
- h.SeatCapacityWorker = seatcapacity.NewWorker(queries, h.SeatCapacity, capacityLocker, seatcapacity.WorkerConfig{
- Metrics: opts.SeatCapacityMetrics,
- })
+ h.SeatCapacityWorker = seatcapacity.NewWorker(queries, h.SeatCapacity, capacityLocker, seatcapacity.WorkerConfig{})
}
if opts.BusinessMetrics != nil {
// Wire the BusinessMetrics receiver into the cloud runtime client
diff --git a/server/cmd/server/runtime_gc_test.go b/server/cmd/server/runtime_gc_test.go
index 7f4af19f14..94acf1446e 100644
--- a/server/cmd/server/runtime_gc_test.go
+++ b/server/cmd/server/runtime_gc_test.go
@@ -149,7 +149,7 @@ func TestRuntimeGC_ProtectsEveryNonTerminalTaskStatus(t *testing.T) {
}
}
-func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testing.T) {
+func TestRuntimeGCCandidates_ExcludeBlockedRuntimes(t *testing.T) {
if testPool == nil {
t.Skip("no database connection")
}
@@ -169,12 +169,6 @@ func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testi
if _, err := testPool.Exec(ctx, `UPDATE agent SET kind = 'system', system_key = $2 WHERE id = $1`, systemAgentID, "runtime_gc_candidate_"+systemAgentID); err != nil {
t.Fatalf("convert candidate to system agent: %v", err)
}
- foreignWorkspaceID := createRuntimeGCFixtureWorkspace(t, ctx, "candidate-mismatch")
- mismatchRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-mismatch")
- mismatchAgentID := createRuntimeGCFixtureAgentForWorkspace(t, ctx, foreignWorkspaceID, mismatchRuntimeID, "candidate-mismatch")
- if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, mismatchAgentID); err != nil {
- t.Fatalf("archive candidate workspace-mismatch agent: %v", err)
- }
_ = createRuntimeGCFixtureTask(t, ctx, blockedRuntimeID, agentID, "deferred", false)
queries := db.New(testPool)
@@ -210,82 +204,6 @@ func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testi
if !foundArchived || !foundSystem {
t.Fatalf("archived/system candidates found=%v/%v, want both", foundArchived, foundSystem)
}
- backlog, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(ctx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- if err != nil {
- t.Fatalf("classify runtime GC backlog: %v", err)
- }
- var activeBlocked, taskBlocked, workspaceMismatch int64
- for _, row := range backlog {
- switch row.Reason {
- case "active_agent":
- activeBlocked = row.Count
- case "non_terminal_task":
- taskBlocked = row.Count
- case "workspace_mismatch":
- workspaceMismatch = row.Count
- }
- }
- if activeBlocked < 1 {
- t.Fatalf("active-agent backlog = %d, want at least 1", activeBlocked)
- }
- if taskBlocked < 1 {
- t.Fatalf("non-terminal-task backlog = %d, want at least 1", taskBlocked)
- }
- if workspaceMismatch < 1 {
- t.Fatalf("workspace-mismatch backlog = %d, want at least 1", workspaceMismatch)
- }
- legacyBlocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- if err != nil {
- t.Fatalf("count legacy task-blocked runtimes: %v", err)
- }
-
- // The second task predicate must remain independently indexable: a task can
- // be pinned to an online runtime after a historical move while its archived
- // owner is still bound to this stale runtime. Only the agent-id path should
- // classify the stale runtime as task-blocked.
- pinnedOwnerRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-agent-task-owner")
- pinnedAgentID := createRuntimeGCFixtureAgent(t, ctx, pinnedOwnerRuntimeID, "candidate-agent-task-owner")
- if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, pinnedAgentID); err != nil {
- t.Fatalf("archive candidate agent-task owner: %v", err)
- }
- onlineTaskRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-agent-task-target")
- if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, onlineTaskRuntimeID); err != nil {
- t.Fatalf("mark task target runtime online: %v", err)
- }
- _ = createRuntimeGCFixtureTask(t, ctx, onlineTaskRuntimeID, pinnedAgentID, "deferred", false)
-
- afterPinnedTask, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(ctx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- if err != nil {
- t.Fatalf("classify runtime GC backlog after pinned agent task: %v", err)
- }
- var taskBlockedAfter int64
- for _, row := range afterPinnedTask {
- if row.Reason == "non_terminal_task" {
- taskBlockedAfter = row.Count
- }
- }
- if taskBlockedAfter != taskBlocked+1 {
- t.Fatalf("non-terminal-task backlog after agent-owned pinned task = %d, want %d", taskBlockedAfter, taskBlocked+1)
- }
- legacyBlockedAfter, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- if err != nil {
- t.Fatalf("recount legacy task-blocked runtimes: %v", err)
- }
- if legacyBlockedAfter != legacyBlocked {
- t.Fatalf("legacy blocked count changed from %d to %d for the broader agent-owned task case", legacyBlocked, legacyBlockedAfter)
- }
}
func TestRuntimeGC_ArchivedAgentTaskPinnedToAnotherRuntimeFailsClosed(t *testing.T) {
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index b718cb946c..fa7853a7d5 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -56,10 +56,6 @@ const (
// 500 preserves a theoretical capacity of 12,000 candidates per day; the
// round timeout remains the hard bound on actual work.
runtimeGCBatchSize = 500
- // runtimeGCBacklogScanLimit bounds the observability query as well. The
- // reason-bucket gauges sample at most this many oldest stale runtimes rather
- // than turning a safety signal into an unbounded recurring scan.
- runtimeGCBacklogScanLimit = 1000
// runtimeGCTickTimeout bounds each independent hourly GC round so lock
// contention cannot occupy its worker indefinitely.
runtimeGCTickTimeout = 15 * time.Second
@@ -399,52 +395,6 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, que
gcCtx, cancelGC := context.WithTimeout(ctx, budget)
defer cancelGC()
- blockedCtx, cancelBlocked := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
- blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(blockedCtx, db.CountStaleOfflineRuntimesBlockedByTasksParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- cancelBlocked()
- if err != nil {
- slog.Warn("runtime GC: failed to count task-blocked runtimes", "error", err)
- metrics.RecordRuntimeGCBlockedObservationFailed()
- } else {
- metrics.SetRuntimeGCBlocked(blocked)
- if blocked > 0 {
- slog.Debug("runtime GC: stale runtimes blocked by non-terminal tasks",
- "count", blocked, "count_capped", blocked == runtimeGCBacklogScanLimit)
- }
- }
-
- countCtx, cancelCount := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
- backlog, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(countCtx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{
- StaleSeconds: offlineRuntimeTTLSeconds,
- MaxRows: runtimeGCBacklogScanLimit,
- })
- cancelCount()
- if err != nil {
- slog.Warn("runtime GC: failed to classify stale runtime backlog", "error", err)
- metrics.RecordRuntimeGCBlockedObservationFailed()
- } else {
- for _, reason := range []string{
- obsmetrics.RuntimeGCBacklogActiveAgent,
- obsmetrics.RuntimeGCBacklogNonTerminalTask,
- obsmetrics.RuntimeGCBacklogWorkspaceMismatch,
- obsmetrics.RuntimeGCBacklogEligible,
- } {
- metrics.SetRuntimeGCBacklog(reason, 0)
- }
- var sampled int64
- for _, row := range backlog {
- metrics.SetRuntimeGCBacklog(row.Reason, row.Count)
- sampled += row.Count
- }
- if sampled > 0 {
- slog.Debug("runtime GC: classified stale runtime backlog",
- "sampled", sampled, "sample_capped", sampled == runtimeGCBacklogScanLimit)
- }
- }
-
listCtx, cancelList := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
candidates, err := queries.ListStaleOfflineRuntimeGCCandidates(listCtx, db.ListStaleOfflineRuntimeGCCandidatesParams{
StaleSeconds: offlineRuntimeTTLSeconds,
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index 5740b06bd1..93cdd4ed2a 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -27,11 +27,6 @@ const (
RuntimeGCSkipEligibilityChanged = "eligibility_changed"
RuntimeGCSkipNonTerminalTask = "non_terminal_task"
RuntimeGCSkipWorkspaceMismatch = "workspace_mismatch"
-
- RuntimeGCBacklogActiveAgent = "active_agent"
- RuntimeGCBacklogNonTerminalTask = "non_terminal_task"
- RuntimeGCBacklogWorkspaceMismatch = "workspace_mismatch"
- RuntimeGCBacklogEligible = "eligible"
)
type activeTaskLabels struct {
@@ -56,27 +51,24 @@ type BusinessMetrics struct {
llmUnpricedTokens *prometheus.CounterVec
llmRequests *prometheus.CounterVec
- taskQueuedExpired *prometheus.CounterVec
- taskLeaseExpired *prometheus.CounterVec
- chatClaimSessionFallbackNeeded prometheus.Counter
- chatClaimSessionFallbackResult *prometheus.CounterVec
- chatClaimResumeQueryDuration *prometheus.HistogramVec
- runtimeSweepStageDuration *prometheus.HistogramVec
- runtimeSweepCandidateRows *prometheus.CounterVec
- runtimeSweepRowsChanged *prometheus.CounterVec
- runtimeGCDeleted prometheus.Counter
- runtimeGCFailed prometheus.Counter
- runtimeGCSkipped *prometheus.CounterVec
- runtimeGCBlocked prometheus.Gauge
- runtimeGCBacklog *prometheus.GaugeVec
- runtimeGCBlockedObservationFailed prometheus.Counter
- entitlementConfigError prometheus.Counter
- entitlementCache *prometheus.CounterVec
- entitlementRefresh *prometheus.CounterVec
- entitlementRefreshDuration *prometheus.HistogramVec
- entitlementDecision *prometheus.CounterVec
- entitlementVersionRegression prometheus.Counter
- autopilotQuotaDecision *prometheus.CounterVec
+ taskQueuedExpired *prometheus.CounterVec
+ taskLeaseExpired *prometheus.CounterVec
+ chatClaimSessionFallbackNeeded prometheus.Counter
+ chatClaimSessionFallbackResult *prometheus.CounterVec
+ chatClaimResumeQueryDuration *prometheus.HistogramVec
+ runtimeSweepStageDuration *prometheus.HistogramVec
+ runtimeSweepCandidateRows *prometheus.CounterVec
+ runtimeSweepRowsChanged *prometheus.CounterVec
+ runtimeGCDeleted prometheus.Counter
+ runtimeGCFailed prometheus.Counter
+ runtimeGCSkipped *prometheus.CounterVec
+ entitlementConfigError prometheus.Counter
+ entitlementCache *prometheus.CounterVec
+ entitlementRefresh *prometheus.CounterVec
+ entitlementRefreshDuration *prometheus.HistogramVec
+ entitlementDecision *prometheus.CounterVec
+ entitlementVersionRegression prometheus.Counter
+ autopilotQuotaDecision *prometheus.CounterVec
activeMu sync.Mutex
activeTasks map[string]activeTaskLabels
@@ -245,24 +237,6 @@ func NewBusinessMetrics() *BusinessMetrics {
Name: "skipped_total",
Help: "Total runtime garbage-collection candidates safely skipped by reason.",
}, metricLabels("multica_runtime_gc_skipped_total")),
- runtimeGCBlocked: prometheus.NewGauge(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "runtime_gc",
- Name: "blocked_runtimes",
- Help: "Bounded count of stale offline runtimes blocked from garbage collection by non-terminal tasks.",
- }),
- runtimeGCBacklog: prometheus.NewGaugeVec(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "runtime_gc",
- Name: "backlog_runtimes",
- Help: "Bounded oldest-first sample of stale offline runtimes classified by garbage-collection state.",
- }, metricLabels("multica_runtime_gc_backlog_runtimes")),
- runtimeGCBlockedObservationFailed: prometheus.NewCounter(prometheus.CounterOpts{
- Namespace: "multica",
- Subsystem: "runtime_gc",
- Name: "blocked_observation_failed_total",
- Help: "Total failures while observing stale runtimes blocked from garbage collection.",
- }),
entitlementConfigError: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "multica", Subsystem: "entitlement", Name: "config_error_total",
Help: "Total startup failures caused by a malformed Multica Cloud URL for entitlement policy.",
@@ -298,9 +272,6 @@ func NewBusinessMetrics() *BusinessMetrics {
for _, reason := range []string{RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch} {
m.runtimeGCSkipped.WithLabelValues(reason).Add(0)
}
- for _, reason := range []string{RuntimeGCBacklogActiveAgent, RuntimeGCBacklogNonTerminalTask, RuntimeGCBacklogWorkspaceMismatch, RuntimeGCBacklogEligible} {
- m.runtimeGCBacklog.WithLabelValues(reason).Set(0)
- }
return m
}
@@ -331,9 +302,6 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {
m.runtimeGCDeleted,
m.runtimeGCFailed,
m.runtimeGCSkipped,
- m.runtimeGCBlocked,
- m.runtimeGCBacklog,
- m.runtimeGCBlockedObservationFailed,
m.entitlementConfigError,
m.entitlementCache,
m.entitlementRefresh,
@@ -409,27 +377,6 @@ func (m *BusinessMetrics) RecordRuntimeGCSkipped(reason string) {
m.runtimeGCSkipped.WithLabelValues(normalizeRuntimeGCSkipReason(reason)).Inc()
}
-func (m *BusinessMetrics) SetRuntimeGCBacklog(reason string, count int64) {
- if m == nil {
- return
- }
- m.runtimeGCBacklog.WithLabelValues(normalizeRuntimeGCBacklogReason(reason)).Set(float64(count))
-}
-
-func (m *BusinessMetrics) SetRuntimeGCBlocked(count int64) {
- if m == nil {
- return
- }
- m.runtimeGCBlocked.Set(float64(count))
-}
-
-func (m *BusinessMetrics) RecordRuntimeGCBlockedObservationFailed() {
- if m == nil {
- return
- }
- m.runtimeGCBlockedObservationFailed.Inc()
-}
-
func normalizeRuntimeGCSkipReason(reason string) string {
switch reason {
case RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch:
@@ -439,15 +386,6 @@ func normalizeRuntimeGCSkipReason(reason string) string {
}
}
-func normalizeRuntimeGCBacklogReason(reason string) string {
- switch reason {
- case RuntimeGCBacklogActiveAgent, RuntimeGCBacklogNonTerminalTask, RuntimeGCBacklogWorkspaceMismatch, RuntimeGCBacklogEligible:
- return reason
- default:
- return "unknown"
- }
-}
-
// ObserveRuntimeSweepStage records one bounded-cardinality maintenance stage.
// candidates is the number of rows returned to or examined by the application,
// not PostgreSQL executor rows; changed is the subset whose persisted
diff --git a/server/internal/metrics/business_sampler.go b/server/internal/metrics/business_sampler.go
deleted file mode 100644
index a377ed9d5b..0000000000
--- a/server/internal/metrics/business_sampler.go
+++ /dev/null
@@ -1,428 +0,0 @@
-// Package-level note for PR4 (MUL-2947): the sampler runs at /metrics scrape
-// time, hits the read replica via the existing pgxpool, and is opt-in. Every
-// individual SQL statement runs in its own short read-only transaction with
-// `SET LOCAL statement_timeout = '500ms'` and a hard `LIMIT 100` so a slow
-// table or a hung connection cannot drag /metrics — and by extension the
-// whole alerting story — down. A 5–10 second TTL cache absorbs concurrent
-// scrapes from multiple Prometheus replicas.
-//
-// The active_users and active_workspaces samplers were retired in MUL-6882:
-// scrape-time distinct scans over growing chat and issue history consumed
-// sustained database CPU. If those metrics are needed again, source them from
-// an asynchronously maintained aggregate instead of querying raw history here.
-package metrics
-
-import (
- "context"
- "errors"
- "fmt"
- "log/slog"
- "sync"
- "time"
-
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgxpool"
- "github.com/prometheus/client_golang/prometheus"
-)
-
-// Default knobs. Kept conservative so the very first scrape on a busy DB
-// cannot stall /metrics for more than ~half a second per query, and so a
-// single scrape can never spawn a flood of identical reads even if multiple
-// Prometheus replicas attach to the same pod at once.
-const (
- defaultSamplerCacheTTL = 8 * time.Second
- defaultSamplerQueryTimeout = 500 * time.Millisecond
-
- // A running task is considered "stuck" once started_at is older
- // than this. Matches the Grafana board threshold from MUL-2328.
- stuckRunningInterval = "30 minutes"
-)
-
-// samplerQueries is the canonical query registry. The refresh deadline and
-// execution loop both derive from it so adding or removing a query cannot
-// leave a stale hand-maintained timeout multiplier behind.
-var samplerQueries = []struct {
- name string
- run func(*BusinessSamplerCollector, context.Context, pgx.Tx, *samplerSnapshot) error
-}{
- {"task_queued", (*BusinessSamplerCollector).queryTaskQueued},
- {"task_running", (*BusinessSamplerCollector).queryTaskRunning},
- {"task_stuck", (*BusinessSamplerCollector).queryTaskStuck},
- {"workspace_total", (*BusinessSamplerCollector).queryWorkspaceTotal},
-}
-
-// BusinessSamplerOptions configures the BusinessSamplerCollector. A nil
-// receiver in the registry means the sampler is disabled, which is the
-// expected state for unit tests and any deployment where the operator does
-// not opt in.
-type BusinessSamplerOptions struct {
- // Pool is the dedicated pgxpool used by the sampler. Callers SHOULD
- // build a small pool (MaxConns 1–2) pointed at the same database as
- // the main app pool, so a sampler stall cannot starve business
- // traffic. If a caller really wants to share the main pool, they may
- // pass it here — the per-query statement_timeout still bounds the
- // blast radius.
- Pool *pgxpool.Pool
-
- // CacheTTL is how long a successful sample is reused before the next
- // scrape triggers a refresh. Defaults to 8s. The spec calls for
- // 5–10s; values outside that range are accepted but logged.
- CacheTTL time.Duration
-
- // QueryTimeout is the per-query statement_timeout pushed to Postgres
- // via SET LOCAL. Defaults to 500ms.
- QueryTimeout time.Duration
-}
-
-// samplerQuerier is the minimal pgx surface the sampler needs. Splitting it
-// out lets unit tests inject a fake without spinning up a real database.
-type samplerQuerier interface {
- Acquire(ctx context.Context) (*pgxpool.Conn, error)
-}
-
-// BusinessSamplerCollector implements prometheus.Collector by issuing a fixed
-// set of read-only SQL queries on each scrape and exposing the results as
-// gauges. See the package note above for the safety contract.
-type BusinessSamplerCollector struct {
- pool samplerQuerier
- cacheTTL time.Duration
- queryTimeout time.Duration
- now func() time.Time
- logger *slog.Logger
-
- // refreshFn is the snapshot-producing function. Defaults to
- // refreshFromDB. Tests swap it out for a fake so they can exercise
- // caching / cardinality / emit logic without spinning up Postgres.
- refreshFn func(ctx context.Context, now time.Time) *samplerSnapshot
-
- // Self-introspection metrics. Registered alongside the collector via
- // Collectors() so /metrics shows query latency and error counts even
- // when the gauges themselves are stale.
- queryDuration *prometheus.HistogramVec
- queryErrors *prometheus.CounterVec
-
- // Gauge descriptors. ConstMetric is preferred over a GaugeVec because
- // the values are computed once per scrape from a fresh DB read; we
- // never want stale series sticking around because a label has stopped
- // appearing in the result set.
- descTaskQueued *prometheus.Desc
- descTaskRunning *prometheus.Desc
- descTaskStuck *prometheus.Desc
- descWorkspaceTotal *prometheus.Desc
-
- mu sync.Mutex
- snapshot *samplerSnapshot
-}
-
-// NewBusinessSamplerCollector builds the collector. Returns nil when opts
-// is nil or has a nil Pool — that signals "sampler disabled" to the
-// registry without forcing every test to provide a stub.
-func NewBusinessSamplerCollector(opts *BusinessSamplerOptions) *BusinessSamplerCollector {
- if opts == nil || opts.Pool == nil {
- return nil
- }
- cacheTTL := opts.CacheTTL
- if cacheTTL <= 0 {
- cacheTTL = defaultSamplerCacheTTL
- }
- queryTimeout := opts.QueryTimeout
- if queryTimeout <= 0 {
- queryTimeout = defaultSamplerQueryTimeout
- }
- c := &BusinessSamplerCollector{
- pool: opts.Pool,
- cacheTTL: cacheTTL,
- queryTimeout: queryTimeout,
- now: time.Now,
- logger: slog.Default(),
-
- queryDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
- Namespace: "multica",
- Subsystem: "business_sampler",
- Name: "query_seconds",
- Help: "Per-query duration of the BusinessSamplerCollector. The `name` label is one of the fixed query identifiers and never user-controlled.",
- Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5},
- }, []string{"name"}),
- queryErrors: prometheus.NewCounterVec(prometheus.CounterOpts{
- Namespace: "multica",
- Subsystem: "business_sampler",
- Name: "query_errors_total",
- Help: "Per-query error count. Includes statement_timeout cancellations, which are the expected outcome of a hung database and the smoking gun for SET LOCAL working as intended.",
- }, []string{"name"}),
-
- descTaskQueued: prometheus.NewDesc(
- "multica_agent_task_queued",
- "Current agent_task_queue rows in `queued` status by inferred source. Sampled from the database.",
- []string{"source"}, nil),
- descTaskRunning: prometheus.NewDesc(
- "multica_agent_task_running",
- "Current agent_task_queue rows in `dispatched` or `running` status by inferred source and runtime mode. Sampled from the database.",
- []string{"source", "runtime_mode"}, nil),
- descTaskStuck: prometheus.NewDesc(
- "multica_agent_task_stuck_total",
- "Current `running` agent_task_queue rows whose started_at is older than the stuck threshold. Sampled from the database.",
- []string{"source"}, nil),
- descWorkspaceTotal: prometheus.NewDesc(
- "multica_workspace_total",
- "Lifetime workspace row count. Useful for sizing alerts and dashboards.",
- nil, nil),
- }
- c.refreshFn = c.refreshFromDB
- return c
-}
-
-// Collectors returns every prometheus.Collector that the registry must mount
-// to expose this sampler — the gauges (the receiver itself) plus the query
-// duration histogram and error counter.
-func (c *BusinessSamplerCollector) Collectors() []prometheus.Collector {
- if c == nil {
- return nil
- }
- return []prometheus.Collector{c, c.queryDuration, c.queryErrors}
-}
-
-// Describe implements prometheus.Collector.
-func (c *BusinessSamplerCollector) Describe(ch chan<- *prometheus.Desc) {
- if c == nil {
- return
- }
- for _, d := range []*prometheus.Desc{
- c.descTaskQueued,
- c.descTaskRunning,
- c.descTaskStuck,
- c.descWorkspaceTotal,
- } {
- ch <- d
- }
-}
-
-// Collect implements prometheus.Collector. It returns the cached snapshot
-// when fresh; otherwise it triggers a refresh under the mutex so concurrent
-// scrapes share one DB round-trip. A refresh failure is logged and the last
-// known snapshot is reused — this is the "metric briefly stale, sampler
-// does not crash" behavior the PR4 spec requires under DB hangs.
-func (c *BusinessSamplerCollector) Collect(ch chan<- prometheus.Metric) {
- if c == nil || c.pool == nil {
- return
- }
- snap := c.maybeRefresh()
- if snap == nil {
- return
- }
- c.emit(ch, snap)
-}
-
-func (c *BusinessSamplerCollector) maybeRefresh() *samplerSnapshot {
- c.mu.Lock()
- defer c.mu.Unlock()
-
- now := c.now()
- if c.snapshot != nil && now.Sub(c.snapshot.takenAt) < c.cacheTTL {
- return c.snapshot
- }
-
- // Bound the entire refresh to N×queryTimeout so an in-flight scrape
- // can never block forever even if SET LOCAL is somehow ignored by a
- // misconfigured Postgres.
- ctx, cancel := context.WithTimeout(
- context.Background(),
- time.Duration(len(samplerQueries))*c.queryTimeout,
- )
- defer cancel()
-
- next := c.refreshFn(ctx, now)
- if next != nil {
- c.snapshot = next
- }
- return c.snapshot
-}
-
-// emit walks a snapshot and writes one prometheus.Metric per (desc, labels)
-// pair. Pure data-shaping; no DB or locking.
-func (c *BusinessSamplerCollector) emit(ch chan<- prometheus.Metric, snap *samplerSnapshot) {
- // Always emit at least one zero-valued series for queued/running per
- // known source so dashboards don't show "no data" right after a
- // process restart. Real values overwrite the zero; missing sources
- // stay at zero.
- for _, source := range knownSourceLabels() {
- ch <- prometheus.MustNewConstMetric(
- c.descTaskQueued, prometheus.GaugeValue, snap.taskQueued[source], source)
- ch <- prometheus.MustNewConstMetric(
- c.descTaskStuck, prometheus.GaugeValue, snap.taskStuck[source], source)
- }
- for _, source := range knownSourceLabels() {
- for _, mode := range knownRuntimeModeLabels() {
- key := taskRunningKey{source: source, runtimeMode: mode}
- ch <- prometheus.MustNewConstMetric(
- c.descTaskRunning, prometheus.GaugeValue, snap.taskRunning[key], source, mode)
- }
- }
-
- if snap.workspaceTotalKnown {
- ch <- prometheus.MustNewConstMetric(
- c.descWorkspaceTotal, prometheus.GaugeValue, snap.workspaceTotal)
- }
-}
-
-// knownSourceLabels enumerates the source values we always emit a zero for.
-// Pulled from the existing BusinessMetrics whitelist so the sampler never
-// invents a new bucket.
-func knownSourceLabels() []string {
- return []string{"chat", "issue", "autopilot", "autopilot_issue", "quick_create", "manual", "api", "other"}
-}
-
-func knownRuntimeModeLabels() []string {
- return []string{"local", "cloud", "unknown"}
-}
-
-// taskRunningKey is the composite gauge label key for the running counter.
-// Defined here because it is shared between the snapshot and the emit path.
-type taskRunningKey struct {
- source string
- runtimeMode string
-}
-
-// samplerSnapshot is the cached output of one full refresh. All maps are
-// pre-allocated so the emit path can read them lock-free once the receiver
-// has handed it back.
-type samplerSnapshot struct {
- takenAt time.Time
-
- taskQueued map[string]float64
- taskRunning map[taskRunningKey]float64
- taskStuck map[string]float64
-
- workspaceTotal float64
- workspaceTotalKnown bool
-}
-
-func newSamplerSnapshot(t time.Time) *samplerSnapshot {
- return &samplerSnapshot{
- takenAt: t,
- taskQueued: map[string]float64{},
- taskRunning: map[taskRunningKey]float64{},
- taskStuck: map[string]float64{},
- }
-}
-
-// refreshFromDB runs every sampler query in sequence on a single acquired
-// connection. Each query is wrapped in its own short read-only transaction
-// with SET LOCAL statement_timeout, so a hang on one statement cannot
-// poison the others. Errors are logged-and-continued: a partial snapshot is
-// strictly better than a missing one.
-func (c *BusinessSamplerCollector) refreshFromDB(ctx context.Context, now time.Time) *samplerSnapshot {
- conn, err := c.pool.Acquire(ctx)
- if err != nil {
- c.queryErrors.WithLabelValues("acquire").Inc()
- c.logger.Warn("business sampler: acquire connection failed", "error", err)
- // Reuse the last snapshot if any; mark nothing fresh.
- return c.snapshot
- }
- defer conn.Release()
-
- snap := newSamplerSnapshot(now)
-
- for _, query := range samplerQueries {
- c.runQuery(ctx, conn, query.name, func(ctx context.Context, tx pgx.Tx) error {
- return query.run(c, ctx, tx, snap)
- })
- }
-
- return snap
-}
-
-// runQuery wraps one logical sampler query: BEGIN READ ONLY, SET LOCAL
-// statement_timeout, run, COMMIT. Failures are recorded on the error
-// counter and the query duration histogram, but never propagate; the
-// snapshot is left with whatever default value (typically 0) the caller
-// pre-seeded.
-func (c *BusinessSamplerCollector) runQuery(
- ctx context.Context,
- conn *pgxpool.Conn,
- name string,
- body func(ctx context.Context, tx pgx.Tx) error,
-) {
- queryCtx, cancel := context.WithTimeout(ctx, c.queryTimeout+50*time.Millisecond)
- defer cancel()
-
- start := c.now()
- defer func() {
- c.queryDuration.WithLabelValues(name).Observe(c.now().Sub(start).Seconds())
- }()
-
- tx, err := conn.BeginTx(queryCtx, pgx.TxOptions{
- AccessMode: pgx.ReadOnly,
- IsoLevel: pgx.ReadCommitted,
- })
- if err != nil {
- c.queryErrors.WithLabelValues(name).Inc()
- c.logger.Warn("business sampler: begin tx failed", "name", name, "error", err)
- return
- }
- committed := false
- defer func() {
- if !committed {
- // Best-effort rollback; the connection is already going
- // back to the pool in the caller's defer.
- _ = tx.Rollback(context.Background())
- }
- }()
-
- // SET LOCAL is the only knob we trust: it is automatically scoped to
- // the surrounding transaction even if the connection is later reused
- // by another caller.
- timeoutMs := int(c.queryTimeout / time.Millisecond)
- if _, err := tx.Exec(queryCtx, fmt.Sprintf("SET LOCAL statement_timeout = %d", timeoutMs)); err != nil {
- c.queryErrors.WithLabelValues(name).Inc()
- c.logger.Warn("business sampler: SET LOCAL statement_timeout failed", "name", name, "error", err)
- return
- }
-
- if err := body(queryCtx, tx); err != nil {
- c.queryErrors.WithLabelValues(name).Inc()
- // Statement timeouts surface as pgx errors with code 57014; we
- // log them at INFO because they are an expected steady-state
- // outcome on a degraded DB, not a bug to alert on.
- level := slog.LevelWarn
- if isStatementTimeout(err) {
- level = slog.LevelInfo
- }
- c.logger.Log(ctx, level, "business sampler: query failed", "name", name, "error", err)
- return
- }
-
- if err := tx.Commit(queryCtx); err != nil {
- c.queryErrors.WithLabelValues(name).Inc()
- c.logger.Warn("business sampler: commit failed", "name", name, "error", err)
- return
- }
- committed = true
-}
-
-// isStatementTimeout returns true when err looks like the canonical
-// statement_timeout cancellation. Used purely to choose a log level.
-func isStatementTimeout(err error) bool {
- if err == nil {
- return false
- }
- if errors.Is(err, context.DeadlineExceeded) {
- return true
- }
- // pgx surfaces SQLSTATE 57014 ("query_canceled") on statement_timeout.
- // We don't import the pgconn type just to type-assert here; a
- // substring check is good enough for a log-level decision.
- msg := err.Error()
- return contains(msg, "57014") || contains(msg, "canceling statement due to statement timeout")
-}
-
-func contains(haystack, needle string) bool {
- if len(needle) == 0 {
- return true
- }
- for i := 0; i+len(needle) <= len(haystack); i++ {
- if haystack[i:i+len(needle)] == needle {
- return true
- }
- }
- return false
-}
diff --git a/server/internal/metrics/business_sampler_pgsleep_test.go b/server/internal/metrics/business_sampler_pgsleep_test.go
deleted file mode 100644
index dcf553c2b0..0000000000
--- a/server/internal/metrics/business_sampler_pgsleep_test.go
+++ /dev/null
@@ -1,116 +0,0 @@
-package metrics
-
-import (
- "context"
- "errors"
- "os"
- "testing"
- "time"
-
- "github.com/jackc/pgx/v5"
- "github.com/jackc/pgx/v5/pgconn"
- "github.com/jackc/pgx/v5/pgxpool"
- "github.com/prometheus/client_golang/prometheus/testutil"
-)
-
-// TestBusinessSamplerStatementTimeoutCutsHungQuery is the integration test
-// that proves the safety net is real. It connects to a live Postgres,
-// asks it to `pg_sleep(2)` inside a sampler-style transaction with
-// SET LOCAL statement_timeout = '500ms', and asserts:
-//
-// 1. The query returns in well under the sleep duration (cancelled by
-// the server, not by our caller-side context — the SET LOCAL is
-// doing the work).
-// 2. The Postgres error we caught carries SQLSTATE 57014
-// ("query_canceled"). This is the canonical proof of statement_timeout
-// firing, and it's the assertion that catches the regression where
-// someone deletes the SET LOCAL line and the test would otherwise
-// pass on a context-cancellation timeout instead.
-// 3. The error counter for that named query advances.
-// 4. The duration histogram records the cancellation latency, so
-// dashboards can see it happen.
-//
-// Skips cleanly when no DATABASE_URL is set, mirroring the integration
-// test pattern already used in cmd/server. Operators running CI without a
-// reachable Postgres see "SKIP", not a failure.
-func TestBusinessSamplerStatementTimeoutCutsHungQuery(t *testing.T) {
- dbURL := os.Getenv("DATABASE_URL")
- if dbURL == "" {
- t.Skip("DATABASE_URL not set; skipping live-Postgres statement_timeout test")
- }
-
- ctx := context.Background()
- pool, err := pgxpool.New(ctx, dbURL)
- if err != nil {
- t.Skipf("could not connect to %s: %v", dbURL, err)
- }
- defer pool.Close()
- if err := pool.Ping(ctx); err != nil {
- t.Skipf("database not reachable at %s: %v", dbURL, err)
- }
-
- c := NewBusinessSamplerCollector(&BusinessSamplerOptions{
- Pool: pool,
- CacheTTL: time.Second,
- QueryTimeout: 500 * time.Millisecond,
- })
- if c == nil {
- t.Fatal("NewBusinessSamplerCollector returned nil for live pool")
- }
-
- conn, err := pool.Acquire(ctx)
- if err != nil {
- t.Fatalf("acquire conn for hung-query test: %v", err)
- }
- defer conn.Release()
-
- const queryName = "pg_sleep_canary"
- var capturedErr error
- start := time.Now()
- c.runQuery(ctx, conn, queryName, func(ctx context.Context, tx pgx.Tx) error {
- // 2 s is comfortably longer than the 500 ms statement_timeout
- // AND the 550 ms outer context deadline, so whichever layer
- // fires first we still observe a cancelled query.
- _, err := tx.Exec(ctx, "SELECT pg_sleep(2)")
- capturedErr = err
- return err
- })
- elapsed := time.Since(start)
-
- // We give a generous upper bound (1.5 s) to absorb local-Postgres
- // scheduler jitter and pgx round-trip overhead. The lower bound
- // (>250 ms) confirms we *did* hit the timeout rather than the query
- // returning instantly because pg_sleep was elided somewhere.
- if elapsed >= 1500*time.Millisecond {
- t.Fatalf("statement_timeout did not cut the hung query: elapsed %s", elapsed)
- }
- if elapsed <= 250*time.Millisecond {
- t.Fatalf("query returned suspiciously fast (%s); SET LOCAL statement_timeout may not be in force", elapsed)
- }
-
- // SQLSTATE 57014 ("query_canceled") is the canonical proof that
- // Postgres itself terminated the query because of statement_timeout.
- // If a future refactor accidentally drops the SET LOCAL line, the
- // query would still get cancelled — but by our caller-side context,
- // not by Postgres, and this assertion would catch it.
- if capturedErr == nil {
- t.Fatal("expected pg_sleep to return an error; got nil")
- }
- var pgErr *pgconn.PgError
- if !errors.As(capturedErr, &pgErr) {
- t.Fatalf("expected *pgconn.PgError from pg_sleep cancellation; got %T: %v", capturedErr, capturedErr)
- }
- if pgErr.Code != "57014" {
- t.Fatalf("expected SQLSTATE 57014 (query_canceled); got %q (%s)", pgErr.Code, pgErr.Message)
- }
-
- // One labelled error must have been recorded against the named query.
- if got := testutil.ToFloat64(c.queryErrors.WithLabelValues(queryName)); got < 1 {
- t.Fatalf("query_errors_total{name=%q} = %v, want >= 1", queryName, got)
- }
-
- // And one observation must have landed on the duration histogram.
- if got := testutil.CollectAndCount(c.queryDuration); got < 1 {
- t.Fatalf("query_seconds histogram saw 0 observations after pg_sleep cancellation")
- }
-}
diff --git a/server/internal/metrics/business_sampler_queries.go b/server/internal/metrics/business_sampler_queries.go
deleted file mode 100644
index 0b82dd6117..0000000000
--- a/server/internal/metrics/business_sampler_queries.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package metrics
-
-import (
- "context"
- "fmt"
-
- "github.com/jackc/pgx/v5"
-)
-
-// SQL bodies for BusinessSamplerCollector. Kept in a separate file so the
-// orchestration logic in business_sampler.go stays readable. Every query:
-// - is parameterised; never concatenates user / label input
-// - uses an explicit `LIMIT 100` belt-and-braces (the result set is
-// already bounded by GROUP BY, but the LIMIT is the spec-mandated
-// last-line-of-defense against an accidental high-cardinality output)
-// - normalises raw column values (source / runtime_mode)
-// through the existing BusinessMetrics whitelists so the sampler
-// cannot widen the metric label space.
-
-// queryTaskQueued counts agent_task_queue rows in `queued` status, grouped
-// by inferred source. The CASE expression here mirrors the source
-// derivation in service/task.go so sampler and event-time metrics agree.
-func (c *BusinessSamplerCollector) queryTaskQueued(
- ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,
-) error {
- const stmt = `
-SELECT
- CASE
- WHEN chat_session_id IS NOT NULL THEN 'chat'
- WHEN autopilot_run_id IS NOT NULL THEN 'autopilot'
- WHEN issue_id IS NOT NULL THEN 'issue'
- ELSE 'other'
- END AS source,
- count(*) AS n
-FROM agent_task_queue
-WHERE status = 'queued'
-GROUP BY 1
-LIMIT 100
-`
- rows, err := tx.Query(ctx, stmt)
- if err != nil {
- return fmt.Errorf("task_queued: %w", err)
- }
- defer rows.Close()
- for rows.Next() {
- var rawSource string
- var n int64
- if err := rows.Scan(&rawSource, &n); err != nil {
- return fmt.Errorf("task_queued scan: %w", err)
- }
- snap.taskQueued[NormalizeTaskSource(rawSource)] += float64(n)
- }
- return rows.Err()
-}
-
-// queryTaskRunning counts agent_task_queue rows in `dispatched` or
-// `running` status, grouped by source × runtime_mode. runtime_mode comes
-// from the joined agent_runtime row; values outside the allow-list collapse
-// to "unknown".
-func (c *BusinessSamplerCollector) queryTaskRunning(
- ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,
-) error {
- // Keep dispatched and running in separate UNION ALL branches so
- // Postgres can match the existing dispatched partial index and the
- // running-only partial index from migration 114 independently.
- const stmt = `
-WITH in_flight AS (
- SELECT chat_session_id, autopilot_run_id, issue_id, runtime_id
- FROM agent_task_queue
- WHERE status = 'dispatched'
- UNION ALL
- SELECT chat_session_id, autopilot_run_id, issue_id, runtime_id
- FROM agent_task_queue
- WHERE status = 'running'
-)
-SELECT
- CASE
- WHEN atq.chat_session_id IS NOT NULL THEN 'chat'
- WHEN atq.autopilot_run_id IS NOT NULL THEN 'autopilot'
- WHEN atq.issue_id IS NOT NULL THEN 'issue'
- ELSE 'other'
- END AS source,
- COALESCE(ar.runtime_mode, 'unknown') AS runtime_mode,
- count(*) AS n
-FROM in_flight atq
-LEFT JOIN agent_runtime ar ON ar.id = atq.runtime_id
-GROUP BY 1, 2
-LIMIT 100
-`
- rows, err := tx.Query(ctx, stmt)
- if err != nil {
- return fmt.Errorf("task_running: %w", err)
- }
- defer rows.Close()
- for rows.Next() {
- var rawSource, rawMode string
- var n int64
- if err := rows.Scan(&rawSource, &rawMode, &n); err != nil {
- return fmt.Errorf("task_running scan: %w", err)
- }
- key := taskRunningKey{
- source: NormalizeTaskSource(rawSource),
- runtimeMode: NormalizeRuntimeMode(rawMode),
- }
- snap.taskRunning[key] += float64(n)
- }
- return rows.Err()
-}
-
-// queryTaskStuck counts `running` agent_task_queue rows whose started_at
-// crosses the stuck threshold, grouped by inferred source.
-func (c *BusinessSamplerCollector) queryTaskStuck(
- ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,
-) error {
- stmt := `
-SELECT
- CASE
- WHEN chat_session_id IS NOT NULL THEN 'chat'
- WHEN autopilot_run_id IS NOT NULL THEN 'autopilot'
- WHEN issue_id IS NOT NULL THEN 'issue'
- ELSE 'other'
- END AS source,
- count(*) AS n
-FROM agent_task_queue
-WHERE status = 'running'
- AND started_at IS NOT NULL
- AND started_at < now() - interval '` + stuckRunningInterval + `'
-GROUP BY 1
-LIMIT 100
-`
- rows, err := tx.Query(ctx, stmt)
- if err != nil {
- return fmt.Errorf("task_stuck: %w", err)
- }
- defer rows.Close()
- for rows.Next() {
- var rawSource string
- var n int64
- if err := rows.Scan(&rawSource, &n); err != nil {
- return fmt.Errorf("task_stuck scan: %w", err)
- }
- snap.taskStuck[NormalizeTaskSource(rawSource)] += float64(n)
- }
- return rows.Err()
-}
-
-// queryWorkspaceTotal exposes a lifetime workspace count. Single integer,
-// no labels — useful for sizing dashboards and capacity planning.
-func (c *BusinessSamplerCollector) queryWorkspaceTotal(
- ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,
-) error {
- const stmt = `SELECT count(*) FROM workspace LIMIT 100`
- var n int64
- if err := tx.QueryRow(ctx, stmt).Scan(&n); err != nil {
- return fmt.Errorf("workspace_total: %w", err)
- }
- snap.workspaceTotal = float64(n)
- snap.workspaceTotalKnown = true
- return nil
-}
diff --git a/server/internal/metrics/business_sampler_test.go b/server/internal/metrics/business_sampler_test.go
deleted file mode 100644
index 4ac38758fc..0000000000
--- a/server/internal/metrics/business_sampler_test.go
+++ /dev/null
@@ -1,289 +0,0 @@
-package metrics
-
-import (
- "context"
- "net/http"
- "net/http/httptest"
- "strings"
- "sync/atomic"
- "testing"
- "time"
-
- "github.com/jackc/pgx/v5/pgxpool"
- "github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/testutil"
-)
-
-// newTestSampler builds a BusinessSamplerCollector wired to a fake refresh
-// function. We bypass NewBusinessSamplerCollector's nil-pool short-circuit
-// by passing a dummy pgxpool — the fake refreshFn never calls into it. This
-// keeps the real DB code path off the hot path of every unit test while
-// still exercising the production registration / emit logic.
-func newTestSampler(t *testing.T, refresh func(ctx context.Context, now time.Time) *samplerSnapshot) *BusinessSamplerCollector {
- t.Helper()
- pool, err := pgxpool.New(context.Background(), "postgres://[email protected]:1/none?sslmode=disable")
- if err != nil {
- t.Fatalf("create dummy pool: %v", err)
- }
- t.Cleanup(pool.Close)
-
- c := NewBusinessSamplerCollector(&BusinessSamplerOptions{
- Pool: pool,
- CacheTTL: 50 * time.Millisecond,
- QueryTimeout: 100 * time.Millisecond,
- })
- if c == nil {
- t.Fatalf("NewBusinessSamplerCollector returned nil")
- }
- c.refreshFn = refresh
- return c
-}
-
-func filledSnapshot(now time.Time) *samplerSnapshot {
- snap := newSamplerSnapshot(now)
- snap.taskQueued["chat"] = 5
- snap.taskQueued["issue"] = 2
-
- snap.taskRunning[taskRunningKey{source: "chat", runtimeMode: "cloud"}] = 3
- snap.taskRunning[taskRunningKey{source: "issue", runtimeMode: "local"}] = 1
-
- snap.taskStuck["issue"] = 1
-
- snap.workspaceTotal = 250
- snap.workspaceTotalKnown = true
- return snap
-}
-
-// TestBusinessSamplerCollectorEmitsExpectedMetrics asserts every current
-// sampler metric family is present on /metrics with the expected
-// values, AND that we always emit a known-source/runtime-mode zero series
-// so dashboards don't show "no data" right after a restart.
-func TestBusinessSamplerCollectorEmitsExpectedMetrics(t *testing.T) {
- now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
- c := newTestSampler(t, func(ctx context.Context, refreshAt time.Time) *samplerSnapshot {
- return filledSnapshot(refreshAt)
- })
- c.now = func() time.Time { return now }
-
- registry := prometheus.NewRegistry()
- registry.MustRegister(c.Collectors()...)
-
- rec := httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- body := rec.Body.String()
-
- wantSubstrings := []string{
- `multica_agent_task_queued{source="chat"} 5`,
- `multica_agent_task_queued{source="issue"} 2`,
- // Zero series for sources that didn't appear in the snapshot.
- `multica_agent_task_queued{source="autopilot"} 0`,
- `multica_agent_task_queued{source="other"} 0`,
- `multica_agent_task_running{runtime_mode="cloud",source="chat"} 3`,
- `multica_agent_task_running{runtime_mode="local",source="issue"} 1`,
- `multica_agent_task_stuck_total{source="issue"} 1`,
- `multica_workspace_total 250`,
- }
- for _, want := range wantSubstrings {
- if !strings.Contains(body, want) {
- t.Errorf("metrics body missing %q\nbody:\n%s", want, body)
- }
- }
- for _, removed := range []string{
- `multica_active_users`,
- `multica_active_workspaces`,
- `multica_runtime_online`,
- `multica_runtime_heartbeat_age_seconds`,
- } {
- if strings.Contains(body, removed) {
- t.Errorf("metrics body still exposes removed series %q\nbody:\n%s", removed, body)
- }
- }
-}
-
-// TestBusinessSamplerSelfIntrospectionHistogramIsExposed observes a value
-// directly on the query-duration histogram and asserts it surfaces on
-// /metrics. Prometheus elides histograms with zero observations, so we have
-// to seed one before scraping.
-func TestBusinessSamplerSelfIntrospectionHistogramIsExposed(t *testing.T) {
- c := newTestSampler(t, func(ctx context.Context, refreshAt time.Time) *samplerSnapshot {
- return newSamplerSnapshot(refreshAt)
- })
- c.queryDuration.WithLabelValues("task_queued").Observe(0.012)
-
- registry := prometheus.NewRegistry()
- registry.MustRegister(c.Collectors()...)
-
- rec := httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- body := rec.Body.String()
- if !strings.Contains(body, `multica_business_sampler_query_seconds_count{name="task_queued"} 1`) {
- t.Fatalf("query duration histogram missing\n%s", body)
- }
-}
-
-// TestBusinessSamplerCollectorCachesSnapshot asserts the TTL cache absorbs
-// concurrent scrapes: two Collect calls inside the TTL window must trigger
-// exactly one refresh, and a third call after the TTL elapses must trigger
-// a second.
-func TestBusinessSamplerCollectorCachesSnapshot(t *testing.T) {
- var refreshCount atomic.Int32
- now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
- current := now
-
- c := newTestSampler(t, func(ctx context.Context, refreshAt time.Time) *samplerSnapshot {
- refreshCount.Add(1)
- return filledSnapshot(refreshAt)
- })
- c.cacheTTL = 100 * time.Millisecond
- c.now = func() time.Time { return current }
-
- registry := prometheus.NewRegistry()
- registry.MustRegister(c.Collectors()...)
-
- rec := httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- rec = httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- if got := refreshCount.Load(); got != 1 {
- t.Fatalf("refresh count after two cached scrapes = %d, want 1", got)
- }
-
- // Advance past the TTL — the next scrape must refresh again.
- current = current.Add(150 * time.Millisecond)
- rec = httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- if got := refreshCount.Load(); got != 2 {
- t.Fatalf("refresh count after TTL expiry = %d, want 2", got)
- }
-}
-
-// TestBusinessSamplerCollectorBoundedCardinality is the cardinality canary.
-// Even with a malicious snapshot that mentions many distinct labels, the
-// sampler must collapse them into the BusinessMetrics whitelist plus
-// known-label zero series. This protects /metrics from a per-runtime or
-// per-workspace explosion.
-func TestBusinessSamplerCollectorBoundedCardinality(t *testing.T) {
- now := time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC)
- c := newTestSampler(t, func(ctx context.Context, refreshAt time.Time) *samplerSnapshot {
- // We can't inject raw rogue labels through the snapshot directly
- // (the maps are typed), so we exercise the normalization path by
- // pre-normalizing here exactly the way refreshFromDB would.
- snap := newSamplerSnapshot(refreshAt)
- for i := 0; i < 50; i++ {
- snap.taskQueued[NormalizeTaskSource("provider-from-user-input-"+string(rune('A'+i%26)))] += 1
- }
- for i := 0; i < 50; i++ {
- snap.taskRunning[taskRunningKey{
- source: NormalizeTaskSource("source-from-user-input-" + string(rune('A'+i%26))),
- runtimeMode: NormalizeRuntimeMode("rogue-mode"),
- }] += 1
- }
- return snap
- })
- c.now = func() time.Time { return now }
-
- registry := prometheus.NewRegistry()
- registry.MustRegister(c.Collectors()...)
-
- if got := testutil.CollectAndCount(c, "multica_agent_task_queued"); got != len(knownSourceLabels()) {
- t.Fatalf("agent_task_queued series = %d, want %d", got, len(knownSourceLabels()))
- }
- expectedRunning := len(knownSourceLabels()) * len(knownRuntimeModeLabels())
- if got := testutil.CollectAndCount(c, "multica_agent_task_running"); got != expectedRunning {
- t.Fatalf("agent_task_running series = %d, want %d", got, expectedRunning)
- }
-
- rec := httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- body := rec.Body.String()
- for _, want := range []string{
- `multica_agent_task_queued{source="other"} 50`,
- `multica_agent_task_running{runtime_mode="unknown",source="other"} 50`,
- } {
- if !strings.Contains(body, want) {
- t.Errorf("normalized sampler series missing %q\nbody:\n%s", want, body)
- }
- }
-}
-
-// TestBusinessSamplerCollectorDisabledWithoutOptions exercises the opt-in
-// path in the registry: no BusinessSampler option means no sampler-related
-// series leak into /metrics, and existing collectors stay registered.
-func TestBusinessSamplerCollectorDisabledWithoutOptions(t *testing.T) {
- registry := NewRegistry(RegistryOptions{})
- if registry.Sampler != nil {
- t.Fatalf("Sampler must be nil when BusinessSampler option is absent")
- }
- rec := httptest.NewRecorder()
- NewHandler(registry.Gatherer).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- body := rec.Body.String()
- for _, forbidden := range []string{
- "multica_active_users",
- "multica_active_workspaces",
- "multica_agent_task_queued",
- "multica_agent_task_running",
- "multica_business_sampler_query_seconds",
- } {
- if strings.Contains(body, forbidden) {
- t.Errorf("/metrics leaked sampler family %q when sampler disabled", forbidden)
- }
- }
-}
-
-// TestBusinessSamplerCollectorDBHangIsolation simulates a hung database
-// using a pgxpool pointed at an unreachable host. The sampler must not
-// panic, must not block /metrics indefinitely, and must record the
-// resulting failure on the query error counter — that's the
-// statement_timeout / connection-acquire safety net the spec asks for.
-func TestBusinessSamplerCollectorDBHangIsolation(t *testing.T) {
- pool, err := pgxpool.New(context.Background(), "postgres://[email protected]:1/none?sslmode=disable")
- if err != nil {
- t.Fatalf("create unreachable pool: %v", err)
- }
- defer pool.Close()
-
- c := NewBusinessSamplerCollector(&BusinessSamplerOptions{
- Pool: pool,
- CacheTTL: time.Second,
- QueryTimeout: 50 * time.Millisecond,
- })
- if c == nil {
- t.Fatalf("NewBusinessSamplerCollector returned nil")
- }
-
- // Use the real refreshFromDB path so we exercise Acquire / SET LOCAL
- // statement_timeout / error counter wiring.
- registry := prometheus.NewRegistry()
- registry.MustRegister(c.Collectors()...)
-
- done := make(chan struct{})
- go func() {
- rec := httptest.NewRecorder()
- NewHandler(registry).ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
- close(done)
- }()
-
- select {
- case <-done:
- // Success — the scrape completed despite no reachable DB.
- case <-time.After(5 * time.Second):
- t.Fatal("metrics scrape blocked > 5s on unreachable DB")
- }
-
- // At least one error must have been recorded against the
- // connection-acquire path. We don't assert exact name to avoid
- // coupling to internal labels; we just want a positive count.
- if got := testutil.CollectAndCount(c.queryErrors); got == 0 {
- t.Fatal("expected at least one query_errors_total series after DB hang")
- }
-}
-
-// TestNewBusinessSamplerCollectorNilPool covers the explicit opt-out path.
-func TestNewBusinessSamplerCollectorNilPool(t *testing.T) {
- if c := NewBusinessSamplerCollector(nil); c != nil {
- t.Fatalf("NewBusinessSamplerCollector(nil) = %p, want nil", c)
- }
- if c := NewBusinessSamplerCollector(&BusinessSamplerOptions{}); c != nil {
- t.Fatalf("NewBusinessSamplerCollector with nil Pool = %p, want nil", c)
- }
-}
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index 4a096e5a3e..2246e8c0b3 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -208,12 +208,6 @@ func TestBusinessMetricsRuntimeGC(t *testing.T) {
m.RecordRuntimeGCDeleted()
m.RecordRuntimeGCFailed()
m.RecordRuntimeGCSkipped(RuntimeGCSkipNonTerminalTask)
- m.SetRuntimeGCBlocked(3)
- m.SetRuntimeGCBacklog(RuntimeGCBacklogActiveAgent, 2)
- m.SetRuntimeGCBacklog(RuntimeGCBacklogNonTerminalTask, 3)
- m.SetRuntimeGCBacklog(RuntimeGCBacklogWorkspaceMismatch, 1)
- m.SetRuntimeGCBacklog(RuntimeGCBacklogEligible, 4)
- m.RecordRuntimeGCBlockedObservationFailed()
if got := testutil.ToFloat64(m.runtimeGCDeleted); got != 1 {
t.Fatalf("runtime GC deleted = %v, want 1", got)
@@ -224,22 +218,6 @@ func TestBusinessMetricsRuntimeGC(t *testing.T) {
if got := testutil.ToFloat64(m.runtimeGCSkipped.WithLabelValues(RuntimeGCSkipNonTerminalTask)); got != 1 {
t.Fatalf("runtime GC skipped = %v, want 1", got)
}
- if got := testutil.ToFloat64(m.runtimeGCBlocked); got != 3 {
- t.Fatalf("runtime GC blocked = %v, want 3", got)
- }
- for reason, want := range map[string]float64{
- RuntimeGCBacklogActiveAgent: 2,
- RuntimeGCBacklogNonTerminalTask: 3,
- RuntimeGCBacklogWorkspaceMismatch: 1,
- RuntimeGCBacklogEligible: 4,
- } {
- if got := testutil.ToFloat64(m.runtimeGCBacklog.WithLabelValues(reason)); got != want {
- t.Fatalf("runtime GC backlog %s = %v, want %v", reason, got, want)
- }
- }
- if got := testutil.ToFloat64(m.runtimeGCBlockedObservationFailed); got != 1 {
- t.Fatalf("runtime GC blocked observation failures = %v, want 1", got)
- }
}
func TestBusinessMetricsRuntimeSweepStage(t *testing.T) {
diff --git a/server/internal/metrics/channel_media.go b/server/internal/metrics/channel_media.go
index f6ea71ff3f..189fd1d0a4 100644
--- a/server/internal/metrics/channel_media.go
+++ b/server/internal/metrics/channel_media.go
@@ -4,15 +4,12 @@ import "github.com/prometheus/client_golang/prometheus"
// ChannelMediaReconcilerMetrics observes the media intent-ledger reconciler:
// how many unreferenced objects it deletes, how many rows it clears because a
-// durable attachment reference exists, how many storage deletes fail (and go
-// to backoff), and the current ledger backlog. Whether the fixed settle/sweep
-// constants ever need a config surface is decided from these numbers.
+// durable attachment reference exists, and how many storage deletes fail (and
+// go to backoff).
type ChannelMediaReconcilerMetrics struct {
ObjectsDeleted prometheus.Counter
RowsReferenced prometheus.Counter
DeleteFailures prometheus.Counter
- Backlog prometheus.Gauge
- Tombstones prometheus.Gauge
// TombstoneReferenced counts an invariant violation, not routine work:
// a tombstone pass found an attachment reading the object it was about to
// re-delete. The object is kept; a non-zero value means the per-message
@@ -40,18 +37,6 @@ func NewChannelMediaReconcilerMetrics() *ChannelMediaReconcilerMetrics {
Name: "reconciler_delete_failures_total",
Help: "Object-storage deletes that failed and were scheduled for retry.",
}),
- Backlog: prometheus.NewGauge(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "channel_media",
- Name: "pending_objects",
- Help: "Live intent rows awaiting bind or reclaim (excludes tombstones).",
- }),
- Tombstones: prometheus.NewGauge(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "channel_media",
- Name: "tombstoned_objects",
- Help: "Deleted objects still tombstoned for scheduled re-deletion.",
- }),
TombstoneReferenced: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: "multica",
Subsystem: "channel_media",
@@ -62,5 +47,5 @@ func NewChannelMediaReconcilerMetrics() *ChannelMediaReconcilerMetrics {
}
func (m *ChannelMediaReconcilerMetrics) Collectors() []prometheus.Collector {
- return []prometheus.Collector{m.ObjectsDeleted, m.RowsReferenced, m.DeleteFailures, m.Backlog, m.Tombstones, m.TombstoneReferenced}
+ return []prometheus.Collector{m.ObjectsDeleted, m.RowsReferenced, m.DeleteFailures, m.TombstoneReferenced}
}
diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.go
index 4b7e76ef62..c60162cf27 100644
--- a/server/internal/metrics/labels.go
+++ b/server/internal/metrics/labels.go
@@ -83,7 +83,6 @@ var businessMetricLabels = map[string][]string{
"multica_runtime_failed_total": {labelRuntimeMode, labelProvider, labelFailureReason, labelRecoverable},
"multica_runtime_offline_total": {labelRuntimeMode, labelProvider},
"multica_runtime_gc_skipped_total": {labelReason},
- "multica_runtime_gc_backlog_runtimes": {labelReason},
"multica_daemon_ws_message_received_total": {labelKind},
"multica_autopilot_run_started_total": {labelCadence, labelTriggerKind},
"multica_autopilot_run_terminal_total": {labelCadence, labelTriggerKind, labelTerminalStatus},
diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.go
index c42641a1b5..6c49d24d80 100644
--- a/server/internal/metrics/registry.go
+++ b/server/internal/metrics/registry.go
@@ -17,13 +17,6 @@ type RegistryOptions struct {
DaemonWS *daemonws.Metrics
Version string
Commit string
-
- // BusinessSampler, when non-nil, opts the registry into the
- // scrape-time SQL sampler from PR4 (MUL-2947). It is intentionally
- // separate from Pool so existing tests (and any deployment without
- // METRICS_ADDR) cannot accidentally start hitting the database on
- // every /metrics scrape.
- BusinessSampler *BusinessSamplerOptions
}
type Registry struct {
@@ -32,12 +25,7 @@ type Registry struct {
Business *BusinessMetrics
ChannelMedia *ChannelMediaReconcilerMetrics
ChannelLease *ChannelLeaseMetrics
- SeatCapacity *SeatCapacityMetrics
Wecom *WecomMetrics
- // Sampler is non-nil only when RegistryOptions.BusinessSampler was
- // supplied with a valid Pool. Exposed so the cmd/server entrypoint
- // can plumb the same instance into health checks if it ever wants to.
- Sampler *BusinessSamplerCollector
}
func NewRegistry(opts RegistryOptions) *Registry {
@@ -64,9 +52,6 @@ func NewRegistry(opts RegistryOptions) *Registry {
channelLease := NewChannelLeaseMetrics()
reg.MustRegister(channelLease.Collectors()...)
- seatCapacity := NewSeatCapacityMetrics()
- reg.MustRegister(seatCapacity.Collectors()...)
-
wecomMetrics := NewWecomMetrics()
reg.MustRegister(wecomMetrics.Collectors()...)
@@ -80,20 +65,13 @@ func NewRegistry(opts RegistryOptions) *Registry {
reg.MustRegister(NewDaemonWSCollector(opts.DaemonWS))
}
- sampler := NewBusinessSamplerCollector(opts.BusinessSampler)
- if sampler != nil {
- reg.MustRegister(sampler.Collectors()...)
- }
-
return &Registry{
Gatherer: reg,
HTTP: httpMetrics,
Business: businessMetrics,
ChannelMedia: channelMedia,
ChannelLease: channelLease,
- SeatCapacity: seatCapacity,
Wecom: wecomMetrics,
- Sampler: sampler,
}
}
diff --git a/server/internal/metrics/registry_test.go b/server/internal/metrics/registry_test.go
new file mode 100644
index 0000000000..07b1f8c95f
--- /dev/null
+++ b/server/internal/metrics/registry_test.go
@@ -0,0 +1,33 @@
+package metrics
+
+import "testing"
+
+func TestRegistryExcludesDatabaseSampledMetrics(t *testing.T) {
+ registry := NewRegistry(RegistryOptions{})
+ families, err := registry.Gatherer.Gather()
+ if err != nil {
+ t.Fatalf("gather metrics: %v", err)
+ }
+
+ retired := map[string]struct{}{
+ "multica_agent_task_queued": {},
+ "multica_agent_task_running": {},
+ "multica_agent_task_stuck_total": {},
+ "multica_business_sampler_query_errors_total": {},
+ "multica_business_sampler_query_seconds": {},
+ "multica_workspace_total": {},
+ "multica_seat_capacity_outbox_pending": {},
+ "multica_seat_capacity_outbox_dead_lettered": {},
+ "multica_seat_capacity_outbox_oldest_pending_age_seconds": {},
+ "multica_channel_media_pending_objects": {},
+ "multica_channel_media_tombstoned_objects": {},
+ "multica_runtime_gc_blocked_observation_failed_total": {},
+ "multica_runtime_gc_blocked_runtimes": {},
+ "multica_runtime_gc_backlog_runtimes": {},
+ }
+ for _, family := range families {
+ if _, found := retired[family.GetName()]; found {
+ t.Errorf("retired database-sampled metric %q is still registered", family.GetName())
+ }
+ }
+}
diff --git a/server/internal/metrics/seat_capacity.go b/server/internal/metrics/seat_capacity.go
deleted file mode 100644
index 0c79c64d96..0000000000
--- a/server/internal/metrics/seat_capacity.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package metrics
-
-import "github.com/prometheus/client_golang/prometheus"
-
-var seatCapacityActions = []string{
- "reserve_invitation",
- "consume_invitation",
- "claim_share_join",
- "confirm",
- "release",
- "release_member",
-}
-
-// SeatCapacityMetrics exposes product-side billing intents without using
-// workspace IDs as labels. Operators can alert on an action becoming old or
-// entering the terminal dead-letter state while preserving tenant privacy.
-type SeatCapacityMetrics struct {
- Pending *prometheus.GaugeVec
- DeadLettered *prometheus.GaugeVec
- OldestPendingAge *prometheus.GaugeVec
-}
-
-func NewSeatCapacityMetrics() *SeatCapacityMetrics {
- m := &SeatCapacityMetrics{
- Pending: prometheus.NewGaugeVec(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "seat_capacity_outbox",
- Name: "pending",
- Help: "Product-side seat capacity intents waiting to settle by action.",
- }, []string{"action"}),
- DeadLettered: prometheus.NewGaugeVec(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "seat_capacity_outbox",
- Name: "dead_lettered",
- Help: "Terminal seat capacity intents requiring operator repair by action.",
- }, []string{"action"}),
- OldestPendingAge: prometheus.NewGaugeVec(prometheus.GaugeOpts{
- Namespace: "multica",
- Subsystem: "seat_capacity_outbox",
- Name: "oldest_pending_age_seconds",
- Help: "Age in seconds of the oldest unsettled seat capacity intent by action.",
- }, []string{"action"}),
- }
- m.ResetOutbox()
- return m
-}
-
-func (m *SeatCapacityMetrics) ResetOutbox() {
- if m == nil {
- return
- }
- m.Pending.Reset()
- m.DeadLettered.Reset()
- m.OldestPendingAge.Reset()
- for _, action := range seatCapacityActions {
- m.SetOutbox(action, 0, 0, 0)
- }
-}
-
-func (m *SeatCapacityMetrics) SetOutbox(action string, pending, deadLettered int64, oldestPendingAgeSeconds float64) {
- if m == nil {
- return
- }
- m.Pending.WithLabelValues(action).Set(float64(pending))
- m.DeadLettered.WithLabelValues(action).Set(float64(deadLettered))
- m.OldestPendingAge.WithLabelValues(action).Set(oldestPendingAgeSeconds)
-}
-
-func (m *SeatCapacityMetrics) Collectors() []prometheus.Collector {
- return []prometheus.Collector{m.Pending, m.DeadLettered, m.OldestPendingAge}
-}
diff --git a/server/internal/metrics/seat_capacity_test.go b/server/internal/metrics/seat_capacity_test.go
deleted file mode 100644
index 4e12c55384..0000000000
--- a/server/internal/metrics/seat_capacity_test.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package metrics
-
-import (
- "testing"
-
- "github.com/prometheus/client_golang/prometheus"
- "github.com/prometheus/client_golang/prometheus/testutil"
-)
-
-func TestSeatCapacityMetricsExposePendingAndDeadLettersByAction(t *testing.T) {
- metrics := NewSeatCapacityMetrics()
- registry := prometheus.NewPedanticRegistry()
- registry.MustRegister(metrics.Collectors()...)
-
- metrics.SetOutbox("release", 3, 1, 901)
-
- if got := testutil.ToFloat64(metrics.Pending.WithLabelValues("release")); got != 3 {
- t.Fatalf("pending release=%v, want 3", got)
- }
- if got := testutil.ToFloat64(metrics.DeadLettered.WithLabelValues("release")); got != 1 {
- t.Fatalf("dead-lettered release=%v, want 1", got)
- }
- if got := testutil.ToFloat64(metrics.OldestPendingAge.WithLabelValues("release")); got != 901 {
- t.Fatalf("oldest release age=%v, want 901", got)
- }
- if _, err := registry.Gather(); err != nil {
- t.Fatal(err)
- }
-
- metrics.ResetOutbox()
- if got := testutil.ToFloat64(metrics.DeadLettered.WithLabelValues("release")); got != 0 {
- t.Fatalf("dead-lettered release after reset=%v, want 0", got)
- }
-}
diff --git a/server/internal/seatcapacity/worker.go b/server/internal/seatcapacity/worker.go
index 52df8f7a54..0fd8eed67b 100644
--- a/server/internal/seatcapacity/worker.go
+++ b/server/internal/seatcapacity/worker.go
@@ -33,7 +33,6 @@ type WorkerConfig struct {
BatchSize int32
MaxAttempts int32
Logger *slog.Logger
- Metrics WorkerMetrics
}
type workerQueries interface {
@@ -45,15 +44,9 @@ type workerQueries interface {
GetInvitation(context.Context, pgtype.UUID) (db.WorkspaceInvitation, error)
MarkClaimedSeatCapacityIntentDeadLettered(context.Context, db.MarkClaimedSeatCapacityIntentDeadLetteredParams) (int64, error)
MarkClaimedSeatCapacityIntentFailed(context.Context, db.MarkClaimedSeatCapacityIntentFailedParams) (int64, error)
- SeatCapacityOutboxStats(context.Context) ([]db.SeatCapacityOutboxStatsRow, error)
TransitionClaimedSeatCapacityIntent(context.Context, db.TransitionClaimedSeatCapacityIntentParams) (int64, error)
}
-type WorkerMetrics interface {
- ResetOutbox()
- SetOutbox(action string, pending, deadLettered int64, oldestPendingAgeSeconds float64)
-}
-
// Worker settles durable product-side intents. Each row is claimed atomically
// before a Cloud request, so API replicas do not amplify the same backlog.
type Worker struct {
@@ -63,7 +56,6 @@ type Worker struct {
batchSize int32
maxAttempts int32
logger *slog.Logger
- metrics WorkerMetrics
workspaceLocker WorkspaceLocker
now func() time.Time
}
@@ -94,7 +86,7 @@ func newWorker(queries workerQueries, executor Executor, cfg WorkerConfig) *Work
return &Worker{
queries: queries, executor: executor, reconcileInterval: interval,
batchSize: batch, maxAttempts: maxAttempts, logger: logger,
- metrics: cfg.Metrics, now: time.Now,
+ now: time.Now,
}
}
@@ -163,7 +155,7 @@ func (w *Worker) ReconcileOnce(ctx context.Context) error {
w.recordFailure(ctx, intent, settleErr)
}
}
- return w.refreshMetrics(ctx)
+ return nil
}
type rateLimitDeferral struct {
@@ -394,21 +386,6 @@ func (w *Worker) recordFailure(ctx context.Context, intent db.SeatCapacityOutbox
}
}
-func (w *Worker) refreshMetrics(ctx context.Context) error {
- if w.metrics == nil {
- return nil
- }
- stats, err := w.queries.SeatCapacityOutboxStats(ctx)
- if err != nil {
- return err
- }
- w.metrics.ResetOutbox()
- for _, stat := range stats {
- w.metrics.SetOutbox(stat.Action, stat.PendingCount, stat.DeadLetteredCount, stat.OldestPendingAgeSeconds)
- }
- return nil
-}
-
func uuidFromPG(value pgtype.UUID) uuid.UUID {
if !value.Valid {
return uuid.Nil
diff --git a/server/internal/seatcapacity/worker_test.go b/server/internal/seatcapacity/worker_test.go
index 555137c10d..a527d507bd 100644
--- a/server/internal/seatcapacity/worker_test.go
+++ b/server/internal/seatcapacity/worker_test.go
@@ -69,7 +69,6 @@ type workerTestQueries struct {
claimAvailable bool
invitation db.WorkspaceInvitation
invitationError error
- stats []db.SeatCapacityOutboxStatsRow
deferredUntil pgtype.Timestamptz
deferredUntils []pgtype.Timestamptz
@@ -168,10 +167,6 @@ func (q *workerTestQueries) MarkClaimedSeatCapacityIntentFailed(_ context.Contex
return 1, nil
}
-func (q *workerTestQueries) SeatCapacityOutboxStats(context.Context) ([]db.SeatCapacityOutboxStatsRow, error) {
- return q.stats, nil
-}
-
func (q *workerTestQueries) TransitionClaimedSeatCapacityIntent(_ context.Context, arg db.TransitionClaimedSeatCapacityIntentParams) (int64, error) {
q.mu.Lock()
defer q.mu.Unlock()
diff --git a/server/internal/service/channel_media_reconciler.go b/server/internal/service/channel_media_reconciler.go
index 12c9d1a93f..4ba8c61bc1 100644
--- a/server/internal/service/channel_media_reconciler.go
+++ b/server/internal/service/channel_media_reconciler.go
@@ -179,12 +179,6 @@ func (r *ChannelMediaReconciler) RunOnce(ctx context.Context) {
}
r.settle(ctx, row, leaseToken)
}
- if r.Metrics != nil {
- if counts, err := r.Queries.CountChannelMediaPendingObjects(ctx); err == nil {
- r.Metrics.Backlog.Set(float64(counts.PendingObjects))
- r.Metrics.Tombstones.Set(float64(counts.TombstonedObjects))
- }
- }
}
// settle runs the row the caller just claimed. The lease it holds only has to
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index b79e4896c5..56cf7c504c 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -407,28 +407,6 @@ func (q *Queries) CopyChannelTaskDelivery(ctx context.Context, arg CopyChannelTa
return err
}
-const countChannelMediaPendingObjects = `-- name: CountChannelMediaPendingObjects :one
-SELECT
- count(*) FILTER (WHERE state <> 'tombstoned') AS pending_objects,
- count(*) FILTER (WHERE state = 'tombstoned') AS tombstoned_objects
-FROM channel_media_pending_object
-`
-
-type CountChannelMediaPendingObjectsRow struct {
- PendingObjects int64 `json:"pending_objects"`
- TombstonedObjects int64 `json:"tombstoned_objects"`
-}
-
-// Ledger backlog gauge for the reconciler's observability. Tombstones are
-// reported separately: they are bounded bookkeeping for already-deleted
-// objects, not a backlog of objects awaiting reclaim.
-func (q *Queries) CountChannelMediaPendingObjects(ctx context.Context) (CountChannelMediaPendingObjectsRow, error) {
- row := q.db.QueryRow(ctx, countChannelMediaPendingObjects)
- var i CountChannelMediaPendingObjectsRow
- err := row.Scan(&i.PendingObjects, &i.TombstonedObjects)
- return i, err
-}
-
const createChannelBindingToken = `-- name: CreateChannelBindingToken :one
INSERT INTO channel_binding_token (
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index c7990c50c3..6096f7e94d 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -132,124 +132,6 @@ func (q *Queries) CountActiveAgentsByRuntime(ctx context.Context, runtimeID pgty
return count, err
}
-const countStaleOfflineRuntimeGCBacklogByReason = `-- name: CountStaleOfflineRuntimeGCBacklogByReason :many
-WITH stale_runtimes AS MATERIALIZED (
- SELECT id, workspace_id FROM agent_runtime
- WHERE status = 'offline'
- AND last_seen_at < now() - make_interval(secs => $1::double precision)
- ORDER BY last_seen_at ASC, id ASC
- LIMIT $2::int
-), classified AS (
- SELECT CASE
- WHEN EXISTS (
- SELECT 1 FROM agent
- WHERE agent.runtime_id = stale_runtimes.id
- AND agent.kind = 'user'
- AND agent.archived_at IS NULL
- ) THEN 'active_agent'::text
- WHEN EXISTS (
- SELECT 1 FROM agent
- WHERE agent.runtime_id = stale_runtimes.id
- AND agent.kind = 'user'
- AND agent.workspace_id <> stale_runtimes.workspace_id
- ) THEN 'workspace_mismatch'::text
- WHEN EXISTS (
- SELECT 1 FROM agent_task_queue AS task
- WHERE task.runtime_id = stale_runtimes.id
- AND task.completed_at IS NULL
- ) OR EXISTS (
- SELECT 1
- FROM agent AS owner
- WHERE owner.runtime_id = stale_runtimes.id
- AND owner.kind = 'user'
- AND EXISTS (
- SELECT 1
- FROM agent_task_queue AS task
- WHERE task.agent_id = owner.id
- AND task.completed_at IS NULL
- )
- ) THEN 'non_terminal_task'::text
- ELSE 'eligible'::text
- END AS reason
- FROM stale_runtimes
-)
-SELECT reason, count(*)::bigint AS count
-FROM classified
-GROUP BY reason
-ORDER BY reason
-`
-
-type CountStaleOfflineRuntimeGCBacklogByReasonParams struct {
- StaleSeconds float64 `json:"stale_seconds"`
- MaxRows int32 `json:"max_rows"`
-}
-
-type CountStaleOfflineRuntimeGCBacklogByReasonRow struct {
- Reason string `json:"reason"`
- Count int64 `json:"count"`
-}
-
-// Classifies one bounded oldest-first cohort into mutually exclusive states.
-// active_agent has priority because it already makes the runtime ineligible;
-// archived cross-workspace bindings get their own diagnostic bucket. The task
-// branch mirrors teardown's fail-closed predicate, including tasks owned by a
-// bound user agent but pinned to another runtime after a historical move.
-func (q *Queries) CountStaleOfflineRuntimeGCBacklogByReason(ctx context.Context, arg CountStaleOfflineRuntimeGCBacklogByReasonParams) ([]CountStaleOfflineRuntimeGCBacklogByReasonRow, error) {
- rows, err := q.db.Query(ctx, countStaleOfflineRuntimeGCBacklogByReason, arg.StaleSeconds, arg.MaxRows)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []CountStaleOfflineRuntimeGCBacklogByReasonRow{}
- for rows.Next() {
- var i CountStaleOfflineRuntimeGCBacklogByReasonRow
- if err := rows.Scan(&i.Reason, &i.Count); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
-const countStaleOfflineRuntimesBlockedByTasks = `-- name: CountStaleOfflineRuntimesBlockedByTasks :one
-SELECT count(*) FROM (
- SELECT 1 FROM agent_runtime
- WHERE status = 'offline'
- AND last_seen_at < now() - make_interval(secs => $1::double precision)
- AND NOT EXISTS (
- SELECT 1
- FROM agent
- WHERE agent.runtime_id = agent_runtime.id
- )
- AND EXISTS (
- SELECT 1
- FROM agent_task_queue
- WHERE agent_task_queue.runtime_id = agent_runtime.id
- AND agent_task_queue.completed_at IS NULL
- )
- LIMIT $2::int
-) AS blocked_runtimes
-`
-
-type CountStaleOfflineRuntimesBlockedByTasksParams struct {
- StaleSeconds float64 `json:"stale_seconds"`
- MaxRows int32 `json:"max_rows"`
-}
-
-// Preserve the original blocked-runtimes signal for dashboard and alert
-// compatibility. This deliberately counts only otherwise-unowned stale
-// runtimes with a directly pinned non-terminal task; the broader reason
-// inventory below is exposed under a separate backlog metric.
-func (q *Queries) CountStaleOfflineRuntimesBlockedByTasks(ctx context.Context, arg CountStaleOfflineRuntimesBlockedByTasksParams) (int64, error) {
- row := q.db.QueryRow(ctx, countStaleOfflineRuntimesBlockedByTasks, arg.StaleSeconds, arg.MaxRows)
- var count int64
- err := row.Scan(&count)
- return count, err
-}
-
const countTasksByRuntime = `-- name: CountTasksByRuntime :one
SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1
`
diff --git a/server/pkg/db/generated/seat_capacity.sql.go b/server/pkg/db/generated/seat_capacity.sql.go
index bf1e1b5102..d72a7c0e01 100644
--- a/server/pkg/db/generated/seat_capacity.sql.go
+++ b/server/pkg/db/generated/seat_capacity.sql.go
@@ -575,50 +575,6 @@ func (q *Queries) PrepareSeatCapacityOperationReleasesForWorkspaceDeletion(ctx c
return err
}
-const seatCapacityOutboxStats = `-- name: SeatCapacityOutboxStats :many
-SELECT action,
- count(*) FILTER (WHERE dead_lettered_at IS NULL)::bigint AS pending_count,
- count(*) FILTER (WHERE dead_lettered_at IS NOT NULL)::bigint AS dead_lettered_count,
- COALESCE(
- EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE dead_lettered_at IS NULL)),
- 0
- )::double precision AS oldest_pending_age_seconds
-FROM seat_capacity_outbox
-GROUP BY action
-`
-
-type SeatCapacityOutboxStatsRow struct {
- Action string `json:"action"`
- PendingCount int64 `json:"pending_count"`
- DeadLetteredCount int64 `json:"dead_lettered_count"`
- OldestPendingAgeSeconds float64 `json:"oldest_pending_age_seconds"`
-}
-
-func (q *Queries) SeatCapacityOutboxStats(ctx context.Context) ([]SeatCapacityOutboxStatsRow, error) {
- rows, err := q.db.Query(ctx, seatCapacityOutboxStats)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []SeatCapacityOutboxStatsRow{}
- for rows.Next() {
- var i SeatCapacityOutboxStatsRow
- if err := rows.Scan(
- &i.Action,
- &i.PendingCount,
- &i.DeadLetteredCount,
- &i.OldestPendingAgeSeconds,
- ); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const transitionClaimedSeatCapacityIntent = `-- name: TransitionClaimedSeatCapacityIntent :execrows
UPDATE seat_capacity_outbox
SET action = $1,
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index d825ac03a5..b9d600086e 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -1204,12 +1204,3 @@ SELECT EXISTS (
AND workspace_id = @workspace_id
AND url = @storage_url
) AS referenced;
-
--- name: CountChannelMediaPendingObjects :one
--- Ledger backlog gauge for the reconciler's observability. Tombstones are
--- reported separately: they are bounded bookkeeping for already-deleted
--- objects, not a backlog of objects awaiting reclaim.
-SELECT
- count(*) FILTER (WHERE state <> 'tombstoned') AS pending_objects,
- count(*) FILTER (WHERE state = 'tombstoned') AS tombstoned_objects
-FROM channel_media_pending_object;
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index e23d4a9ffb..cd008f32d4 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -530,77 +530,3 @@ SELECT EXISTS (
-- Final fail-closed assertion after UnbindTasksFromRuntime. A non-zero result
-- aborts the transaction instead of relying on the legacy ON DELETE CASCADE.
SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1;
-
--- name: CountStaleOfflineRuntimesBlockedByTasks :one
--- Preserve the original blocked-runtimes signal for dashboard and alert
--- compatibility. This deliberately counts only otherwise-unowned stale
--- runtimes with a directly pinned non-terminal task; the broader reason
--- inventory below is exposed under a separate backlog metric.
-SELECT count(*) FROM (
- SELECT 1 FROM agent_runtime
- WHERE status = 'offline'
- AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
- AND NOT EXISTS (
- SELECT 1
- FROM agent
- WHERE agent.runtime_id = agent_runtime.id
- )
- AND EXISTS (
- SELECT 1
- FROM agent_task_queue
- WHERE agent_task_queue.runtime_id = agent_runtime.id
- AND agent_task_queue.completed_at IS NULL
- )
- LIMIT @max_rows::int
-) AS blocked_runtimes;
-
--- name: CountStaleOfflineRuntimeGCBacklogByReason :many
--- Classifies one bounded oldest-first cohort into mutually exclusive states.
--- active_agent has priority because it already makes the runtime ineligible;
--- archived cross-workspace bindings get their own diagnostic bucket. The task
--- branch mirrors teardown's fail-closed predicate, including tasks owned by a
--- bound user agent but pinned to another runtime after a historical move.
-WITH stale_runtimes AS MATERIALIZED (
- SELECT id, workspace_id FROM agent_runtime
- WHERE status = 'offline'
- AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
- ORDER BY last_seen_at ASC, id ASC
- LIMIT @max_rows::int
-), classified AS (
- SELECT CASE
- WHEN EXISTS (
- SELECT 1 FROM agent
- WHERE agent.runtime_id = stale_runtimes.id
- AND agent.kind = 'user'
- AND agent.archived_at IS NULL
- ) THEN 'active_agent'::text
- WHEN EXISTS (
- SELECT 1 FROM agent
- WHERE agent.runtime_id = stale_runtimes.id
- AND agent.kind = 'user'
- AND agent.workspace_id <> stale_runtimes.workspace_id
- ) THEN 'workspace_mismatch'::text
- WHEN EXISTS (
- SELECT 1 FROM agent_task_queue AS task
- WHERE task.runtime_id = stale_runtimes.id
- AND task.completed_at IS NULL
- ) OR EXISTS (
- SELECT 1
- FROM agent AS owner
- WHERE owner.runtime_id = stale_runtimes.id
- AND owner.kind = 'user'
- AND EXISTS (
- SELECT 1
- FROM agent_task_queue AS task
- WHERE task.agent_id = owner.id
- AND task.completed_at IS NULL
- )
- ) THEN 'non_terminal_task'::text
- ELSE 'eligible'::text
- END AS reason
- FROM stale_runtimes
-)
-SELECT reason, count(*)::bigint AS count
-FROM classified
-GROUP BY reason
-ORDER BY reason;
diff --git a/server/pkg/db/queries/seat_capacity.sql b/server/pkg/db/queries/seat_capacity.sql
index c32e432301..13860db0cd 100644
--- a/server/pkg/db/queries/seat_capacity.sql
+++ b/server/pkg/db/queries/seat_capacity.sql
@@ -186,17 +186,6 @@ FROM due
WHERE outbox.operation_token = due.operation_token
RETURNING outbox.*;
--- name: SeatCapacityOutboxStats :many
-SELECT action,
- count(*) FILTER (WHERE dead_lettered_at IS NULL)::bigint AS pending_count,
- count(*) FILTER (WHERE dead_lettered_at IS NOT NULL)::bigint AS dead_lettered_count,
- COALESCE(
- EXTRACT(EPOCH FROM now() - min(created_at) FILTER (WHERE dead_lettered_at IS NULL)),
- 0
- )::double precision AS oldest_pending_age_seconds
-FROM seat_capacity_outbox
-GROUP BY action;
-
-- name: MarkSeatCapacityIntentDelivered :exec
UPDATE seat_capacity_outbox
SET delivered_at = now(),