Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6882: remove unused active database samplers (#7817)
Multica Eve3e55ce4db033
diff --git a/deploy/helm/multica/templates/prometheusrule.yaml b/deploy/helm/multica/templates/prometheusrule.yamlindex 4715daac12..2cf6295e9b 100644--- a/deploy/helm/multica/templates/prometheusrule.yaml+++ b/deploy/helm/multica/templates/prometheusrule.yaml@@ -1,5 +1,5 @@{{- if .Values.monitoring.prometheusRule.enabled }}-{{- $samplerQueryNames := "active_users|active_workspaces|task_queued|task_running|task_stuck|workspace_total" -}}+{{- $samplerQueryNames := "task_queued|task_running|task_stuck|workspace_total" -}}{{- $samplerErrorNames := printf "acquire|%s" $samplerQueryNames -}}apiVersion: monitoring.coreos.com/v1kind: PrometheusRulediff --git a/server/internal/metrics/business_sampler.go b/server/internal/metrics/business_sampler.goindex 5823ac9bab..a377ed9d5b 100644--- a/server/internal/metrics/business_sampler.go+++ b/server/internal/metrics/business_sampler.go@@ -5,6 +5,11 @@// 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 metricsimport (@@ -27,30 +32,12 @@ import (const (defaultSamplerCacheTTL = 8 * time.SeconddefaultSamplerQueryTimeout = 500 * time.Millisecond- samplerRowLimit = 100-- // Active-user / active-workspace DB windows. Keep this DB-sampled path- // to the short window only: PR2's counters do not carry user/workspace- // IDs, so PromQL cannot derive distinct 1h/24h active estimates without- // adding high-cardinality labels. Long-window actives need a separate- // counter-derived aggregation, not expanding this sampler over history.- windowFiveMinutes = "5m"// 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},-}-// 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.@@ -58,8 +45,6 @@ var samplerQueries = []struct {name stringrun func(*BusinessSamplerCollector, context.Context, pgx.Tx, *samplerSnapshot) error}{- {"active_users", (*BusinessSamplerCollector).queryActiveUsers},- {"active_workspaces", (*BusinessSamplerCollector).queryActiveWorkspaces},{"task_queued", (*BusinessSamplerCollector).queryTaskQueued},{"task_running", (*BusinessSamplerCollector).queryTaskRunning},{"task_stuck", (*BusinessSamplerCollector).queryTaskStuck},@@ -120,12 +105,10 @@ type BusinessSamplerCollector struct {// 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- descWorkspaceTotal *prometheus.Desc+ descTaskQueued *prometheus.Desc+ descTaskRunning *prometheus.Desc+ descTaskStuck *prometheus.Desc+ descWorkspaceTotal *prometheus.Descmu sync.Mutexsnapshot *samplerSnapshot@@ -167,14 +150,6 @@ func NewBusinessSamplerCollector(opts *BusinessSamplerOptions) *BusinessSamplerCHelp: "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.",@@ -212,8 +187,6 @@ func (c *BusinessSamplerCollector) Describe(ch chan<- *prometheus.Desc) {return}for _, d := range []*prometheus.Desc{- c.descActiveUsers,- c.descActiveWorkspaces,c.descTaskQueued,c.descTaskRunning,c.descTaskStuck,@@ -267,13 +240,6 @@ func (c *BusinessSamplerCollector) maybeRefresh() *samplerSnapshot {// 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@@ -322,9 +288,6 @@ type taskRunningKey struct {type samplerSnapshot struct {takenAt time.Time- activeUsers map[string]float64- activeWorkspaces map[string]float64-taskQueued map[string]float64taskRunning map[taskRunningKey]float64taskStuck map[string]float64@@ -335,12 +298,10 @@ type samplerSnapshot struct {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{},+ takenAt: t,+ taskQueued: map[string]float64{},+ taskRunning: map[taskRunningKey]float64{},+ taskStuck: map[string]float64{},}}diff --git a/server/internal/metrics/business_sampler_queries.go b/server/internal/metrics/business_sampler_queries.goindex bc14200b04..0b82dd6117 100644--- a/server/internal/metrics/business_sampler_queries.go+++ b/server/internal/metrics/business_sampler_queries.go@@ -17,87 +17,6 @@ import (// 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 the short 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 the short 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.diff --git a/server/internal/metrics/business_sampler_test.go b/server/internal/metrics/business_sampler_test.goindex c4c61e2eba..4ac38758fc 100644--- a/server/internal/metrics/business_sampler_test.go+++ b/server/internal/metrics/business_sampler_test.go@@ -41,9 +41,6 @@ func newTestSampler(t *testing.T, refresh func(ctx context.Context, now time.Timfunc filledSnapshot(now time.Time) *samplerSnapshot {snap := newSamplerSnapshot(now)- snap.activeUsers[windowFiveMinutes] = 7- snap.activeWorkspaces[windowFiveMinutes] = 3-snap.taskQueued["chat"] = 5snap.taskQueued["issue"] = 2@@ -76,8 +73,6 @@ func TestBusinessSamplerCollectorEmitsExpectedMetrics(t *testing.T) {body := rec.Body.String()wantSubstrings := []string{- `multica_active_users{window="5m"} 7`,- `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.@@ -94,10 +89,8 @@ func TestBusinessSamplerCollectorEmitsExpectedMetrics(t *testing.T) {}}for _, removed := range []string{- `multica_active_users{window="1h"}`,- `multica_active_users{window="24h"}`,- `multica_active_workspaces{window="1h"}`,- `multica_active_workspaces{window="24h"}`,+ `multica_active_users`,+ `multica_active_workspaces`,`multica_runtime_online`,`multica_runtime_heartbeat_age_seconds`,} {@@ -115,7 +108,7 @@ 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)+ c.queryDuration.WithLabelValues("task_queued").Observe(0.012)registry := prometheus.NewRegistry()registry.MustRegister(c.Collectors()...)@@ -123,7 +116,7 @@ func TestBusinessSamplerSelfIntrospectionHistogramIsExposed(t *testing.T) {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`) {+ if !strings.Contains(body, `multica_business_sampler_query_seconds_count{name="task_queued"} 1`) {t.Fatalf("query duration histogram missing\n%s", body)}}@@ -167,7 +160,7 @@ func TestBusinessSamplerCollectorCachesSnapshot(t *testing.T) {// 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+// 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)@@ -226,6 +219,7 @@ func TestBusinessSamplerCollectorDisabledWithoutOptions(t *testing.T) {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",