Skip to content

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

Go

MUL-6107: preserve task history during runtime GC (#6894)

Multica Eve96bf122f2cf6
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index a251d1bff7..a229d2add6 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -432,7 +432,7 @@ func main() {
}
// Start background sweeper to mark stale runtimes as offline.
- go runRuntimeSweeper(sweepCtx, queries, liveness, taskSvc, bus)
+ go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus)
go heartbeatScheduler.Run(sweepCtx)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
go runDBStatsLogger(sweepCtx, pool)
diff --git a/server/cmd/server/runtime_gc_test.go b/server/cmd/server/runtime_gc_test.go
new file mode 100644
index 0000000000..86fcecc10d
--- /dev/null
+++ b/server/cmd/server/runtime_gc_test.go
@@ -0,0 +1,469 @@
+package main
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "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/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestRuntimeGC_KeepsTerminalTaskHistory(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ 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)
+ }
+
+ tasks := make([]string, 0, 3)
+ for _, status := range []string{"completed", "failed", "cancelled"} {
+ tasks = append(tasks, createRuntimeGCFixtureTask(t, ctx, runtimeID, agentID, status, true))
+ }
+ taskID := tasks[0]
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_message (task_id, seq, type, content)
+ VALUES ($1, 1, 'assistant', 'runtime GC must preserve this transcript')
+ `, taskID); err != nil {
+ t.Fatalf("insert task message: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens)
+ VALUES ($1, 'test', 'runtime-gc', 10, 20)
+ `, taskID); err != nil {
+ t.Fatalf("insert task usage: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_token (token_hash, task_id, agent_id, workspace_id, user_id, expires_at)
+ VALUES ($1, $2, $3, $4, $5, now() + interval '1 hour')
+ `, "runtime-gc-"+taskID, taskID, agentID, testWorkspaceID, testUserID); err != nil {
+ t.Fatalf("insert task token: %v", err)
+ }
+
+ workspaceID, deleted, blocked, 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 workspaceID != testWorkspaceID {
+ t.Fatalf("workspace id = %q, want %q", workspaceID, testWorkspaceID)
+ }
+
+ var runtimeRows 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 runtimeRows != 0 {
+ t.Fatalf("runtime rows = %d, want 0", runtimeRows)
+ }
+ for _, id := range tasks {
+ var taskRows int
+ var runtimeDetached bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT count(*), bool_and(runtime_id IS NULL)
+ FROM agent_task_queue WHERE id = $1
+ `, id).Scan(&taskRows, &runtimeDetached); err != nil {
+ t.Fatalf("read task %s: %v", id, err)
+ }
+ if taskRows != 1 || !runtimeDetached {
+ t.Fatalf("task %s rows=%d detached=%v, want preserved and detached", id, taskRows, runtimeDetached)
+ }
+ }
+ for table, want := range map[string]int{"task_message": 1, "task_usage": 1, "task_token": 1} {
+ var rows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM `+table+` WHERE task_id = $1`, taskID).Scan(&rows); err != nil {
+ t.Fatalf("count %s: %v", table, err)
+ }
+ if rows != want {
+ t.Fatalf("%s rows = %d, want %d", table, rows, want)
+ }
+ }
+}
+
+func TestRuntimeGC_ProtectsEveryNonTerminalTaskStatus(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ agentID := runtimeGCFixtureAgentID(t, ctx)
+
+ for _, status := range []string{"queued", "dispatched", "running", "waiting_local_directory", "deferred"} {
+ t.Run(status, func(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))
+ if err != nil {
+ t.Fatalf("gcRuntime: %v", err)
+ }
+ if deleted || !blocked {
+ t.Fatalf("gc result deleted=%v blocked=%v, want safely blocked", deleted, blocked)
+ }
+
+ var runtimeRows, taskRows int
+ var taskRuntime 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 count(*), min(runtime_id::text) FROM agent_task_queue WHERE id = $1
+ `, taskID).Scan(&taskRows, &taskRuntime); err != nil {
+ t.Fatalf("read task: %v", err)
+ }
+ if runtimeRows != 1 || taskRows != 1 || taskRuntime != runtimeID {
+ t.Fatalf("runtime rows=%d task rows=%d task runtime=%q; GC changed blocked data", runtimeRows, taskRows, taskRuntime)
+ }
+ })
+ }
+}
+
+func TestRuntimeGCCandidates_ExcludeBlockedRuntimesWithoutHidingBacklog(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ agentID := runtimeGCFixtureAgentID(t, ctx)
+ drainableRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-drainable")
+ blockedRuntimeID := createRuntimeGCFixtureRuntime(t, ctx, "candidate-blocked")
+ _ = createRuntimeGCFixtureTask(t, ctx, blockedRuntimeID, agentID, "deferred", false)
+ queries := db.New(testPool)
+
+ candidates, err := queries.ListStaleOfflineRuntimeGCCandidates(ctx, db.ListStaleOfflineRuntimeGCCandidatesParams{
+ StaleSeconds: offlineRuntimeTTLSeconds,
+ MaxPerTick: runtimeGCBatchSize,
+ })
+ if err != nil {
+ t.Fatalf("list GC candidates: %v", err)
+ }
+ foundDrainable := false
+ for _, id := range candidates {
+ idString := util.UUIDToString(id)
+ if idString == blockedRuntimeID {
+ t.Fatal("non-terminal task owner entered the bounded GC batch")
+ }
+ if idString == drainableRuntimeID {
+ foundDrainable = true
+ }
+ }
+ if !foundDrainable {
+ t.Fatal("drainable runtime missing from GC candidates")
+ }
+ blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(ctx, db.CountStaleOfflineRuntimesBlockedByTasksParams{
+ StaleSeconds: offlineRuntimeTTLSeconds,
+ MaxRows: runtimeGCBlockedScanLimit,
+ })
+ if err != nil {
+ t.Fatalf("count blocked GC runtimes: %v", err)
+ }
+ if blocked < 1 {
+ t.Fatalf("blocked runtime gauge source = %d, want at least 1", blocked)
+ }
+}
+
+func TestRuntimeGC_RollsBackDetachedHistoryWhenDeleteFails(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "rollback")
+ agentID := runtimeGCFixtureAgentID(t, ctx)
+ taskID := createRuntimeGCFixtureTask(t, ctx, runtimeID, agentID, "completed", true)
+
+ starter := failRuntimeDeleteTxStarter{pool: testPool}
+ _, deleted, blocked, 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)
+ }
+
+ var runtimeRows int
+ var taskRuntime 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_task_queue WHERE id = $1`, taskID).Scan(&taskRuntime); err != nil {
+ t.Fatalf("read rolled-back task: %v", err)
+ }
+ if runtimeRows != 1 || taskRuntime != runtimeID {
+ t.Fatalf("rollback left runtime rows=%d task runtime=%q", runtimeRows, taskRuntime)
+ }
+}
+
+func TestRuntimeGC_RuntimeLockRejectsConcurrentEnqueue(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "enqueue-race")
+ agentID := runtimeGCFixtureAgentID(t, ctx)
+
+ locked := make(chan struct{})
+ proceed := make(chan struct{})
+ starter := signalRuntimeLockTxStarter{pool: testPool, locked: locked, proceed: proceed}
+ type gcResult struct {
+ deleted bool
+ blocked bool
+ 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}
+ }()
+ select {
+ case <-locked:
+ case <-ctx.Done():
+ t.Fatal("runtime GC never acquired its FOR UPDATE lock")
+ }
+
+ writer, err := testPool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire writer connection: %v", err)
+ }
+ defer writer.Release()
+ var writerPID int32
+ if err := writer.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&writerPID); err != nil {
+ t.Fatalf("read writer pid: %v", err)
+ }
+ writerDone := make(chan error, 1)
+ go func() {
+ _, err := db.New(writer).CreateAgentTask(ctx, db.CreateAgentTaskParams{
+ AgentID: parseUUID(agentID),
+ RuntimeID: parseUUID(runtimeID),
+ Priority: 0,
+ })
+ writerDone <- err
+ }()
+ waitErr := waitForRuntimeGCBlockedWriter(ctx, writerPID)
+ close(proceed)
+ if waitErr != nil {
+ t.Fatal(waitErr)
+ }
+
+ 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 err := <-writerDone; !errors.Is(err, pgx.ErrNoRows) {
+ t.Fatalf("concurrent enqueue error = %v, want pgx.ErrNoRows from ownership fence", err)
+ }
+ var tasks int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1`, runtimeID).Scan(&tasks); err != nil {
+ t.Fatalf("count raced tasks: %v", err)
+ }
+ if tasks != 0 {
+ t.Fatalf("concurrent enqueue created %d tasks for deleted runtime", tasks)
+ }
+}
+
+func TestRuntimeGC_TickBudgetBoundsWholeBatch(t *testing.T) {
+ if testPool == nil {
+ t.Skip("no database connection")
+ }
+ ctx := context.Background()
+ runtimeID := createRuntimeGCFixtureRuntime(t, ctx, "tick-budget")
+ starter := &blockingRuntimeGCTxStarter{}
+
+ startedAt := time.Now()
+ gcRuntimesWithBudget(ctx, starter, db.New(testPool), nil, events.New(), 250*time.Millisecond)
+ elapsed := time.Since(startedAt)
+
+ if got := starter.begins.Load(); got != 1 {
+ t.Fatalf("GC transactions started = %d, want 1 before the tick budget stopped the batch", got)
+ }
+ if elapsed > 2*time.Second {
+ t.Fatalf("GC exceeded its tick budget by too much: %s", elapsed)
+ }
+ var runtimeRows int
+ if err := testPool.QueryRow(ctx, `SELECT count(*) FROM agent_runtime WHERE id = $1`, runtimeID).Scan(&runtimeRows); err != nil {
+ t.Fatalf("count budget-blocked runtime: %v", err)
+ }
+ if runtimeRows != 1 {
+ t.Fatalf("runtime rows after tick timeout = %d, want 1", runtimeRows)
+ }
+}
+
+type blockingRuntimeGCTxStarter struct {
+ begins atomic.Int32
+}
+
+func (s *blockingRuntimeGCTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ s.begins.Add(1)
+ <-ctx.Done()
+ return nil, ctx.Err()
+}
+
+type failRuntimeDeleteTxStarter struct {
+ pool *pgxpool.Pool
+}
+
+func (s failRuntimeDeleteTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return failRuntimeDeleteTx{Tx: tx}, nil
+}
+
+type failRuntimeDeleteTx struct {
+ pgx.Tx
+}
+
+func (tx failRuntimeDeleteTx) Exec(ctx context.Context, sql string, arguments ...any) (pgconn.CommandTag, error) {
+ if strings.Contains(sql, "-- name: DeleteAgentRuntime") {
+ return pgconn.CommandTag{}, errors.New("injected runtime delete failure")
+ }
+ return tx.Tx.Exec(ctx, sql, arguments...)
+}
+
+type signalRuntimeLockTxStarter struct {
+ pool *pgxpool.Pool
+ locked chan struct{}
+ proceed chan struct{}
+}
+
+func (s signalRuntimeLockTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return signalRuntimeLockTx{Tx: tx, locked: s.locked, proceed: s.proceed}, nil
+}
+
+type signalRuntimeLockTx struct {
+ pgx.Tx
+ locked chan struct{}
+ proceed chan struct{}
+}
+
+func (tx signalRuntimeLockTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ row := tx.Tx.QueryRow(ctx, sql, args...)
+ if !strings.Contains(sql, "-- name: LockAgentRuntime") {
+ return row
+ }
+ return signalRuntimeLockRow{Row: row, locked: tx.locked, proceed: tx.proceed}
+}
+
+type signalRuntimeLockRow struct {
+ pgx.Row
+ locked chan struct{}
+ proceed chan struct{}
+}
+
+func (row signalRuntimeLockRow) Scan(dest ...any) error {
+ err := row.Row.Scan(dest...)
+ close(row.locked)
+ <-row.proceed
+ return err
+}
+
+func waitForRuntimeGCBlockedWriter(ctx context.Context, pid int32) error {
+ deadline := time.Now().Add(10 * time.Second)
+ for time.Now().Before(deadline) {
+ var waiting bool
+ if err := testPool.QueryRow(ctx, `
+ SELECT EXISTS (
+ SELECT 1 FROM pg_stat_activity
+ WHERE pid = $1 AND state = 'active' AND wait_event_type = 'Lock'
+ )
+ `, pid).Scan(&waiting); err != nil {
+ return fmt.Errorf("poll writer lock: %w", err)
+ }
+ if waiting {
+ return nil
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ return fmt.Errorf("writer backend %d never blocked on the runtime GC lock", pid)
+}
+
+func createRuntimeGCFixtureRuntime(t *testing.T, ctx context.Context, suffix string) string {
+ t.Helper()
+ var runtimeID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (
+ workspace_id, name, runtime_mode, provider, status,
+ device_info, metadata, owner_id, last_seen_at
+ )
+ VALUES ($1, $2, 'cloud', 'runtime-gc-test', 'offline',
+ '', '{}'::jsonb, $3, now() - interval '8 days')
+ RETURNING id
+ `, testWorkspaceID, "Runtime GC "+suffix, testUserID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime fixture: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE runtime_id = $1`, runtimeID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID)
+ })
+ return runtimeID
+}
+
+func createRuntimeGCFixtureAgent(t *testing.T, ctx context.Context, runtimeID, suffix string) string {
+ t.Helper()
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, max_concurrent_tasks, owner_id
+ )
+ VALUES ($1, $2, '', 'cloud', '{}'::jsonb, $3, 'private', 1, $4)
+ RETURNING id
+ `, testWorkspaceID, "Runtime GC Agent "+suffix, runtimeID, testUserID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent fixture: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE agent_id = $1`, agentID)
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, agentID)
+ })
+ return agentID
+}
+
+func runtimeGCFixtureAgentID(t *testing.T, ctx context.Context) string {
+ t.Helper()
+ var agentID string
+ if err := testPool.QueryRow(ctx, `
+ SELECT id FROM agent
+ WHERE workspace_id = $1 AND name = 'Integration Test Agent'
+ LIMIT 1
+ `, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatalf("load integration fixture agent: %v", err)
+ }
+ return agentID
+}
+
+func createRuntimeGCFixtureTask(t *testing.T, ctx context.Context, runtimeID, agentID, status string, terminal bool) string {
+ t.Helper()
+ completedAt := "NULL"
+ if terminal {
+ completedAt = "now()"
+ }
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, context, completed_at)
+ VALUES ($1, $2, $3, '{"runtime_gc_fixture":true}'::jsonb, `+completedAt+`)
+ RETURNING id
+ `, agentID, runtimeID, status).Scan(&taskID); err != nil {
+ t.Fatalf("create %s task fixture: %v", status, err)
+ }
+ t.Cleanup(func() {
+ _, _ = testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ return taskID
+}
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 3bc09ed859..46583f92d8 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -2,9 +2,12 @@ package main
import (
"context"
+ "errors"
+ "fmt"
"log/slog"
"time"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
@@ -33,6 +36,19 @@ const (
// offlineRuntimeTTLSeconds deletes offline runtimes with no active agents
// 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
+ // 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 = 15 * time.Second
+ // runtimeGCOperationTimeout prevents one contended or unhealthy runtime from
+ // stalling every later sweeper stage indefinitely.
+ runtimeGCOperationTimeout = 5 * time.Second
// dispatchTimeoutSeconds fails tasks stuck in 'dispatched' beyond this.
// The dispatched→running transition should be near-instant, so 5 minutes
// means something went wrong (e.g. StartTask API call failed silently).
@@ -79,6 +95,10 @@ const (
chatFinalizeBatchSize = 100
)
+type runtimeGCTxStarter interface {
+ Begin(context.Context) (pgx.Tx, error)
+}
+
// 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
@@ -90,7 +110,7 @@ const (
// 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, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {
+func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, liveness handler.LivenessStore, taskSvc *service.TaskService, bus *events.Bus) {
ticker := time.NewTicker(sweepInterval)
defer ticker.Stop()
@@ -103,7 +123,7 @@ func runRuntimeSweeper(ctx context.Context, queries *db.Queries, liveness handle
sweepStaleTasks(ctx, queries, taskSvc, bus)
sweepExpiredQueuedTasks(ctx, queries, taskSvc)
sweepDeferredChatFinalizations(ctx, queries, taskSvc)
- gcRuntimes(ctx, queries, bus)
+ gcRuntimes(ctx, txStarter, queries, taskSvc.Metrics, bus)
}
}
}
@@ -224,25 +244,89 @@ func filterStaleRuntimesByLiveness(ctx context.Context, candidates []db.SelectSt
return ids
}
-// gcRuntimes deletes offline runtimes that have exceeded the TTL and have
-// no active (non-archived) agents. Before deleting, it cleans up any
-// archived agents so the FK constraint (ON DELETE RESTRICT) doesn't block.
-func gcRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {
- deleted, err := queries.DeleteStaleOfflineRuntimes(ctx, offlineRuntimeTTLSeconds)
+// gcRuntimes deletes old offline runtimes without relying on the legacy
+// 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 gcRuntimesWithBudget(ctx context.Context, txStarter runtimeGCTxStarter, queries *db.Queries, metrics *obsmetrics.BusinessMetrics, bus *events.Bus, budget time.Duration) {
+ gcCtx, cancelGC := context.WithTimeout(ctx, budget)
+ defer cancelGC()
+
+ countCtx, cancelCount := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
+ blocked, err := queries.CountStaleOfflineRuntimesBlockedByTasks(countCtx, db.CountStaleOfflineRuntimesBlockedByTasksParams{
+ StaleSeconds: offlineRuntimeTTLSeconds,
+ MaxRows: runtimeGCBlockedScanLimit,
+ })
+ cancelCount()
+ if err != nil {
+ slog.Warn("runtime GC: failed to count task-blocked runtimes", "error", err)
+ metrics.RecordRuntimeGCBlockedObservationFailed()
+ } else {
+ metrics.SetRuntimeGCBlocked(blocked)
+ if blocked > 0 {
+ slog.Debug("runtime GC: stale runtimes blocked by non-terminal tasks",
+ "count", blocked, "count_capped", blocked == runtimeGCBlockedScanLimit)
+ }
+ }
+
+ listCtx, cancelList := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
+ candidates, err := queries.ListStaleOfflineRuntimeGCCandidates(listCtx, db.ListStaleOfflineRuntimeGCCandidatesParams{
+ StaleSeconds: offlineRuntimeTTLSeconds,
+ MaxPerTick: runtimeGCBatchSize,
+ })
+ cancelList()
if err != nil {
- slog.Warn("runtime GC: failed to delete stale offline runtimes", "error", err)
+ slog.Warn("runtime GC: failed to list stale offline runtimes", "error", err)
+ metrics.RecordRuntimeGCFailed()
return
}
- if len(deleted) == 0 {
+ if len(candidates) == 0 {
return
}
gcWorkspaces := make(map[string]bool)
- for _, row := range deleted {
- gcWorkspaces[util.UUIDToString(row.WorkspaceID)] = true
+ deleted := 0
+ for i, runtimeID := range candidates {
+ if gcCtx.Err() != nil {
+ slog.Info("runtime GC: tick budget exhausted",
+ "deleted", deleted, "remaining_candidates", len(candidates)-i)
+ break
+ }
+ runtimeCtx, cancelRuntime := context.WithTimeout(gcCtx, runtimeGCOperationTimeout)
+ workspaceID, didDelete, taskBlocked, err := gcRuntime(runtimeCtx, txStarter, queries, runtimeID)
+ cancelRuntime()
+ if err != nil {
+ if gcCtx.Err() != nil {
+ slog.Info("runtime GC: tick budget exhausted",
+ "deleted", deleted, "remaining_candidates", len(candidates)-i)
+ break
+ }
+ slog.Warn("runtime GC: failed to delete stale offline runtime",
+ "runtime_id", util.UUIDToString(runtimeID), "error", err)
+ metrics.RecordRuntimeGCFailed()
+ continue
+ }
+ if taskBlocked {
+ slog.Warn("runtime GC: candidate gained a non-terminal task; skipping",
+ "runtime_id", util.UUIDToString(runtimeID))
+ continue
+ }
+ if !didDelete {
+ continue
+ }
+ deleted++
+ metrics.RecordRuntimeGCDeleted()
+ gcWorkspaces[workspaceID] = true
+ }
+ if deleted == 0 {
+ return
}
- slog.Info("runtime GC: deleted stale offline runtimes", "count", len(deleted), "workspaces", len(gcWorkspaces))
+ slog.Info("runtime GC: deleted stale offline runtimes", "count", deleted, "workspaces", len(gcWorkspaces))
for wsID := range gcWorkspaces {
bus.Publish(events.Event{
@@ -256,6 +340,76 @@ func gcRuntimes(ctx context.Context, queries *db.Queries, bus *events.Bus) {
}
}
+// 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) {
+ tx, err := txStarter.Begin(ctx)
+ if err != nil {
+ return "", false, false, fmt.Errorf("begin transaction: %w", err)
+ }
+ defer func() {
+ // The operation context may already be cancelled on a timeout. Give
+ // rollback its own short window so the pool does not retain an open
+ // transaction/connection after a failed GC attempt.
+ rollbackCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), runtimeGCOperationTimeout)
+ defer cancel()
+ _ = tx.Rollback(rollbackCtx)
+ }()
+ qtx := queries.WithTx(tx)
+
+ runtime, err := qtx.LockAgentRuntime(ctx, runtimeID)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", false, false, nil
+ }
+ if err != nil {
+ return "", false, false, fmt.Errorf("lock runtime: %w", err)
+ }
+
+ eligible, err := qtx.IsAgentRuntimeEligibleForGC(ctx, db.IsAgentRuntimeEligibleForGCParams{
+ ID: runtimeID,
+ StaleSeconds: offlineRuntimeTTLSeconds,
+ })
+ if err != nil {
+ return "", false, false, fmt.Errorf("re-check eligibility: %w", err)
+ }
+ if !eligible {
+ return "", false, false, nil
+ }
+
+ undrained, err := qtx.CountUndrainedTasksByRuntimeOrAgent(ctx, db.CountUndrainedTasksByRuntimeOrAgentParams{
+ RuntimeIds: []pgtype.UUID{runtimeID},
+ AgentIds: []pgtype.UUID{},
+ })
+ if err != nil {
+ return "", false, false, fmt.Errorf("count non-terminal tasks: %w", err)
+ }
+ if undrained > 0 {
+ return "", false, true, 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)
+ 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 err := qtx.DeleteAgentRuntime(ctx, runtimeID); err != nil {
+ return "", false, false, fmt.Errorf("delete runtime: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return "", false, false, fmt.Errorf("commit transaction: %w", err)
+ }
+
+ return util.UUIDToString(runtime.WorkspaceID), true, false, nil
+}
+
// sweepStaleTasks fails tasks stuck in dispatched/running for too long,
// even when the runtime is still online at the row level. Each branch pairs
// the wall clock with a task-appropriate liveness signal so healthy long
diff --git a/server/internal/handler/runtime_unbind_preserves_data_test.go b/server/internal/handler/runtime_unbind_preserves_data_test.go
index 3b1ad1649a..8d0ba22626 100644
--- a/server/internal/handler/runtime_unbind_preserves_data_test.go
+++ b/server/internal/handler/runtime_unbind_preserves_data_test.go
@@ -207,50 +207,6 @@ func TestCountUndrainedTasksByRuntimeOrAgent_IncludesCrossRuntimeTask(t *testing
}
}
-func TestDeleteStaleOfflineRuntimes_UnboundAgentDoesNotDisableGC(t *testing.T) {
- if testHandler == nil {
- t.Skip("database not available")
- }
- ctx := context.Background()
-
- boundRuntimeID := createCascadeFixtureRuntime(t, ctx, "GC Unbound Agent Source")
- agentID := createCascadeFixtureAgent(t, ctx, boundRuntimeID, "GC Unbound Agent")
- if _, err := testPool.Exec(ctx, `UPDATE agent SET runtime_id = NULL WHERE id = $1`, agentID); err != nil {
- t.Fatalf("unbind GC fixture agent: %v", err)
- }
-
- var staleRuntimeID string
- if err := testPool.QueryRow(ctx, `
- INSERT INTO agent_runtime (
- workspace_id, name, runtime_mode, provider, status,
- device_info, metadata, owner_id, last_seen_at
- )
- VALUES ($1, 'GC stale candidate', 'cloud', 'gc-regression', 'offline',
- 'GC stale candidate', '{}'::jsonb, $2, now() - interval '200 years')
- RETURNING id
- `, testWorkspaceID, testUserID).Scan(&staleRuntimeID); err != nil {
- t.Fatalf("seed stale runtime: %v", err)
- }
- t.Cleanup(func() {
- testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, staleRuntimeID)
- })
-
- deleted, err := testHandler.Queries.DeleteStaleOfflineRuntimes(ctx, 3_000_000_000)
- if err != nil {
- t.Fatalf("delete stale runtimes: %v", err)
- }
- found := false
- for _, row := range deleted {
- if uuidToString(row.ID) == staleRuntimeID {
- found = true
- break
- }
- }
- if !found {
- t.Fatal("unbound agent made stale-runtime GC skip an unrelated candidate")
- }
-}
-
// TestUnbindAgentsAndDeleteRuntime_KeepsAutopilotConfig pauses an automation
// whose assignee cannot run after teardown. Leaving it active would append an
// identical skipped run every schedule tick forever. Its assignee and config
diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.go
index f25008ff8c..1ee16e9590 100644
--- a/server/internal/metrics/business.go
+++ b/server/internal/metrics/business.go
@@ -31,8 +31,12 @@ type BusinessMetrics struct {
llmUnpricedTokens *prometheus.CounterVec
llmRequests *prometheus.CounterVec
- taskQueuedExpired *prometheus.CounterVec
- taskLeaseExpired *prometheus.CounterVec
+ taskQueuedExpired *prometheus.CounterVec
+ taskLeaseExpired *prometheus.CounterVec
+ runtimeGCDeleted prometheus.Counter
+ runtimeGCFailed prometheus.Counter
+ runtimeGCBlocked prometheus.Gauge
+ runtimeGCBlockedObservationFailed prometheus.Counter
activeMu sync.Mutex
activeTasks map[string]activeTaskLabels
@@ -145,6 +149,30 @@ func NewBusinessMetrics() *BusinessMetrics {
Name: "lease_expired_total",
Help: "Total dispatched or running task leases expired by the scheduler.",
}, metricLabels("multica_task_lease_expired_total")),
+ runtimeGCDeleted: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "runtime_gc",
+ Name: "deleted_total",
+ Help: "Total stale offline runtimes safely deleted by garbage collection.",
+ }),
+ runtimeGCFailed: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "runtime_gc",
+ Name: "failed_total",
+ Help: "Total runtime garbage-collection operations that failed.",
+ }),
+ 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.",
+ }),
+ runtimeGCBlockedObservationFailed: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "runtime_gc",
+ Name: "blocked_observation_failed_total",
+ Help: "Total failures while observing stale runtimes blocked from garbage collection.",
+ }),
activeTasks: map[string]activeTaskLabels{},
events: newBusinessEventMetrics(),
}
@@ -170,9 +198,41 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {
m.llmRequests,
m.taskQueuedExpired,
m.taskLeaseExpired,
+ m.runtimeGCDeleted,
+ m.runtimeGCFailed,
+ m.runtimeGCBlocked,
+ m.runtimeGCBlockedObservationFailed,
}, m.events.collectors()...)
}
+func (m *BusinessMetrics) RecordRuntimeGCDeleted() {
+ if m == nil {
+ return
+ }
+ m.runtimeGCDeleted.Inc()
+}
+
+func (m *BusinessMetrics) RecordRuntimeGCFailed() {
+ if m == nil {
+ return
+ }
+ m.runtimeGCFailed.Inc()
+}
+
+func (m *BusinessMetrics) SetRuntimeGCBlocked(count int64) {
+ if m == nil {
+ return
+ }
+ m.runtimeGCBlocked.Set(float64(count))
+}
+
+func (m *BusinessMetrics) RecordRuntimeGCBlockedObservationFailed() {
+ if m == nil {
+ return
+ }
+ m.runtimeGCBlockedObservationFailed.Inc()
+}
+
func (m *BusinessMetrics) RecordTaskEnqueued(source, runtimeMode string) {
if m == nil {
return
diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.go
index ebcabb51af..a2b6a2f50b 100644
--- a/server/internal/metrics/business_test.go
+++ b/server/internal/metrics/business_test.go
@@ -164,6 +164,27 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {
}
}
+func TestBusinessMetricsRuntimeGC(t *testing.T) {
+ m := NewBusinessMetrics()
+ m.RecordRuntimeGCDeleted()
+ m.RecordRuntimeGCFailed()
+ m.SetRuntimeGCBlocked(3)
+ m.RecordRuntimeGCBlockedObservationFailed()
+
+ if got := testutil.ToFloat64(m.runtimeGCDeleted); got != 1 {
+ t.Fatalf("runtime GC deleted = %v, want 1", got)
+ }
+ if got := testutil.ToFloat64(m.runtimeGCFailed); got != 1 {
+ t.Fatalf("runtime GC failed = %v, want 1", got)
+ }
+ if got := testutil.ToFloat64(m.runtimeGCBlocked); got != 3 {
+ t.Fatalf("runtime GC blocked = %v, want 3", got)
+ }
+ if got := testutil.ToFloat64(m.runtimeGCBlockedObservationFailed); got != 1 {
+ t.Fatalf("runtime GC blocked observation failures = %v, want 1", got)
+ }
+}
+
func exerciseEvent(m *BusinessMetrics, name string, props map[string]any) {
if props == nil {
props = map[string]any{}
diff --git a/server/migrations/309_agent_runtime_id_index.down.sql b/server/migrations/309_agent_runtime_id_index.down.sql
new file mode 100644
index 0000000000..7d1ff42a80
--- /dev/null
+++ b/server/migrations/309_agent_runtime_id_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_runtime_id;
diff --git a/server/migrations/309_agent_runtime_id_index.up.sql b/server/migrations/309_agent_runtime_id_index.up.sql
new file mode 100644
index 0000000000..7a004c5c84
--- /dev/null
+++ b/server/migrations/309_agent_runtime_id_index.up.sql
@@ -0,0 +1,10 @@
+-- Runtime GC re-checks that no Agent references a candidate after locking the
+-- runtime row, then agent.runtime_id's existing RESTRICT foreign key repeats
+-- the same lookup while deleting it. Without a runtime-leading index, each
+-- bounded GC batch can scan the full Agent table once per candidate.
+--
+-- Keep this as the migration's only statement: the runner executes files
+-- outside an explicit transaction so PostgreSQL can build the index without
+-- blocking Agent writes for the duration of the scan.
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_runtime_id
+ ON agent (runtime_id);
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index c0f4c8f0ec..e712a7b538 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -131,6 +131,56 @@ func (q *Queries) CountActiveAgentsByRuntime(ctx context.Context, runtimeID pgty
return count, err
}
+const countStaleOfflineRuntimesBlockedByTasks = `-- name: CountStaleOfflineRuntimesBlockedByTasks :one
+SELECT count(*) FROM (
+ SELECT 1 FROM agent_runtime
+ WHERE status = 'offline'
+ AND last_seen_at < now() - make_interval(secs => $1::double precision)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue
+ WHERE agent_task_queue.runtime_id = agent_runtime.id
+ AND agent_task_queue.completed_at IS NULL
+ )
+ LIMIT $2::int
+) AS blocked_runtimes
+`
+
+type CountStaleOfflineRuntimesBlockedByTasksParams struct {
+ StaleSeconds float64 `json:"stale_seconds"`
+ MaxRows int32 `json:"max_rows"`
+}
+
+// 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.
+func (q *Queries) CountStaleOfflineRuntimesBlockedByTasks(ctx context.Context, arg CountStaleOfflineRuntimesBlockedByTasksParams) (int64, error) {
+ row := q.db.QueryRow(ctx, countStaleOfflineRuntimesBlockedByTasks, arg.StaleSeconds, arg.MaxRows)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
+const countTasksByRuntime = `-- name: CountTasksByRuntime :one
+SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1
+`
+
+// Final fail-closed assertion after UnbindTasksFromRuntime. A non-zero result
+// aborts the transaction instead of relying on the legacy ON DELETE CASCADE.
+func (q *Queries) CountTasksByRuntime(ctx context.Context, runtimeID pgtype.UUID) (int64, error) {
+ row := q.db.QueryRow(ctx, countTasksByRuntime, runtimeID)
+ var count int64
+ err := row.Scan(&count)
+ return count, err
+}
+
const countUndrainedTasksByRuntimeOrAgent = `-- name: CountUndrainedTasksByRuntimeOrAgent :one
SELECT count(*) FROM agent_task_queue
WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))
@@ -166,46 +216,6 @@ func (q *Queries) DeleteAgentRuntime(ctx context.Context, id pgtype.UUID) error
return err
}
-const deleteStaleOfflineRuntimes = `-- name: DeleteStaleOfflineRuntimes :many
-DELETE FROM agent_runtime
-WHERE status = 'offline'
- AND last_seen_at < now() - make_interval(secs => $1::double precision)
- AND NOT EXISTS (
- SELECT 1
- FROM agent
- WHERE agent.runtime_id = agent_runtime.id
- )
-RETURNING id, workspace_id
-`
-
-type DeleteStaleOfflineRuntimesRow struct {
- ID pgtype.UUID `json:"id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
-}
-
-// Deletes runtimes that have been offline for longer than the TTL and have
-// no agents bound (active or archived). The FK constraint on agent.runtime_id
-// is ON DELETE RESTRICT, so we must exclude all agent references.
-func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds float64) ([]DeleteStaleOfflineRuntimesRow, error) {
- rows, err := q.db.Query(ctx, deleteStaleOfflineRuntimes, staleSeconds)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
- items := []DeleteStaleOfflineRuntimesRow{}
- for rows.Next() {
- var i DeleteStaleOfflineRuntimesRow
- if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {
- return nil, err
- }
- items = append(items, i)
- }
- if err := rows.Err(); err != nil {
- return nil, err
- }
- return items, nil
-}
-
const deleteSystemAgentsByRuntime = `-- name: DeleteSystemAgentsByRuntime :exec
DELETE FROM agent WHERE runtime_id = $1 AND kind = 'system'
`
@@ -533,6 +543,36 @@ func (q *Queries) GetAgentRuntimes(ctx context.Context, ids []pgtype.UUID) ([]Ag
return items, nil
}
+const isAgentRuntimeEligibleForGC = `-- name: IsAgentRuntimeEligibleForGC :one
+SELECT EXISTS (
+ SELECT 1 FROM agent_runtime
+ WHERE agent_runtime.id = $1
+ AND status = 'offline'
+ AND last_seen_at < now() - make_interval(secs => $2::double precision)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
+) AS eligible
+`
+
+type IsAgentRuntimeEligibleForGCParams struct {
+ ID pgtype.UUID `json:"id"`
+ StaleSeconds float64 `json:"stale_seconds"`
+}
+
+// Re-checks the mutable GC predicates after the caller has locked the runtime
+// row FOR UPDATE. Agent inserts/updates and task ownership writes take FOR KEY
+// SHARE on that row, so no new dependency can commit between this check and
+// DeleteAgentRuntime in the same transaction.
+func (q *Queries) IsAgentRuntimeEligibleForGC(ctx context.Context, arg IsAgentRuntimeEligibleForGCParams) (bool, error) {
+ row := q.db.QueryRow(ctx, isAgentRuntimeEligibleForGC, arg.ID, arg.StaleSeconds)
+ var eligible bool
+ err := row.Scan(&eligible)
+ return eligible, err
+}
+
const listAgentRuntimes = `-- name: ListAgentRuntimes :many
SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtime
WHERE workspace_id = $1
@@ -666,6 +706,55 @@ func (q *Queries) ListDaemonCustomNames(ctx context.Context, arg ListDaemonCusto
return items, nil
}
+const listStaleOfflineRuntimeGCCandidates = `-- name: ListStaleOfflineRuntimeGCCandidates :many
+SELECT id FROM agent_runtime
+WHERE status = 'offline'
+ AND last_seen_at < now() - make_interval(secs => $1::double precision)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue
+ WHERE agent_task_queue.runtime_id = agent_runtime.id
+ AND agent_task_queue.completed_at IS NULL
+ )
+ORDER BY last_seen_at ASC, id ASC
+LIMIT $2::int
+`
+
+type ListStaleOfflineRuntimeGCCandidatesParams struct {
+ StaleSeconds float64 `json:"stale_seconds"`
+ MaxPerTick int32 `json:"max_per_tick"`
+}
+
+// Bounded gather for runtime GC. Non-terminal task owners are deliberately
+// excluded here so one permanently-deferred task cannot monopolise the front
+// of every batch and starve otherwise-drainable runtimes. The per-runtime
+// transaction re-checks every predicate after taking FOR UPDATE, so this is an
+// efficiency filter rather than the correctness boundary.
+func (q *Queries) ListStaleOfflineRuntimeGCCandidates(ctx context.Context, arg ListStaleOfflineRuntimeGCCandidatesParams) ([]pgtype.UUID, error) {
+ rows, err := q.db.Query(ctx, listStaleOfflineRuntimeGCCandidates, arg.StaleSeconds, arg.MaxPerTick)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []pgtype.UUID{}
+ for rows.Next() {
+ var id pgtype.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ items = append(items, id)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const lockAgentRuntime = `-- name: LockAgentRuntime :one
SELECT id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, visibility, profile_id, custom_name FROM agent_runtime
WHERE id = $1
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 528e2f9c0f..b2d65338cd 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -441,11 +441,13 @@ UPDATE agent_runtime
SET legacy_daemon_id = COALESCE(legacy_daemon_id, $2)
WHERE id = $1;
--- name: DeleteStaleOfflineRuntimes :many
--- Deletes runtimes that have been offline for longer than the TTL and have
--- no agents bound (active or archived). The FK constraint on agent.runtime_id
--- is ON DELETE RESTRICT, so we must exclude all agent references.
-DELETE FROM agent_runtime
+-- name: ListStaleOfflineRuntimeGCCandidates :many
+-- Bounded gather for runtime GC. Non-terminal task owners are deliberately
+-- excluded here so one permanently-deferred task cannot monopolise the front
+-- of every batch and starve otherwise-drainable runtimes. The per-runtime
+-- transaction re-checks every predicate after taking FOR UPDATE, so this is an
+-- efficiency filter rather than the correctness boundary.
+SELECT id FROM agent_runtime
WHERE status = 'offline'
AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
AND NOT EXISTS (
@@ -453,4 +455,57 @@ WHERE status = 'offline'
FROM agent
WHERE agent.runtime_id = agent_runtime.id
)
-RETURNING id, workspace_id;
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent_task_queue
+ WHERE agent_task_queue.runtime_id = agent_runtime.id
+ AND agent_task_queue.completed_at IS NULL
+ )
+ORDER BY last_seen_at ASC, id ASC
+LIMIT @max_per_tick::int;
+
+-- name: IsAgentRuntimeEligibleForGC :one
+-- Re-checks the mutable GC predicates after the caller has locked the runtime
+-- row FOR UPDATE. Agent inserts/updates and task ownership writes take FOR KEY
+-- SHARE on that row, so no new dependency can commit between this check and
+-- DeleteAgentRuntime in the same transaction.
+SELECT EXISTS (
+ SELECT 1 FROM agent_runtime
+ WHERE agent_runtime.id = @id
+ AND status = 'offline'
+ AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
+) AS eligible;
+
+-- name: CountTasksByRuntime :one
+-- Final fail-closed assertion after UnbindTasksFromRuntime. A non-zero result
+-- aborts the transaction instead of relying on the legacy ON DELETE CASCADE.
+SELECT count(*) FROM agent_task_queue WHERE runtime_id = $1;
+
+-- name: CountStaleOfflineRuntimesBlockedByTasks :one
+-- 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.
+SELECT count(*) FROM (
+ SELECT 1 FROM agent_runtime
+ WHERE status = 'offline'
+ AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
+ AND NOT EXISTS (
+ SELECT 1
+ FROM agent
+ WHERE agent.runtime_id = agent_runtime.id
+ )
+ AND EXISTS (
+ SELECT 1
+ FROM agent_task_queue
+ WHERE agent_task_queue.runtime_id = agent_runtime.id
+ AND agent_task_queue.completed_at IS NULL
+ )
+ LIMIT @max_rows::int
+) AS blocked_runtimes;