Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6742: fix archived-agent runtime garbage collection (#7641)
Multica Eve08a1e6e934ab
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 3fadd92c3d..a292b4b030 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -609,7 +609,7 @@ func main() {// 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)+ go runRuntimeGCSweeper(sweepCtx, pool, queries, taskSvc.Metrics, h)// 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_gc_test.go b/server/cmd/server/runtime_gc_test.goindex 86fcecc10d..7f4af19f14 100644--- a/server/cmd/server/runtime_gc_test.go+++ b/server/cmd/server/runtime_gc_test.go@@ -12,7 +12,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgconn""github.com/jackc/pgx/v5/pgxpool"- "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -24,8 +24,8 @@ func TestRuntimeGC_KeepsTerminalTaskHistory(t *testing.T) {ctx := context.Background()runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "history")agentID := createRuntimeGCFixtureAgent(t, ctx, runtimeID, "history")- if _, err := testPool.Exec(ctx, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, agentID); err != nil {- t.Fatalf("unbind fixture agent: %v", err)+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID); err != nil {+ t.Fatalf("archive fixture agent: %v", err)}tasks := make([]string, 0, 3)@@ -52,15 +52,18 @@ func TestRuntimeGC_KeepsTerminalTaskHistory(t *testing.T) {t.Fatalf("insert task token: %v", err)}- workspaceID, deleted, blocked, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))if err != nil {t.Fatalf("gcRuntime: %v", err)}- if !deleted || blocked {- t.Fatalf("gc result deleted=%v blocked=%v, want deleted", deleted, blocked)+ if !result.deleted || result.skipReason != "" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want deleted", result.deleted, result.skipReason)}- if workspaceID != testWorkspaceID {- t.Fatalf("workspace id = %q, want %q", workspaceID, testWorkspaceID)+ if result.workspaceID != testWorkspaceID {+ t.Fatalf("workspace id = %q, want %q", result.workspaceID, testWorkspaceID)+ }+ if len(result.teardown.CancelledTasks) != 0 {+ t.Fatalf("automatic GC cancelled %d tasks, want none", len(result.teardown.CancelledTasks))}var runtimeRows int@@ -70,6 +73,17 @@ func TestRuntimeGC_KeepsTerminalTaskHistory(t *testing.T) {if runtimeRows != 0 {t.Fatalf("runtime rows = %d, want 0", runtimeRows)}+ var survivingAgents int+ var agentUnbound bool+ if err := testPool.QueryRow(ctx, `+ SELECT count(*), bool_and(runtime_id IS NULL)+ FROM agent WHERE id = $1+ `, agentID).Scan(&survivingAgents, &agentUnbound); err != nil {+ t.Fatalf("read archived agent: %v", err)+ }+ if survivingAgents != 1 || !agentUnbound {+ t.Fatalf("archived agent rows=%d unbound=%v, want preserved and unbound", survivingAgents, agentUnbound)+ }for _, id := range tasks {var taskRows intvar runtimeDetached bool@@ -92,6 +106,10 @@ func TestRuntimeGC_KeepsTerminalTaskHistory(t *testing.T) {t.Fatalf("%s rows = %d, want %d", table, rows, want)}}+ repeated, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ if err != nil || repeated.deleted || repeated.skipReason != "" {+ t.Fatalf("repeated GC result deleted=%v skip_reason=%q err=%v, want idempotent no-op", repeated.deleted, repeated.skipReason, err)+ }}func TestRuntimeGC_ProtectsEveryNonTerminalTaskStatus(t *testing.T) {@@ -106,12 +124,12 @@ func TestRuntimeGC_ProtectsEveryNonTerminalTaskStatus(t *testing.T) {runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "blocked-"+status)taskID := createRuntimeGCFixtureTask(t, ctx, runtimeID, agentID, status, false)- _, deleted, blocked, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))if err != nil {t.Fatalf("gcRuntime: %v", err)}- if deleted || !blocked {- t.Fatalf("gc result deleted=%v blocked=%v, want safely blocked", deleted, blocked)+ if result.deleted || result.skipReason != "non_terminal_task" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want safely task-blocked", result.deleted, result.skipReason)}var runtimeRows, taskRows int@@ -139,6 +157,24 @@ func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testiagentID := runtimeGCFixtureAgentID(t, ctx)drainableRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-drainable")blockedRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-blocked")+ activeRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-active")+ _ = createRuntimeGCFixtureAgent(t, ctx, activeRuntimeID, "candidate-active")+ archivedRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-archived")+ archivedAgentID := createRuntimeGCFixtureAgent(t, ctx, archivedRuntimeID, "candidate-archived")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, archivedAgentID); err != nil {+ t.Fatalf("archive candidate agent: %v", err)+ }+ systemRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-system")+ systemAgentID := createRuntimeGCFixtureAgent(t, ctx, systemRuntimeID, "candidate-system")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET kind = 'system', system_key = $2 WHERE id = $1`, systemAgentID, "runtime_gc_candidate_"+systemAgentID); err != nil {+ t.Fatalf("convert candidate to system agent: %v", err)+ }+ foreignWorkspaceID := createRuntimeGCFixtureWorkspace(t, ctx, "candidate-mismatch")+ mismatchRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-mismatch")+ mismatchAgentID := createRuntimeGCFixtureAgentForWorkspace(t, ctx, foreignWorkspaceID, mismatchRuntimeID, "candidate-mismatch")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, mismatchAgentID); err != nil {+ t.Fatalf("archive candidate workspace-mismatch agent: %v", err)+ }_ = createRuntimeGCFixtureTask(t, ctx, blockedRuntimeID, agentID, "deferred", false)queries := db.New(testPool)@@ -149,28 +185,293 @@ func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testiif err != nil {t.Fatalf("list GC candidates: %v", err)}- foundDrainable := false+ foundDrainable, foundArchived, foundSystem := false, false, falsefor _, id := range candidates {idString := util.UUIDToString(id)if idString == blockedRuntimeID {t.Fatal("non-terminal task owner entered the bounded GC batch")}+ if idString == activeRuntimeID {+ t.Fatal("runtime with an active user agent entered the bounded GC batch")+ }if idString == drainableRuntimeID {foundDrainable = true}+ if idString == archivedRuntimeID {+ foundArchived = true+ }+ if idString == systemRuntimeID {+ foundSystem = true+ }}if !foundDrainable {t.Fatal("drainable runtime missing from GC candidates")}- blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{+ if !foundArchived || !foundSystem {+ t.Fatalf("archived/system candidates found=%v/%v, want both", foundArchived, foundSystem)+ }+ backlog, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(ctx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{StaleSeconds: offlineRuntimeTTLSeconds,- MaxRows: runtimeGCBlockedScanLimit,+ MaxRows: runtimeGCBacklogScanLimit,})if err != nil {- t.Fatalf("count blocked GC runtimes: %v", err)+ t.Fatalf("classify runtime GC backlog: %v", err)+ }+ var activeBlocked, taskBlocked, workspaceMismatch int64+ for _, row := range backlog {+ switch row.Reason {+ case "active_agent":+ activeBlocked = row.Count+ case "non_terminal_task":+ taskBlocked = row.Count+ case "workspace_mismatch":+ workspaceMismatch = row.Count+ }+ }+ if activeBlocked < 1 {+ t.Fatalf("active-agent backlog = %d, want at least 1", activeBlocked)+ }+ if taskBlocked < 1 {+ t.Fatalf("non-terminal-task backlog = %d, want at least 1", taskBlocked)+ }+ if workspaceMismatch < 1 {+ t.Fatalf("workspace-mismatch backlog = %d, want at least 1", workspaceMismatch)+ }+ legacyBlocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{+ StaleSeconds: offlineRuntimeTTLSeconds,+ MaxRows: runtimeGCBacklogScanLimit,+ })+ if err != nil {+ t.Fatalf("count legacy task-blocked runtimes: %v", err)+ }++ // The second task predicate must remain independently indexable: a task can+ // be pinned to an online runtime after a historical move while its archived+ // owner is still bound to this stale runtime. Only the agent-id path should+ // classify the stale runtime as task-blocked.+ pinnedOwnerRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-agent-task-owner")+ pinnedAgentID := createRuntimeGCFixtureAgent(t, ctx, pinnedOwnerRuntimeID, "candidate-agent-task-owner")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, pinnedAgentID); err != nil {+ t.Fatalf("archive candidate agent-task owner: %v", err)+ }+ onlineTaskRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-agent-task-target")+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, onlineTaskRuntimeID); err != nil {+ t.Fatalf("mark task target runtime online: %v", err)+ }+ _ = createRuntimeGCFixtureTask(t, ctx, onlineTaskRuntimeID, pinnedAgentID, "deferred", false)++ afterPinnedTask, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(ctx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{+ StaleSeconds: offlineRuntimeTTLSeconds,+ MaxRows: runtimeGCBacklogScanLimit,+ })+ if err != nil {+ t.Fatalf("classify runtime GC backlog after pinned agent task: %v", err)+ }+ var taskBlockedAfter int64+ for _, row := range afterPinnedTask {+ if row.Reason == "non_terminal_task" {+ taskBlockedAfter = row.Count+ }+ }+ if taskBlockedAfter != taskBlocked+1 {+ t.Fatalf("non-terminal-task backlog after agent-owned pinned task = %d, want %d", taskBlockedAfter, taskBlocked+1)+ }+ legacyBlockedAfter, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{+ StaleSeconds: offlineRuntimeTTLSeconds,+ MaxRows: runtimeGCBacklogScanLimit,+ })+ if err != nil {+ t.Fatalf("recount legacy task-blocked runtimes: %v", err)+ }+ if legacyBlockedAfter != legacyBlocked {+ t.Fatalf("legacy blocked count changed from %d to %d for the broader agent-owned task case", legacyBlocked, legacyBlockedAfter)+ }+}++func TestRuntimeGC_ArchivedAgentTaskPinnedToAnotherRuntimeFailsClosed(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ staleRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "cross-runtime-owner")+ otherRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "cross-runtime-task")+ agentID := createRuntimeGCFixtureAgent(t, ctx, staleRuntimeID, "cross-runtime")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID); err != nil {+ t.Fatalf("archive fixture agent: %v", err)+ }+ taskID := createRuntimeGCFixtureTask(t, ctx, otherRuntimeID, agentID, "queued", false)++ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(staleRuntimeID))+ if err != nil {+ t.Fatalf("gcRuntime: %v", err)+ }+ if result.deleted || result.skipReason != "non_terminal_task" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want non-terminal-task skip", result.deleted, result.skipReason)+ }++ var agentRuntime, taskRuntime, taskStatus string+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&agentRuntime); err != nil {+ t.Fatalf("read agent runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text, status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&taskRuntime, &taskStatus); err != nil {+ t.Fatalf("read task: %v", err)+ }+ if agentRuntime != staleRuntimeID || taskRuntime != otherRuntimeID || taskStatus != "queued" {+ t.Fatalf("GC mutated blocked data: agent runtime=%q task runtime=%q status=%q", agentRuntime, taskRuntime, taskStatus)+ }+}++func TestRuntimeGC_RechecksRuntimeEligibilityUnderLock(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "eligibility-changed")+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET status = 'online', last_seen_at = now() WHERE id = $1`, runtimeID); err != nil {+ t.Fatalf("bring fixture runtime online: %v", err)+ }++ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ if err != nil {+ t.Fatalf("gcRuntime: %v", err)+ }+ if result.deleted || result.skipReason != "eligibility_changed" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want eligibility-changed skip", result.deleted, result.skipReason)+ }+ var status string+ if err := testPool.QueryRow(ctx, `SELECT status FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&status); err != nil {+ t.Fatalf("read runtime: %v", err)+ }+ if status != "online" {+ t.Fatalf("runtime status=%q, want online", status)+ }+}++func TestRuntimeGC_DeletesSystemAgentAndRuntime(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "system-agent")+ agentID := createRuntimeGCFixtureAgent(t, ctx, runtimeID, "system-agent")+ if _, err := testPool.Exec(ctx, `+ UPDATE agent SET kind = 'system', system_key = $2 WHERE id = $1+ `, agentID, "runtime_gc_probe_"+agentID); err != nil {+ t.Fatalf("convert fixture to system agent: %v", err)+ }++ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ if err != nil {+ t.Fatalf("gcRuntime: %v", err)+ }+ if !result.deleted || result.skipReason != "" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want deleted", result.deleted, result.skipReason)+ }+ var runtimeRows, agentRows int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeRows); err != nil {+ t.Fatalf("count runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent WHERE id = $1`, agentID).Scan(&agentRows); err != nil {+ t.Fatalf("count system agent: %v", err)}- if blocked < 1 {- t.Fatalf("blocked runtime gauge source = %d, want at least 1", blocked)+ if runtimeRows != 0 || agentRows != 0 {+ t.Fatalf("runtime rows=%d system agent rows=%d, want both deleted", runtimeRows, agentRows)+ }+}++func TestRuntimeGC_ProfileBackedInstanceKeepsProfile(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ profileID := createRuntimeGCFixtureProfile(t, ctx, "preserved")+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "profile-backed")+ if _, err := testPool.Exec(ctx, `UPDATE agent_runtime SET profile_id = $2 WHERE id = $1`, runtimeID, profileID); err != nil {+ t.Fatalf("bind runtime profile: %v", err)+ }++ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ if err != nil {+ t.Fatalf("gcRuntime: %v", err)+ }+ if !result.deleted || result.skipReason != "" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want deleted", result.deleted, result.skipReason)+ }+ var profiles int+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profiles); err != nil {+ t.Fatalf("count runtime profile: %v", err)+ }+ if profiles != 1 {+ t.Fatalf("runtime profile rows=%d, want preserved", profiles)+ }+}++func TestRuntimeGC_CrossWorkspaceAgentReferenceFailsClosed(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ foreignWorkspaceID := createRuntimeGCFixtureWorkspace(t, ctx, "mismatch")+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "workspace-mismatch")+ agentID := createRuntimeGCFixtureAgentForWorkspace(t, ctx, foreignWorkspaceID, runtimeID, "workspace-mismatch")+ if _, err := testPool.Exec(ctx, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID); err != nil {+ t.Fatalf("archive cross-workspace agent: %v", err)+ }++ result, err := gcRuntime(ctx, testPool, db.New(testPool), parseUUID(runtimeID))+ if err != nil {+ t.Fatalf("gcRuntime: %v", err)+ }+ if result.deleted || result.skipReason != "workspace_mismatch" {+ t.Fatalf("gc result deleted=%v skip_reason=%q, want workspace-mismatch skip", result.deleted, result.skipReason)+ }+ var runtimeRows int+ var agentRuntime string+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeRows); err != nil {+ t.Fatalf("count runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&agentRuntime); err != nil {+ t.Fatalf("read cross-workspace agent: %v", err)+ }+ if runtimeRows != 1 || agentRuntime != runtimeID {+ t.Fatalf("workspace mismatch mutated data: runtime rows=%d agent runtime=%q", runtimeRows, agentRuntime)+ }+}++func TestRuntimeGCBatch_PublishesSystemActorAndDeduplicatesWorkspaceRefresh(t *testing.T) {+ if testPool == nil {+ t.Skip("no database connection")+ }+ ctx := context.Background()+ workspaceID := createRuntimeGCFixtureWorkspace(t, ctx, "events")+ _ = createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-a")+ _ = createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, workspaceID, "events-b")+ publisher := &recordingRuntimeGCPublisher{}++ gcRuntimesWithBudget(ctx, testPool, db.New(testPool), nil, publisher, 5*time.Second)++ var teardownCalls, refreshCalls int+ for _, call := range publisher.calls {+ if call.workspaceID != workspaceID {+ continue+ }+ if call.actorType != "system" || call.actorID != "" || call.action != "runtime_gc" {+ t.Fatalf("unexpected GC event metadata: %+v", call)+ }+ if call.kind == "teardown" {+ teardownCalls+++ if call.publishRuntimeRefresh {+ t.Fatal("per-runtime teardown published an undeduplicated refresh")+ }+ if call.cancelledTasks != 0 {+ t.Fatalf("automatic GC exposed %d cancelled tasks", call.cancelledTasks)+ }+ } else if call.kind == "refresh" {+ refreshCalls+++ }+ }+ if teardownCalls != 2 || refreshCalls != 1 {+ t.Fatalf("workspace GC events: teardown=%d refresh=%d, want 2 and 1", teardownCalls, refreshCalls)}}@@ -184,12 +485,12 @@ func TestRuntimeGC_RollsBackDetachedHistoryWhenDeleteFails(t *testing.T) {taskID := createRuntimeGCFixtureTask(t, ctx, runtimeID, agentID, "completed", true)starter := failRuntimeDeleteTxStarter{pool: testPool}- _, deleted, blocked, err := gcRuntime(ctx, starter, db.New(testPool), parseUUID(runtimeID))+ result, err := gcRuntime(ctx, starter, db.New(testPool), parseUUID(runtimeID))if err == nil || !strings.Contains(err.Error(), "injected runtime delete failure") {t.Fatalf("gcRuntime error = %v, want injected delete failure", err)}- if deleted || blocked {- t.Fatalf("gc result deleted=%v blocked=%v after error", deleted, blocked)+ if result.deleted || result.skipReason != "" {+ t.Fatalf("gc result deleted=%v skip_reason=%q after error", result.deleted, result.skipReason)}var runtimeRows int@@ -218,14 +519,13 @@ func TestRuntimeGC_RuntimeLockRejectsConcurrentEnqueue(t *testing.T) {proceed := make(chan struct{})starter := signalRuntimeLockTxStarter{pool: testPool, locked: locked, proceed: proceed}type gcResult struct {- deleted bool- blocked bool- err error+ result runtimeGCResult+ err error}gcDone := make(chan gcResult, 1)go func() {- _, deleted, blocked, err := gcRuntime(ctx, starter, db.New(testPool), parseUUID(runtimeID))- gcDone <- gcResult{deleted: deleted, blocked: blocked, err: err}+ result, err := gcRuntime(ctx, starter, db.New(testPool), parseUUID(runtimeID))+ gcDone <- gcResult{result: result, err: err}}()select {case <-locked:@@ -258,8 +558,8 @@ func TestRuntimeGC_RuntimeLockRejectsConcurrentEnqueue(t *testing.T) {}result := <-gcDone- if result.err != nil || !result.deleted || result.blocked {- t.Fatalf("gc result deleted=%v blocked=%v err=%v", result.deleted, result.blocked, result.err)+ if result.err != nil || !result.result.deleted || result.result.skipReason != "" {+ t.Fatalf("gc result deleted=%v skip_reason=%q err=%v", result.result.deleted, result.result.skipReason, result.err)}if err := <-writerDone; !errors.Is(err, pgx.ErrNoRows) {t.Fatalf("concurrent enqueue error = %v, want pgx.ErrNoRows from ownership fence", err)@@ -282,7 +582,7 @@ func TestRuntimeGC_TickBudgetBoundsWholeBatch(t *testing.T) {starter := &blockingRuntimeGCTxStarter{}startedAt := time.Now()- gcRuntimesWithBudget(ctx, starter, db.New(testPool), nil, events.New(), 250*time.Millisecond)+ gcRuntimesWithBudget(ctx, starter, db.New(testPool), nil, nil, 250*time.Millisecond)elapsed := time.Since(startedAt)if got := starter.begins.Load(); got != 1 {@@ -304,6 +604,42 @@ type blockingRuntimeGCTxStarter struct {begins atomic.Int32}+type runtimeGCPublishCall struct {+ kind string+ workspaceID string+ actorType string+ actorID string+ action string+ publishRuntimeRefresh bool+ cancelledTasks int+}++type recordingRuntimeGCPublisher struct {+ calls []runtimeGCPublishCall+}++func (p *recordingRuntimeGCPublisher) PublishRuntimeTeardown(_ context.Context, result service.RuntimeTeardownResult, workspaceID, actorType, actorID, action string, publishRuntimeRefresh bool) {+ p.calls = append(p.calls, runtimeGCPublishCall{+ kind: "teardown",+ workspaceID: workspaceID,+ actorType: actorType,+ actorID: actorID,+ action: action,+ publishRuntimeRefresh: publishRuntimeRefresh,+ cancelledTasks: len(result.CancelledTasks),+ })+}++func (p *recordingRuntimeGCPublisher) PublishRuntimeRefresh(workspaceID, actorType, actorID, action string) {+ p.calls = append(p.calls, runtimeGCPublishCall{+ kind: "refresh",+ workspaceID: workspaceID,+ actorType: actorType,+ actorID: actorID,+ action: action,+ })+}+func (s *blockingRuntimeGCTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {s.begins.Add(1)<-ctx.Done()@@ -369,8 +705,14 @@ type signalRuntimeLockRow struct {func (row signalRuntimeLockRow) Scan(dest ...any) error {err := row.Row.Scan(dest...)- close(row.locked)- <-row.proceed+ select {+ case <-row.locked:+ // The shared teardown defensively re-acquires the same runtime lock.+ // Only the first acquisition is the synchronization point for this test.+ default:+ close(row.locked)+ <-row.proceed+ }return err}@@ -395,6 +737,10 @@ func waitForRuntimeGCBlockedWriter(ctx context.Context, pid int32) error {}func createRuntimeGCFixtureRuntime(t *testing.T, ctx context.Context, suffix string) string {+ return createRuntimeGCFixtureRuntimeForWorkspace(t, ctx, testWorkspaceID, suffix)+}++func createRuntimeGCFixtureRuntimeForWorkspace(t *testing.T, ctx context.Context, workspaceID, suffix string) string {t.Helper()var runtimeID stringif err := testPool.QueryRow(ctx, `@@ -405,7 +751,7 @@ func createRuntimeGCFixtureRuntime(t *testing.T, ctx context.Context, suffix strVALUES ($1, $2, 'cloud', 'runtime-gc-test', 'offline','', '{}'::jsonb, $3, now() - interval '8 days')RETURNING id- `, testWorkspaceID, "Runtime GC "+suffix, testUserID).Scan(&runtimeID); err != nil {+ `, workspaceID, "Runtime GC "+suffix, testUserID).Scan(&runtimeID); err != nil {t.Fatalf("create runtime fixture: %v", err)}t.Cleanup(func() {@@ -416,6 +762,10 @@ func createRuntimeGCFixtureRuntime(t *testing.T, ctx context.Context, suffix str}func createRuntimeGCFixtureAgent(t *testing.T, ctx context.Context, runtimeID, suffix string) string {+ return createRuntimeGCFixtureAgentForWorkspace(t, ctx, testWorkspaceID, runtimeID, suffix)+}++func createRuntimeGCFixtureAgentForWorkspace(t *testing.T, ctx context.Context, workspaceID, runtimeID, suffix string) string {t.Helper()var agentID stringif err := testPool.QueryRow(ctx, `@@ -425,7 +775,7 @@ func createRuntimeGCFixtureAgent(t *testing.T, ctx context.Context, runtimeID, s)VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)RETURNING id- `, testWorkspaceID, "Runtime GC Agent "+suffix, runtimeID, testUserID).Scan(&agentID); err != nil {+ `, workspaceID, "Runtime GC Agent "+suffix, runtimeID, testUserID).Scan(&agentID); err != nil {t.Fatalf("create agent fixture: %v", err)}t.Cleanup(func() {@@ -435,6 +785,40 @@ func createRuntimeGCFixtureAgent(t *testing.T, ctx context.Context, runtimeID, sreturn agentID}+func createRuntimeGCFixtureProfile(t *testing.T, ctx context.Context, suffix string) string {+ t.Helper()+ var profileID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO runtime_profile (+ workspace_id, display_name, protocol_family, command_name, created_by+ )+ VALUES ($1, $2, 'codex', $3, $4)+ RETURNING id+ `, testWorkspaceID, "Runtime GC Profile "+suffix, "runtime-gc-"+suffix, testUserID).Scan(&profileID); err != nil {+ t.Fatalf("create runtime profile fixture: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM runtime_profile WHERE id = $1`, profileID)+ })+ return profileID+}++func createRuntimeGCFixtureWorkspace(t *testing.T, ctx context.Context, suffix string) string {+ t.Helper()+ var workspaceID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO workspace (name, slug, description)+ VALUES ($1, $2 || '-' || substr(gen_random_uuid()::text, 1, 8), '')+ RETURNING id+ `, "Runtime GC "+suffix, "runtime-gc-"+suffix).Scan(&workspaceID); err != nil {+ t.Fatalf("create workspace fixture: %v", err)+ }+ t.Cleanup(func() {+ _, _ = testPool.Exec(context.Background(), `DELETE FROM workspace WHERE id = $1`, workspaceID)+ })+ return workspaceID+}+func runtimeGCFixtureAgentID(t *testing.T, ctx context.Context) string {t.Helper()var agentID stringdiff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.goindex 6d526d8328..74f699bd60 100644--- a/server/cmd/server/runtime_sweeper.go+++ b/server/cmd/server/runtime_sweeper.go@@ -56,10 +56,10 @@ const (// 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+ // runtimeGCBacklogScanLimit bounds the observability query as well. The+ // reason-bucket gauges sample at most this many oldest stale runtimes rather+ // than turning a safety signal into an unbounded recurring scan.+ runtimeGCBacklogScanLimit = 1000// runtimeGCTickTimeout bounds each independent hourly GC round so lock// contention cannot occupy its worker indefinitely.runtimeGCTickTimeout = 15 * time.Second@@ -124,6 +124,11 @@ type runtimeGCTxStarter interface {Begin(context.Context) (pgx.Tx, error)}+type runtimeGCEventPublisher interface {+ PublishRuntimeTeardown(context.Context, service.RuntimeTeardownResult, string, string, string, string, bool)+ PublishRuntimeRefresh(string, string, string, string)+}+type runtimeSweepStageStats struct {candidates intchanged int@@ -184,9 +189,9 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handle})}-func runRuntimeGCSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus) {+func runRuntimeGCSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, publisher runtimeGCEventPublisher) {runPeriodicSweep(ctx, runtimeGCSweepInterval, func() {- gcRuntimes(ctx, txStarter, queries, metrics, bus)+ gcRuntimes(ctx, txStarter, queries, metrics, publisher)})}@@ -398,24 +403,24 @@ 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) (stats runtimeSweepStageStats) {+func gcRuntimes(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, publisher runtimeGCEventPublisher) (stats runtimeSweepStageStats) {startedAt := time.Now()defer func() {observeRuntimeSweepStage(metrics, obsmetrics.RuntimeSweepStageGC, startedAt, stats)}()- return gcRuntimesWithBudget(ctx, txStarter, queries, metrics, bus, runtimeGCTickTimeout)+ return gcRuntimesWithBudget(ctx, txStarter, queries, metrics, publisher, runtimeGCTickTimeout)}-func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus, budget time.Duration) (stats runtimeSweepStageStats) {+func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, publisher runtimeGCEventPublisher, budget time.Duration) (stats runtimeSweepStageStats) {gcCtx, cancelGC := context.WithTimeout(ctx, budget)defer cancelGC()- countCtx, cancelCount := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)- blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(countCtx, db.CountStaleOfflineRuntimesBlockedByTasksParams{+ blockedCtx, cancelBlocked := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)+ blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(blockedCtx, db.CountStaleOfflineRuntimesBlockedByTasksParams{StaleSeconds: offlineRuntimeTTLSeconds,- MaxRows: runtimeGCBlockedScanLimit,+ MaxRows: runtimeGCBacklogScanLimit,})- cancelCount()+ cancelBlocked()if err != nil {slog.Warn("runtime GC: failed to count task-blocked runtimes", "error", err)metrics.RecordRuntimeGCBlockedObservationFailed()@@ -423,7 +428,36 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quemetrics.SetRuntimeGCBlocked(blocked)if blocked > 0 {slog.Debug("runtime GC: stale runtimes blocked by non-terminal tasks",- "count", blocked, "count_capped", blocked == runtimeGCBlockedScanLimit)+ "count", blocked, "count_capped", blocked == runtimeGCBacklogScanLimit)+ }+ }++ countCtx, cancelCount := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)+ backlog, err := queries.CountStaleOfflineRuntimeGCBacklogByReason(countCtx, db.CountStaleOfflineRuntimeGCBacklogByReasonParams{+ StaleSeconds: offlineRuntimeTTLSeconds,+ MaxRows: runtimeGCBacklogScanLimit,+ })+ cancelCount()+ if err != nil {+ slog.Warn("runtime GC: failed to classify stale runtime backlog", "error", err)+ metrics.RecordRuntimeGCBlockedObservationFailed()+ } else {+ for _, reason := range []string{+ obsmetrics.RuntimeGCBacklogActiveAgent,+ obsmetrics.RuntimeGCBacklogNonTerminalTask,+ obsmetrics.RuntimeGCBacklogWorkspaceMismatch,+ obsmetrics.RuntimeGCBacklogEligible,+ } {+ metrics.SetRuntimeGCBacklog(reason, 0)+ }+ var sampled int64+ for _, row := range backlog {+ metrics.SetRuntimeGCBacklog(row.Reason, row.Count)+ sampled += row.Count+ }+ if sampled > 0 {+ slog.Debug("runtime GC: classified stale runtime backlog",+ "sampled", sampled, "sample_capped", sampled == runtimeGCBacklogScanLimit)}}@@ -452,7 +486,7 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quebreak}runtimeCtx, cancelRuntime := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)- workspaceID, didDelete, taskBlocked, err := gcRuntime(runtimeCtx, txStarter, queries, runtimeID)+ result, err := gcRuntime(runtimeCtx, txStarter, queries, runtimeID)cancelRuntime()if err != nil {if gcCtx.Err() != nil {@@ -465,18 +499,22 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, quemetrics.RecordRuntimeGCFailed()continue}- if taskBlocked {- slog.Warn("runtime GC: candidate gained a non-terminal task; skipping",- "runtime_id", util.UUIDToString(runtimeID))+ if result.skipReason != "" {+ metrics.RecordRuntimeGCSkipped(result.skipReason)+ slog.Warn("runtime GC: candidate no longer safe to delete; skipping",+ "runtime_id", util.UUIDToString(runtimeID), "reason", result.skipReason)continue}- if !didDelete {+ if !result.deleted {continue}deleted++stats.changed++metrics.RecordRuntimeGCDeleted()- gcWorkspaces[workspaceID] = true+ gcWorkspaces[result.workspaceID] = true+ if publisher != nil {+ publisher.PublishRuntimeTeardown(gcCtx, result.teardown, result.workspaceID, "system", "", "runtime_gc", false)+ }}if deleted == 0 {return@@ -485,27 +523,30 @@ func gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queslog.Info("runtime GC: deleted stale offline runtimes", "count", deleted, "workspaces", len(gcWorkspaces))for wsID := range gcWorkspaces {- bus.Publish(events.Event{- Type: protocol.EventDaemonRegister,- WorkspaceID: wsID,- ActorType: "system",- Payload: map[string]any{- "action": "runtime_gc",- },- })+ if publisher != nil {+ publisher.PublishRuntimeRefresh(wsID, "system", "", "runtime_gc")+ }}return}+type runtimeGCResult struct {+ workspaceID string+ teardown service.RuntimeTeardownResult+ deleted bool+ skipReason string+}+// gcRuntime re-checks and deletes one candidate under a runtime-row FOR UPDATE// lock. Task ownership writes take FOR KEY SHARE on the same row through// lock_task_owner_rows, so a concurrent enqueue either commits before the// checks below and blocks deletion, or waits until deletion commits and then// observes that its runtime no longer exists.-func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, runtimeID pgtype.UUID) (workspaceID string, deleted bool, taskBlocked bool, err error) {+func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, runtimeID pgtype.UUID) (runtimeGCResult, error) {+ var result runtimeGCResulttx, err := txStarter.Begin(ctx)if err != nil {- return "", false, false, fmt.Errorf("begin transaction: %w", err)+ return result, fmt.Errorf("begin transaction: %w", err)}defer func() {// The operation context may already be cancelled on a timeout. Give@@ -519,10 +560,16 @@ func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Quruntime, err := qtx.LockAgentRuntime(ctx, runtimeID)if errors.Is(err, pgx.ErrNoRows) {- return "", false, false, nil+ return result, nil}if err != nil {- return "", false, false, fmt.Errorf("lock runtime: %w", err)+ return result, fmt.Errorf("lock runtime: %w", err)+ }+ result.workspaceID = util.UUIDToString(runtime.WorkspaceID)++ lockedAgents, err := qtx.ListUserAgentsByRuntimeForUpdate(ctx, runtimeID)+ if err != nil {+ return result, fmt.Errorf("lock runtime agents: %w", err)}eligible, err := qtx.IsAgentRuntimeEligibleForGC(ctx, db.IsAgentRuntimeEligibleForGCParams{@@ -530,41 +577,59 @@ func gcRuntime(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.QuStaleSeconds: offlineRuntimeTTLSeconds,})if err != nil {- return "", false, false, fmt.Errorf("re-check eligibility: %w", err)+ return result, fmt.Errorf("re-check eligibility: %w", err)}if !eligible {- return "", false, false, nil+ result.skipReason = obsmetrics.RuntimeGCSkipEligibilityChanged+ return result, nil+ }+ if err := service.ValidateRuntimeAgentWorkspaces(runtime, lockedAgents); err != nil {+ if errors.Is(err, service.ErrRuntimeWorkspaceMismatch) {+ result.skipReason = obsmetrics.RuntimeGCSkipWorkspaceMismatch+ return result, nil+ }+ return result, fmt.Errorf("validate runtime agent workspaces: %w", err)+ }++ lockedAgentIDs := make([]pgtype.UUID, len(lockedAgents))+ for i, agent := range lockedAgents {+ lockedAgentIDs[i] = agent.ID}undrained, err := qtx.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{RuntimeIds: []pgtype.UUID{runtimeID},- AgentIds: []pgtype.UUID{},+ AgentIds: lockedAgentIDs,})if err != nil {- return "", false, false, fmt.Errorf("count non-terminal tasks: %w", err)+ return result, fmt.Errorf("count non-terminal tasks: %w", err)}if undrained > 0 {- return "", false, true, nil+ result.skipReason = obsmetrics.RuntimeGCSkipNonTerminalTask+ return result, nil}- if _, err := qtx.UnbindTasksFromRuntime(ctx, runtimeID); err != nil {- return "", false, false, fmt.Errorf("unbind task history: %w", err)- }- remaining, err := qtx.CountTasksByRuntime(ctx, runtimeID)+ teardown, err := service.TeardownRuntime(ctx, qtx, runtimeID, service.RuntimeTeardownOptions{CancelNonTerminalTasks: false})if err != nil {- return "", false, false, fmt.Errorf("confirm task history detached: %w", err)- }- if remaining != 0 {- return "", false, false, fmt.Errorf("task history still references runtime after detach: %d", remaining)+ if errors.Is(err, service.ErrRuntimeNotDrained) {+ result.skipReason = obsmetrics.RuntimeGCSkipNonTerminalTask+ return result, nil+ }+ if errors.Is(err, service.ErrRuntimeWorkspaceMismatch) {+ result.skipReason = obsmetrics.RuntimeGCSkipWorkspaceMismatch+ return result, nil+ }+ return result, fmt.Errorf("teardown runtime: %w", err)}if err := qtx.DeleteAgentRuntime(ctx, runtimeID); err != nil {- return "", false, false, fmt.Errorf("delete runtime: %w", err)+ return result, fmt.Errorf("delete runtime: %w", err)}if err := tx.Commit(ctx); err != nil {- return "", false, false, fmt.Errorf("commit transaction: %w", err)+ return result, fmt.Errorf("commit transaction: %w", err)}- return util.UUIDToString(runtime.WorkspaceID), true, false, nil+ result.teardown = teardown+ result.deleted = true+ return result, nil}// sweepStaleTasks fails tasks stuck in dispatched/running for too long,diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex 24fe825084..ef415c5711 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -1455,37 +1455,6 @@ func (h *Handler) ConsumeChatDraftRestore(w http.ResponseWriter, r *http.Requestw.WriteHeader(http.StatusNoContent)}-// pruneRuntimeSystemAgentChatDraftRestores drops the pending draft restores of-// every chat_session a runtime teardown is about to remove through the agent-// cascade (chat_session.agent_id is ON DELETE CASCADE, migration 033).-// chat_draft_restore has no FK (MUL-3515) and no reaper, so a restore left-// behind keeps the user's prompt text forever, unreachable and undeletable.-//-// Every runtime/agent teardown path must call this in its own transaction and-// BEFORE deleting the agent rows — the queries join through them. Only system-// agents are in scope: since MUL-5559 a runtime delete unbinds its user agents-// instead of deleting them, so their sessions and restores must survive.-//-// The sessions are locked before the sweep: that is the deleter half of the-// mutual-exclusion protocol with FinalizeDeferredCancelledChat, which would-// otherwise insert a restore this sweep can no longer see (see LockChatSession*-// in chat.sql).-//-// The workspace teardown has its own copy of this shape (locks, then sweeps-// inside the DeleteWorkspace CTE) because that statement's prune must stay in-// the same statement as the workspace row it commits with.-func pruneRuntimeSystemAgentChatDraftRestores(ctx context.Context, q *db.Queries, runtimeID pgtype.UUID) error {- if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return err- }- if err := q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return err- }- // Builder drafts only ever hang off a system carrier, so they are pruned- // here and nowhere else — the archived-agent sweep above has none to find.- return q.DeleteAgentBuilderDraftsBySystemRuntimeAgents(ctx, runtimeID)-}-// PendingChatTasksResponse is the aggregate view consumed by the FAB.type PendingChatTasksResponse struct {Tasks []PendingChatTaskItem `json:"tasks"`diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 5ce6e221e0..fb2a7012ef 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -4,7 +4,6 @@ import ("context""encoding/json""errors"- "fmt""log/slog""net/http""strconv"@@ -14,6 +13,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/internal/util""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -764,130 +764,10 @@ func (h *Handler) ListAgentRuntimes(w http.ResponseWriter, r *http.Request) {// confirm dialog without an extra round-trip. The confirmed variant lives at// POST /api/runtimes/:id/unbind-agents-and-delete (UnbindAgentsAndDeleteRuntime// below) and runs the multi-write teardown inside a single transaction.-// errRuntimeNotDrained means the runtime still owned a non-terminal task after-// the teardown's own cancel pass. That should be impossible — it only happens if-// a new non-terminal task status was added without extending-// CancelAgentTasksByRuntimeOrAgent — so the teardown refuses rather than-// deleting the rows or tripping the agent_task_queue_active_requires_runtime-// CHECK with an opaque 500.-var errRuntimeNotDrained = errors.New("runtime still has non-terminal tasks")--// runtimeTeardownResult reports what the shared teardown changed so the caller-// can broadcast it after the transaction commits.-type runtimeTeardownResult struct {- UnboundAgents []db.Agent- CancelledTasks []db.AgentTaskQueue- PausedAutopilots []db.Autopilot-}--// unbindRuntimeForDelete is the teardown every runtime-delete path runs inside-// its transaction, immediately before deleting the agent_runtime row (MUL-5559).-//-// It replaces the old archive-then-hard-delete of the runtime's agents. An agent-// is a persistent business object — identity, instructions, skills, chats,-// labels, channel installations, autopilot config — while a runtime is-// replaceable execution capacity, so retiring a machine unbinds its agents-// instead of destroying them. Unbound (runtime_id IS NULL) is a normal state,-// orthogonal to archived: service.AgentReadiness already refuses to give work to-// an agent with no runtime, and every trigger entry point reports-// agent_runtime_required.-//-// Order matters:-//-// 1. Unbind the user agents. Archived ones included: an agent archived earlier-// is just as much the user's data. System agents are excluded — they are-// invisible infrastructure with no rebind affordance, so they are deleted in-// step 5 as before.-// 2. Pause active Autopilots assigned directly to those agents or to squads-// they lead. The automation config stays intact and the persisted reason-// explains that rebinding the Agent is the recovery path.-// 3. Cancel the non-terminal tasks of this runtime AND of the agents we just-// unbound. The agent-side match is load-bearing: agent.runtime_id can move-// without rewriting agent_task_queue.runtime_id, so a task an unbound agent-// left pinned to another runtime would otherwise stay claimable while its-// owner is no longer allowed to run.-// 4. Assert the runtime is drained (see errRuntimeNotDrained).-// 5. Detach the task history. Without this, deleting the runtime row would-// cascade agent_task_queue away — and task_message / task_usage /-// task_token with it — so the agents would survive with no record of what-// they ever did.-// 6. Hard-delete the system agents, clearing first the rows whose cleanup has-// no FK to follow (invocation targets, channel installations, chat pins,-// labels, chat draft restores).-func unbindRuntimeForDelete(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUID) (runtimeTeardownResult, error) {- var out runtimeTeardownResult-- unbound, err := qtx.UnbindUserAgentsFromRuntime(ctx, runtimeID)- if err != nil {- return out, fmt.Errorf("unbind agents: %w", err)- }- out.UnboundAgents = unbound-- unboundIDs := make([]pgtype.UUID, len(unbound))- for i, a := range unbound {- unboundIDs[i] = a.ID- }- paused, err := qtx.PauseAutopilotsByUnboundAgents(ctx, unboundIDs)- if err != nil {- return out, fmt.Errorf("pause autopilots: %w", err)- }- out.PausedAutopilots = paused-- cancelled, err := qtx.CancelAgentTasksByRuntimeOrAgent(ctx, db.CancelAgentTasksByRuntimeOrAgentParams{- RuntimeIds: []pgtype.UUID{runtimeID},- AgentIds: unboundIDs,- })- if err != nil {- return out, fmt.Errorf("cancel tasks: %w", err)- }- out.CancelledTasks = cancelled-- undrained, err := qtx.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{- RuntimeIds: []pgtype.UUID{runtimeID},- AgentIds: unboundIDs,- })- if err != nil {- return out, fmt.Errorf("count undrained tasks: %w", err)- }- if undrained > 0 {- return out, fmt.Errorf("%w: %d", errRuntimeNotDrained, undrained)- }- if _, err := qtx.UnbindTasksFromRuntime(ctx, runtimeID); err != nil {- return out, fmt.Errorf("unbind task history: %w", err)- }-- // agent_invocation_target has no agent_id FK (MUL-3963).- if err := qtx.DeleteAgentInvocationTargetsBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return out, fmt.Errorf("clean up agent invocation targets: %w", err)- }- // channel_* has no workspace/agent FK (MUL-3515 §4); an orphaned- // installation would keep occupying its bot's (channel_type, app_id)- // routing slot and make that bot un-rebindable (#4810).- if err := qtx.DeleteChannelInstallationsBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return out, fmt.Errorf("clean up channel installations: %w", err)- }- if err := qtx.DeleteChatPinnedAgentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return out, fmt.Errorf("clean up chat pins: %w", err)- }- // agent_to_label has no agent_id FK.- if err := qtx.DeleteAgentLabelAssignmentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {- return out, fmt.Errorf("clean up agent label assignments: %w", err)- }- // chat_session cascades from agent and chat_draft_restore has no FK to- // follow it (#5219), so prune the restores before the agent rows go.- if err := pruneRuntimeSystemAgentChatDraftRestores(ctx, qtx, runtimeID); err != nil {- return out, fmt.Errorf("clean up chat draft restores: %w", err)- }- if err := qtx.DeleteSystemAgentsByRuntime(ctx, runtimeID); err != nil {- return out, fmt.Errorf("clean up system agents: %w", err)- }- return out, nil-}--// publishRuntimeTeardown fans out a committed teardown. Ordering matches the-// other revocation paths: task:cancelled, then per-agent and Autopilot updates,-// then the runtime-list refresh.-func (h *Handler) publishRuntimeTeardown(ctx context.Context, res runtimeTeardownResult, wsID, userID string) {+// PublishRuntimeTeardown fans out a committed teardown. The caller controls+// actor metadata and whether to append a runtime-list refresh so automatic GC+// can deduplicate that refresh once per workspace and batch.+func (h *Handler) PublishRuntimeTeardown(ctx context.Context, res service.RuntimeTeardownResult, wsID, actorType, actorID, action string, publishRuntimeRefresh bool) {if h.TaskService != nil && len(res.CancelledTasks) > 0 {// The teardown deletes the runtime's system agents, and a system agent's// chat sessions go with it, so the workspace of a cancelled chat task is@@ -898,18 +778,27 @@ func (h *Handler) publishRuntimeTeardown(ctx context.Context, res runtimeTeardow// agent:status is the generic "this agent changed" broadcast the agent// update path already uses; subscribers refresh the row and see// runtime_bound=false. No agent:archived here — nothing was archived.- h.publish(protocol.EventAgentStatus, wsID, "member", userID, map[string]any{+ h.publish(protocol.EventAgentStatus, wsID, actorType, actorID, map[string]any{"agent": broadcastAgentResponse(h.agentToResponse(a)),})}for _, a := range res.PausedAutopilots {- h.publish(protocol.EventAutopilotUpdated, wsID, "member", userID, map[string]any{+ h.publish(protocol.EventAutopilotUpdated, wsID, actorType, actorID, map[string]any{"autopilot": autopilotToResponse(a, nil),})}- h.publish(protocol.EventDaemonRegister, wsID, "member", userID, map[string]any{- "action": "delete",- })+ if publishRuntimeRefresh {+ h.PublishRuntimeRefresh(wsID, actorType, actorID, action)+ }+}++// PublishRuntimeRefresh asks connected clients to refetch runtime state.+func (h *Handler) PublishRuntimeRefresh(wsID, actorType, actorID, action string) {+ h.publish(protocol.EventDaemonRegister, wsID, actorType, actorID, map[string]any{"action": action})+}++func (h *Handler) publishRuntimeTeardown(ctx context.Context, res service.RuntimeTeardownResult, wsID, userID string) {+ h.PublishRuntimeTeardown(ctx, res, wsID, "member", userID, "delete", true)}func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {@@ -1009,9 +898,9 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {// their task history, cancel what was still active, remove only the system// agents. There is no active agent here by definition, but archived ones and// their history can still be bound to this runtime.- teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rt.ID)+ teardown, err := service.TeardownRuntime(r.Context(), qtx, rt.ID, service.RuntimeTeardownOptions{CancelNonTerminalTasks: true})if err != nil {- if errors.Is(err, errRuntimeNotDrained) {+ if errors.Is(err, service.ErrRuntimeNotDrained) {slog.Error("runtime delete aborted: tasks not drained","runtime_id", uuidToString(rt.ID), "error", err)writeJSON(w, http.StatusConflict, map[string]any{@@ -1020,6 +909,15 @@ func (h *Handler) DeleteAgentRuntime(w http.ResponseWriter, r *http.Request) {})return}+ if errors.Is(err, service.ErrRuntimeWorkspaceMismatch) {+ slog.Error("runtime delete aborted: agent workspace mismatch",+ "runtime_id", uuidToString(rt.ID), "error", err)+ writeJSON(w, http.StatusConflict, map[string]any{+ "error": "the runtime has an invalid cross-workspace agent binding.",+ "code": "runtime_delete_workspace_mismatch",+ })+ return+ }slog.Error("runtime delete teardown failed", "runtime_id", uuidToString(rt.ID), "error", err)writeError(w, http.StatusInternalServerError, "failed to delete runtime")return@@ -1220,9 +1118,9 @@ func (h *Handler) UnbindAgentsAndDeleteRuntime(w http.ResponseWriter, r *http.Re// agent (active and archived) plus their task history, cancel what was// running or queued, and hard-delete only the system agents. Nothing the// user configured is destroyed — the agents just need a new runtime.- teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rt.ID)+ teardown, err := service.TeardownRuntime(r.Context(), qtx, rt.ID, service.RuntimeTeardownOptions{CancelNonTerminalTasks: true})if err != nil {- if errors.Is(err, errRuntimeNotDrained) {+ if errors.Is(err, service.ErrRuntimeNotDrained) {slog.Error("runtime delete aborted: tasks not drained","runtime_id", uuidToString(rt.ID), "error", err)writeJSON(w, http.StatusConflict, map[string]any{diff --git a/server/internal/handler/runtime_profile.go b/server/internal/handler/runtime_profile.goindex 611ceee720..a2226fdf75 100644--- a/server/internal/handler/runtime_profile.go+++ b/server/internal/handler/runtime_profile.go@@ -10,6 +10,7 @@ import ("github.com/go-chi/chi/v5""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service""github.com/multica-ai/multica/server/pkg/agent"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -363,7 +364,7 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {// path uses for each one: agent.runtime_id is ON DELETE RESTRICT, so an// agent still pointing at one of these rows would turn a bare delete into a// 500. Active agents are refused (409); everything else is unbound rather- // than destroyed, exactly as in unbindRuntimeForDelete.+ // than destroyed, exactly as in service.TeardownRuntime.// Guard: refuse while any active (non-archived) agent is bound to one of// the profile's runtimes. Keep this a 409 — the profile is the thing that// defines those runtimes, so the user should retire the agents or move them@@ -429,11 +430,11 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {// remaining (archived) agents and their task history, cancel anything still// in flight, and hard-delete only the system agents, so removing the runtime// rows below cannot destroy an agent, a conversation or a task record.- var teardowns []runtimeTeardownResult+ var teardowns []service.RuntimeTeardownResultfor _, rid := range runtimeIDs {- teardown, err := unbindRuntimeForDelete(r.Context(), qtx, rid)+ teardown, err := service.TeardownRuntime(r.Context(), qtx, rid, service.RuntimeTeardownOptions{CancelNonTerminalTasks: true})if err != nil {- if errors.Is(err, errRuntimeNotDrained) {+ if errors.Is(err, service.ErrRuntimeNotDrained) {slog.Error("runtime profile delete aborted: tasks not drained","runtime_id", uuidToString(rid), "profile_id", uuidToString(profileUUID), "error", err)writeJSON(w, http.StatusConflict, map[string]any{@@ -442,6 +443,15 @@ func (h *Handler) DeleteRuntimeProfile(w http.ResponseWriter, r *http.Request) {})return}+ if errors.Is(err, service.ErrRuntimeWorkspaceMismatch) {+ slog.Error("runtime profile delete aborted: agent workspace mismatch",+ "runtime_id", uuidToString(rid), "profile_id", uuidToString(profileUUID), "error", err)+ writeJSON(w, http.StatusConflict, map[string]any{+ "error": "a runtime of this profile has an invalid cross-workspace agent binding.",+ "code": "runtime_delete_workspace_mismatch",+ })+ return+ }slog.Error("runtime profile delete teardown failed","runtime_id", uuidToString(rid), "profile_id", uuidToString(profileUUID), "error", err)writeError(w, http.StatusInternalServerError, "failed to unbind agents")diff --git a/server/internal/handler/runtime_profile_handler_test.go b/server/internal/handler/runtime_profile_handler_test.goindex aa680795ab..5f9bb973e4 100644--- a/server/internal/handler/runtime_profile_handler_test.go+++ b/server/internal/handler/runtime_profile_handler_test.go@@ -191,6 +191,49 @@ func TestDeleteRuntimeProfile_ActiveAgentBlocks(t *testing.T) {}}+func TestDeleteRuntimeProfile_WorkspaceMismatchReturnsStructuredConflict(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ profileID := insertRuntimeProfileFixture(t, ctx, "Workspace Mismatch Profile", "codex", "workspace-mismatch-codex")+ runtimeID := insertProfileRuntimeFixture(t, ctx, profileID, "Workspace Mismatch Runtime", "codex")+ agentID := createArchivedWorkspaceMismatchedAgent(t, runtimeID, "Profile Workspace Mismatch Agent")++ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil)+ req = withURLParams(req, "id", testWorkspaceID, "profileId", profileID)+ testHandler.DeleteRuntimeProfile(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ }+ var body struct {+ Code string `json:"code"`+ }+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if body.Code != "runtime_delete_workspace_mismatch" {+ t.Fatalf("code = %q, want runtime_delete_workspace_mismatch", body.Code)+ }++ var profileRows, runtimeRows int+ var boundRuntime string+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM runtime_profile WHERE id = $1`, profileID).Scan(&profileRows); err != nil {+ t.Fatalf("count profile rows: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeRows); err != nil {+ t.Fatalf("count runtime rows: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&boundRuntime); err != nil {+ t.Fatalf("read mismatched agent binding: %v", err)+ }+ if profileRows != 1 || runtimeRows != 1 || boundRuntime != runtimeID {+ t.Fatalf("workspace mismatch mutated data: profile rows=%d runtime rows=%d agent runtime=%q", profileRows, runtimeRows, boundRuntime)+ }+}+func TestDeleteRuntimeProfile_MissingProfileWithOrphanRuntimesCleansUp(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/runtime_unbind_delete_test.go b/server/internal/handler/runtime_unbind_delete_test.goindex a8e5e43c47..97759b39ef 100644--- a/server/internal/handler/runtime_unbind_delete_test.go+++ b/server/internal/handler/runtime_unbind_delete_test.go@@ -8,6 +8,7 @@ import ("testing""github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil"db "github.com/multica-ai/multica/server/pkg/db/generated")@@ -168,6 +169,45 @@ func TestDeleteAgentRuntime_StructuredConflict(t *testing.T) {}}+func TestDeleteAgentRuntime_WorkspaceMismatchReturnsStructuredConflict(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createCascadeFixtureRuntime(t, ctx, "Runtime Workspace Mismatch")+ agentID := createArchivedWorkspaceMismatchedAgent(t, runtimeID, "Runtime Workspace Mismatch Agent")++ w := httptest.NewRecorder()+ req := newRequest("DELETE", "/api/runtimes/"+runtimeID, nil)+ req = withURLParam(req, "runtimeId", runtimeID)+ testHandler.DeleteAgentRuntime(w, req)++ if w.Code != http.StatusConflict {+ t.Fatalf("expected 409, got %d: %s", w.Code, w.Body.String())+ }+ var body struct {+ Code string `json:"code"`+ }+ if err := json.NewDecoder(w.Body).Decode(&body); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if body.Code != "runtime_delete_workspace_mismatch" {+ t.Fatalf("code = %q, want runtime_delete_workspace_mismatch", body.Code)+ }++ var runtimeRows int+ var boundRuntime string+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeRows); err != nil {+ t.Fatalf("count runtime rows: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT runtime_id::text FROM agent WHERE id = $1`, agentID).Scan(&boundRuntime); err != nil {+ t.Fatalf("read mismatched agent binding: %v", err)+ }+ if runtimeRows != 1 || boundRuntime != runtimeID {+ t.Fatalf("workspace mismatch mutated data: runtime rows=%d agent runtime=%q", runtimeRows, boundRuntime)+ }+}+func TestRuntimeDeleteLockBlocksConcurrentAgentBinding(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -576,3 +616,13 @@ func createCascadeFixtureAgent(t *testing.T, ctx context.Context, runtimeID, nam})return agentID}++func createArchivedWorkspaceMismatchedAgent(t *testing.T, runtimeID, name string) string {+ t.Helper()+ foreignWorkspaceID := dbfx.Workspace(t, name+" Workspace", "runtime-mismatch-"+runtimeID[:8])+ return dbfx.Agent(t, name, runtimeID, testutil.Cols{+ "workspace_id": foreignWorkspaceID,+ "archived_at": testutil.Raw("now()"),+ "owner_id": nil,+ })+}diff --git a/server/internal/handler/runtime_unbind_preserves_data_test.go b/server/internal/handler/runtime_unbind_preserves_data_test.goindex 8d0ba22626..c52008ebbf 100644--- a/server/internal/handler/runtime_unbind_preserves_data_test.go+++ b/server/internal/handler/runtime_unbind_preserves_data_test.go@@ -9,6 +9,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/service"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol")@@ -19,6 +20,43 @@ import (// "archive". Each test below pins one thing that must now survive, plus the two// invariants that keep the new flow safe.+func TestPublishRuntimeTeardown_UsesAutomaticGCActorAndRefreshAction(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createCascadeFixtureRuntime(t, ctx, "GC Event Runtime")+ agentID := createCascadeFixtureAgent(t, ctx, runtimeID, "GC Event Agent")+ agent, err := testHandler.Queries.GetAgent(ctx, parseUUID(agentID))+ if err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ bus := events.New()+ var published []events.Event+ bus.SubscribeAll(func(event events.Event) { published = append(published, event) })+ publisher := *testHandler+ publisher.Bus = bus+ publisher.TaskService = nil++ publisher.PublishRuntimeTeardown(ctx, service.RuntimeTeardownResult{UnboundAgents: []db.Agent{agent}}, testWorkspaceID, "system", "", "runtime_gc", false)+ publisher.PublishRuntimeRefresh(testWorkspaceID, "system", "", "runtime_gc")++ if len(published) != 2 {+ t.Fatalf("published events=%d, want agent update and one runtime refresh", len(published))+ }+ if published[0].Type != protocol.EventAgentStatus || published[0].ActorType != "system" || published[0].ActorID != "" {+ t.Fatalf("unexpected agent event: %+v", published[0])+ }+ if published[1].Type != protocol.EventDaemonRegister || published[1].ActorType != "system" || published[1].ActorID != "" {+ t.Fatalf("unexpected runtime event: %+v", published[1])+ }+ payload, ok := published[1].Payload.(map[string]any)+ if !ok || payload["action"] != "runtime_gc" {+ t.Fatalf("runtime refresh payload=%v, want runtime_gc action", published[1].Payload)+ }+}+// TestUnbindAgentsAndDeleteRuntime_KeepsChatHistory: the agent's chat sessions// and messages cascade from the agent row, so hard-deleting it destroyed every// conversation with it. Unbinding must leave them readable.diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 8388011995..5740b06bd1 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -23,6 +23,15 @@ const (RuntimeSweepStageDelegatedFailureRecovery = "delegated_failure_recovery"RuntimeSweepStageDeferredChatFinalization = "deferred_chat_finalize"RuntimeSweepStageGC = "runtime_gc"++ RuntimeGCSkipEligibilityChanged = "eligibility_changed"+ RuntimeGCSkipNonTerminalTask = "non_terminal_task"+ RuntimeGCSkipWorkspaceMismatch = "workspace_mismatch"++ RuntimeGCBacklogActiveAgent = "active_agent"+ RuntimeGCBacklogNonTerminalTask = "non_terminal_task"+ RuntimeGCBacklogWorkspaceMismatch = "workspace_mismatch"+ RuntimeGCBacklogEligible = "eligible")type activeTaskLabels struct {@@ -57,7 +66,9 @@ type BusinessMetrics struct {runtimeSweepRowsChanged *prometheus.CounterVecruntimeGCDeleted prometheus.CounterruntimeGCFailed prometheus.Counter+ runtimeGCSkipped *prometheus.CounterVecruntimeGCBlocked prometheus.Gauge+ runtimeGCBacklog *prometheus.GaugeVecruntimeGCBlockedObservationFailed prometheus.CounterentitlementConfigError prometheus.CounterentitlementCache *prometheus.CounterVec@@ -228,12 +239,24 @@ func NewBusinessMetrics() *BusinessMetrics {Name: "failed_total",Help: "Total runtime garbage-collection operations that failed.",}),+ runtimeGCSkipped: prometheus.NewCounterVec(prometheus.CounterOpts{+ Namespace: "multica",+ Subsystem: "runtime_gc",+ Name: "skipped_total",+ Help: "Total runtime garbage-collection candidates safely skipped by reason.",+ }, metricLabels("multica_runtime_gc_skipped_total")),runtimeGCBlocked: prometheus.NewGauge(prometheus.GaugeOpts{Namespace: "multica",Subsystem: "runtime_gc",Name: "blocked_runtimes",Help: "Bounded count of stale offline runtimes blocked from garbage collection by non-terminal tasks.",}),+ runtimeGCBacklog: prometheus.NewGaugeVec(prometheus.GaugeOpts{+ Namespace: "multica",+ Subsystem: "runtime_gc",+ Name: "backlog_runtimes",+ Help: "Bounded oldest-first sample of stale offline runtimes classified by garbage-collection state.",+ }, metricLabels("multica_runtime_gc_backlog_runtimes")),runtimeGCBlockedObservationFailed: prometheus.NewCounter(prometheus.CounterOpts{Namespace: "multica",Subsystem: "runtime_gc",@@ -272,6 +295,12 @@ func NewBusinessMetrics() *BusinessMetrics {events: newBusinessEventMetrics(),}m.prewarmFailureReasons()+ for _, reason := range []string{RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch} {+ m.runtimeGCSkipped.WithLabelValues(reason).Add(0)+ }+ for _, reason := range []string{RuntimeGCBacklogActiveAgent, RuntimeGCBacklogNonTerminalTask, RuntimeGCBacklogWorkspaceMismatch, RuntimeGCBacklogEligible} {+ m.runtimeGCBacklog.WithLabelValues(reason).Set(0)+ }return m}@@ -301,7 +330,9 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.runtimeSweepRowsChanged,m.runtimeGCDeleted,m.runtimeGCFailed,+ m.runtimeGCSkipped,m.runtimeGCBlocked,+ m.runtimeGCBacklog,m.runtimeGCBlockedObservationFailed,m.entitlementConfigError,m.entitlementCache,@@ -371,6 +402,20 @@ func (m *BusinessMetrics) RecordRuntimeGCFailed() {m.runtimeGCFailed.Inc()}+func (m *BusinessMetrics) RecordRuntimeGCSkipped(reason string) {+ if m == nil {+ return+ }+ m.runtimeGCSkipped.WithLabelValues(normalizeRuntimeGCSkipReason(reason)).Inc()+}++func (m *BusinessMetrics) SetRuntimeGCBacklog(reason string, count int64) {+ if m == nil {+ return+ }+ m.runtimeGCBacklog.WithLabelValues(normalizeRuntimeGCBacklogReason(reason)).Set(float64(count))+}+func (m *BusinessMetrics) SetRuntimeGCBlocked(count int64) {if m == nil {return@@ -385,6 +430,24 @@ func (m *BusinessMetrics) RecordRuntimeGCBlockedObservationFailed() {m.runtimeGCBlockedObservationFailed.Inc()}+func normalizeRuntimeGCSkipReason(reason string) string {+ switch reason {+ case RuntimeGCSkipEligibilityChanged, RuntimeGCSkipNonTerminalTask, RuntimeGCSkipWorkspaceMismatch:+ return reason+ default:+ return "unknown"+ }+}++func normalizeRuntimeGCBacklogReason(reason string) string {+ switch reason {+ case RuntimeGCBacklogActiveAgent, RuntimeGCBacklogNonTerminalTask, RuntimeGCBacklogWorkspaceMismatch, RuntimeGCBacklogEligible:+ return reason+ default:+ return "unknown"+ }+}+// ObserveRuntimeSweepStage records one bounded-cardinality maintenance stage.// candidates is the number of rows returned to or examined by the application,// not PostgreSQL executor rows; changed is the subset whose persisteddiff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 8423953c17..4a096e5a3e 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -207,7 +207,12 @@ func TestBusinessMetricsRuntimeGC(t *testing.T) {m := NewBusinessMetrics()m.RecordRuntimeGCDeleted()m.RecordRuntimeGCFailed()+ m.RecordRuntimeGCSkipped(RuntimeGCSkipNonTerminalTask)m.SetRuntimeGCBlocked(3)+ m.SetRuntimeGCBacklog(RuntimeGCBacklogActiveAgent, 2)+ m.SetRuntimeGCBacklog(RuntimeGCBacklogNonTerminalTask, 3)+ m.SetRuntimeGCBacklog(RuntimeGCBacklogWorkspaceMismatch, 1)+ m.SetRuntimeGCBacklog(RuntimeGCBacklogEligible, 4)m.RecordRuntimeGCBlockedObservationFailed()if got := testutil.ToFloat64(m.runtimeGCDeleted); got != 1 {@@ -216,9 +221,22 @@ func TestBusinessMetricsRuntimeGC(t *testing.T) {if got := testutil.ToFloat64(m.runtimeGCFailed); got != 1 {t.Fatalf("runtime GC failed = %v, want 1", got)}+ if got := testutil.ToFloat64(m.runtimeGCSkipped.WithLabelValues(RuntimeGCSkipNonTerminalTask)); got != 1 {+ t.Fatalf("runtime GC skipped = %v, want 1", got)+ }if got := testutil.ToFloat64(m.runtimeGCBlocked); got != 3 {t.Fatalf("runtime GC blocked = %v, want 3", got)}+ for reason, want := range map[string]float64{+ RuntimeGCBacklogActiveAgent: 2,+ RuntimeGCBacklogNonTerminalTask: 3,+ RuntimeGCBacklogWorkspaceMismatch: 1,+ RuntimeGCBacklogEligible: 4,+ } {+ if got := testutil.ToFloat64(m.runtimeGCBacklog.WithLabelValues(reason)); got != want {+ t.Fatalf("runtime GC backlog %s = %v, want %v", reason, got, want)+ }+ }if got := testutil.ToFloat64(m.runtimeGCBlockedObservationFailed); got != 1 {t.Fatalf("runtime GC blocked observation failures = %v, want 1", got)}diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 5a75798a7c..31a08d1e6d 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -82,6 +82,8 @@ var businessMetricLabels = map[string][]string{"multica_runtime_ready_seconds": {labelRuntimeMode, labelProvider},"multica_runtime_failed_total": {labelRuntimeMode, labelProvider, labelFailureReason, labelRecoverable},"multica_runtime_offline_total": {labelRuntimeMode, labelProvider},+ "multica_runtime_gc_skipped_total": {labelReason},+ "multica_runtime_gc_backlog_runtimes": {labelReason},"multica_daemon_ws_message_received_total": {labelKind},"multica_autopilot_run_started_total": {labelCadence, labelTriggerKind},"multica_autopilot_run_terminal_total": {labelCadence, labelTriggerKind, labelTerminalStatus},diff --git a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.mdindex aef3ae11a7..9f79283345 100644--- a/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md+++ b/server/internal/service/builtin_skills/multica-runtimes-and-repos/references/runtimes-and-repos-source-map.md@@ -3,7 +3,7 @@- `server/cmd/multica/cmd_runtime.go` registers `runtime list`, `usage`, `activity`, `update`, and `delete`.- `runtime list` reads `/api/runtimes` and prints `id`, `name`, `runtime_mode`, `provider`, `status`, and `last_seen_at`.- `runtime update` posts to `/api/runtimes/{runtime-id}/update`; with `--wait` it polls update status. Initiation enforces runtime-owner or workspace-owner/admin access through `canEditRuntime`; status polling additionally permits that request's immutable initiator so an in-flight poll survives an admin-role change (`server/internal/handler/runtime_update.go` and `runtime.go`).-- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/unbind-agents-and-delete` (the older `/archive-agents-and-delete` path still routes to the same handler for installed clients). Both delete paths run `unbindRuntimeForDelete` in `server/internal/handler/runtime.go`: user agents are unbound (`runtime_id = NULL`, MUL-5559), their task history is detached so deleting the runtime cannot cascade it away, active tasks are cancelled, and only `kind='system'` agents are hard-deleted.+- `runtime delete` deletes `/api/runtimes/{runtime-id}`; with `--cascade`, it first reads the `runtime_has_active_agents` conflict payload and posts those ids to `/api/runtimes/{runtime-id}/unbind-agents-and-delete` (the older `/archive-agents-and-delete` path still routes to the same handler for installed clients). Both delete paths run `service.TeardownRuntime` in `server/internal/service/runtime_teardown.go`: user agents are unbound (`runtime_id = NULL`, MUL-5559), their task history is detached so deleting the runtime cannot cascade it away, active tasks are cancelled for user-confirmed deletion, and only `kind='system'` agents are hard-deleted.- `server/cmd/multica/cmd_repo.go` registers `repo checkout <url> [--ref]`.- `repo checkout` requires `MULTICA_DAEMON_PORT` plus the injected task-scoped `MULTICA_TOKEN`. It sends the token as a localhost bearer credential along with `workspace_id`, `workdir`, `ref`, `agent_name`, `task_id`, and the daemon-managed optional `checkout_mode`, then prints the checked-out path.- `server/internal/daemon/daemon.go` registers each provider execution in an in-memory checkout registry keyed by its task token and removes it when execution ends. `server/internal/daemon/health.go` authenticates `/repo/checkout` against that registry, requires the requested workspace/task and canonical workdir to belong to the active task, and derives the branch's agent name from the registry instead of trusting the request. It then resolves the checkout ref: request `ref` wins; otherwise it asks `daemon.go` for the current task's project repo default ref, and forwards the validated isolated-checkout mode into `repocache.WorktreeParams`.diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.gonew file mode 100644index 0000000000..834c252568--- /dev/null+++ b/server/internal/service/runtime_teardown.go@@ -0,0 +1,161 @@+package service++import (+ "context"+ "errors"+ "fmt"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++var (+ // ErrRuntimeNotDrained means a runtime or one of its bound user agents+ // still owns a non-terminal task. Callers must abort the transaction rather+ // than deleting the runtime and relying on database cascades.+ ErrRuntimeNotDrained = errors.New("runtime still has non-terminal tasks")+ // ErrRuntimeWorkspaceMismatch protects tenant isolation if legacy or+ // corrupted data binds an agent to a runtime from another workspace.+ ErrRuntimeWorkspaceMismatch = errors.New("runtime agent workspace mismatch")+)++// RuntimeTeardownOptions controls the only intentional semantic difference+// between user-confirmed deletion and retention GC. Manual deletion cancels+// active work; automatic GC must fail closed and leave it untouched.+type RuntimeTeardownOptions struct {+ CancelNonTerminalTasks bool+}++// RuntimeTeardownResult reports committed business-object changes so callers+// can publish events after their transaction commits.+type RuntimeTeardownResult struct {+ UnboundAgents []db.Agent+ CancelledTasks []db.AgentTaskQueue+ PausedAutopilots []db.Autopilot+}++// ValidateRuntimeAgentWorkspaces refuses to mutate cross-workspace bindings.+// agent.runtime_id is not backed by a composite workspace foreign key, so this+// application-layer guard is required before a runtime teardown changes data.+func ValidateRuntimeAgentWorkspaces(runtime db.AgentRuntime, agents []db.Agent) error {+ for _, agent := range agents {+ if agent.WorkspaceID != runtime.WorkspaceID {+ return fmt.Errorf("%w: agent %x runtime %x", ErrRuntimeWorkspaceMismatch, agent.ID.Bytes, runtime.ID.Bytes)+ }+ }+ return nil+}++// TeardownRuntime performs the shared mutation phase used immediately before+// deleting an agent_runtime row. It takes the runtime and bound-user-agent row+// locks itself; callers that already locked them for a confirmation check can+// safely acquire the same locks again in their transaction.+//+// User agents are persistent business objects and survive unbound. System+// agents are runtime-local infrastructure and are deleted only after their+// non-FK dependencies are pruned; their runtime-local builder drafts and chat+// draft restores are deleted with them. Task history is detached before runtime+// deletion so the legacy ON DELETE CASCADE cannot erase it.+func TeardownRuntime(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUID, opts RuntimeTeardownOptions) (RuntimeTeardownResult, error) {+ var out RuntimeTeardownResult++ runtime, err := qtx.LockAgentRuntime(ctx, runtimeID)+ if err != nil {+ return out, fmt.Errorf("load runtime: %w", err)+ }+ lockedAgents, err := qtx.ListUserAgentsByRuntimeForUpdate(ctx, runtimeID)+ if err != nil {+ return out, fmt.Errorf("lock runtime agents: %w", err)+ }+ if err := ValidateRuntimeAgentWorkspaces(runtime, lockedAgents); err != nil {+ return out, err+ }++ lockedAgentIDs := make([]pgtype.UUID, len(lockedAgents))+ for i, agent := range lockedAgents {+ lockedAgentIDs[i] = agent.ID+ }++ if opts.CancelNonTerminalTasks {+ cancelled, err := qtx.CancelAgentTasksByRuntimeOrAgent(ctx, db.CancelAgentTasksByRuntimeOrAgentParams{+ RuntimeIds: []pgtype.UUID{runtimeID},+ AgentIds: lockedAgentIDs,+ })+ if err != nil {+ return out, fmt.Errorf("cancel tasks: %w", err)+ }+ out.CancelledTasks = cancelled+ }++ undrained, err := qtx.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{+ RuntimeIds: []pgtype.UUID{runtimeID},+ AgentIds: lockedAgentIDs,+ })+ if err != nil {+ return out, fmt.Errorf("count undrained tasks: %w", err)+ }+ if undrained > 0 {+ return out, fmt.Errorf("%w: %d", ErrRuntimeNotDrained, undrained)+ }++ unbound, err := qtx.UnbindUserAgentsFromRuntime(ctx, runtimeID)+ if err != nil {+ return out, fmt.Errorf("unbind agents: %w", err)+ }+ out.UnboundAgents = unbound++ unboundIDs := make([]pgtype.UUID, len(unbound))+ for i, agent := range unbound {+ unboundIDs[i] = agent.ID+ }+ paused, err := qtx.PauseAutopilotsByUnboundAgents(ctx, unboundIDs)+ if err != nil {+ return out, fmt.Errorf("pause autopilots: %w", err)+ }+ out.PausedAutopilots = paused++ if _, err := qtx.UnbindTasksFromRuntime(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("unbind task history: %w", err)+ }+ remaining, err := qtx.CountTasksByRuntime(ctx, runtimeID)+ if err != nil {+ return out, fmt.Errorf("confirm task history detached: %w", err)+ }+ if remaining != 0 {+ return out, fmt.Errorf("task history still references runtime after detach: %d", remaining)+ }++ // These tables intentionally lack agent foreign keys, so they must be+ // pruned before the system-agent rows disappear.+ if err := qtx.DeleteAgentInvocationTargetsBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up agent invocation targets: %w", err)+ }+ if err := qtx.DeleteChannelInstallationsBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up channel installations: %w", err)+ }+ if err := qtx.DeleteChatPinnedAgentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up chat pins: %w", err)+ }+ if err := qtx.DeleteAgentLabelAssignmentsBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up agent label assignments: %w", err)+ }+ if err := pruneRuntimeSystemAgentChatDraftRestores(ctx, qtx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up chat draft restores: %w", err)+ }+ if err := qtx.DeleteSystemAgentsByRuntime(ctx, runtimeID); err != nil {+ return out, fmt.Errorf("clean up system agents: %w", err)+ }+ return out, nil+}++// pruneRuntimeSystemAgentChatDraftRestores removes rows without a database FK+// before the system agents and their chat sessions cascade away.+func pruneRuntimeSystemAgentChatDraftRestores(ctx context.Context, q *db.Queries, runtimeID pgtype.UUID) error {+ if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return err+ }+ if err := q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID); err != nil {+ return err+ }+ return q.DeleteAgentBuilderDraftsBySystemRuntimeAgents(ctx, runtimeID)+}diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 218f470fa9..c7990c50c3 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -132,6 +132,88 @@ func (q *Queries) CountActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyreturn count, err}+const countStaleOfflineRuntimeGCBacklogByReason = `-- name: CountStaleOfflineRuntimeGCBacklogByReason :many+WITH stale_runtimes AS MATERIALIZED (+ SELECT id, workspace_id FROM agent_runtime+ WHERE status = 'offline'+ AND last_seen_at < now() - make_interval(secs => $1::double precision)+ ORDER BY last_seen_at ASC, id ASC+ LIMIT $2::int+), classified AS (+ SELECT CASE+ WHEN EXISTS (+ SELECT 1 FROM agent+ WHERE agent.runtime_id = stale_runtimes.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL+ ) THEN 'active_agent'::text+ WHEN EXISTS (+ SELECT 1 FROM agent+ WHERE agent.runtime_id = stale_runtimes.id+ AND agent.kind = 'user'+ AND agent.workspace_id <> stale_runtimes.workspace_id+ ) THEN 'workspace_mismatch'::text+ WHEN EXISTS (+ SELECT 1 FROM agent_task_queue AS task+ WHERE task.runtime_id = stale_runtimes.id+ AND task.completed_at IS NULL+ ) OR EXISTS (+ SELECT 1+ FROM agent AS owner+ WHERE owner.runtime_id = stale_runtimes.id+ AND owner.kind = 'user'+ AND EXISTS (+ SELECT 1+ FROM agent_task_queue AS task+ WHERE task.agent_id = owner.id+ AND task.completed_at IS NULL+ )+ ) THEN 'non_terminal_task'::text+ ELSE 'eligible'::text+ END AS reason+ FROM stale_runtimes+)+SELECT reason, count(*)::bigint AS count+FROM classified+GROUP BY reason+ORDER BY reason+`++type CountStaleOfflineRuntimeGCBacklogByReasonParams struct {+ StaleSeconds float64 `json:"stale_seconds"`+ MaxRows int32 `json:"max_rows"`+}++type CountStaleOfflineRuntimeGCBacklogByReasonRow struct {+ Reason string `json:"reason"`+ Count int64 `json:"count"`+}++// Classifies one bounded oldest-first cohort into mutually exclusive states.+// active_agent has priority because it already makes the runtime ineligible;+// archived cross-workspace bindings get their own diagnostic bucket. The task+// branch mirrors teardown's fail-closed predicate, including tasks owned by a+// bound user agent but pinned to another runtime after a historical move.+func (q *Queries) CountStaleOfflineRuntimeGCBacklogByReason(ctx context.Context, arg CountStaleOfflineRuntimeGCBacklogByReasonParams) ([]CountStaleOfflineRuntimeGCBacklogByReasonRow, error) {+ rows, err := q.db.Query(ctx, countStaleOfflineRuntimeGCBacklogByReason, arg.StaleSeconds, arg.MaxRows)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []CountStaleOfflineRuntimeGCBacklogByReasonRow{}+ for rows.Next() {+ var i CountStaleOfflineRuntimeGCBacklogByReasonRow+ if err := rows.Scan(&i.Reason, &i.Count); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const countStaleOfflineRuntimesBlockedByTasks = `-- name: CountStaleOfflineRuntimesBlockedByTasks :oneSELECT count(*) FROM (SELECT 1 FROM agent_runtime@@ -157,11 +239,10 @@ type CountStaleOfflineRuntimesBlockedByTasksParams struct {MaxRows int32 `json:"max_rows"`}-// Bounded observability sample of runtimes that are otherwise GC-eligible but-// retain a non-terminal task. In particular, deferred tasks have no generic-// TTL, so silently filtering them from the candidate batch would hide a-// permanently-starved runtime. The count saturates at max_rows so this-// recurring safety signal cannot become an unbounded backlog scan.+// Preserve the original blocked-runtimes signal for dashboard and alert+// compatibility. This deliberately counts only otherwise-unowned stale+// runtimes with a directly pinned non-terminal task; the broader reason+// inventory below is exposed under a separate backlog metric.func (q *Queries) CountStaleOfflineRuntimesBlockedByTasks(ctx context.Context, arg CountStaleOfflineRuntimesBlockedByTasksParams) (int64, error) {row := q.db.QueryRow(ctx, countStaleOfflineRuntimesBlockedByTasks, arg.StaleSeconds, arg.MaxRows)var count int64@@ -576,6 +657,8 @@ SELECT EXISTS (SELECT 1FROM agentWHERE agent.runtime_id = agent_runtime.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL)) AS eligible`@@ -737,6 +820,8 @@ WHERE status = 'offline'SELECT 1FROM agentWHERE agent.runtime_id = agent_runtime.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL)AND NOT EXISTS (SELECT 1diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 11dca94657..e23d4a9ffb 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -495,6 +495,8 @@ WHERE status = 'offline'SELECT 1FROM agentWHERE agent.runtime_id = agent_runtime.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL)AND NOT EXISTS (SELECT 1@@ -519,6 +521,8 @@ SELECT EXISTS (SELECT 1FROM agentWHERE agent.runtime_id = agent_runtime.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL)) AS eligible;@@ -528,11 +532,10 @@ SELECT EXISTS (SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1;-- name: CountStaleOfflineRuntimesBlockedByTasks :one--- Bounded observability sample of runtimes that are otherwise GC-eligible but--- retain a non-terminal task. In particular, deferred tasks have no generic--- TTL, so silently filtering them from the candidate batch would hide a--- permanently-starved runtime. The count saturates at max_rows so this--- recurring safety signal cannot become an unbounded backlog scan.+-- Preserve the original blocked-runtimes signal for dashboard and alert+-- compatibility. This deliberately counts only otherwise-unowned stale+-- runtimes with a directly pinned non-terminal task; the broader reason+-- inventory below is exposed under a separate backlog metric.SELECT count(*) FROM (SELECT 1 FROM agent_runtimeWHERE status = 'offline'@@ -550,3 +553,54 @@ SELECT count(*) FROM ()LIMIT @max_rows::int) AS blocked_runtimes;++-- name: CountStaleOfflineRuntimeGCBacklogByReason :many+-- Classifies one bounded oldest-first cohort into mutually exclusive states.+-- active_agent has priority because it already makes the runtime ineligible;+-- archived cross-workspace bindings get their own diagnostic bucket. The task+-- branch mirrors teardown's fail-closed predicate, including tasks owned by a+-- bound user agent but pinned to another runtime after a historical move.+WITH stale_runtimes AS MATERIALIZED (+ SELECT id, workspace_id FROM agent_runtime+ WHERE status = 'offline'+ AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)+ ORDER BY last_seen_at ASC, id ASC+ LIMIT @max_rows::int+), classified AS (+ SELECT CASE+ WHEN EXISTS (+ SELECT 1 FROM agent+ WHERE agent.runtime_id = stale_runtimes.id+ AND agent.kind = 'user'+ AND agent.archived_at IS NULL+ ) THEN 'active_agent'::text+ WHEN EXISTS (+ SELECT 1 FROM agent+ WHERE agent.runtime_id = stale_runtimes.id+ AND agent.kind = 'user'+ AND agent.workspace_id <> stale_runtimes.workspace_id+ ) THEN 'workspace_mismatch'::text+ WHEN EXISTS (+ SELECT 1 FROM agent_task_queue AS task+ WHERE task.runtime_id = stale_runtimes.id+ AND task.completed_at IS NULL+ ) OR EXISTS (+ SELECT 1+ FROM agent AS owner+ WHERE owner.runtime_id = stale_runtimes.id+ AND owner.kind = 'user'+ AND EXISTS (+ SELECT 1+ FROM agent_task_queue AS task+ WHERE task.agent_id = owner.id+ AND task.completed_at IS NULL+ )+ ) THEN 'non_terminal_task'::text+ ELSE 'eligible'::text+ END AS reason+ FROM stale_runtimes+)+SELECT reason, count(*)::bigint AS count+FROM classified+GROUP BY reason+ORDER BY reason;