Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(metrics): BusinessSamplerCollector for active users / queued / runtime gauges (MUL-2947) (#3706)
LinYushen9c9afd4a6653
diff --git a/server/cmd/server/dbstats.go b/server/cmd/server/dbstats.goindex 4928f39ce6..1feab52904 100644--- a/server/cmd/server/dbstats.go+++ b/server/cmd/server/dbstats.go@@ -191,3 +191,33 @@ 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.goindex b398b38b1b..b8d06b0ec2 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -11,6 +11,7 @@ import ("syscall""time"+ "github.com/jackc/pgx/v5/pgxpool""github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/daemonws""github.com/multica-ai/multica/server/internal/events"@@ -260,13 +261,31 @@ func main() {var metricsServer *http.Servervar httpMetrics *obsmetrics.HTTPMetricsvar businessMetrics *obsmetrics.BusinessMetrics+ var samplerPool *pgxpool.Poolif 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.HTTPbusinessMetrics = metricsRegistry.Business@@ -283,6 +302,9 @@ 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 belowdiff --git a/server/internal/metrics/business_sampler.go b/server/internal/metrics/business_sampler.gonew file mode 100644index 0000000000..97bb3386f8--- /dev/null+++ b/server/internal/metrics/business_sampler.go@@ -0,0 +1,525 @@+// 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.+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+ samplerRowLimit = 100++ // Active-user / active-workspace windows. The label set is fixed —+ // new windows must be added explicitly here so cardinality stays+ // bounded under all input.+ windowFiveMinutes = "5m"+ windowOneHour = "1h"+ windowOneDay = "24h"++ // Runtime is considered online if its last_seen_at is within this+ // many seconds of `now()`. 60s matches the daemon heartbeat cadence+ // (~15s) plus headroom for redis relay lag and clock skew.+ runtimeOnlineWindowSeconds = 60++ // A running task is considered "stuck" once started_at is older+ // than this. Matches the Grafana board threshold from MUL-2328.+ stuckRunningInterval = "30 minutes"+)++// samplerWindows is the canonical list emitted on every scrape. The slice+// (rather than ranging a map) is intentional: order is stable in+// /metrics output, which keeps diffs readable and golden tests honest.+var samplerWindows = []struct {+ label string+ d time.Duration+}{+ {windowFiveMinutes, 5 * time.Minute},+ {windowOneHour, time.Hour},+ {windowOneDay, 24 * time.Hour},+}++// 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.+ descActiveUsers *prometheus.Desc+ descActiveWorkspaces *prometheus.Desc+ descTaskQueued *prometheus.Desc+ descTaskRunning *prometheus.Desc+ descTaskStuck *prometheus.Desc+ descRuntimeOnline *prometheus.Desc+ descHeartbeatAgeHist *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"}),++ descActiveUsers: prometheus.NewDesc(+ "multica_active_users",+ "Distinct users with chat / task activity in the rolling window. Sampled from the database; stale up to the sampler cache TTL.",+ []string{"window"}, nil),+ descActiveWorkspaces: prometheus.NewDesc(+ "multica_active_workspaces",+ "Distinct workspaces with chat / task activity in the rolling window. Sampled from the database.",+ []string{"window"}, nil),+ 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),+ descRuntimeOnline: prometheus.NewDesc(+ "multica_runtime_online",+ "Count of agent_runtime rows with last_seen_at within the online heartbeat window. Sampled from the database.",+ []string{"runtime_mode", "provider"}, nil),+ descHeartbeatAgeHist: prometheus.NewDesc(+ "multica_runtime_heartbeat_age_seconds",+ "Distribution of (now() - agent_runtime.last_seen_at) for runtimes considered online by the sampler.",+ []string{"runtime_mode"}, 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.descActiveUsers,+ c.descActiveWorkspaces,+ c.descTaskQueued,+ c.descTaskRunning,+ c.descTaskStuck,+ c.descRuntimeOnline,+ c.descHeartbeatAgeHist,+ 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(), 8*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) {+ for _, w := range samplerWindows {+ ch <- prometheus.MustNewConstMetric(+ c.descActiveUsers, prometheus.GaugeValue, snap.activeUsers[w.label], w.label)+ ch <- prometheus.MustNewConstMetric(+ c.descActiveWorkspaces, prometheus.GaugeValue, snap.activeWorkspaces[w.label], w.label)+ }++ // 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)+ }+ }++ for key, val := range snap.runtimeOnline {+ ch <- prometheus.MustNewConstMetric(+ c.descRuntimeOnline, prometheus.GaugeValue, val, key.runtimeMode, key.provider)+ }++ for mode, hist := range snap.heartbeatAge {+ ch <- prometheus.MustNewConstHistogram(+ c.descHeartbeatAgeHist,+ hist.count,+ hist.sum,+ hist.buckets,+ 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"}+}++// heartbeatAgeBuckets matches the Grafana board's runtime-health view: a few+// seconds for healthy heartbeats, then quickly out to "definitely stale".+var heartbeatAgeBuckets = []float64{1, 5, 15, 30, 60, 120, 300, 600}++// 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+}++type runtimeOnlineKey struct {+ runtimeMode string+ provider string+}++// samplerHistogram is the in-memory representation of a single+// prometheus.ConstHistogram for one runtime_mode. We bucketise in Go+// because Postgres does not return histogram-shaped data directly.+type samplerHistogram struct {+ count uint64+ sum float64+ buckets map[float64]uint64+}++// 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++ activeUsers map[string]float64+ activeWorkspaces map[string]float64++ taskQueued map[string]float64+ taskRunning map[taskRunningKey]float64+ taskStuck map[string]float64++ runtimeOnline map[runtimeOnlineKey]float64+ heartbeatAge map[string]samplerHistogram++ workspaceTotal float64+ workspaceTotalKnown bool+}++func newSamplerSnapshot(t time.Time) *samplerSnapshot {+ return &samplerSnapshot{+ takenAt: t,+ activeUsers: map[string]float64{},+ activeWorkspaces: map[string]float64{},+ taskQueued: map[string]float64{},+ taskRunning: map[taskRunningKey]float64{},+ taskStuck: map[string]float64{},+ runtimeOnline: map[runtimeOnlineKey]float64{},+ heartbeatAge: map[string]samplerHistogram{},+ }+}++// 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)++ c.runQuery(ctx, conn, "active_users", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryActiveUsers(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "active_workspaces", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryActiveWorkspaces(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "task_queued", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryTaskQueued(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "task_running", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryTaskRunning(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "task_stuck", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryTaskStuck(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "runtime_online", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryRuntimeOnline(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "runtime_heartbeat_age", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryRuntimeHeartbeatAge(ctx, tx, snap)+ })+ c.runQuery(ctx, conn, "workspace_total", func(ctx context.Context, tx pgx.Tx) error {+ return c.queryWorkspaceTotal(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.gonew file mode 100644index 0000000000..dcf553c2b0--- /dev/null+++ b/server/internal/metrics/business_sampler_pgsleep_test.go@@ -0,0 +1,116 @@+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.gonew file mode 100644index 0000000000..76baa28470--- /dev/null+++ b/server/internal/metrics/business_sampler_queries.go@@ -0,0 +1,323 @@+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 / provider)+// through the existing BusinessMetrics whitelists so the sampler+// cannot widen the metric label space.++// queryActiveUsers fills snap.activeUsers with a count of distinct user_ids+// that have either sent a chat message or had an agent task created for one+// of their issues inside each rolling window. We deliberately skip Postgres+// `now() - interval '$1'` substitution and instead pass a typed interval as+// a bind parameter so the caller cannot inject SQL via the window string.+//+// Note on cardinality: there is intentionally NO `LIMIT` on the inner+// distinct subquery — capping it would silently truncate the COUNT to 100+// and report a wrong active-user value. The result row count is already+// pinned to 1 (the COUNT scalar). Cardinality of the *output metric* is+// bounded by the fixed `samplerWindows` allow-list, not by the SQL shape.+func (c *BusinessSamplerCollector) queryActiveUsers(+ ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,+) error {+ const stmt = `+SELECT count(DISTINCT user_id) FROM (+ SELECT cs.creator_id AS user_id+ FROM chat_session cs+ WHERE EXISTS (+ SELECT 1 FROM chat_message cm+ WHERE cm.chat_session_id = cs.id+ AND cm.created_at > now() - $1::interval+ )+ UNION ALL+ SELECT i.creator_id AS user_id+ FROM issue i+ WHERE i.creator_type = 'member'+ AND EXISTS (+ SELECT 1 FROM agent_task_queue atq+ WHERE atq.issue_id = i.id+ AND atq.created_at > now() - $1::interval+ )+) u+`+ for _, w := range samplerWindows {+ var n int64+ if err := tx.QueryRow(ctx, stmt, w.d).Scan(&n); err != nil {+ return fmt.Errorf("active_users window=%s: %w", w.label, err)+ }+ snap.activeUsers[w.label] = float64(n)+ }+ return nil+}++// queryActiveWorkspaces counts distinct workspaces with chat or task+// activity in each window. Mirrors queryActiveUsers and intentionally has+// no inner LIMIT for the same reason: a LIMIT inside the distinct subquery+// would truncate the COUNT and report a wrong value.+func (c *BusinessSamplerCollector) queryActiveWorkspaces(+ ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,+) error {+ const stmt = `+SELECT count(DISTINCT workspace_id) FROM (+ SELECT cs.workspace_id+ FROM chat_session cs+ WHERE EXISTS (+ SELECT 1 FROM chat_message cm+ WHERE cm.chat_session_id = cs.id+ AND cm.created_at > now() - $1::interval+ )+ UNION ALL+ SELECT i.workspace_id+ FROM issue i+ WHERE EXISTS (+ SELECT 1 FROM agent_task_queue atq+ WHERE atq.issue_id = i.id+ AND atq.created_at > now() - $1::interval+ )+) w+`+ for _, w := range samplerWindows {+ var n int64+ if err := tx.QueryRow(ctx, stmt, w.d).Scan(&n); err != nil {+ return fmt.Errorf("active_workspaces window=%s: %w", w.label, err)+ }+ snap.activeWorkspaces[w.label] = float64(n)+ }+ return nil+}++// 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 {+ const stmt = `+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 agent_task_queue atq+LEFT JOIN agent_runtime ar ON ar.id = atq.runtime_id+WHERE atq.status IN ('dispatched', 'running')+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()+}++// queryRuntimeOnline counts agent_runtime rows whose last_seen_at is within+// the online window, grouped by runtime_mode × provider. Both labels go+// through the BusinessMetrics whitelists so a misbehaving runtime registering+// itself with an exotic provider name cannot inflate the series space.+func (c *BusinessSamplerCollector) queryRuntimeOnline(+ ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,+) error {+ const stmt = `+SELECT runtime_mode, provider, count(*) AS n+FROM agent_runtime+WHERE last_seen_at IS NOT NULL+ AND last_seen_at > now() - ($1::int * interval '1 second')+GROUP BY 1, 2+LIMIT 100+`+ rows, err := tx.Query(ctx, stmt, runtimeOnlineWindowSeconds)+ if err != nil {+ return fmt.Errorf("runtime_online: %w", err)+ }+ defer rows.Close()+ for rows.Next() {+ var rawMode, rawProvider string+ var n int64+ if err := rows.Scan(&rawMode, &rawProvider, &n); err != nil {+ return fmt.Errorf("runtime_online scan: %w", err)+ }+ key := runtimeOnlineKey{+ runtimeMode: NormalizeRuntimeMode(rawMode),+ provider: NormalizeRuntimeProvider(rawProvider),+ }+ snap.runtimeOnline[key] += float64(n)+ }+ return rows.Err()+}++// queryRuntimeHeartbeatAge fills the heartbeat-age histogram per runtime_mode.+// We pull at most 100 rows and bucketise in Go because Postgres does not+// return histogram-shaped output. Rows older than 15 minutes are dropped —+// they are clearly offline and would just smear the tail of the histogram.+func (c *BusinessSamplerCollector) queryRuntimeHeartbeatAge(+ ctx context.Context, tx pgx.Tx, snap *samplerSnapshot,+) error {+ const stmt = `+SELECT runtime_mode, EXTRACT(EPOCH FROM (now() - last_seen_at))::float8 AS age+FROM agent_runtime+WHERE last_seen_at IS NOT NULL+ AND last_seen_at > now() - interval '15 minutes'+ORDER BY last_seen_at DESC+LIMIT 100+`+ rows, err := tx.Query(ctx, stmt)+ if err != nil {+ return fmt.Errorf("runtime_heartbeat_age: %w", err)+ }+ defer rows.Close()++ perMode := map[string][]float64{}+ for rows.Next() {+ var rawMode string+ var age float64+ if err := rows.Scan(&rawMode, &age); err != nil {+ return fmt.Errorf("runtime_heartbeat_age scan: %w", err)+ }+ if age < 0 {+ age = 0+ }+ mode := NormalizeRuntimeMode(rawMode)+ perMode[mode] = append(perMode[mode], age)+ }+ if err := rows.Err(); err != nil {+ return err+ }++ for mode, ages := range perMode {+ hist := samplerHistogram{+ buckets: make(map[float64]uint64, len(heartbeatAgeBuckets)),+ }+ for _, b := range heartbeatAgeBuckets {+ hist.buckets[b] = 0+ }+ for _, age := range ages {+ hist.count+++ hist.sum += age+ for _, b := range heartbeatAgeBuckets {+ if age <= b {+ hist.buckets[b]+++ }+ }+ }+ snap.heartbeatAge[mode] = hist+ }+ return nil+}++// 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.gonew file mode 100644index 0000000000..9728b8ff4b--- /dev/null+++ b/server/internal/metrics/business_sampler_test.go@@ -0,0 +1,328 @@+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.activeUsers[windowFiveMinutes] = 7+ snap.activeUsers[windowOneHour] = 42+ snap.activeUsers[windowOneDay] = 100+ snap.activeWorkspaces[windowFiveMinutes] = 3+ snap.activeWorkspaces[windowOneHour] = 11+ snap.activeWorkspaces[windowOneDay] = 25++ 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.runtimeOnline[runtimeOnlineKey{runtimeMode: "local", provider: "claude"}] = 4+ snap.runtimeOnline[runtimeOnlineKey{runtimeMode: "cloud", provider: "kiro"}] = 2++ snap.heartbeatAge["local"] = samplerHistogram{+ count: 3,+ sum: 45,+ buckets: bucketsFor([]float64{5, 15, 30}),+ }+ snap.heartbeatAge["cloud"] = samplerHistogram{+ count: 1,+ sum: 2,+ buckets: bucketsFor([]float64{2}),+ }++ snap.workspaceTotal = 250+ snap.workspaceTotalKnown = true+ return snap+}++func bucketsFor(observations []float64) map[float64]uint64 {+ buckets := make(map[float64]uint64, len(heartbeatAgeBuckets))+ for _, b := range heartbeatAgeBuckets {+ buckets[b] = 0+ }+ for _, o := range observations {+ for _, b := range heartbeatAgeBuckets {+ if o <= b {+ buckets[b]+++ }+ }+ }+ return buckets+}++// TestBusinessSamplerCollectorEmitsExpectedMetrics asserts every metric+// family from the PR4 spec 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_active_users{window="5m"} 7`,+ `multica_active_users{window="1h"} 42`,+ `multica_active_users{window="24h"} 100`,+ `multica_active_workspaces{window="5m"} 3`,+ `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_runtime_online{provider="claude",runtime_mode="local"} 4`,+ `multica_runtime_online{provider="kiro",runtime_mode="cloud"} 2`,+ `multica_runtime_heartbeat_age_seconds_count{runtime_mode="local"} 3`,+ `multica_runtime_heartbeat_age_seconds_sum{runtime_mode="local"} 45`,+ `multica_workspace_total 250`,+ }+ for _, want := range wantSubstrings {+ if !strings.Contains(body, want) {+ t.Errorf("metrics body missing %q\nbody:\n%s", want, 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("active_users").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="active_users"} 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-window zeros. 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.runtimeOnline[runtimeOnlineKey{+ runtimeMode: NormalizeRuntimeMode("rogue-mode"),+ provider: NormalizeRuntimeProvider("attacker-provider"),+ }] += 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)+ }+ if got := testutil.CollectAndCount(c, "multica_runtime_online"); got != 1 {+ t.Fatalf("runtime_online series = %d, want 1 (collapsed by normalizers)", got)+ }+}++// 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_agent_task_queued",+ "multica_runtime_online",+ "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)+ }+}++// TestSamplerHistogramBucketing exercises the in-memory bucketing logic so+// a regression in heartbeat-age accounting is caught before it ships to+// dashboards.+func TestSamplerHistogramBucketing(t *testing.T) {+ buckets := bucketsFor([]float64{0.5, 5, 30, 75})+ expectations := map[float64]uint64{+ 1: 1, 5: 2, 15: 2, 30: 3, 60: 3, 120: 4, 300: 4, 600: 4,+ }+ for b, want := range expectations {+ if got := buckets[b]; got != want {+ t.Errorf("bucket le=%g count = %d, want %d", b, got, want)+ }+ }+}diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.goindex 44206800c9..35fb025b31 100644--- a/server/internal/metrics/registry.go+++ b/server/internal/metrics/registry.go@@ -17,12 +17,23 @@ type RegistryOptions struct {DaemonWS *daemonws.MetricsVersion stringCommit 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 {Gatherer prometheus.GathererHTTP *HTTPMetricsBusiness *BusinessMetrics+ // 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 {@@ -53,10 +64,16 @@ 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,+ Sampler: sampler,}}