Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6747: reduce runtime sweeper scan cost (#7628)
Multica Eve6e2b2877b7aa
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex d6d409caea..2d276cd288 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -271,6 +271,8 @@ var concurrentIndexCleanups = map[string]string{"428_channel_task_delivery_binding_index": "idx_channel_task_delivery_binding","429_channel_task_delivery_installation_index": "idx_channel_task_delivery_installation","430_channel_outbound_message_binding_index": "idx_channel_outbound_message_binding_route",+ "438_agent_runtime_online_last_seen_index": "idx_agent_runtime_online_last_seen",+ "439_agent_runtime_offline_last_seen_index": "idx_agent_runtime_offline_last_seen",}// concurrentDownIndexCleanups covers every migration whose down directiondiff --git a/server/cmd/migrate/migrate_agent_runtime_last_seen_at_index_retirement_test.go b/server/cmd/migrate/migrate_agent_runtime_last_seen_at_index_retirement_test.goindex 924c024f43..230971d116 100644--- a/server/cmd/migrate/migrate_agent_runtime_last_seen_at_index_retirement_test.go+++ b/server/cmd/migrate/migrate_agent_runtime_last_seen_at_index_retirement_test.go@@ -65,6 +65,67 @@ func TestAgentRuntimeLastSeenAtIndexRetirement(t *testing.T) {t.Fatalf("reapply runtime index retirement migration: %v", err)}assertIndexExists(t, pool, schema, "idx_agent_runtime_last_seen_at", false)++ partialIndexes := []struct {+ version string+ index string+ keyColumns string+ predicate string+ }{+ {+ version: "438_agent_runtime_online_last_seen_index",+ index: "idx_agent_runtime_online_last_seen",+ keyColumns: "last_seen_at",+ predicate: "status = 'online'::text",+ },+ {+ version: "439_agent_runtime_offline_last_seen_index",+ index: "idx_agent_runtime_offline_last_seen",+ keyColumns: "last_seen_at, id",+ predicate: "status = 'offline'::text",+ },+ }+ for _, partial := range partialIndexes {+ options.Files = realMigrationFiles(t, []string{partial.version}, "up")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("apply %s: %v", partial.version, err)+ }+ assertRuntimeLastSeenPartialIndex(t, ctx, pool, schema, partial.index, partial.keyColumns, partial.predicate)+ }+ // The replacement indexes are deliberately partial: applying them must not+ // recreate migration 115's full-table index.+ assertIndexExists(t, pool, schema, "idx_agent_runtime_last_seen_at", false)++ options.Direction = "down"+ options.Hooks = hooksForDirection("down")+ for i := len(partialIndexes) - 1; i >= 0; i-- {+ partial := partialIndexes[i]+ options.Files = realMigrationFiles(t, []string{partial.version}, "down")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatalf("roll back %s: %v", partial.version, err)+ }+ assertIndexExists(t, pool, schema, partial.index, false)+ }+}++func assertRuntimeLastSeenPartialIndex(t *testing.T, ctx context.Context, pool *pgxpool.Pool, schema, index, keyColumns, predicate string) {+ t.Helper()+ assertIndexValidity(t, pool, schema, index, true)++ var definition, actualPredicate string+ if err := pool.QueryRow(ctx, `+ SELECT pg_get_indexdef(i.indexrelid), pg_get_expr(i.indpred, i.indrelid)+ FROM pg_index i+ WHERE i.indexrelid = $1::regclass+ `, pgx.Identifier{schema, index}.Sanitize()).Scan(&definition, &actualPredicate); err != nil {+ t.Fatalf("read %s definition: %v", index, err)+ }+ if !strings.Contains(definition, "USING btree ("+keyColumns+")") {+ t.Fatalf("%s key columns differ from query ordering: %s", index, definition)+ }+ if actualPredicate != "("+predicate+")" {+ t.Fatalf("%s predicate = %q, want %q", index, actualPredicate, "("+predicate+")")+ }}func createAgentRuntimeLastSeenAtIndexFixture(@@ -90,7 +151,8 @@ func createAgentRuntimeLastSeenAtIndexFixture(pool := openTestPoolWithSearchPath(t, schema)if _, err := pool.Exec(ctx, `CREATE TABLE agent_runtime (id UUID PRIMARY KEY,- last_seen_at TIMESTAMPTZ+ last_seen_at TIMESTAMPTZ,+ status TEXT NOT NULL DEFAULT 'offline')`); err != nil {t.Fatalf("create agent_runtime fixture: %v", err)}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex bf9e5a2e65..3fadd92c3d 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -604,8 +604,12 @@ func main() {// hold queued work behind long-running tasks — e.g. a runtime with low// task concurrency — raise the built-in 2h queued expiry without losing// work to queued_expired failures.- go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus, runtimeReconnectGrace,+ go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus, runtimeReconnectGrace,envDuration("MULTICA_TASK_QUEUED_TTL", defaultTaskQueuedTTL))+ // Seven-day runtime retention does not share the 30-second liveness tick:+ // its bounded transactions run independently once per hour, so a slow GC+ // round cannot delay offline detection or task recovery.+ go runRuntimeGCSweeper(sweepCtx, pool, queries, taskSvc.Metrics, bus)// Source-context cleanup is object-store work, so it gets its own goroutine// instead of a slot in the runtime sweep tick.go runSourceContextSweeper(sweepCtx, taskSvc)diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex f870810c3e..6d526d8328 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -24,6 +24,10 @@ import (const (// sweepInterval is how often we check for stale runtimes and tasks.sweepInterval = 30 * time.Second+ // runtimeGCSweepInterval keeps seven-day retention cleanup off the+ // latency-sensitive 30-second liveness path. GC remains independently+ // bounded by runtimeGCTickTimeout once each hourly round begins.+ runtimeGCSweepInterval = time.Hour// staleThresholdSeconds marks runtimes offline if no heartbeat for this// long. The heartbeat timing derivation lives with the shared service// constant so every task release path uses the same eligibility window.@@ -48,17 +52,19 @@ const (// after this duration. 7 days gives users plenty of time to restart daemons.offlineRuntimeTTLSeconds = 7 * 24 * 3600.0// runtimeGCBatchSize bounds both the candidate scan and the number of- // per-runtime transactions one sweeper tick may open.- runtimeGCBatchSize = 100+ // per-runtime transactions one sweeper tick may open. At the hourly cadence,+ // 500 preserves a theoretical capacity of 12,000 candidates per day; the+ // round timeout remains the hard bound on actual work.+ runtimeGCBatchSize = 500// runtimeGCBlockedScanLimit bounds the observability query as well. The// gauge saturates at this value rather than turning a safety signal into an// unbounded recurring scan when a large task backlog exists.runtimeGCBlockedScanLimit = 1000- // runtimeGCTickTimeout bounds the whole GC stage so lock contention cannot- // starve the stale-runtime and task sweeps that run before it every 30s.+ // runtimeGCTickTimeout bounds each independent hourly GC round so lock+ // contention cannot occupy its worker indefinitely.runtimeGCTickTimeout = 15 * time.Second// runtimeGCOperationTimeout prevents one contended or unhealthy runtime from- // stalling every later sweeper stage indefinitely.+ // stalling every later GC candidate indefinitely.runtimeGCOperationTimeout = 5 * time.Second// dispatchTimeoutSeconds fails tasks stuck in 'dispatched' beyond this.// The dispatched→running transition should be near-instant, so 5 minutes@@ -118,6 +124,39 @@ type runtimeGCTxStarter interface {Begin(context.Context) (pgx.Tx, error)}+type runtimeSweepStageStats struct {+ candidates int+ changed int+}++func taskServiceMetrics(taskSvc *service.TaskService) *obsmetrics.BusinessMetrics {+ if taskSvc == nil {+ return nil+ }+ return taskSvc.Metrics+}++func observeRuntimeSweepStage(metrics *obsmetrics.BusinessMetrics, stage string, startedAt time.Time, stats runtimeSweepStageStats) {+ metrics.ObserveRuntimeSweepStage(stage, time.Since(startedAt), stats.candidates, stats.changed)+}++// runPeriodicSweep serializes rounds and drops ticker events while a round is+// still running. That preserves the existing no-overlap behavior while letting+// low-frequency maintenance run independently from runtime liveness.+func runPeriodicSweep(ctx context.Context, interval time.Duration, sweep func()) {+ ticker := time.NewTicker(interval)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ sweep()+ }+ }+}+// runRuntimeSweeper periodically marks runtimes as offline if their// last_seen_at exceeds the stale threshold, and fails orphaned tasks.// This handles cases where the daemon crashes, is killed without calling@@ -129,37 +168,41 @@ type runtimeGCTxStarter interface {// hot heartbeat path; the DB is allowed to lag up to runtimeHeartbeatDBFlushInterval).// When liveness is unavailable or errors, we fall back to trusting the DB// stale window — that is the original behavior.-func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration, queuedTTL time.Duration) {- ticker := time.NewTicker(sweepInterval)- defer ticker.Stop()+func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration, queuedTTL time.Duration) {+ runPeriodicSweep(ctx, sweepInterval, func() {+ // These stages retain the existing cadence and ordering in PR1 so the+ // rollout changes no business predicate or recovery semantics. Runtime+ // GC is the one exception: its seven-day retention work now runs in the+ // independent hourly loop below and cannot delay this liveness path.+ sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)+ sweepOfflineRuntimeTasks(ctx, queries, taskSvc, reconnectGrace)+ sweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)+ sweepStaleTasks(ctx, queries, taskSvc, bus, reconnectGrace)+ sweepExpiredQueuedTasks(ctx, queries, taskSvc, queuedTTL)+ sweepPendingDelegatedFailureRecoveries(ctx, taskSvc)+ sweepDeferredChatFinalizations(ctx, queries, taskSvc)+ })+}- for {- select {- case <-ctx.Done():- return- case <-ticker.C:- // Every stage below is DB-only and latency-critical: it is what- // flips a dead runtime offline and reclaims its orphaned tasks- // within ~180s. Object-store work belongs on its own goroutine- // (runSourceContextSweeper), never in this tick.- sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)- sweepOfflineRuntimeTasks(ctx, queries, taskSvc, reconnectGrace)- sweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)- sweepStaleTasks(ctx, queries, taskSvc, bus, reconnectGrace)- sweepExpiredQueuedTasks(ctx, queries, taskSvc, queuedTTL)- sweepPendingDelegatedFailureRecoveries(ctx, taskSvc)- sweepDeferredChatFinalizations(ctx, queries, taskSvc)- gcRuntimes(ctx, txStarter, queries, taskSvc.Metrics, bus)- }- }+func runRuntimeGCSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus) {+ runPeriodicSweep(ctx, runtimeGCSweepInterval, func() {+ gcRuntimes(ctx, txStarter, queries, metrics, bus)+ })}// sweepPendingDelegatedFailureRecoveries retries durable coordinator handoffs// that were not acquired by an executable task. It runs even when no stale// task was found in this tick, which is what repairs a recovery dispatch lost// before a server restart.-func sweepPendingDelegatedFailureRecoveries(ctx context.Context, taskSvc *service.TaskService) {+func sweepPendingDelegatedFailureRecoveries(ctx context.Context, taskSvc *service.TaskService) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageDelegatedFailureRecovery, startedAt, stats)+ }()+result, err := taskSvc.RecoverPendingDelegatedFailures(ctx, delegatedFailureRecoveryBatchSize)+ stats.candidates = result.Scanned+ stats.changed = result.Replayed + result.Exhaustedif err != nil {slog.Warn("delegated failure recovery sweeper: replay failed","replayed", result.Replayed,@@ -174,17 +217,24 @@ func sweepPendingDelegatedFailureRecoveries(ctx context.Context, taskSvc *servicif result.Exhausted > 0 {slog.Warn("delegated failure recovery sweeper: automatic attempts exhausted", "count", result.Exhausted)}+ return}// sweepStaleRuntimes marks runtimes offline if they haven't heartbeated. Task// termination is a separate every-tick stage so reconnect grace is measured// independently of the one tick where the runtime first flips offline.-func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {+func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageLiveness, startedAt, stats)+ }()+candidates, err := queries.SelectStaleOnlineRuntimes(ctx, staleThresholdSeconds)if err != nil {slog.Warn("runtime sweeper: failed to list stale online runtimes", "error", err)return}+ stats.candidates = len(candidates)if len(candidates) == 0 {return}@@ -202,6 +252,7 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handlslog.Warn("runtime sweeper: failed to mark stale runtimes offline", "error", err)return}+ stats.changed = len(staleRows)if len(staleRows) == 0 {// All filtered candidates raced into a non-online state between the// SELECT and the UPDATE. Nothing to broadcast.@@ -248,13 +299,19 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handl},})}+ return}// sweepOfflineRuntimeTasks terminates work only after the runtime's last// heartbeat has exceeded the bounded reconnect grace. Running it every tick is// essential: the grace usually expires long after sweepStaleRuntimes performed// the one-time online→offline transition.-func sweepOfflineRuntimeTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) {+func sweepOfflineRuntimeTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageOfflineTasks, startedAt, stats)+ }()+failedTasks, err := queries.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{ReconnectGraceSecs: reconnectGrace.Seconds(),MaxPerTick: offlineTaskFailBatchSize,@@ -263,18 +320,26 @@ func sweepOfflineRuntimeTasks(ctx context.Context, queries *db.Queries, taskSvcslog.Warn("runtime sweeper: failed to clean up long-offline tasks", "error", err)return}+ stats.candidates = len(failedTasks)+ stats.changed = len(failedTasks)if len(failedTasks) == 0 {return}slog.Info("runtime sweeper: failed tasks beyond reconnect grace", "count", len(failedTasks))taskSvc.HandleFailedTasks(ctx, failedTasks)+ return}// sweepExpiredRuntimeReconnectRetries gives health-gated retry waiting a// bounded terminal path. Without this stage a daemon that never returns leaves// the issue active and prevents its runtime from ever becoming GC-eligible.-func sweepExpiredRuntimeReconnectRetries(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) {+func sweepExpiredRuntimeReconnectRetries(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, reconnectGrace time.Duration) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageReconnectRetries, startedAt, stats)+ }()+failedTasks, err := queries.FailExpiredRuntimeReconnectRetries(ctx, db.FailExpiredRuntimeReconnectRetriesParams{ReconnectGraceSecs: reconnectGrace.Seconds(),RuntimeStaleSecs: staleThresholdSeconds,@@ -284,12 +349,15 @@ func sweepExpiredRuntimeReconnectRetries(ctx context.Context, queries *db.Querieslog.Warn("runtime sweeper: failed to expire reconnect retries", "error", err)return}+ stats.candidates = len(failedTasks)+ stats.changed = len(failedTasks)if len(failedTasks) == 0 {return}slog.Info("runtime sweeper: expired reconnect retries", "count", len(failedTasks))taskSvc.HandleFailedTasks(ctx, failedTasks)+ return}// filterStaleRuntimesByLiveness narrows a SELECT-of-stale-candidates down to@@ -330,11 +398,15 @@ func filterStaleRuntimesByLiveness(ctx context.Context, candidates []db.SelectSt// agent_task_queue.runtime_id ON DELETE CASCADE. Candidate discovery is bounded;// each runtime then gets an independent transaction so one bad row cannot abort// the whole sweep.-func gcRuntimes(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus) {- gcRuntimesWithBudget(ctx, txStarter, queries, metrics, bus, runtimeGCTickTimeout)+func gcRuntimes(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(metrics, obsmetrics.RuntimeSweepStageGC, startedAt, stats)+ }()+ return gcRuntimesWithBudget(ctx, txStarter, queries, metrics, bus, runtimeGCTickTimeout)}-func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus, budget time.Duration) {+func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus, budget time.Duration) (stats runtimeSweepStageStats) {gcCtx, cancelGC := context.WithTimeout(ctx, budget)defer cancelGC()@@ -366,6 +438,7 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quemetrics.RecordRuntimeGCFailed()return}+ stats.candidates = len(candidates)if len(candidates) == 0 {return}@@ -401,6 +474,7 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quecontinue}deleted+++ stats.changed++metrics.RecordRuntimeGCDeleted()gcWorkspaces[workspaceID] = true}@@ -420,6 +494,7 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, que},})}+ return}// gcRuntime re-checks and deletes one candidate under a runtime-row FOR UPDATE@@ -505,7 +580,12 @@ func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Qu// in the same tick; this function is a defensive backstop for the residual// edge where a runtime row lingers online-with-stale-heartbeat past the// wall clock (MUL-4107).-func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration) {+func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, bus *events.Bus, reconnectGrace time.Duration) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageStaleTasks, startedAt, stats)+ }()+failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{DispatchTimeoutSecs: dispatchTimeoutSeconds,RunningTimeoutSecs: runningTimeoutSeconds,@@ -518,6 +598,8 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.slog.Warn("task sweeper: failed to clean up stale tasks", "error", err)return}+ stats.candidates = len(failedTasks)+ stats.changed = len(failedTasks)if len(failedTasks) == 0 {return}@@ -525,6 +607,7 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.slog.Info("task sweeper: failed stale tasks", "count", len(failedTasks))taskSvc.CaptureLeaseExpiredTasks(ctx, failedTasks)taskSvc.HandleFailedTasks(ctx, failedTasks)+ return}// sweepExpiredQueuedTasks fails tasks that have been sitting in 'queued' for@@ -533,7 +616,12 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.// historical backlog and catches the race where a runtime goes offline AFTER// a task is already queued. Capped to queuedExpireBatchSize per tick so a// big backlog can't monopolise the DB.-func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, queuedTTL time.Duration) {+func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService, queuedTTL time.Duration) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageQueuedExpiry, startedAt, stats)+ }()+failedTasks, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{TtlSecs: queuedTTL.Seconds(),MaxPerTick: queuedExpireBatchSize,@@ -542,6 +630,8 @@ func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *slog.Warn("task sweeper: failed to expire stale queued tasks", "error", err)return}+ stats.candidates = len(failedTasks)+ stats.changed = len(failedTasks)if len(failedTasks) == 0 {return}@@ -549,6 +639,7 @@ func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *slog.Info("task sweeper: expired stale queued tasks", "count", len(failedTasks))taskSvc.CaptureQueuedExpiredTasks(ctx, failedTasks)taskSvc.HandleFailedTasks(ctx, failedTasks)+ return}// sweepDeferredChatFinalizations settles cancelled chat tasks whose deferred@@ -556,7 +647,12 @@ func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *// the grace period — the daemon died, was partitioned, or its ack was lost.// FinalizeDeferredCancelledChat claims the marker atomically, so racing a// late ack is harmless.-func sweepDeferredChatFinalizations(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService) {+func sweepDeferredChatFinalizations(ctx context.Context, queries *db.Queries, taskSvc *service.TaskService) (stats runtimeSweepStageStats) {+ startedAt := time.Now()+ defer func() {+ observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageDeferredChatFinalization, startedAt, stats)+ }()+rows, err := queries.ListChatFinalizeDeferredExpired(ctx, db.ListChatFinalizeDeferredExpiredParams{GraceSecs: chatFinalizeGraceSeconds,MaxPerTick: chatFinalizeBatchSize,@@ -565,13 +661,17 @@ func sweepDeferredChatFinalizations(ctx context.Context, queries *db.Queries, taslog.Warn("chat finalize sweeper: list deferred failed", "error", err)return}+ stats.candidates = len(rows)if len(rows) == 0 {return}for _, t := range rows {- taskSvc.FinalizeDeferredCancelledChat(ctx, t.ID)+ if taskSvc.FinalizeDeferredCancelledChat(ctx, t.ID) {+ stats.changed+++ }}slog.Info("chat finalize sweeper: settled deferred cancellations", "count", len(rows))+ return}// broadcastFailedTasks is preserved as a thin shim for the integration testsdiff --git a/server/cmd/server/runtime_sweeper_test.go b/server/cmd/server/runtime_sweeper_test.goindex 82372c5d15..e40d5af949 100644--- a/server/cmd/server/runtime_sweeper_test.go+++ b/server/cmd/server/runtime_sweeper_test.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "os""strings""sync""testing"@@ -12,6 +13,65 @@ import (db "github.com/multica-ai/multica/server/pkg/db/generated")+// TestRuntimeGCRunsOutsideTheLivenessLoop pins PR1's deployment boundary: GC+// keeps its existing predicates and budgets, but its seven-day retention scan+// no longer occupies the 30-second runtime/task loop.+func TestRuntimeGCRunsOutsideTheLivenessLoop(t *testing.T) {+ if runtimeGCSweepInterval != time.Hour {+ t.Fatalf("runtime GC interval = %s, want 1h", runtimeGCSweepInterval)+ }++ source, err := os.ReadFile("runtime_sweeper.go")+ if err != nil {+ t.Fatalf("read runtime_sweeper.go: %v", err)+ }+ start := strings.Index(string(source), "func runRuntimeSweeper(")+ end := strings.Index(string(source), "func runRuntimeGCSweeper(")+ if start < 0 || end <= start {+ t.Fatal("could not isolate runtime sweeper loops")+ }+ if strings.Contains(string(source[start:end]), "gcRuntimes(") {+ t.Fatal("runtime GC is still invoked from the 30-second liveness loop")+ }+}++// TestRuntimeGCDailyCandidateCapacity prevents an interval or batch-size change+// from silently reducing the hourly GC worker below its agreed daily capacity.+func TestRuntimeGCDailyCandidateCapacity(t *testing.T) {+ const wantCandidatesPerDay = 12_000+ got := int(24*time.Hour/runtimeGCSweepInterval) * runtimeGCBatchSize+ if got != wantCandidatesPerDay {+ t.Fatalf("runtime GC candidate capacity = %d/day, want %d/day", got, wantCandidatesPerDay)+ }+}++func TestPeriodicSweepStopsWithItsContext(t *testing.T) {+ ctx, cancel := context.WithCancel(context.Background())+ called := make(chan struct{}, 1)+ stopped := make(chan struct{})+ go func() {+ runPeriodicSweep(ctx, 10*time.Millisecond, func() {+ select {+ case called <- struct{}{}:+ default:+ }+ })+ close(stopped)+ }()++ select {+ case <-called:+ case <-time.After(2 * time.Second):+ t.Fatal("periodic sweep did not run")+ }+ cancel()+ select {+ case <-stopped:+ case <-time.After(2 * time.Second):+ t.Fatal("periodic sweep did not stop with its context")+ }+}+// setupSweeperTestFixture creates an issue and a task in the given status with// timestamps old enough to trigger the sweeper. Returns (issueID, agentID, taskID).func setupSweeperTestFixture(t *testing.T, taskStatus string) (string, string, string) {diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 6e52e2ecba..8388011995 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -2,6 +2,7 @@ package metricsimport ("sync"+ "time""github.com/multica-ai/multica/server/pkg/taskfailure""github.com/prometheus/client_golang/prometheus"@@ -11,6 +12,19 @@ var taskDurationBuckets = []float64{1, 2.5, 5, 10, 30, 60, 120, 300, 600, 1200,var chatClaimResumeQueryDurationBuckets = []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5}+var runtimeSweepStageDurationBuckets = []float64{0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 15, 30, 60}++const (+ RuntimeSweepStageLiveness = "runtime_liveness"+ RuntimeSweepStageOfflineTasks = "offline_runtime_tasks"+ RuntimeSweepStageReconnectRetries = "runtime_reconnect_retries"+ RuntimeSweepStageStaleTasks = "stale_tasks"+ RuntimeSweepStageQueuedExpiry = "queued_task_expiry"+ RuntimeSweepStageDelegatedFailureRecovery = "delegated_failure_recovery"+ RuntimeSweepStageDeferredChatFinalization = "deferred_chat_finalize"+ RuntimeSweepStageGC = "runtime_gc"+)+type activeTaskLabels struct {source stringruntimeMode string@@ -38,6 +52,9 @@ type BusinessMetrics struct {chatClaimSessionFallbackNeeded prometheus.CounterchatClaimSessionFallbackResult *prometheus.CounterVecchatClaimResumeQueryDuration *prometheus.HistogramVec+ runtimeSweepStageDuration *prometheus.HistogramVec+ runtimeSweepCandidateRows *prometheus.CounterVec+ runtimeSweepRowsChanged *prometheus.CounterVecruntimeGCDeleted prometheus.CounterruntimeGCFailed prometheus.CounterruntimeGCBlocked prometheus.Gauge@@ -180,6 +197,25 @@ func NewBusinessMetrics() *BusinessMetrics {Help: "Duration of chat-claim resume-history queries by fixed query name.",Buckets: chatClaimResumeQueryDurationBuckets,}, metricLabels("multica_chat_claim_resume_query_duration_seconds")),+ runtimeSweepStageDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Namespace: "multica",+ Subsystem: "runtime_sweeper",+ Name: "stage_duration_seconds",+ Help: "Duration of each runtime maintenance sweeper stage.",+ Buckets: runtimeSweepStageDurationBuckets,+ }, metricLabels("multica_runtime_sweeper_stage_duration_seconds")),+ runtimeSweepCandidateRows: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica",+ Subsystem: "runtime_sweeper",+ Name: "candidate_rows_total",+ Help: "Total candidate rows returned to or examined by the application in each runtime maintenance sweeper stage.",+ }, metricLabels("multica_runtime_sweeper_candidate_rows_total")),+ runtimeSweepRowsChanged: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica",+ Subsystem: "runtime_sweeper",+ Name: "rows_changed_total",+ Help: "Total rows whose persisted maintenance state changed in each runtime sweeper stage.",+ }, metricLabels("multica_runtime_sweeper_rows_changed_total")),runtimeGCDeleted: prometheus.NewCounter(prometheus.CounterOpts{Namespace: "multica",Subsystem: "runtime_gc",@@ -260,6 +296,9 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.chatClaimSessionFallbackNeeded,m.chatClaimSessionFallbackResult,m.chatClaimResumeQueryDuration,+ m.runtimeSweepStageDuration,+ m.runtimeSweepCandidateRows,+ m.runtimeSweepRowsChanged,m.runtimeGCDeleted,m.runtimeGCFailed,m.runtimeGCBlocked,@@ -346,6 +385,42 @@ func (m *BusinessMetrics) RecordRuntimeGCBlockedObservationFailed() {m.runtimeGCBlockedObservationFailed.Inc()}+// 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+// maintenance state changed.+func (m *BusinessMetrics) ObserveRuntimeSweepStage(stage string, duration time.Duration, candidates, changed int) {+ if m == nil {+ return+ }+ stage = normalizeRuntimeSweepStage(stage)+ if candidates < 0 {+ candidates = 0+ }+ if changed < 0 {+ changed = 0+ }+ m.runtimeSweepStageDuration.WithLabelValues(stage).Observe(duration.Seconds())+ m.runtimeSweepCandidateRows.WithLabelValues(stage).Add(float64(candidates))+ m.runtimeSweepRowsChanged.WithLabelValues(stage).Add(float64(changed))+}++func normalizeRuntimeSweepStage(stage string) string {+ switch stage {+ case RuntimeSweepStageLiveness,+ RuntimeSweepStageOfflineTasks,+ RuntimeSweepStageReconnectRetries,+ RuntimeSweepStageStaleTasks,+ RuntimeSweepStageQueuedExpiry,+ RuntimeSweepStageDelegatedFailureRecovery,+ RuntimeSweepStageDeferredChatFinalization,+ RuntimeSweepStageGC:+ return stage+ default:+ return "other"+ }+}+func (m *BusinessMetrics) RecordTaskEnqueued(source, runtimeMode string) {if m == nil {returndiff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 70fbe8ee7d..8423953c17 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -4,6 +4,7 @@ import ("math""strconv""testing"+ "time""github.com/prometheus/client_golang/prometheus""github.com/prometheus/client_golang/prometheus/testutil"@@ -182,6 +183,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {m.RecordEntitlementDecision("autopilot_runs", "observe", "cache_fresh")m.RecordEntitlementVersionRegression()m.RecordAutopilotQuotaDecision("observe", "manual", "admitted")+ m.ObserveRuntimeSweepStage(RuntimeSweepStageLiveness, time.Second, 2, 1)families, err := registry.Gather()if err != nil {@@ -222,6 +224,25 @@ func TestBusinessMetricsRuntimeGC(t *testing.T) {}}+func TestBusinessMetricsRuntimeSweepStage(t *testing.T) {+ m := NewBusinessMetrics()+ m.ObserveRuntimeSweepStage(RuntimeSweepStageLiveness, 250*time.Millisecond, 3, 1)+ m.ObserveRuntimeSweepStage("unbounded-user-value", time.Second, -1, -1)++ if got := testutil.ToFloat64(m.runtimeSweepCandidateRows.WithLabelValues(RuntimeSweepStageLiveness)); got != 3 {+ t.Fatalf("runtime liveness candidate rows = %v, want 3", got)+ }+ if got := testutil.ToFloat64(m.runtimeSweepRowsChanged.WithLabelValues(RuntimeSweepStageLiveness)); got != 1 {+ t.Fatalf("runtime liveness changed rows = %v, want 1", got)+ }+ if got := testutil.ToFloat64(m.runtimeSweepCandidateRows.WithLabelValues("other")); got != 0 {+ t.Fatalf("normalized other candidate rows = %v, want 0", got)+ }+ if got := testutil.CollectAndCount(m.runtimeSweepStageDuration); got != 2 {+ t.Fatalf("runtime sweep duration series = %d, want 2", got)+ }+}+func exerciseEvent(m *BusinessMetrics, name string, props map[string]any) {if props == nil {props = map[string]any{}diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 3694cf4f21..5a75798a7c 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -34,6 +34,7 @@ const (labelOp = "op"labelGate = "gate"labelOutcome = "outcome"+ labelStage = "stage")var businessMetricLabels = map[string][]string{@@ -56,6 +57,9 @@ var businessMetricLabels = map[string][]string{"multica_chat_claim_session_fallback_needed_total": {},"multica_chat_claim_session_fallback_result_total": {labelResult},"multica_chat_claim_resume_query_duration_seconds": {labelQuery},+ "multica_runtime_sweeper_stage_duration_seconds": {labelStage},+ "multica_runtime_sweeper_candidate_rows_total": {labelStage},+ "multica_runtime_sweeper_rows_changed_total": {labelStage},// PR3 funnel / community / commercial."multica_signup_total": {labelSignupSource},diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex c50c0d48fd..017ef0157c 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3185,10 +3185,11 @@ func (s *TaskService) RebroadcastCancelledTask(ctx context.Context, taskID pgtyps.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, task)}-func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) {+func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID pgtype.UUID) bool {var (task db.AgentTaskQueuepayload protocol.ChatCancelFinalizedPayload+ changed boolsettled bool)if err := s.runInTx(ctx, func(qtx *db.Queries) error {@@ -3221,6 +3222,7 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskIDif err != nil {return fmt.Errorf("claim deferred chat finalize: %w", err)}+ changed = truetask = claimedif sessionGone {// The session cascaded away (its FK NULLs the column below anyway):@@ -3318,12 +3320,13 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID"task_id", util.UUIDToString(taskID),"error", err,)- return+ return false}if !settled || payload.Outcome == "" {- return+ return changed}s.broadcastChatCancelFinalized(ctx, task, payload)+ return changed}func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.AgentTaskQueue, payload protocol.ChatCancelFinalizedPayload) {@@ -5727,6 +5730,7 @@ const (// replays from terminally exhausted outbox entries so operators never mistake// a bounded stop for a successful replay.type DelegatedFailureRecoverySweepResult struct {+ Scanned intReplayed intExhausted int}@@ -6203,6 +6207,7 @@ func (s *TaskService) RecoverPendingDelegatedFailures(ctx context.Context, maxPeif err != nil {return result, fmt.Errorf("list pending delegated failure recoveries: %w", err)}+ result.Scanned = len(pending)errs := make([]error, 0)for _, comment := range pending {diff --git a/server/internal/service/task_cancel_finalize_test.go b/server/internal/service/task_cancel_finalize_test.goindex 5c0e10e42b..5b6ed752aa 100644--- a/server/internal/service/task_cancel_finalize_test.go+++ b/server/internal/service/task_cancel_finalize_test.go@@ -522,8 +522,12 @@ func TestFinalizeDeferredCancelledChat_SecondCallIsNoop(t *testing.T) {}f.insertTranscriptRow(t, ctx)- svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))- svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))+ if changed := svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID)); !changed {+ t.Fatal("first deferred finalize did not report its marker claim")+ }+ if changed := svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID)); changed {+ t.Fatal("duplicate deferred finalize reported a persisted change")+ }if got := f.assistantMessages(t, ctx); len(got) != 1 {t.Errorf("assistant messages = %v, want exactly one Stopped.", got)diff --git a/server/migrations/438_agent_runtime_online_last_seen_index.down.sql b/server/migrations/438_agent_runtime_online_last_seen_index.down.sqlnew file mode 100644index 0000000000..9e969b4bb2--- /dev/null+++ b/server/migrations/438_agent_runtime_online_last_seen_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_runtime_online_last_seen;diff --git a/server/migrations/438_agent_runtime_online_last_seen_index.up.sql b/server/migrations/438_agent_runtime_online_last_seen_index.up.sqlnew file mode 100644index 0000000000..cb94a3358b--- /dev/null+++ b/server/migrations/438_agent_runtime_online_last_seen_index.up.sql@@ -0,0 +1,7 @@+-- Keep the 30-second global liveness sweep off agent_runtime's offline+-- history. Only online rows receive heartbeat writes, and that set is small;+-- the partial index preserves the range predicate without restoring the+-- retired full-table last_seen_at index.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_runtime_online_last_seen+ ON agent_runtime (last_seen_at)+ WHERE status = 'online';diff --git a/server/migrations/439_agent_runtime_offline_last_seen_index.down.sql b/server/migrations/439_agent_runtime_offline_last_seen_index.down.sqlnew file mode 100644index 0000000000..cd3cfbdecc--- /dev/null+++ b/server/migrations/439_agent_runtime_offline_last_seen_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_runtime_offline_last_seen;diff --git a/server/migrations/439_agent_runtime_offline_last_seen_index.up.sql b/server/migrations/439_agent_runtime_offline_last_seen_index.up.sqlnew file mode 100644index 0000000000..666411380f--- /dev/null+++ b/server/migrations/439_agent_runtime_offline_last_seen_index.up.sql@@ -0,0 +1,6 @@+-- Runtime GC orders stale offline candidates by last_seen_at and takes a+-- bounded prefix. Offline heartbeat timestamps are stable, so this partial+-- index removes the full-table sort with negligible steady-state write cost.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_runtime_offline_last_seen+ ON agent_runtime (last_seen_at, id)+ WHERE status = 'offline';