Skip to content

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

Go

MUL-6883 perf(server): stop rescanning settled delegated-failure recoveries (#7820)

Bohan Jiangf1ce9d454253
diff --git a/server/cmd/backfill_delegated_failure_settled/main.go b/server/cmd/backfill_delegated_failure_settled/main.go
new file mode 100644
index 0000000000..db296da293
--- /dev/null
+++ b/server/cmd/backfill_delegated_failure_settled/main.go
@@ -0,0 +1,253 @@
+// backfill_delegated_failure_settled retires delegated-failure recovery
+// comments that were already closed by a terminal delivery receipt before
+// comment.recovery_settled_at existed.
+//
+// Run it after every backend in a rolling deployment carries the code that
+// writes the marker. Until it finishes, the outbox scan behaves exactly as it
+// did before — unmarked history is still scanned and no recovery is lost — so
+// this is a performance recovery step, not a correctness step, and it is safe
+// to run off-peak or in several sittings.
+//
+// # Resuming
+//
+// The walk is keyed on (created_at, id), matching
+// idx_comment_delegated_failure_unsettled, and the watermark advances over
+// every candidate EXAMINED rather than only the ones marked. That distinction
+// is what makes a bounded run resumable: the rows this walk deliberately leaves
+// pending — a recovery still genuinely open — sit permanently at the front of
+// the index, so a run that only remembered marked rows would restart inside
+// that same prefix forever and never reach the settleable history behind it.
+//
+// Pass --checkpoint-file to persist the watermark after every committed batch
+// and resume from it automatically, or read the resume_after_* fields this
+// command logs on every exit path and pass them back with --after-created-at /
+// --after-id. Without either, a rerun starts from the beginning; that is
+// correct but repeats work.
+//
+// A session advisory lock keeps two operators from walking at once. It is
+// operator mutual exclusion for this manual command only — the periodic
+// sweeper's single-instance gate is a separate concern and is not this lock.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io/fs"
+ "log/slog"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "syscall"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/delegatedrecoverybackfill"
+ "github.com/multica-ai/multica/server/internal/logger"
+)
+
+const advisoryLockName = "delegated_failure_recovery_settled_backfill"
+
+// checkpoint is the on-disk form of a keyset watermark.
+type checkpoint struct {
+ AfterCreatedAt time.Time `json:"after_created_at"`
+ AfterID string `json:"after_id"`
+}
+
+func readCheckpoint(path string) (*delegatedrecoverybackfill.Cursor, error) {
+ raw, err := os.ReadFile(path)
+ if errors.Is(err, fs.ErrNotExist) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("read checkpoint %s: %w", path, err)
+ }
+ var cp checkpoint
+ if err := json.Unmarshal(raw, &cp); err != nil {
+ return nil, fmt.Errorf("parse checkpoint %s: %w", path, err)
+ }
+ if cp.AfterID == "" {
+ return nil, nil
+ }
+ return &delegatedrecoverybackfill.Cursor{CreatedAt: cp.AfterCreatedAt, ID: cp.AfterID}, nil
+}
+
+// writeCheckpoint replaces the file atomically so an interrupted write cannot
+// leave behind a half-written watermark that resumes in the wrong place.
+func writeCheckpoint(path string, cursor *delegatedrecoverybackfill.Cursor) error {
+ raw, err := json.Marshal(checkpoint{AfterCreatedAt: cursor.CreatedAt, AfterID: cursor.ID})
+ if err != nil {
+ return fmt.Errorf("encode checkpoint: %w", err)
+ }
+ tmp, err := os.CreateTemp(filepath.Dir(path), ".checkpoint-*")
+ if err != nil {
+ return fmt.Errorf("create checkpoint temp file: %w", err)
+ }
+ defer os.Remove(tmp.Name())
+ if _, err := tmp.Write(raw); err != nil {
+ tmp.Close()
+ return fmt.Errorf("write checkpoint: %w", err)
+ }
+ if err := tmp.Close(); err != nil {
+ return fmt.Errorf("close checkpoint: %w", err)
+ }
+ if err := os.Rename(tmp.Name(), path); err != nil {
+ return fmt.Errorf("install checkpoint %s: %w", path, err)
+ }
+ return nil
+}
+
+func resolveStart(checkpointFile, afterCreatedAt, afterID string) (*delegatedrecoverybackfill.Cursor, error) {
+ if (afterCreatedAt == "") != (afterID == "") {
+ return nil, fmt.Errorf("--after-created-at and --after-id must be given together")
+ }
+ if afterID != "" {
+ createdAt, err := time.Parse(time.RFC3339Nano, afterCreatedAt)
+ if err != nil {
+ return nil, fmt.Errorf("--after-created-at must be RFC3339: %w", err)
+ }
+ // An explicit flag wins over the file: it is how an operator overrides
+ // a checkpoint they no longer trust.
+ return &delegatedrecoverybackfill.Cursor{CreatedAt: createdAt, ID: afterID}, nil
+ }
+ if checkpointFile == "" {
+ return nil, nil
+ }
+ return readCheckpoint(checkpointFile)
+}
+
+func main() {
+ logger.Init()
+ if err := run(); err != nil {
+ slog.Error("delegated failure recovery settled backfill failed", "error", err)
+ os.Exit(1)
+ }
+}
+
+func run() error {
+ batchSize := flag.Int("batch-size", delegatedrecoverybackfill.DefaultBatchSize, "maximum candidate recovery comments examined per statement")
+ delay := flag.Duration("sleep-between-batches", 100*time.Millisecond, "delay between committed batches")
+ maxBatches := flag.Int("max-batches", 0, "stop after N batches (0 = walk the whole history)")
+ checkpointFile := flag.String("checkpoint-file", "", "persist the keyset watermark here after every batch and resume from it")
+ afterCreatedAt := flag.String("after-created-at", "", "resume after this comment created_at (RFC3339); requires --after-id")
+ afterID := flag.String("after-id", "", "resume after this comment id; requires --after-created-at")
+ flag.Parse()
+ if *batchSize < 1 {
+ return fmt.Errorf("--batch-size must be at least 1")
+ }
+ if *delay < 0 {
+ return fmt.Errorf("--sleep-between-batches must not be negative")
+ }
+ if *maxBatches < 0 {
+ return fmt.Errorf("--max-batches must not be negative")
+ }
+ cursor, err := resolveStart(*checkpointFile, *afterCreatedAt, *afterID)
+ if err != nil {
+ return err
+ }
+
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
+ defer stop()
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ pool, err := pgxpool.New(ctx, dbURL)
+ if err != nil {
+ return fmt.Errorf("connect to database: %w", err)
+ }
+ defer pool.Close()
+ if err := pool.Ping(ctx); err != nil {
+ return fmt.Errorf("ping database: %w", err)
+ }
+
+ lockConn, err := pool.Acquire(ctx)
+ if err != nil {
+ return fmt.Errorf("acquire advisory-lock connection: %w", err)
+ }
+ defer lockConn.Release()
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock(hashtextextended($1, 0))`, advisoryLockName); err != nil {
+ return fmt.Errorf("acquire advisory lock: %w", err)
+ }
+ defer func() {
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock(hashtextextended($1, 0))`, advisoryLockName)
+ }()
+
+ remaining, err := delegatedrecoverybackfill.CountRemaining(ctx, pool, "")
+ if err != nil {
+ return err
+ }
+ slog.Info("delegated failure recovery settled backfill started",
+ "unsettled", remaining, "batch_size", *batchSize, "delay", delay.String(),
+ "resumed_from_id", cursorID(cursor))
+
+ var scanned, settled int64
+ // Report the watermark on EVERY exit, including SIGTERM and --max-batches,
+ // so a run without --checkpoint-file is still resumable from the logs.
+ defer func() {
+ slog.Info("delegated failure recovery settled backfill stopped",
+ "scanned", scanned, "settled", settled,
+ "resume_after_created_at", cursorCreatedAt(cursor),
+ "resume_after_id", cursorID(cursor))
+ }()
+
+ for batch := 1; *maxBatches == 0 || batch <= *maxBatches; batch++ {
+ result, err := delegatedrecoverybackfill.Batch(ctx, pool, delegatedrecoverybackfill.Options{
+ BatchSize: *batchSize,
+ After: cursor,
+ })
+ if err != nil {
+ return err
+ }
+ if result.Scanned == 0 {
+ break
+ }
+ if result.Last == nil {
+ return fmt.Errorf("backfill batch examined %d candidates without a keyset watermark", result.Scanned)
+ }
+ scanned += result.Scanned
+ settled += result.Settled
+ cursor = result.Last
+ if *checkpointFile != "" {
+ if err := writeCheckpoint(*checkpointFile, cursor); err != nil {
+ return err
+ }
+ }
+ slog.Info("delegated failure recovery settled batch committed",
+ "batch", batch, "scanned", result.Scanned, "settled", result.Settled,
+ "scanned_total", scanned, "settled_total", settled, "last_id", cursor.ID)
+ if *delay > 0 {
+ select {
+ case <-time.After(*delay):
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ }
+
+ remaining, err = delegatedrecoverybackfill.CountRemaining(ctx, pool, "")
+ if err != nil {
+ return err
+ }
+ // The remainder is the genuinely open backlog plus anything a reversible
+ // exclusion is holding, which is what the index is supposed to contain.
+ slog.Info("delegated failure recovery settled backfill finished",
+ "scanned", scanned, "settled", settled, "unsettled_remaining", remaining)
+ return nil
+}
+
+func cursorID(c *delegatedrecoverybackfill.Cursor) string {
+ if c == nil {
+ return ""
+ }
+ return c.ID
+}
+
+func cursorCreatedAt(c *delegatedrecoverybackfill.Cursor) string {
+ if c == nil {
+ return ""
+ }
+ return c.CreatedAt.Format(time.RFC3339Nano)
+}
diff --git a/server/cmd/backfill_delegated_failure_settled/main_test.go b/server/cmd/backfill_delegated_failure_settled/main_test.go
new file mode 100644
index 0000000000..7a069fd3fc
--- /dev/null
+++ b/server/cmd/backfill_delegated_failure_settled/main_test.go
@@ -0,0 +1,99 @@
+package main
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/delegatedrecoverybackfill"
+)
+
+func cursorFor(createdAt time.Time, id string) *delegatedrecoverybackfill.Cursor {
+ return &delegatedrecoverybackfill.Cursor{CreatedAt: createdAt, ID: id}
+}
+
+// A bounded run (--max-batches, SIGTERM) is only resumable if the watermark
+// outlives the process. Without this the next run restarts at the front of the
+// index — which is exactly where the rows this walk deliberately never settles
+// live, so repeated bounded runs would rescan the same prefix forever.
+func TestCheckpointRoundTripsTheWatermark(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "checkpoint.json")
+ if got, err := readCheckpoint(path); err != nil || got != nil {
+ t.Fatalf("missing checkpoint = %v, %v; want nil, nil", got, err)
+ }
+
+ createdAt := time.Date(2026, 8, 31, 9, 30, 0, 123456000, time.UTC)
+ want := cursorFor(createdAt, "6f1a0d4e-0000-4000-8000-000000000001")
+ if err := writeCheckpoint(path, want); err != nil {
+ t.Fatalf("writeCheckpoint: %v", err)
+ }
+ got, err := readCheckpoint(path)
+ if err != nil {
+ t.Fatalf("readCheckpoint: %v", err)
+ }
+ if got == nil || got.ID != want.ID || !got.CreatedAt.Equal(want.CreatedAt) {
+ t.Fatalf("checkpoint round trip = %+v, want %+v", got, want)
+ }
+}
+
+// The file is replaced atomically, so a crash mid-write cannot leave a
+// truncated watermark that resumes in the wrong place.
+func TestCheckpointWriteLeavesNoTempFilesBehind(t *testing.T) {
+ dir := t.TempDir()
+ path := filepath.Join(dir, "checkpoint.json")
+ for i := range 3 {
+ if err := writeCheckpoint(path, cursorFor(time.Unix(int64(i), 0).UTC(), "id")); err != nil {
+ t.Fatalf("writeCheckpoint %d: %v", i, err)
+ }
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("read dir: %v", err)
+ }
+ if len(entries) != 1 || entries[0].Name() != "checkpoint.json" {
+ names := make([]string, len(entries))
+ for i, e := range entries {
+ names[i] = e.Name()
+ }
+ t.Fatalf("checkpoint dir = %v, want only checkpoint.json", names)
+ }
+}
+
+func TestResolveStartPrefersExplicitFlagsOverTheCheckpointFile(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "checkpoint.json")
+ stale := cursorFor(time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC), "stale-id")
+ if err := writeCheckpoint(path, stale); err != nil {
+ t.Fatalf("writeCheckpoint: %v", err)
+ }
+
+ got, err := resolveStart(path, "2026-08-31T09:30:00Z", "override-id")
+ if err != nil {
+ t.Fatalf("resolveStart: %v", err)
+ }
+ if got == nil || got.ID != "override-id" {
+ t.Fatalf("resolveStart = %+v, want the explicit override to win", got)
+ }
+
+ got, err = resolveStart(path, "", "")
+ if err != nil {
+ t.Fatalf("resolveStart from file: %v", err)
+ }
+ if got == nil || got.ID != "stale-id" {
+ t.Fatalf("resolveStart from file = %+v, want the persisted watermark", got)
+ }
+
+ if _, err := resolveStart("", "2026-08-31T09:30:00Z", ""); err == nil {
+ t.Fatal("half an explicit cursor was accepted; it would silently resume from the wrong place")
+ }
+ if _, err := resolveStart("", "not-a-timestamp", "some-id"); err == nil {
+ t.Fatal("an unparseable --after-created-at was accepted")
+ }
+}
+
+func TestResolveStartWithoutAnySourceStartsFromTheBeginning(t *testing.T) {
+ got, err := resolveStart("", "", "")
+ if err != nil || got != nil {
+ t.Fatalf("resolveStart = %v, %v; want nil, nil", got, err)
+ }
+}
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 6edae57686..00f90513fb 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -275,6 +275,7 @@ var concurrentIndexCleanups = map[string]string{
"439_agent_runtime_offline_last_seen_index": "idx_agent_runtime_offline_last_seen",
"440_github_pr_head_sha_index": "idx_github_pull_request_head_sha",
"443_issue_project_status_index": "idx_issue_project_status",
+ "445_comment_delegated_failure_unsettled_index": "idx_comment_delegated_failure_unsettled",
}
// concurrentDownIndexCleanups covers every migration whose down direction
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index fa7853a7d5..f12d6e16d5 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -297,7 +297,7 @@ func sweepOfflineRuntimeTasks(ctx context.Context, queries *db.Queries, taskSvc
observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageOfflineTasks, startedAt, stats)
}()
- failedTasks, err := queries.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{
+ failedTasks, err := taskSvc.FailTasksForOfflineRuntimes(ctx, db.FailTasksForOfflineRuntimesParams{
ReconnectGraceSecs: reconnectGrace.Seconds(),
MaxPerTick: offlineTaskFailBatchSize,
})
@@ -325,7 +325,7 @@ func sweepExpiredRuntimeReconnectRetries(ctx context.Context, queries *db.Querie
observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageReconnectRetries, startedAt, stats)
}()
- failedTasks, err := queries.FailExpiredRuntimeReconnectRetries(ctx, db.FailExpiredRuntimeReconnectRetriesParams{
+ failedTasks, err := taskSvc.FailExpiredRuntimeReconnectRetries(ctx, db.FailExpiredRuntimeReconnectRetriesParams{
ReconnectGraceSecs: reconnectGrace.Seconds(),
RuntimeStaleSecs: staleThresholdSeconds,
MaxPerTick: reconnectRetryExpireBatchSize,
@@ -585,7 +585,7 @@ func sweepStaleTasks(ctx context.Context, queries *db.Queries, taskSvc *service.
observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageStaleTasks, startedAt, stats)
}()
- failedTasks, err := queries.FailStaleTasks(ctx, db.FailStaleTasksParams{
+ failedTasks, err := taskSvc.FailStaleTasks(ctx, db.FailStaleTasksParams{
DispatchTimeoutSecs: dispatchTimeoutSeconds,
RunningTimeoutSecs: runningTimeoutSeconds,
// Reuse the runtime stale window so the running-task backstop
@@ -622,7 +622,7 @@ func sweepExpiredQueuedTasks(ctx context.Context, queries *db.Queries, taskSvc *
observeRuntimeSweepStage(taskServiceMetrics(taskSvc), obsmetrics.RuntimeSweepStageQueuedExpiry, startedAt, stats)
}()
- failedTasks, err := queries.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
+ failedTasks, err := taskSvc.ExpireStaleQueuedTasks(ctx, db.ExpireStaleQueuedTasksParams{
ReconnectGraceSecs: reconnectGrace.Seconds(),
MaxPerTick: queuedExpireBatchSize,
})
diff --git a/server/internal/delegatedrecoverybackfill/backfill.go b/server/internal/delegatedrecoverybackfill/backfill.go
new file mode 100644
index 0000000000..37cd188888
--- /dev/null
+++ b/server/internal/delegatedrecoverybackfill/backfill.go
@@ -0,0 +1,164 @@
+// Package delegatedrecoverybackfill provides bounded, resumable batches that
+// retire delegated-failure recovery comments already closed by a terminal
+// delivery receipt.
+//
+// migrations 444/445 add comment.recovery_settled_at and the partial index that
+// only holds unsettled recovery comments, and TaskService writes the marker
+// inside every terminal task transaction. Neither reaches the history written
+// before the marker existed: those rows keep matching the index predicate and
+// keep being re-proven settled by the sweeper's outbox scan on every tick. This
+// walk marks them once.
+//
+// Run it after every backend in a rolling deployment carries the writing code.
+// Running it earlier is not harmful — an in-flight task simply gets marked by
+// whichever path reaches its terminal receipt first — but it leaves rows behind
+// that a second pass has to pick up.
+package delegatedrecoverybackfill
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+// DefaultBatchSize bounds the candidate comments examined per statement.
+//
+// Measured on a synthetic table of 500k comments / 200k tasks / 50k unsettled
+// recoveries, total walk time is flat across batch size — 50x228ms at 1000,
+// 10x1016ms at 5000, 5x2199ms at 10000, all ~11s — because the per-batch
+// agent_task_queue read is not the dominant cost. Batch size therefore only
+// trades how long a single statement holds row locks on comment, so take the
+// smallest of the equal-throughput options. The command's inter-batch delay is
+// what actually paces the walk.
+const DefaultBatchSize = 1000
+
+// Cursor is the keyset position of a walk. It is (created_at, id) rather than
+// id alone so it matches idx_comment_delegated_failure_unsettled — an id-only
+// keyset cannot use that index for both the predicate and the ordering, which
+// is the same "LIMIT bounds what is returned, not what is examined" mistake
+// this whole change set exists to remove.
+type Cursor struct {
+ CreatedAt time.Time
+ ID string
+}
+
+// Options controls one backfill batch. Zero values are production defaults.
+type Options struct {
+ BatchSize int
+ // After is the exclusive keyset watermark. Nil starts from the beginning.
+ After *Cursor
+ // Schema is a trusted identifier override used only by tests.
+ Schema string
+}
+
+// BatchResult advances a caller's keyset walk.
+//
+// Last tracks the SCANNED candidates rather than the settled ones: a recovery
+// that is genuinely still pending — or that is currently excluded only by a
+// reversible condition such as its issue sitting in 'done' — must never be
+// marked, and must not stall the walk either. Last is nil only when the batch
+// found no candidates at all, which is how the caller detects the end.
+type BatchResult struct {
+ Scanned int64
+ Settled int64
+ Last *Cursor
+}
+
+func qualify(schema, table string) string {
+ if schema == "" {
+ return table
+ }
+ return fmt.Sprintf("%q.%s", schema, table)
+}
+
+// Batch settles at most BatchSize candidate recovery comments.
+//
+// A candidate is settled only when some terminal task already recorded it in
+// delivered_comment_ids — the one exclusion in
+// ListPendingDelegatedFailureRecoveries that cannot be taken back. Every other
+// exclusion that query applies is reversible, so a row it currently skips for
+// another reason is deliberately left pending here.
+//
+// The receipt lookup is inverted relative to the runtime query: instead of
+// asking "does any terminal task hold THIS comment" once per candidate — which
+// re-reads agent_task_queue, the largest table in the database, for every row
+// examined — it reads agent_task_queue once per BATCH and hash-joins the
+// delivered ids back against the candidates. Both CTEs are MATERIALIZED so that
+// stays true regardless of how the planner would otherwise inline them.
+func Batch(ctx context.Context, pool *pgxpool.Pool, opts Options) (BatchResult, error) {
+ batchSize := opts.BatchSize
+ if batchSize <= 0 {
+ batchSize = DefaultBatchSize
+ }
+ comment := qualify(opts.Schema, "comment")
+ task := qualify(opts.Schema, "agent_task_queue")
+
+ var afterCreatedAt any
+ var afterID any
+ if opts.After != nil {
+ afterCreatedAt = opts.After.CreatedAt
+ afterID = opts.After.ID
+ }
+
+ query := fmt.Sprintf(`
+WITH batch AS MATERIALIZED (
+ SELECT id, created_at
+ FROM %s
+ WHERE author_type = 'system'
+ AND type = 'progress_update'
+ AND source_task_id IS NOT NULL
+ AND recovery_settled_at IS NULL
+ AND ($2::timestamptz IS NULL OR (created_at, id) > ($2::timestamptz, $3::uuid))
+ ORDER BY created_at, id
+ LIMIT $1
+), receipts AS MATERIALIZED (
+ SELECT DISTINCT batch.id
+ FROM %s covering
+ CROSS JOIN LATERAL unnest(covering.delivered_comment_ids) AS delivered(id)
+ JOIN batch ON batch.id = delivered.id
+ WHERE covering.status IN ('completed', 'failed', 'cancelled')
+ AND covering.delivered_comment_ids && (SELECT array_agg(id) FROM batch)
+), settled AS (
+ UPDATE %s recovery
+ SET recovery_settled_at = now()
+ WHERE recovery.id IN (SELECT id FROM receipts)
+ AND recovery.recovery_settled_at IS NULL
+ RETURNING recovery.id
+)
+SELECT (SELECT count(*)::bigint FROM batch),
+ (SELECT count(*)::bigint FROM settled),
+ (SELECT created_at FROM batch ORDER BY created_at DESC, id DESC LIMIT 1),
+ COALESCE((SELECT id::text FROM batch ORDER BY created_at DESC, id DESC LIMIT 1), '')`,
+ comment, task, comment)
+
+ var result BatchResult
+ var lastCreatedAt *time.Time
+ var lastID string
+ if err := pool.QueryRow(ctx, query, batchSize, afterCreatedAt, afterID).
+ Scan(&result.Scanned, &result.Settled, &lastCreatedAt, &lastID); err != nil {
+ return BatchResult{}, fmt.Errorf("backfill delegated failure recovery settled batch: %w", err)
+ }
+ if lastCreatedAt != nil && lastID != "" {
+ result.Last = &Cursor{CreatedAt: *lastCreatedAt, ID: lastID}
+ }
+ return result, nil
+}
+
+// CountRemaining reports how many recovery comments are still unsettled, which
+// is exactly the row count of idx_comment_delegated_failure_unsettled. After a
+// completed walk this should be the genuinely pending backlog, not history.
+func CountRemaining(ctx context.Context, pool *pgxpool.Pool, schema string) (int64, error) {
+ var count int64
+ if err := pool.QueryRow(ctx, fmt.Sprintf(`
+SELECT count(*)
+FROM %s
+WHERE author_type = 'system'
+ AND type = 'progress_update'
+ AND source_task_id IS NOT NULL
+ AND recovery_settled_at IS NULL`, qualify(schema, "comment"))).Scan(&count); err != nil {
+ return 0, fmt.Errorf("count unsettled delegated failure recoveries: %w", err)
+ }
+ return count, nil
+}
diff --git a/server/internal/delegatedrecoverybackfill/backfill_test.go b/server/internal/delegatedrecoverybackfill/backfill_test.go
new file mode 100644
index 0000000000..04fbb3f3c2
--- /dev/null
+++ b/server/internal/delegatedrecoverybackfill/backfill_test.go
@@ -0,0 +1,262 @@
+package delegatedrecoverybackfill
+
+import (
+ "context"
+ "fmt"
+ "math/rand/v2"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+)
+
+func testPool(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dbURL := os.Getenv("DATABASE_URL")
+ if dbURL == "" {
+ dbURL = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ pool, err := pgxpool.New(context.Background(), dbURL)
+ if err != nil {
+ t.Skipf("connect to database: %v", err)
+ }
+ if err := pool.Ping(context.Background()); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ return pool
+}
+
+// fixture mirrors only the columns the walk reads, in a throwaway schema, so
+// the test never touches the real comment or agent_task_queue tables.
+func fixture(t *testing.T, pool *pgxpool.Pool) string {
+ t.Helper()
+ ctx := context.Background()
+ schema := fmt.Sprintf("delegated_recovery_backfill_%d_%d", time.Now().UnixNano(), rand.IntN(1_000_000))
+ if _, err := pool.Exec(ctx, fmt.Sprintf(`CREATE SCHEMA %q`, schema)); err != nil {
+ t.Fatalf("create schema: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), fmt.Sprintf(`DROP SCHEMA %q CASCADE`, schema))
+ })
+ if _, err := pool.Exec(ctx, fmt.Sprintf(`
+CREATE TABLE %q.comment (
+ id UUID PRIMARY KEY,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ author_type TEXT NOT NULL,
+ type TEXT NOT NULL,
+ source_task_id UUID,
+ recovery_settled_at TIMESTAMPTZ
+);
+CREATE TABLE %q.agent_task_queue (
+ id UUID PRIMARY KEY,
+ status TEXT NOT NULL,
+ delivered_comment_ids UUID[] NOT NULL DEFAULT '{}'
+)`, schema, schema)); err != nil {
+ t.Fatalf("create fixture: %v", err)
+ }
+ return schema
+}
+
+func id(n int) string {
+ return fmt.Sprintf("00000000-0000-0000-0000-%012d", n)
+}
+
+func seed(t *testing.T, pool *pgxpool.Pool, schema, comments, tasks string) {
+ t.Helper()
+ if _, err := pool.Exec(context.Background(), fmt.Sprintf(
+ `INSERT INTO %q.comment (id, created_at, author_type, type, source_task_id) VALUES %s`, schema, comments)); err != nil {
+ t.Fatalf("seed comments: %v", err)
+ }
+ if tasks == "" {
+ return
+ }
+ if _, err := pool.Exec(context.Background(), fmt.Sprintf(
+ `INSERT INTO %q.agent_task_queue (id, status, delivered_comment_ids) VALUES %s`, schema, tasks)); err != nil {
+ t.Fatalf("seed tasks: %v", err)
+ }
+}
+
+func unsettled(t *testing.T, pool *pgxpool.Pool, schema string) []string {
+ t.Helper()
+ rows, err := pool.Query(context.Background(), fmt.Sprintf(`
+SELECT id::text FROM %q.comment
+WHERE author_type = 'system' AND type = 'progress_update'
+ AND source_task_id IS NOT NULL AND recovery_settled_at IS NULL
+ORDER BY id`, schema))
+ if err != nil {
+ t.Fatalf("read unsettled: %v", err)
+ }
+ defer rows.Close()
+ var ids []string
+ for rows.Next() {
+ var got string
+ if err := rows.Scan(&got); err != nil {
+ t.Fatalf("scan unsettled: %v", err)
+ }
+ ids = append(ids, got)
+ }
+ return ids
+}
+
+// The walk retires only recovery comments a terminal task already received.
+// Everything else — a live receipt, a comment nobody delivered, an ordinary
+// comment — has to survive, because those are exactly the rows the sweeper
+// still needs to see.
+func TestBatchSettlesOnlyTerminallyDeliveredRecoveries(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ schema := fixture(t, pool)
+
+ seed(t, pool, schema, fmt.Sprintf(`
+('%s', '2026-01-01T00:00:01Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:02Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:03Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:04Z', 'member', 'comment', NULL)`,
+ id(1), id(90), // delivered to a completed task -> settle
+ id(2), id(90), // delivered to a still-running task -> keep
+ id(3), id(90), // never delivered -> keep
+ id(4)), fmt.Sprintf(`
+('%s', 'completed', ARRAY['%s']::uuid[]),
+('%s', 'running', ARRAY['%s']::uuid[])`,
+ id(80), id(1),
+ id(81), id(2)))
+
+ result, err := Batch(ctx, pool, Options{Schema: schema})
+ if err != nil {
+ t.Fatalf("Batch: %v", err)
+ }
+ if result.Scanned != 3 || result.Settled != 1 {
+ t.Fatalf("batch = scanned %d settled %d, want 3/1", result.Scanned, result.Settled)
+ }
+ if result.Last == nil || result.Last.ID != id(3) {
+ t.Fatalf("watermark = %v, want the highest SCANNED candidate %q", result.Last, id(3))
+ }
+ if got := unsettled(t, pool, schema); len(got) != 2 || got[0] != id(2) || got[1] != id(3) {
+ t.Fatalf("unsettled = %v, want the live receipt and the undelivered comment", got)
+ }
+ remaining, err := CountRemaining(ctx, pool, schema)
+ if err != nil {
+ t.Fatalf("CountRemaining: %v", err)
+ }
+ if remaining != 2 {
+ t.Fatalf("CountRemaining = %d, want 2", remaining)
+ }
+}
+
+// The watermark has to advance over candidates the walk deliberately leaves
+// alone. Keyed on settled rows instead, a batch holding only untouchable
+// candidates would hand back the same watermark forever and never terminate.
+func TestBatchWatermarkAdvancesPastUnsettleableCandidates(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ schema := fixture(t, pool)
+
+ seed(t, pool, schema, fmt.Sprintf(`
+('%s', '2026-01-01T00:00:01Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:02Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:03Z', 'system', 'progress_update', '%s')`,
+ id(1), id(90),
+ id(2), id(90),
+ id(3), id(90)), fmt.Sprintf(`
+('%s', 'cancelled', ARRAY['%s']::uuid[])`, id(80), id(3)))
+
+ var after *Cursor
+ var scanned, settled int64
+ batches := 0
+ for batches < 5 {
+ result, err := Batch(ctx, pool, Options{BatchSize: 1, After: after, Schema: schema})
+ if err != nil {
+ t.Fatalf("batch %d: %v", batches, err)
+ }
+ if result.Scanned == 0 {
+ break
+ }
+ batches++
+ scanned += result.Scanned
+ settled += result.Settled
+ after = result.Last
+ }
+ if batches != 3 {
+ t.Fatalf("walk took %d batches, want one per candidate (3)", batches)
+ }
+ if scanned != 3 || settled != 1 {
+ t.Fatalf("walk = scanned %d settled %d, want 3/1", scanned, settled)
+ }
+}
+
+// The per-batch receipt scan reads every terminal task's delivered ids, not
+// just the ones in this batch. Those extra ids must be discarded: settling a
+// candidate the current batch never examined would move it behind the keyset
+// watermark without the walk ever having looked at it.
+func TestBatchSettlesNothingOutsideTheCurrentBatch(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ schema := fixture(t, pool)
+
+ seed(t, pool, schema, fmt.Sprintf(`
+('%s', '2026-01-01T00:00:01Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:02Z', 'system', 'progress_update', '%s')`,
+ id(1), id(90),
+ id(2), id(90)), fmt.Sprintf(`
+('%s', 'completed', ARRAY['%s','%s']::uuid[])`, id(80), id(1), id(2)))
+
+ // One candidate per batch, while the single covering task carries both.
+ result, err := Batch(ctx, pool, Options{BatchSize: 1, Schema: schema})
+ if err != nil {
+ t.Fatalf("Batch: %v", err)
+ }
+ if result.Scanned != 1 || result.Settled != 1 {
+ t.Fatalf("batch = scanned %d settled %d, want 1/1", result.Scanned, result.Settled)
+ }
+ if got := unsettled(t, pool, schema); len(got) != 1 || got[0] != id(2) {
+ t.Fatalf("unsettled = %v, want only the candidate this batch never examined (%s)", got, id(2))
+ }
+}
+
+// The keyset must be (created_at, id) to match
+// idx_comment_delegated_failure_unsettled. Ordering by id alone would walk a
+// different sequence than the index provides, so a run resumed from a
+// checkpoint could skip candidates entirely.
+func TestBatchOrdersByCreatedAtNotID(t *testing.T) {
+ pool := testPool(t)
+ defer pool.Close()
+ ctx := context.Background()
+ schema := fixture(t, pool)
+
+ // created_at order is the reverse of id order.
+ seed(t, pool, schema, fmt.Sprintf(`
+('%s', '2026-01-01T00:00:03Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:02Z', 'system', 'progress_update', '%s'),
+('%s', '2026-01-01T00:00:01Z', 'system', 'progress_update', '%s')`,
+ id(1), id(90),
+ id(2), id(90),
+ id(3), id(90)), "")
+
+ var seen []string
+ var after *Cursor
+ for range 3 {
+ result, err := Batch(ctx, pool, Options{BatchSize: 1, After: after, Schema: schema})
+ if err != nil {
+ t.Fatalf("Batch: %v", err)
+ }
+ if result.Scanned == 0 {
+ break
+ }
+ seen = append(seen, result.Last.ID)
+ after = result.Last
+ }
+ want := []string{id(3), id(2), id(1)}
+ if len(seen) != len(want) {
+ t.Fatalf("walked %v, want %v", seen, want)
+ }
+ for i := range want {
+ if seen[i] != want[i] {
+ t.Fatalf("walked %v, want created_at order %v", seen, want)
+ }
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index 5cadc877c2..9df1275057 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -2352,11 +2352,12 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {
return
}
- // Cancel all pending/active tasks for this agent. Discard the returned
- // rows here — the agent:archived event below already triggers a full
- // active-tasks invalidation on every connected client, so per-task
- // task:cancelled events would be redundant noise.
- if cancelled, err := h.Queries.CancelAgentTasksByAgent(r.Context(), agent.ID); err != nil {
+ // Cancel all pending/active tasks for this agent. The cancel and its
+ // delegated-failure settlement commit together — a settlement issued after
+ // the cancel committed could never be repaired. Per-task task:cancelled
+ // events are still skipped: the agent:archived event below already triggers
+ // a full active-tasks invalidation on every connected client.
+ if cancelled, err := h.TaskService.CancelTasksForArchivedAgent(r.Context(), agent.ID); err != nil {
slog.Warn("cancel agent tasks on archive failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
} else {
h.TaskService.CaptureCancelledTasks(r.Context(), cancelled)
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index d790bcc84e..57138fb333 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -613,6 +613,10 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusInternalServerError, "failed to cancel queued tasks for the archived session")
return
}
+ if err = service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to settle delegated failure recoveries")
+ return
+ }
case errors.Is(bindingErr, pgx.ErrNoRows):
// A web-only chat has no room, no adapter and nowhere for a late
// answer to land, so there is nothing here to protect anyone from
@@ -718,6 +722,10 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to cancel chat session tasks")
return
}
+ if err := service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to settle delegated failure recoveries")
+ return
+ }
// channel_chat_session_binding used to carry a chat_session FK with
// ON DELETE CASCADE; MUL-3515 §4 dropped every channel_* foreign key, so
diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.go
index 35f45bd3bd..edde459933 100644
--- a/server/internal/handler/comment.go
+++ b/server/internal/handler/comment.go
@@ -3380,6 +3380,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
}
if err == nil && oldContent != req.Content && strictContentEdit {
cancelled, err = qtx.CancelAgentTasksByTriggerComment(r.Context(), existing.ID)
+ if err == nil {
+ err = service.SettleDeliveredDelegatedFailureRecoveries(r.Context(), qtx, cancelled...)
+ }
}
if err == nil && replaceAttachments {
var changed int64
diff --git a/server/internal/handler/task_lifecycle.go b/server/internal/handler/task_lifecycle.go
index 5686375c80..03e4fbfbb9 100644
--- a/server/internal/handler/task_lifecycle.go
+++ b/server/internal/handler/task_lifecycle.go
@@ -30,7 +30,7 @@ func (h *Handler) RecoverOrphanedTasks(w http.ResponseWriter, r *http.Request) {
return
}
- rows, err := h.Queries.RecoverOrphanedTasksForRuntime(r.Context(), parseUUID(runtimeID))
+ rows, err := h.TaskService.RecoverOrphanedTasksForRuntime(r.Context(), parseUUID(runtimeID))
if err != nil {
slog.Warn("recover-orphans failed", "runtime_id", runtimeID, "error", err)
writeError(w, http.StatusInternalServerError, "recover orphans failed")
diff --git a/server/internal/handler/workspace_revoke.go b/server/internal/handler/workspace_revoke.go
index cc0ea86962..f96b335f9c 100644
--- a/server/internal/handler/workspace_revoke.go
+++ b/server/internal/handler/workspace_revoke.go
@@ -6,6 +6,7 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgtype"
+ "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"
)
@@ -109,6 +110,9 @@ func (h *Handler) revokeAndRemoveMember(ctx context.Context, workspaceID, userID
if err != nil {
return empty, err
}
+ if err = service.SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, result.CancelledTasks...); err != nil {
+ return empty, err
+ }
result.OfflineRuntimeIDs, err = qtx.ForceOfflineRuntimesByIDs(ctx, runtimeIDs)
if err != nil {
diff --git a/server/internal/service/delegated_failure_recovery_settled_test.go b/server/internal/service/delegated_failure_recovery_settled_test.go
new file mode 100644
index 0000000000..7a6dea0564
--- /dev/null
+++ b/server/internal/service/delegated_failure_recovery_settled_test.go
@@ -0,0 +1,353 @@
+package service
+
+import (
+ "context"
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// seedRecoverySignal drives one delegated failure to the point where the
+// durable recovery comment and its coordinator task exist, and returns both.
+func (f *delegatedFailureFixture) seedRecoverySignal(t *testing.T, svc *TaskService) (recoveryTaskID, recoveryCommentID pgtype.UUID) {
+ t.Helper()
+ ctx := context.Background()
+ failedID := f.insertWorkerTask(t, "failed", "comment", 1, 2)
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET failure_reason = 'agent_error.process_failure', error = 'worker exited', completed_at = now()
+ WHERE id = $1`, failedID); err != nil {
+ t.Fatalf("stamp failed task: %v", err)
+ }
+ failed, err := svc.Queries.GetAgentTask(ctx, failedID)
+ if err != nil {
+ t.Fatalf("load failed task: %v", err)
+ }
+ if handled, err := svc.recoverDelegatedTaskFailure(ctx, failed); err != nil || !handled {
+ t.Fatalf("initial recovery = handled %v err %v", handled, err)
+ }
+ if err := f.pool.QueryRow(ctx, `
+ SELECT task.id, recovery.id
+ FROM agent_task_queue task
+ JOIN comment recovery ON recovery.id = task.trigger_comment_id
+ WHERE task.trigger_evidence_kind = 'delegated_failure'
+ AND task.trigger_evidence_ref_id = $1`, failedID).Scan(&recoveryTaskID, &recoveryCommentID); err != nil {
+ t.Fatalf("load recovery task/comment: %v", err)
+ }
+ return recoveryTaskID, recoveryCommentID
+}
+
+func (f *delegatedFailureFixture) settled(t *testing.T, commentID pgtype.UUID) bool {
+ t.Helper()
+ var marked bool
+ if err := f.pool.QueryRow(context.Background(),
+ `SELECT recovery_settled_at IS NOT NULL FROM comment WHERE id = $1`, commentID).Scan(&marked); err != nil {
+ t.Fatalf("read recovery_settled_at: %v", err)
+ }
+ return marked
+}
+
+// markDelivered simulates the dispatch receipt a daemon writes before it runs
+// the coordinator task, and puts the task in the status the terminal callbacks
+// expect.
+func (f *delegatedFailureFixture) markDelivered(t *testing.T, taskID, commentID pgtype.UUID) {
+ t.Helper()
+ if _, err := f.pool.Exec(context.Background(), `
+ UPDATE agent_task_queue
+ SET status = 'running', started_at = now(), dispatched_at = now(),
+ delivered_comment_ids = ARRAY[$2]::uuid[]
+ WHERE id = $1`, taskID, commentID); err != nil {
+ t.Fatalf("mark recovery delivered: %v", err)
+ }
+}
+
+// A coordinator task that received the recovery comment and then reached a
+// terminal status has consumed the obligation. The marker is what lets the
+// outbox scan skip that comment through the partial index instead of
+// re-proving it settled through four joins on every tick.
+func TestTerminalCoordinatorTaskSettlesDeliveredRecovery(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ finalize func(t *testing.T, svc *TaskService, taskID pgtype.UUID)
+ }{
+ {"complete", func(t *testing.T, svc *TaskService, taskID pgtype.UUID) {
+ if _, err := svc.CompleteTask(context.Background(), taskID, []byte(`{"ok":true}`), "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ }},
+ {"fail", func(t *testing.T, svc *TaskService, taskID pgtype.UUID) {
+ if _, err := svc.FailTask(context.Background(), taskID, "coordinator crashed", "", "", "", "agent_error.process_failure", false, "", ""); err != nil {
+ t.Fatalf("FailTask: %v", err)
+ }
+ }},
+ {"cancel", func(t *testing.T, svc *TaskService, taskID pgtype.UUID) {
+ if _, err := svc.CancelTask(context.Background(), taskID); err != nil {
+ t.Fatalf("CancelTask: %v", err)
+ }
+ }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+ f.markDelivered(t, recoveryTaskID, recoveryCommentID)
+
+ if f.settled(t, recoveryCommentID) {
+ t.Fatal("recovery settled before the coordinator task reached a terminal status")
+ }
+ tc.finalize(t, svc, recoveryTaskID)
+
+ if !f.settled(t, recoveryCommentID) {
+ t.Fatalf("delivered recovery not settled after %s", tc.name)
+ }
+ pending, err := svc.Queries.ListPendingDelegatedFailureRecoveries(ctx, 100)
+ if err != nil {
+ t.Fatalf("ListPendingDelegatedFailureRecoveries: %v", err)
+ }
+ for _, c := range pending {
+ if c.ID == recoveryCommentID {
+ t.Fatalf("settled recovery %s still scanned as pending", util.UUIDToString(recoveryCommentID))
+ }
+ }
+ })
+ }
+}
+
+// The marker must never run ahead of delivery. A task that only planned the
+// comment and was cancelled automatically leaves the obligation open, and the
+// sweeper still has to replay it — this is the regression that would silently
+// drop crash recovery.
+func TestPlannedButUndeliveredRecoveryStaysPending(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+
+ if _, err := svc.CancelTask(ctx, recoveryTaskID); err != nil {
+ t.Fatalf("CancelTask: %v", err)
+ }
+ if f.settled(t, recoveryCommentID) {
+ t.Fatal("automatic cancellation settled a recovery it never delivered")
+ }
+
+ result, err := svc.RecoverPendingDelegatedFailures(ctx, 100)
+ if err != nil {
+ t.Fatalf("RecoverPendingDelegatedFailures: %v", err)
+ }
+ if result.Replayed != 1 {
+ t.Fatalf("sweep after undelivered cancellation = %+v, want one replay", result)
+ }
+}
+
+// The user's explicit cancellation is a terminal acknowledgement: the receipt
+// is appended and the comment retires in the same transaction.
+func TestUserCancelledRecoveryIsSettled(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+
+ if _, err := svc.CancelTaskByUser(ctx, recoveryTaskID); err != nil {
+ t.Fatalf("CancelTaskByUser: %v", err)
+ }
+ if !f.settled(t, recoveryCommentID) {
+ t.Fatal("user cancellation did not settle the recovery signal")
+ }
+ if result, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil || result != (DelegatedFailureRecoverySweepResult{}) {
+ t.Fatalf("sweep after user cancel = %+v, %v; want zero result, nil", result, err)
+ }
+}
+
+// Exhaustion writes its receipt onto an attempt row that may still be running,
+// so the task-scoped settle cannot see it. It has to retire the comment
+// directly or the outbox keeps re-checking a permanently stopped obligation.
+func TestExhaustedRecoveryIsSettled(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ _, recoveryCommentID := f.seedRecoverySignal(t, svc)
+
+ for attempt := 1; attempt <= delegatedFailureRecoveryMaxTaskAttempts; attempt++ {
+ var currentTaskID pgtype.UUID
+ if err := f.pool.QueryRow(ctx, `
+ SELECT id FROM agent_task_queue
+ WHERE trigger_comment_id = $1 AND status = 'queued'
+ ORDER BY created_at DESC, id DESC
+ LIMIT 1`, recoveryCommentID).Scan(&currentTaskID); err != nil {
+ t.Fatalf("load recovery attempt %d: %v", attempt, err)
+ }
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = 'failed', completed_at = now(), failure_reason = 'queued_expired',
+ delivered_comment_ids = '{}'
+ WHERE id = $1`, currentTaskID); err != nil {
+ t.Fatalf("fail recovery attempt %d: %v", attempt, err)
+ }
+ if _, err := svc.RecoverPendingDelegatedFailures(ctx, 100); err != nil {
+ t.Fatalf("recovery sweep after attempt %d: %v", attempt, err)
+ }
+ }
+
+ if !f.settled(t, recoveryCommentID) {
+ t.Fatal("exhausted recovery was not settled")
+ }
+ pending, err := svc.Queries.ListPendingDelegatedFailureRecoveries(ctx, 100)
+ if err != nil {
+ t.Fatalf("ListPendingDelegatedFailureRecoveries: %v", err)
+ }
+ for _, c := range pending {
+ if c.ID == recoveryCommentID {
+ t.Fatal("exhausted recovery still scanned as pending")
+ }
+ }
+}
+
+// A manual rerun clears the pending slot with its own bulk cancel. That
+// statement terminates a coordinator task that may already hold a recovery
+// receipt, so it has to settle like every other terminal path — otherwise the
+// row stays in the unsettled index forever and the index regrows the unbounded
+// history this change set removes.
+func TestManualRerunSettlesDeliveredRecovery(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+
+ // The rerun path only clears tasks that have not begun executing, so leave
+ // the coordinator task queued and give it the dispatch receipt.
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE agent_task_queue SET delivered_comment_ids = ARRAY[$2]::uuid[] WHERE id = $1`,
+ recoveryTaskID, recoveryCommentID); err != nil {
+ t.Fatalf("mark recovery delivered: %v", err)
+ }
+
+ issueID, err := util.ParseUUID(f.issueID)
+ if err != nil {
+ t.Fatalf("parse issue id: %v", err)
+ }
+ actorID, err := util.ParseUUID(f.userID)
+ if err != nil {
+ t.Fatalf("parse actor id: %v", err)
+ }
+ if _, err := svc.RerunIssue(ctx, issueID, pgtype.UUID{}, pgtype.UUID{}, actorID, func(db.Agent) bool { return true }); err != nil {
+ t.Fatalf("RerunIssue: %v", err)
+ }
+
+ var status string
+ if err := f.pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, recoveryTaskID).Scan(&status); err != nil {
+ t.Fatalf("read coordinator task status: %v", err)
+ }
+ if status != "cancelled" {
+ t.Fatalf("rerun left the pending coordinator task in %q; the test no longer covers the cancel path", status)
+ }
+ if !f.settled(t, recoveryCommentID) {
+ t.Fatal("manual rerun cancelled a task holding a recovery receipt without settling it")
+ }
+}
+
+// Archiving an agent cancels its tasks with a bulk statement. The cancel and
+// the settlement have to commit together: CaptureCancelledTasks runs after the
+// commit, so a settlement there could neither be rolled back nor repaired.
+func TestArchivedAgentCancelSettlesDeliveredRecovery(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+ f.markDelivered(t, recoveryTaskID, recoveryCommentID)
+
+ agentID, err := util.ParseUUID(f.coordinator)
+ if err != nil {
+ t.Fatalf("parse agent id: %v", err)
+ }
+ cancelled, err := svc.CancelTasksForArchivedAgent(ctx, agentID)
+ if err != nil {
+ t.Fatalf("CancelTasksForArchivedAgent: %v", err)
+ }
+ if len(cancelled) == 0 {
+ t.Fatal("archive cancelled nothing; the test no longer covers the cancel path")
+ }
+ if !f.settled(t, recoveryCommentID) {
+ t.Fatal("archive cancellation did not settle the delivered recovery receipt")
+ }
+}
+
+// The settlement marker is monotonic — nothing can undo it — so the terminal
+// requirement has to live in the SQL rather than in caller discipline. A
+// dispatched task's receipt is still replaceable by a reclaiming daemon, so
+// settling one would freeze that window into a permanently lost recovery.
+func TestNonTerminalTaskWithAReceiptIsNotSettled(t *testing.T) {
+ for _, status := range []string{"dispatched", "running"} {
+ t.Run(status, func(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE agent_task_queue
+ SET status = $2, dispatched_at = now(), delivered_comment_ids = ARRAY[$3]::uuid[]
+ WHERE id = $1`, recoveryTaskID, status, recoveryCommentID); err != nil {
+ t.Fatalf("stage %s task: %v", status, err)
+ }
+
+ task, err := svc.Queries.GetAgentTask(ctx, recoveryTaskID)
+ if err != nil {
+ t.Fatalf("load task: %v", err)
+ }
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, svc.Queries, task); err != nil {
+ t.Fatalf("SettleDeliveredDelegatedFailureRecoveries: %v", err)
+ }
+ if f.settled(t, recoveryCommentID) {
+ t.Fatalf("a %s task's receipt was settled; a reclaim would now lose the recovery", status)
+ }
+ })
+ }
+}
+
+// The atomicity that replaced the old best-effort call: if settlement cannot
+// commit, the terminal write must not commit either. Otherwise the stranded
+// receipt is unreachable — the outbox scan excludes a comment whose covering
+// task is terminal and holds it, so it would never replay and never settle.
+func TestBulkCancelRollsBackWhenSettlementFails(t *testing.T) {
+ f, svc := seedDelegatedFailureFixture(t)
+ ctx := context.Background()
+ recoveryTaskID, recoveryCommentID := f.seedRecoverySignal(t, svc)
+ f.markDelivered(t, recoveryTaskID, recoveryCommentID)
+
+ // A trigger that fails only on the settlement UPDATE, so the cancel inside
+ // the same transaction has to roll back with it.
+ if _, err := f.pool.Exec(ctx, `
+ CREATE OR REPLACE FUNCTION reject_recovery_settlement() RETURNS trigger AS $$
+ BEGIN RAISE EXCEPTION 'settlement rejected'; END;
+ $$ LANGUAGE plpgsql`); err != nil {
+ t.Fatalf("create settlement trigger function: %v", err)
+ }
+ if _, err := f.pool.Exec(ctx, `
+ CREATE TRIGGER reject_recovery_settlement
+ BEFORE UPDATE OF recovery_settled_at ON comment
+ FOR EACH ROW EXECUTE FUNCTION reject_recovery_settlement()`); err != nil {
+ t.Fatalf("install settlement trigger: %v", err)
+ }
+ // Drop the function as well as the trigger: the test database is shared, so
+ // a leftover reject_recovery_settlement() would outlive this test and stay
+ // attachable to comment by any later run.
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ _, _ = f.pool.Exec(cleanupCtx, `DROP TRIGGER IF EXISTS reject_recovery_settlement ON comment`)
+ _, _ = f.pool.Exec(cleanupCtx, `DROP FUNCTION IF EXISTS reject_recovery_settlement()`)
+ })
+
+ agentID, err := util.ParseUUID(f.coordinator)
+ if err != nil {
+ t.Fatalf("parse agent id: %v", err)
+ }
+ if _, err := svc.CancelTasksForArchivedAgent(ctx, agentID); err == nil {
+ t.Fatal("bulk cancel reported success while its settlement failed")
+ }
+
+ var status string
+ if err := f.pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, recoveryTaskID).Scan(&status); err != nil {
+ t.Fatalf("read task status: %v", err)
+ }
+ if status == "cancelled" {
+ t.Fatal("the cancel committed without its settlement, stranding the receipt permanently")
+ }
+ if f.settled(t, recoveryCommentID) {
+ t.Fatal("settlement committed despite the failure")
+ }
+}
diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.go
index 834c252568..5079fe066f 100644
--- a/server/internal/service/runtime_teardown.go
+++ b/server/internal/service/runtime_teardown.go
@@ -84,6 +84,9 @@ func TeardownRuntime(ctx context.Context, qtx *db.Queries, runtimeID pgtype.UUID
if err != nil {
return out, fmt.Errorf("cancel tasks: %w", err)
}
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...); err != nil {
+ return out, err
+ }
out.CancelledTasks = cancelled
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index a4f0b3becf..346d916daf 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2544,8 +2544,20 @@ func (s *TaskService) OpenMikaOnboardingChat(ctx context.Context, session db.Cha
// `multica agent update <id> --status idle` to unwedge. It now reconciles agent
// status and broadcasts task:cancelled, matching CancelTask and RerunIssue.
func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UUID) error {
- cancelled, err := s.Queries.CancelAgentTasksByIssue(ctx, issueID)
- if err != nil {
+ var cancelled []db.AgentTaskQueue
+ // The cancel and its settlement commit together: a settlement that failed
+ // after the cancel committed could never be repaired, because the outbox
+ // scan excludes a comment whose covering task is terminal and already holds
+ // the receipt. It would neither replay nor settle — it would sit in the
+ // partial index forever.
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelAgentTasksByIssue(ctx, issueID)
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)
+ }); err != nil {
return err
}
for _, t := range cancelled {
@@ -2588,8 +2600,15 @@ func distinctAgentIDs(cancelled []db.AgentTaskQueue) []pgtype.UUID {
//
// Returns the cancelled rows so callers can report counts / log them.
func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
- cancelled, err := s.Queries.CancelAgentTasksByAgent(ctx, agentID)
- if err != nil {
+ var cancelled []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelAgentTasksByAgent(ctx, agentID)
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)
+ }); err != nil {
return nil, err
}
for _, t := range cancelled {
@@ -2609,8 +2628,15 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UU
// retained for call-site stability. It must run before deletion clears the
// trigger FK; the returned rows let the handler re-route every surviving input.
func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
- cancelled, err := s.Queries.CancelAgentTasksByTriggerComment(ctx, commentID)
- if err != nil {
+ var cancelled []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelAgentTasksByTriggerComment(ctx, commentID)
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)
+ }); err != nil {
return nil, err
}
for _, t := range cancelled {
@@ -2657,6 +2683,11 @@ func (s *TaskService) BroadcastTaskQueued(ctx context.Context, task db.AgentTask
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
}
+// CaptureCancelledTasks records analytics for an already-committed bulk
+// cancellation. It deliberately does NOT settle delegated-failure recoveries:
+// by the time it runs the cancel has committed, so a failure here could not be
+// rolled back and the stranded receipt could never be repaired. Callers settle
+// inside the transaction that performs the cancel.
func (s *TaskService) CaptureCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
for _, t := range cancelled {
s.captureTaskCancelled(ctx, t)
@@ -2826,6 +2857,11 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
return err
}
task = cancelled
+ // CancelAgentTaskByUser appends the recovery receipt in the same
+ // statement, so the returned row already carries it.
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled); err != nil {
+ return err
+ }
if !cancelled.ChatSessionID.Valid {
return nil
}
@@ -2885,6 +2921,9 @@ func (s *TaskService) CancelQueuedChatTasks(ctx context.Context, sessionID, agen
if err != nil {
return fmt.Errorf("cancel queued chat tasks: %w", err)
}
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, tasks...); err != nil {
+ return err
+ }
for _, task := range tasks {
if _, err := s.settleQueuedChatInput(ctx, qtx, task, "remove"); err != nil {
return err
@@ -4209,6 +4248,12 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
task = t
+ // Atomic with the status flip: a crash between the two would leave a
+ // finished obligation looking pending forever.
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, t); err != nil {
+ return err
+ }
+
if t.ChatSessionID.Valid {
// Pin the chat_session's runtime_id alongside the session_id so the
// next claim can apply the runtime-guard. Both fields move together:
@@ -4688,6 +4733,14 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
}
task = t
+ // Atomic with the status flip, same as the completion path. A failed
+ // coordinator that already received the recovery comment has consumed
+ // the obligation: the pre-existing delivered_comment_ids coverage check
+ // never looked at the covering task's status either.
+ if err := SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, t); err != nil {
+ return err
+ }
+
// Keep resume-unsafe sessions on the task row for observability, but
// do not promote them to the chat-level resume pointer.
//
@@ -5477,9 +5530,20 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, sourc
// working on; interrupting an in-flight run is what CancelTask /
// `multica issue cancel-task` is for.
clearPendingSlot := func() int {
- cancelled, cerr := s.Queries.CancelPendingTasksByIssueAndAgent(ctx, db.CancelPendingTasksByIssueAndAgentParams{
- IssueID: issueID,
- AgentID: agentID,
+ var cancelled []db.AgentTaskQueue
+ // Atomic with the cancel: a pending coordinator task can already hold a
+ // recovery receipt, and nothing downstream could repair a settlement
+ // that failed after this committed.
+ cerr := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ cancelled, err = qtx.CancelPendingTasksByIssueAndAgent(ctx, db.CancelPendingTasksByIssueAndAgentParams{
+ IssueID: issueID,
+ AgentID: agentID,
+ })
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, cancelled...)
})
if cerr != nil {
slog.Warn("rerun: cancel pending tasks failed",
@@ -5606,6 +5670,83 @@ func (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agen
return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID)
}
+// The bulk terminal writes below are the sweeper, archive and daemon-recovery
+// paths that finalize many tasks in one statement. They exist on TaskService rather than
+// being called as bare queries so the statement and its delegated-failure
+// settlement share a transaction.
+//
+// That is not a stylistic preference. HandleFailedTasks and
+// CaptureCancelledTasks run AFTER their caller committed, so a settlement
+// issued there could not be rolled back — and could not be repaired either,
+// because ListPendingDelegatedFailureRecoveries excludes a comment whose
+// covering task is terminal and already holds the receipt. Such a row would
+// neither replay nor settle; it would sit in the partial index forever,
+// restoring the unbounded history scan this change set removes.
+
+// FailTasksForOfflineRuntimes fails in-flight tasks whose runtime stayed
+// offline past the reconnect grace.
+func (s *TaskService) FailTasksForOfflineRuntimes(ctx context.Context, arg db.FailTasksForOfflineRuntimesParams) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.FailTasksForOfflineRuntimes(ctx, arg)
+ })
+}
+
+// FailExpiredRuntimeReconnectRetries fails deferred retries that reached their
+// terminal reconnect deadline.
+func (s *TaskService) FailExpiredRuntimeReconnectRetries(ctx context.Context, arg db.FailExpiredRuntimeReconnectRetriesParams) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.FailExpiredRuntimeReconnectRetries(ctx, arg)
+ })
+}
+
+// FailStaleTasks fails claimed work whose runtime stopped reporting.
+func (s *TaskService) FailStaleTasks(ctx context.Context, arg db.FailStaleTasksParams) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.FailStaleTasks(ctx, arg)
+ })
+}
+
+// ExpireStaleQueuedTasks fails queued work whose runtime never came back.
+func (s *TaskService) ExpireStaleQueuedTasks(ctx context.Context, arg db.ExpireStaleQueuedTasksParams) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.ExpireStaleQueuedTasks(ctx, arg)
+ })
+}
+
+// RecoverOrphanedTasksForRuntime fails work a restarted daemon reports it lost.
+func (s *TaskService) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.RecoverOrphanedTasksForRuntime(ctx, runtimeID)
+ })
+}
+
+// CancelTasksForArchivedAgent cancels every active task belonging to an agent
+// being archived and settles their recovery receipts in the same transaction.
+//
+// Unlike CancelTasksForAgent it emits no per-task task:cancelled event: the
+// agent:archived event the caller publishes already invalidates every client's
+// active-task view, so per-row events would be redundant noise.
+func (s *TaskService) CancelTasksForArchivedAgent(ctx context.Context, agentID pgtype.UUID) ([]db.AgentTaskQueue, error) {
+ return s.terminateTasksInTx(ctx, func(qtx *db.Queries) ([]db.AgentTaskQueue, error) {
+ return qtx.CancelAgentTasksByAgent(ctx, agentID)
+ })
+}
+
+func (s *TaskService) terminateTasksInTx(ctx context.Context, fail func(*db.Queries) ([]db.AgentTaskQueue, error)) ([]db.AgentTaskQueue, error) {
+ var failed []db.AgentTaskQueue
+ if err := s.runInTx(ctx, func(qtx *db.Queries) error {
+ var err error
+ failed, err = fail(qtx)
+ if err != nil {
+ return err
+ }
+ return SettleDeliveredDelegatedFailureRecoveries(ctx, qtx, failed...)
+ }); err != nil {
+ return nil, err
+ }
+ return failed, nil
+}
+
// HandleFailedTasks runs the post-failure side effects for a batch of
// freshly-failed tasks: optional auto-retry, task:failed event broadcast,
// agent status reconciliation, and (when an issue has no remaining active
@@ -5718,6 +5859,48 @@ const (
delegatedFailureRecoveryCommentType = "progress_update"
)
+// SettleDeliveredDelegatedFailureRecoveries retires every delegated-failure
+// recovery comment the given now-terminal tasks actually received, so those
+// comments drop out of idx_comment_delegated_failure_unsettled instead of
+// being re-proven settled by ListPendingDelegatedFailureRecoveries on every
+// sweeper tick. Without it the outbox scan grows with total history even when
+// it returns nothing.
+//
+// INVARIANT: every path that moves tasks to a terminal status must reach this
+// with the same qtx as the terminal write — per-task writes and bulk
+// cancellations alike, so the marker commits atomically with the status change
+// or not at all. A row stranded by a committed-but-unsettled terminal write
+// cannot be repaired later: ListPendingDelegatedFailureRecoveries excludes a
+// comment whose covering task is already terminal and holds its receipt, so
+// nothing replays the settlement and nothing else marks it, and the index
+// reacquires the unbounded growth it exists to remove.
+//
+// For the same reason the post-commit helpers — BroadcastCancelledTasks,
+// CaptureCancelledTasks, HandleFailedTasks — must never call this: they run
+// after their caller has committed, where a failure here can neither roll back
+// nor be compensated. Do not reintroduce a best-effort settlement outside the
+// transaction; the old one was deleted, not kept.
+//
+// Call this only once the task is terminal. A dispatched task's receipt is
+// still replaceable (SetTaskDeliveredCommentIDs), so settling earlier would
+// freeze a legitimate reclaim window into a permanently lost recovery.
+// SettleDelegatedFailureRecoveriesForTask re-checks the terminal status in SQL,
+// so a mistaken early call updates nothing rather than losing a recovery.
+//
+// A task with no delivery receipt — nearly every task — costs a slice length
+// check and no query.
+func SettleDeliveredDelegatedFailureRecoveries(ctx context.Context, q *db.Queries, tasks ...db.AgentTaskQueue) error {
+ for _, t := range tasks {
+ if len(t.DeliveredCommentIds) == 0 {
+ continue
+ }
+ if _, err := q.SettleDelegatedFailureRecoveriesForTask(ctx, t.ID); err != nil {
+ return fmt.Errorf("settle delegated failure recoveries for task %s: %w", util.UUIDToString(t.ID), err)
+ }
+ }
+ return nil
+}
+
type delegatedFailureRecoveryDispatchOutcome uint8
const (
@@ -5936,6 +6119,15 @@ func (s *TaskService) exhaustDelegatedFailureRecovery(ctx context.Context, targe
return fmt.Errorf("acknowledge exhausted delegated failure recovery: %w", err)
}
+ // The receipt above lands on the newest attempt row, which may still be
+ // running, so the task-scoped settle cannot see it. Exhaustion is
+ // terminal on its own terms — the attempt budget is spent and the
+ // visible explanation below tells the user why nothing else will run —
+ // so retire the comment directly, in this same transaction.
+ if _, err := qtx.SettleDelegatedFailureRecoveryComment(ctx, target.comment.ID); err != nil {
+ return fmt.Errorf("settle exhausted delegated failure recovery: %w", err)
+ }
+
comment, err := qtx.GetDelegatedFailureRecoveryExhaustionComment(ctx, db.GetDelegatedFailureRecoveryExhaustionCommentParams{
IssueID: target.issue.ID,
WorkspaceID: target.issue.WorkspaceID,
diff --git a/server/migrations/444_comment_recovery_settled_at.down.sql b/server/migrations/444_comment_recovery_settled_at.down.sql
new file mode 100644
index 0000000000..30274b3a54
--- /dev/null
+++ b/server/migrations/444_comment_recovery_settled_at.down.sql
@@ -0,0 +1 @@
+ALTER TABLE comment DROP COLUMN IF EXISTS recovery_settled_at;
diff --git a/server/migrations/444_comment_recovery_settled_at.up.sql b/server/migrations/444_comment_recovery_settled_at.up.sql
new file mode 100644
index 0000000000..2fee78a253
--- /dev/null
+++ b/server/migrations/444_comment_recovery_settled_at.up.sql
@@ -0,0 +1,23 @@
+-- Durable "this delegated-failure recovery is finished" marker.
+--
+-- The recovery outbox scan (ListPendingDelegatedFailureRecoveries) had no
+-- indexable settled state: every recovery comment ever written stayed in the
+-- candidate partial index from migration 343 forever, and each sweeper tick
+-- re-proved through four joins and two NOT EXISTS subqueries that it was
+-- already handled. LIMIT bounded the rows RETURNED, never the rows CHECKED, so
+-- a tick that found nothing still grew more expensive as history accumulated.
+--
+-- This column is that missing state. It is written only inside the transaction
+-- that makes a task terminal, and only for recovery comments already present in
+-- that task's delivered_comment_ids receipt — the one condition in the scan
+-- that is monotonic. A NULL therefore means "not proven finished", which is the
+-- safe direction: an unmarked row is still scanned exactly as it is today and
+-- no recovery can be lost, while a marked row is provably settled.
+--
+-- Nullable with no default keeps this metadata-only and instant on a hot table,
+-- the same reason comment.quick_action_id (239) and comment.via_plugin_id (348)
+-- are shaped this way. No FK per repository policy.
+--
+-- The matching partial index is migration 445: PostgreSQL rejects CREATE INDEX
+-- CONCURRENTLY in a multi-command string, so the two cannot share a file.
+ALTER TABLE comment ADD COLUMN IF NOT EXISTS recovery_settled_at TIMESTAMPTZ;
diff --git a/server/migrations/445_comment_delegated_failure_unsettled_index.down.sql b/server/migrations/445_comment_delegated_failure_unsettled_index.down.sql
new file mode 100644
index 0000000000..435252f14b
--- /dev/null
+++ b/server/migrations/445_comment_delegated_failure_unsettled_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_comment_delegated_failure_unsettled;
diff --git a/server/migrations/445_comment_delegated_failure_unsettled_index.up.sql b/server/migrations/445_comment_delegated_failure_unsettled_index.up.sql
new file mode 100644
index 0000000000..b67e85b15b
--- /dev/null
+++ b/server/migrations/445_comment_delegated_failure_unsettled_index.up.sql
@@ -0,0 +1,6 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_comment_delegated_failure_unsettled
+ON comment (created_at, id)
+WHERE author_type = 'system'
+ AND type = 'progress_update'
+ AND source_task_id IS NOT NULL
+ AND recovery_settled_at IS NULL;
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 907f3af531..a6b8c9bcd0 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -5689,7 +5689,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC
}
const listPendingDelegatedFailureRecoveries = `-- name: ListPendingDelegatedFailureRecoveries :many
-SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision
+SELECT recovery.id, recovery.issue_id, recovery.author_type, recovery.author_id, recovery.content, recovery.type, recovery.created_at, recovery.updated_at, recovery.parent_id, recovery.workspace_id, recovery.resolved_at, recovery.resolved_by_type, recovery.resolved_by_id, recovery.source_task_id, recovery.quick_action_id, recovery.via_plugin_id, recovery.revision, recovery.recovery_settled_at
FROM comment recovery
JOIN agent_task_queue failed ON failed.id = recovery.source_task_id
JOIN agent_task_queue source ON source.id = failed.delegated_from_task_id
@@ -5701,6 +5701,7 @@ LEFT JOIN issue_status source_status
WHERE recovery.author_type = 'system'
AND recovery.type = 'progress_update'
AND recovery.source_task_id IS NOT NULL
+ AND recovery.recovery_settled_at IS NULL
AND recovery.issue_id = source_issue.id
AND recovery.workspace_id = source_issue.workspace_id
AND failed.status = 'failed'
@@ -5751,6 +5752,15 @@ LIMIT $1
// explicit recovery signal avoids retroactively waking unrelated historical
// delegated failures. A bounded runtime sweeper replays these comments after a
// transient dispatch error or process restart.
+//
+// recovery_settled_at is what keeps this scan from growing with history. Every
+// other exclusion below is reversible — an issue can leave 'done', a cancelled
+// retry can be superseded — so none of them can be frozen into the index
+// predicate. A delivery receipt on a terminal task cannot be taken back, so
+// that one condition is recorded as durable state instead of being re-proven
+// through four joins and two NOT EXISTS subqueries on every tick. The predicate
+// of idx_comment_delegated_failure_unsettled matches the first four conditions,
+// so LIMIT now bounds the rows CHECKED and not just the rows RETURNED.
func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, maxPerTick int32) ([]Comment, error) {
rows, err := q.db.Query(ctx, listPendingDelegatedFailureRecoveries, maxPerTick)
if err != nil {
@@ -5778,6 +5788,7 @@ func (q *Queries) ListPendingDelegatedFailureRecoveries(ctx context.Context, max
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -8137,6 +8148,70 @@ func (q *Queries) SetTaskDeliveredCommentIDs(ctx context.Context, arg SetTaskDel
return delivered_comment_ids, err
}
+const settleDelegatedFailureRecoveriesForTask = `-- name: SettleDelegatedFailureRecoveriesForTask :execrows
+UPDATE comment recovery
+SET recovery_settled_at = now()
+FROM agent_task_queue task
+WHERE task.id = $1
+ AND task.status IN ('completed', 'failed', 'cancelled')
+ AND recovery.id = ANY(task.delivered_comment_ids)
+ AND recovery.author_type = 'system'
+ AND recovery.type = 'progress_update'
+ AND recovery.source_task_id IS NOT NULL
+ AND recovery.recovery_settled_at IS NULL
+`
+
+// Retire every delegated-failure recovery comment this task actually received.
+//
+// Callers MUST run this inside the same transaction that makes the task
+// terminal, and only there. While a task is still dispatched its receipt is
+// REPLACED rather than appended (SetTaskDeliveredCommentIDs), because a reclaim
+// by a differently-capable daemon must be able to drop an id it will not
+// deliver. Settling at receipt-write time would freeze that legitimate
+// transient window into a permanently lost recovery. Once the task is terminal
+// the receipt is final, which is exactly the guarantee this marker records.
+//
+// A comment that was only planned into the task and never delivered is absent
+// from delivered_comment_ids, so an automatic cancellation correctly leaves it
+// pending for the sweeper to replay.
+//
+// The terminal-status predicate is the guarantee itself, not a caller
+// convention. Settling a dispatched or running task's receipt would freeze the
+// reclaim window into a permanently lost recovery, and this marker is
+// monotonic — there is no later pass that could undo it. A caller that passes a
+// non-terminal task therefore updates nothing rather than silently destroying
+// the obligation.
+func (q *Queries) SettleDelegatedFailureRecoveriesForTask(ctx context.Context, taskID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, settleDelegatedFailureRecoveriesForTask, taskID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
+const settleDelegatedFailureRecoveryComment = `-- name: SettleDelegatedFailureRecoveryComment :execrows
+UPDATE comment
+SET recovery_settled_at = now()
+WHERE id = $1
+ AND author_type = 'system'
+ AND type = 'progress_update'
+ AND source_task_id IS NOT NULL
+ AND recovery_settled_at IS NULL
+`
+
+// Retire one recovery comment by id, for the terminal outcomes that are not a
+// task reaching a terminal status: exhaustion of the bounded automatic attempts
+// writes its receipt onto an attempt row that may still be running, and the
+// user-visible explanation comment is what closes the obligation. Callers run
+// this in the same transaction that records that outcome.
+func (q *Queries) SettleDelegatedFailureRecoveryComment(ctx context.Context, commentID pgtype.UUID) (int64, error) {
+ result, err := q.db.Exec(ctx, settleDelegatedFailureRecoveryComment, commentID)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const startAgentTask = `-- name: StartAgentTask :one
UPDATE agent_task_queue
SET status = 'running',
diff --git a/server/pkg/db/generated/comment.sql.go b/server/pkg/db/generated/comment.sql.go
index a405649d00..fa14ce8dcf 100644
--- a/server/pkg/db/generated/comment.sql.go
+++ b/server/pkg/db/generated/comment.sql.go
@@ -17,7 +17,7 @@ SET revision = revision + 1,
updated_at = now()
WHERE id = $1
AND workspace_id = $2
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
`
type BumpCommentRevisionParams struct {
@@ -46,6 +46,7 @@ func (q *Queries) BumpCommentRevision(ctx context.Context, arg BumpCommentRevisi
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
@@ -85,7 +86,7 @@ UPDATE comment SET
WHERE comment.id IN (SELECT id FROM descendants)
AND comment.id <> $1
AND comment.resolved_at IS NOT NULL
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
`
type ClearOtherThreadResolutionsParams struct {
@@ -131,6 +132,7 @@ func (q *Queries) ClearOtherThreadResolutions(ctx context.Context, arg ClearOthe
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -209,9 +211,9 @@ WITH touched_issue AS (
INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content, type, parent_id, source_task_id, quick_action_id, via_plugin_id, id)
SELECT ti.id, ti.workspace_id, $3, $4, $5, $6, $7, $8, $9, $10, COALESCE($11::uuid, gen_random_uuid())
FROM touched_issue ti
- RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+ RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
)
-SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, touched_issue.revision AS issue_revision
+SELECT inserted_comment.id, inserted_comment.issue_id, inserted_comment.author_type, inserted_comment.author_id, inserted_comment.content, inserted_comment.type, inserted_comment.created_at, inserted_comment.updated_at, inserted_comment.parent_id, inserted_comment.workspace_id, inserted_comment.resolved_at, inserted_comment.resolved_by_type, inserted_comment.resolved_by_id, inserted_comment.source_task_id, inserted_comment.quick_action_id, inserted_comment.via_plugin_id, inserted_comment.revision, inserted_comment.recovery_settled_at, touched_issue.revision AS issue_revision
FROM inserted_comment
JOIN touched_issue ON touched_issue.id = inserted_comment.issue_id
`
@@ -231,24 +233,25 @@ type CreateCommentParams struct {
}
type CreateCommentRow struct {
- ID pgtype.UUID `json:"id"`
- IssueID pgtype.UUID `json:"issue_id"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- ParentID pgtype.UUID `json:"parent_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
- ResolvedByType pgtype.Text `json:"resolved_by_type"`
- ResolvedByID pgtype.UUID `json:"resolved_by_id"`
- SourceTaskID pgtype.UUID `json:"source_task_id"`
- QuickActionID pgtype.UUID `json:"quick_action_id"`
- ViaPluginID pgtype.UUID `json:"via_plugin_id"`
- Revision int64 `json:"revision"`
- IssueRevision int64 `json:"issue_revision"`
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
+ IssueRevision int64 `json:"issue_revision"`
}
// A new comment counts as activity on its issue, so the same statement bumps
@@ -300,6 +303,7 @@ func (q *Queries) CreateComment(ctx context.Context, arg CreateCommentParams) (C
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
&i.IssueRevision,
)
return i, err
@@ -358,7 +362,7 @@ func (q *Queries) DeleteComment(ctx context.Context, arg DeleteCommentParams) (D
}
const getComment = `-- name: GetComment :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE id = $1
`
@@ -383,12 +387,13 @@ func (q *Queries) GetComment(ctx context.Context, id pgtype.UUID) (Comment, erro
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
const getCommentInWorkspace = `-- name: GetCommentInWorkspace :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE id = $1 AND workspace_id = $2
`
@@ -418,12 +423,13 @@ func (q *Queries) GetCommentInWorkspace(ctx context.Context, arg GetCommentInWor
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
const getDelegatedFailureRecoveryComment = `-- name: GetDelegatedFailureRecoveryComment :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -464,12 +470,13 @@ func (q *Queries) GetDelegatedFailureRecoveryComment(ctx context.Context, arg Ge
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
const getDelegatedFailureRecoveryExhaustionComment = `-- name: GetDelegatedFailureRecoveryExhaustionComment :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1
AND workspace_id = $2
AND author_type = 'system'
@@ -510,12 +517,13 @@ func (q *Queries) GetDelegatedFailureRecoveryExhaustionComment(ctx context.Conte
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
const getLatestMemberCommentForIssueSince = `-- name: GetLatestMemberCommentForIssueSince :one
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1
AND author_type = 'member'
AND created_at > $2
@@ -558,6 +566,7 @@ func (q *Queries) GetLatestMemberCommentForIssueSince(ctx context.Context, arg G
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
@@ -572,7 +581,7 @@ WITH RECURSIVE root_of AS (
FROM comment p
JOIN root_of r ON p.id = r.parent_id
)
-SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision FROM comment c
+SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at FROM comment c
WHERE c.id = (SELECT id FROM root_of WHERE parent_id IS NULL LIMIT 1)
`
@@ -607,6 +616,7 @@ func (q *Queries) GetThreadRoot(ctx context.Context, arg GetThreadRootParams) (C
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
@@ -655,7 +665,7 @@ func (q *Queries) HasAgentRepliedInThread(ctx context.Context, arg HasAgentRepli
}
const listChildCommentsForParents = `-- name: ListChildCommentsForParents :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE parent_id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -716,6 +726,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -729,7 +740,7 @@ func (q *Queries) ListChildCommentsForParents(ctx context.Context, arg ListChild
const listCommentAncestorPath = `-- name: ListCommentAncestorPath :many
WITH RECURSIVE ancestor_path AS (
- SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycle
+ SELECT c.id, c.issue_id, c.author_type, c.author_id, c.content, c.type, c.created_at, c.updated_at, c.parent_id, c.workspace_id, c.resolved_at, c.resolved_by_type, c.resolved_by_id, c.source_task_id, c.quick_action_id, c.via_plugin_id, c.revision, c.recovery_settled_at, ARRAY[c.id]::uuid[] AS visited_ids, 1::integer AS depth, false AS cycle
FROM comment c
WHERE c.id = $1
AND c.workspace_id = $2
@@ -737,7 +748,7 @@ WITH RECURSIVE ancestor_path AS (
UNION ALL
- SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision,
+ SELECT parent.id, parent.issue_id, parent.author_type, parent.author_id, parent.content, parent.type, parent.created_at, parent.updated_at, parent.parent_id, parent.workspace_id, parent.resolved_at, parent.resolved_by_type, parent.resolved_by_id, parent.source_task_id, parent.quick_action_id, parent.via_plugin_id, parent.revision, parent.recovery_settled_at,
path.visited_ids || parent.id,
path.depth + 1,
parent.id = ANY(path.visited_ids)
@@ -826,7 +837,7 @@ func (q *Queries) ListCommentAncestorPath(ctx context.Context, arg ListCommentAn
const listCommentThreadHistory = `-- name: ListCommentThreadHistory :many
WITH RECURSIVE thread_history AS (
- SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision
+ SELECT root.id, root.issue_id, root.author_type, root.author_id, root.content, root.type, root.created_at, root.updated_at, root.parent_id, root.workspace_id, root.resolved_at, root.resolved_by_type, root.resolved_by_id, root.source_task_id, root.quick_action_id, root.via_plugin_id, root.revision, root.recovery_settled_at
FROM comment root
WHERE root.id = $2
AND root.workspace_id = $3
@@ -839,7 +850,7 @@ WITH RECURSIVE thread_history AS (
UNION ALL
- SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision
+ SELECT child.id, child.issue_id, child.author_type, child.author_id, child.content, child.type, child.created_at, child.updated_at, child.parent_id, child.workspace_id, child.resolved_at, child.resolved_by_type, child.resolved_by_id, child.source_task_id, child.quick_action_id, child.via_plugin_id, child.revision, child.recovery_settled_at
FROM comment child
JOIN thread_history parent ON child.parent_id = parent.id
WHERE child.workspace_id = $3
@@ -849,7 +860,7 @@ WITH RECURSIVE thread_history AS (
$6::uuid
)
)
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
FROM thread_history
ORDER BY created_at, id
LIMIT $1
@@ -865,23 +876,24 @@ type ListCommentThreadHistoryParams struct {
}
type ListCommentThreadHistoryRow struct {
- ID pgtype.UUID `json:"id"`
- IssueID pgtype.UUID `json:"issue_id"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- ParentID pgtype.UUID `json:"parent_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
- ResolvedByType pgtype.Text `json:"resolved_by_type"`
- ResolvedByID pgtype.UUID `json:"resolved_by_id"`
- SourceTaskID pgtype.UUID `json:"source_task_id"`
- QuickActionID pgtype.UUID `json:"quick_action_id"`
- ViaPluginID pgtype.UUID `json:"via_plugin_id"`
- Revision int64 `json:"revision"`
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
}
// Capture the anchor comment's complete chronological thread through that
@@ -921,6 +933,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -933,7 +946,7 @@ func (q *Queries) ListCommentThreadHistory(ctx context.Context, arg ListCommentT
}
const listCommentsByIDsForIssue = `-- name: ListCommentsByIDsForIssue :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE id = ANY($1::uuid[])
AND issue_id = $2
AND workspace_id = $3
@@ -982,6 +995,7 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -994,8 +1008,8 @@ func (q *Queries) ListCommentsByIDsForIssue(ctx context.Context, arg ListComment
}
const listCommentsForIssue = `-- name: ListCommentsForIssue :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM (
- SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM (
+ SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1 AND workspace_id = $2
ORDER BY created_at DESC, id DESC
LIMIT $3
@@ -1053,6 +1067,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -1065,7 +1080,7 @@ func (q *Queries) ListCommentsForIssue(ctx context.Context, arg ListCommentsForI
}
const listCommentsSinceForIssue = `-- name: ListCommentsSinceForIssue :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1 AND workspace_id = $2 AND created_at > $3
ORDER BY created_at ASC, id ASC
LIMIT $4
@@ -1112,6 +1127,7 @@ func (q *Queries) ListCommentsSinceForIssue(ctx context.Context, arg ListComment
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -1271,7 +1287,7 @@ func (q *Queries) ListRecentThreadCommentsForIssue(ctx context.Context, arg List
}
const listReconcilableCommentsForIssueSince = `-- name: ListReconcilableCommentsForIssueSince :many
-SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision FROM comment
+SELECT id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at FROM comment
WHERE issue_id = $1
AND (
(
@@ -1353,6 +1369,7 @@ func (q *Queries) ListReconcilableCommentsForIssueSince(ctx context.Context, arg
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
); err != nil {
return nil, err
}
@@ -1813,7 +1830,7 @@ UPDATE comment SET
revision = revision + CASE WHEN resolved_at IS NULL THEN 1 ELSE 0 END,
updated_at = CASE WHEN resolved_at IS NULL THEN now() ELSE updated_at END
WHERE id = $1
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
`
type ResolveCommentParams struct {
@@ -1845,6 +1862,7 @@ func (q *Queries) ResolveComment(ctx context.Context, arg ResolveCommentParams)
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
@@ -1857,7 +1875,7 @@ UPDATE comment SET
revision = revision + CASE WHEN resolved_at IS NOT NULL THEN 1 ELSE 0 END,
updated_at = CASE WHEN resolved_at IS NOT NULL THEN now() ELSE updated_at END
WHERE id = $1
-RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision
+RETURNING id, issue_id, author_type, author_id, content, type, created_at, updated_at, parent_id, workspace_id, resolved_at, resolved_by_type, resolved_by_id, source_task_id, quick_action_id, via_plugin_id, revision, recovery_settled_at
`
// Idempotent: a no-op clear (already unresolved) just returns the row.
@@ -1882,6 +1900,7 @@ func (q *Queries) UnresolveComment(ctx context.Context, id pgtype.UUID) (Comment
&i.QuickActionID,
&i.ViaPluginID,
&i.Revision,
+ &i.RecoverySettledAt,
)
return i, err
}
@@ -1904,7 +1923,7 @@ WITH locked_issue AS MATERIALIZED (
-- prevents folding/re-evaluation; it does not itself establish lock order.
SELECT count(*) AS locked_count FROM locked_issue
), target AS MATERIALIZED (
- SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision,
+ SELECT comment.id, comment.issue_id, comment.author_type, comment.author_id, comment.content, comment.type, comment.created_at, comment.updated_at, comment.parent_id, comment.workspace_id, comment.resolved_at, comment.resolved_by_type, comment.resolved_by_id, comment.source_task_id, comment.quick_action_id, comment.via_plugin_id, comment.revision, comment.recovery_settled_at,
ROW(comment.content, comment.source_task_id) IS DISTINCT FROM
ROW($2, $3::uuid) AS did_change
FROM comment
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index acc26c9f1f..a3ec697ddf 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -531,23 +531,24 @@ type ClientUsageDaily struct {
}
type Comment struct {
- ID pgtype.UUID `json:"id"`
- IssueID pgtype.UUID `json:"issue_id"`
- AuthorType string `json:"author_type"`
- AuthorID pgtype.UUID `json:"author_id"`
- Content string `json:"content"`
- Type string `json:"type"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- UpdatedAt pgtype.Timestamptz `json:"updated_at"`
- ParentID pgtype.UUID `json:"parent_id"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
- ResolvedByType pgtype.Text `json:"resolved_by_type"`
- ResolvedByID pgtype.UUID `json:"resolved_by_id"`
- SourceTaskID pgtype.UUID `json:"source_task_id"`
- QuickActionID pgtype.UUID `json:"quick_action_id"`
- ViaPluginID pgtype.UUID `json:"via_plugin_id"`
- Revision int64 `json:"revision"`
+ ID pgtype.UUID `json:"id"`
+ IssueID pgtype.UUID `json:"issue_id"`
+ AuthorType string `json:"author_type"`
+ AuthorID pgtype.UUID `json:"author_id"`
+ Content string `json:"content"`
+ Type string `json:"type"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ ParentID pgtype.UUID `json:"parent_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ResolvedAt pgtype.Timestamptz `json:"resolved_at"`
+ ResolvedByType pgtype.Text `json:"resolved_by_type"`
+ ResolvedByID pgtype.UUID `json:"resolved_by_id"`
+ SourceTaskID pgtype.UUID `json:"source_task_id"`
+ QuickActionID pgtype.UUID `json:"quick_action_id"`
+ ViaPluginID pgtype.UUID `json:"via_plugin_id"`
+ Revision int64 `json:"revision"`
+ RecoverySettledAt pgtype.Timestamptz `json:"recovery_settled_at"`
}
type CommentReaction struct {
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 4cc14c7d3f..fdfb50a491 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -2038,12 +2038,67 @@ WHERE acknowledged.id = (
) >= @max_attempts::int
RETURNING acknowledged.*;
+-- name: SettleDelegatedFailureRecoveriesForTask :execrows
+-- Retire every delegated-failure recovery comment this task actually received.
+--
+-- Callers MUST run this inside the same transaction that makes the task
+-- terminal, and only there. While a task is still dispatched its receipt is
+-- REPLACED rather than appended (SetTaskDeliveredCommentIDs), because a reclaim
+-- by a differently-capable daemon must be able to drop an id it will not
+-- deliver. Settling at receipt-write time would freeze that legitimate
+-- transient window into a permanently lost recovery. Once the task is terminal
+-- the receipt is final, which is exactly the guarantee this marker records.
+--
+-- A comment that was only planned into the task and never delivered is absent
+-- from delivered_comment_ids, so an automatic cancellation correctly leaves it
+-- pending for the sweeper to replay.
+--
+-- The terminal-status predicate is the guarantee itself, not a caller
+-- convention. Settling a dispatched or running task's receipt would freeze the
+-- reclaim window into a permanently lost recovery, and this marker is
+-- monotonic — there is no later pass that could undo it. A caller that passes a
+-- non-terminal task therefore updates nothing rather than silently destroying
+-- the obligation.
+UPDATE comment recovery
+SET recovery_settled_at = now()
+FROM agent_task_queue task
+WHERE task.id = @task_id
+ AND task.status IN ('completed', 'failed', 'cancelled')
+ AND recovery.id = ANY(task.delivered_comment_ids)
+ AND recovery.author_type = 'system'
+ AND recovery.type = 'progress_update'
+ AND recovery.source_task_id IS NOT NULL
+ AND recovery.recovery_settled_at IS NULL;
+
+-- name: SettleDelegatedFailureRecoveryComment :execrows
+-- Retire one recovery comment by id, for the terminal outcomes that are not a
+-- task reaching a terminal status: exhaustion of the bounded automatic attempts
+-- writes its receipt onto an attempt row that may still be running, and the
+-- user-visible explanation comment is what closes the obligation. Callers run
+-- this in the same transaction that records that outcome.
+UPDATE comment
+SET recovery_settled_at = now()
+WHERE id = @comment_id
+ AND author_type = 'system'
+ AND type = 'progress_update'
+ AND source_task_id IS NOT NULL
+ AND recovery_settled_at IS NULL;
+
-- name: ListPendingDelegatedFailureRecoveries :many
-- Durable outbox scan for platform recovery comments that are not yet owned by
-- an executable task and have no terminal delivery receipt. Starting from the
-- explicit recovery signal avoids retroactively waking unrelated historical
-- delegated failures. A bounded runtime sweeper replays these comments after a
-- transient dispatch error or process restart.
+--
+-- recovery_settled_at is what keeps this scan from growing with history. Every
+-- other exclusion below is reversible — an issue can leave 'done', a cancelled
+-- retry can be superseded — so none of them can be frozen into the index
+-- predicate. A delivery receipt on a terminal task cannot be taken back, so
+-- that one condition is recorded as durable state instead of being re-proven
+-- through four joins and two NOT EXISTS subqueries on every tick. The predicate
+-- of idx_comment_delegated_failure_unsettled matches the first four conditions,
+-- so LIMIT now bounds the rows CHECKED and not just the rows RETURNED.
SELECT recovery.*
FROM comment recovery
JOIN agent_task_queue failed ON failed.id = recovery.source_task_id
@@ -2056,6 +2111,7 @@ LEFT JOIN issue_status source_status
WHERE recovery.author_type = 'system'
AND recovery.type = 'progress_update'
AND recovery.source_task_id IS NOT NULL
+ AND recovery.recovery_settled_at IS NULL
AND recovery.issue_id = source_issue.id
AND recovery.workspace_id = source_issue.workspace_id
AND failed.status = 'failed'