Skip to content

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

Go

fix(server): keep source-context cleanup off the runtime sweep tick (#7541)

Bohan Jiange5f976144b50
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 90535e283d..ade3007571 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -607,6 +607,9 @@ func main() {
// work to queued_expired failures.
go runRuntimeSweeper(sweepCtx, pool, queries, liveness, taskSvc, bus, runtimeReconnectGrace,
envDuration("MULTICA_TASK_QUEUED_TTL", defaultTaskQueuedTTL))
+ // Source-context cleanup is object-store work, so it gets its own goroutine
+ // instead of a slot in the runtime sweep tick.
+ go runSourceContextSweeper(sweepCtx, taskSvc)
go heartbeatScheduler.Run(sweepCtx)
go runAutopilotFailureMonitor(autopilotCtx, queries, bus, envFailureMonitorConfig())
if autopilotSvc.QuotaEnabled() {
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 62e52ab07d..f870810c3e 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -138,16 +138,10 @@ func runRuntimeSweeper(ctx context.Context, txStarter runtimeGCTxStarter, querie
case <-ctx.Done():
return
case <-ticker.C:
- if cleaned, err := taskSvc.CleanupSourceContextObjectIntents(ctx, 50); err != nil {
- slog.Warn("source context object intent cleanup failed", "error", err)
- } else if cleaned > 0 {
- slog.Info("source context object intent cleanup completed", "count", cleaned)
- }
- if cleaned, err := taskSvc.CleanupAbandonedSourceContexts(ctx, 50); err != nil {
- slog.Warn("source context cleanup sweeper failed", "error", err)
- } else if cleaned > 0 {
- slog.Info("source context cleanup sweeper removed abandoned captures", "count", cleaned)
- }
+ // Every stage below is DB-only and latency-critical: it is what
+ // flips a dead runtime offline and reclaims its orphaned tasks
+ // within ~180s. Object-store work belongs on its own goroutine
+ // (runSourceContextSweeper), never in this tick.
sweepStaleRuntimes(ctx, queries, liveness, taskSvc, bus)
sweepOfflineRuntimeTasks(ctx, queries, taskSvc, reconnectGrace)
sweepExpiredRuntimeReconnectRetries(ctx, queries, taskSvc, reconnectGrace)
diff --git a/server/cmd/server/source_context_sweeper.go b/server/cmd/server/source_context_sweeper.go
new file mode 100644
index 0000000000..3866daf9a4
--- /dev/null
+++ b/server/cmd/server/source_context_sweeper.go
@@ -0,0 +1,72 @@
+package main
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+const (
+ // sourceContextSweepInterval paces snapshot cleanup (MUL-6555). Nothing
+ // here is latency-critical: an orphaned object intent only becomes eligible
+ // one hour after its capture failed and carries a five-minute retry
+ // backoff, and an abandoned capture waits out a 30-day retention window.
+ // A minute keeps the drain rate for a fresh backlog close to what the old
+ // placement in the 30s runtime tick gave, at two cheap queries per round.
+ sourceContextSweepInterval = time.Minute
+ // sourceContextSweepBudget bounds one round below the interval so a slow
+ // object store delays cleanup instead of stacking rounds. Per-object
+ // deadlines live in the service; this is the whole-round backstop.
+ sourceContextSweepBudget = 45 * time.Second
+ // sourceContextCleanupBatchSize bounds delete attempts per round.
+ sourceContextCleanupBatchSize = 50
+)
+
+// sourceContextCleaner is the slice of TaskService this sweeper drives, kept as
+// an interface so the round can be tested against a stalled object store.
+type sourceContextCleaner interface {
+ CleanupSourceContextObjectIntents(ctx context.Context, limit int) (int, error)
+ CleanupAbandonedSourceContexts(ctx context.Context, limit int32) (int, error)
+}
+
+var _ sourceContextCleaner = (*service.TaskService)(nil)
+
+// runSourceContextSweeper reclaims snapshot objects whose capture never
+// committed and captures whose retry window has expired.
+//
+// It deliberately runs on its own goroutine rather than inside the runtime
+// sweep tick. Both stages talk to the object store, and a stalled or throttled
+// endpoint there must never delay marking runtimes offline, reclaiming
+// orphaned tasks, or replaying delegated failure recoveries — those are the
+// stages that keep the board truthful within ~180s of a daemon dying.
+func runSourceContextSweeper(ctx context.Context, cleaner sourceContextCleaner) {
+ ticker := time.NewTicker(sourceContextSweepInterval)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ sweepSourceContextsWithBudget(ctx, cleaner, sourceContextSweepBudget)
+ }
+ }
+}
+
+func sweepSourceContextsWithBudget(ctx context.Context, cleaner sourceContextCleaner, budget time.Duration) {
+ sweepCtx, cancel := context.WithTimeout(ctx, budget)
+ defer cancel()
+
+ if cleaned, err := cleaner.CleanupSourceContextObjectIntents(sweepCtx, sourceContextCleanupBatchSize); err != nil {
+ slog.Warn("source context object intent cleanup failed", "error", err)
+ } else if cleaned > 0 {
+ slog.Info("source context object intent cleanup completed", "count", cleaned)
+ }
+ if cleaned, err := cleaner.CleanupAbandonedSourceContexts(sweepCtx, sourceContextCleanupBatchSize); err != nil {
+ slog.Warn("source context cleanup sweeper failed", "error", err)
+ } else if cleaned > 0 {
+ slog.Info("source context cleanup sweeper removed abandoned captures", "count", cleaned)
+ }
+}
diff --git a/server/cmd/server/source_context_sweeper_test.go b/server/cmd/server/source_context_sweeper_test.go
new file mode 100644
index 0000000000..01be715bf2
--- /dev/null
+++ b/server/cmd/server/source_context_sweeper_test.go
@@ -0,0 +1,111 @@
+package main
+
+import (
+ "context"
+ "os"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// stalledSourceContextCleaner models an object store that stopped answering:
+// every stage blocks until its context is done, which is what a hung or
+// throttled endpoint looks like from inside a cleanup round.
+type stalledSourceContextCleaner struct {
+ intentCalls atomic.Int32
+ abandonedCalls atomic.Int32
+ intentLimit atomic.Int32
+ abandonedLimit atomic.Int32
+ intentDeadlineBounded atomic.Bool
+}
+
+func (c *stalledSourceContextCleaner) CleanupSourceContextObjectIntents(ctx context.Context, limit int) (int, error) {
+ c.intentCalls.Add(1)
+ c.intentLimit.Store(int32(limit))
+ if deadline, ok := ctx.Deadline(); ok {
+ c.intentDeadlineBounded.Store(time.Until(deadline) <= sourceContextSweepBudget)
+ }
+ <-ctx.Done()
+ return 0, nil
+}
+
+func (c *stalledSourceContextCleaner) CleanupAbandonedSourceContexts(ctx context.Context, limit int32) (int, error) {
+ c.abandonedCalls.Add(1)
+ c.abandonedLimit.Store(limit)
+ <-ctx.Done()
+ return 0, nil
+}
+
+// TestSourceContextSweepRoundEndsAtItsBudget proves a stalled object store
+// cannot hold a cleanup round open. Rounds are paced by their own ticker, so
+// this budget is what keeps a stuck round from overlapping the next one.
+func TestSourceContextSweepRoundEndsAtItsBudget(t *testing.T) {
+ cleaner := &stalledSourceContextCleaner{}
+ budget := 200 * time.Millisecond
+
+ startedAt := time.Now()
+ sweepSourceContextsWithBudget(context.Background(), cleaner, budget)
+ elapsed := time.Since(startedAt)
+
+ if elapsed > 2*time.Second {
+ t.Fatalf("cleanup round ran %s, want it bounded by its %s budget", elapsed, budget)
+ }
+ if got := cleaner.intentCalls.Load(); got != 1 {
+ t.Fatalf("object intent cleanup calls = %d, want 1", got)
+ }
+ if got := cleaner.abandonedCalls.Load(); got != 1 {
+ t.Fatalf("abandoned capture cleanup calls = %d, want 1 even after the first stage used up the budget", got)
+ }
+ if got := cleaner.intentLimit.Load(); got != sourceContextCleanupBatchSize {
+ t.Fatalf("object intent batch size = %d, want %d", got, sourceContextCleanupBatchSize)
+ }
+ if got := cleaner.abandonedLimit.Load(); got != sourceContextCleanupBatchSize {
+ t.Fatalf("abandoned capture batch size = %d, want %d", got, sourceContextCleanupBatchSize)
+ }
+}
+
+// TestSourceContextSweepPassesABoundedDeadline keeps the round budget wired to
+// the service calls; without a deadline on that context the per-object timeouts
+// derived from it would be the only bound left.
+func TestSourceContextSweepPassesABoundedDeadline(t *testing.T) {
+ cleaner := &stalledSourceContextCleaner{}
+ sweepSourceContextsWithBudget(context.Background(), cleaner, 100*time.Millisecond)
+ if !cleaner.intentDeadlineBounded.Load() {
+ t.Fatal("cleanup stage ran without a deadline bounded by the round budget")
+ }
+}
+
+// TestSourceContextSweeperStopsWithItsContext keeps shutdown clean: the loop
+// must exit on context cancellation rather than waiting out a full interval.
+func TestSourceContextSweeperStopsWithItsContext(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ stopped := make(chan struct{})
+ go func() {
+ runSourceContextSweeper(ctx, &stalledSourceContextCleaner{})
+ close(stopped)
+ }()
+ cancel()
+ select {
+ case <-stopped:
+ case <-time.After(5 * time.Second):
+ t.Fatal("source context sweeper did not stop with its context")
+ }
+}
+
+// TestRuntimeSweepTickHasNoObjectStoreStage is a regression guard for the
+// reason this sweeper exists (MUL-6555 / MUL-6670): source-context cleanup used
+// to run at the top of the 30s runtime tick, so a slow object store delayed
+// marking runtimes offline and reclaiming their orphaned tasks. Object-store
+// work must stay out of that tick; put it in runSourceContextSweeper instead.
+func TestRuntimeSweepTickHasNoObjectStoreStage(t *testing.T) {
+ source, err := os.ReadFile("runtime_sweeper.go")
+ if err != nil {
+ t.Fatalf("read runtime_sweeper.go: %v", err)
+ }
+ for _, stage := range []string{"CleanupSourceContextObjectIntents", "CleanupAbandonedSourceContexts"} {
+ if strings.Contains(string(source), stage) {
+ t.Fatalf("runtime_sweeper.go calls %s; object-store cleanup belongs on runSourceContextSweeper", stage)
+ }
+ }
+}
diff --git a/server/internal/service/source_context.go b/server/internal/service/source_context.go
index 66f821f2f8..bd3c6e2ca3 100644
--- a/server/internal/service/source_context.go
+++ b/server/internal/service/source_context.go
@@ -38,6 +38,20 @@ const (
SourceContextMaxAttachmentBytes = int64(500 << 20)
)
+const (
+ // sourceContextObjectDeleteTimeout bounds a single object-store delete.
+ // Cleanup runs on its own sweeper goroutine, so an unhealthy endpoint can no
+ // longer starve runtime and task recovery, but without a per-object deadline
+ // one hung delete would still hold a whole cleanup round open.
+ sourceContextObjectDeleteTimeout = 30 * time.Second
+ // sourceContextIntentReleaseTimeout bounds the retry-backoff write that
+ // follows a failed delete. It runs detached from the caller's round budget:
+ // when the budget is what cut the delete short, a cancelled release would
+ // leave the intent immediately claimable and every later round would retry
+ // the same unhealthy object ahead of the ones queued behind it.
+ sourceContextIntentReleaseTimeout = 5 * time.Second
+)
+
var (
ErrAnchorCommentDeleted = errors.New("anchor comment deleted")
ErrSourceIssueDeleted = errors.New("source issue deleted")
@@ -633,13 +647,25 @@ func (s *TaskService) CleanupSourceContextObjectIntents(ctx context.Context, lim
return 0, nil
}
cleaned := 0
- for cleaned < limit {
+ // limit bounds ATTEMPTS, not successes. Counting successes alone made one
+ // round's work proportional to the number of due intents rather than to the
+ // batch size, which is exactly what a storage outage produces: every delete
+ // fails, nothing increments, and the round keeps claiming the next row.
+ for attempt := 0; attempt < limit; attempt++ {
+ if ctx.Err() != nil {
+ return cleaned, nil
+ }
leaseToken := dbid.NewV7()
intent, err := s.Queries.ClaimSourceContextObjectIntentForCleanup(ctx, leaseToken)
if errors.Is(err, pgx.ErrNoRows) {
break
}
if err != nil {
+ // A round that ran out of budget mid-claim is a normal stop, not a
+ // failure worth alerting on; the next round resumes where this left off.
+ if ctx.Err() != nil {
+ return cleaned, nil
+ }
return cleaned, fmt.Errorf("claim source context object intent: %w", err)
}
referenced, err := s.Queries.SourceContextObjectIntentIsReferenced(ctx, db.SourceContextObjectIntentIsReferencedParams{
@@ -647,19 +673,15 @@ func (s *TaskService) CleanupSourceContextObjectIntents(ctx context.Context, lim
AttachmentID: intent.AttachmentID, ObjectUrl: intent.ObjectUrl,
})
if err != nil {
- _, _ = s.Queries.ReleaseSourceContextObjectIntent(ctx, db.ReleaseSourceContextObjectIntentParams{
- LastError: pgtype.Text{String: err.Error(), Valid: true}, StorageKey: intent.StorageKey, WorkspaceID: intent.WorkspaceID, LeaseToken: leaseToken,
- })
+ s.releaseSourceContextObjectIntent(ctx, intent, leaseToken, err)
return cleaned, fmt.Errorf("check source context object reference: %w", err)
}
if !referenced {
- deleteCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ deleteCtx, cancel := context.WithTimeout(ctx, sourceContextObjectDeleteTimeout)
deleteErr := s.SourceContextStorage.DeleteObject(deleteCtx, intent.StorageKey)
cancel()
if deleteErr != nil {
- _, _ = s.Queries.ReleaseSourceContextObjectIntent(ctx, db.ReleaseSourceContextObjectIntentParams{
- LastError: pgtype.Text{String: deleteErr.Error(), Valid: true}, StorageKey: intent.StorageKey, WorkspaceID: intent.WorkspaceID, LeaseToken: leaseToken,
- })
+ s.releaseSourceContextObjectIntent(ctx, intent, leaseToken, deleteErr)
continue
}
}
@@ -674,6 +696,23 @@ func (s *TaskService) CleanupSourceContextObjectIntents(ctx context.Context, lim
return cleaned, nil
}
+// releaseSourceContextObjectIntent stamps the retry backoff for an intent this
+// round could not settle. The write is detached from the round budget on
+// purpose: when the budget is what stopped the delete, a cancelled release
+// would leave the row claimable with no backoff, so the next round would pick
+// the same unhealthy object again instead of making progress on the rest.
+func (s *TaskService) releaseSourceContextObjectIntent(ctx context.Context, intent db.IssueSourceContextObjectIntent, leaseToken pgtype.UUID, cause error) {
+ releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sourceContextIntentReleaseTimeout)
+ defer cancel()
+ if _, err := s.Queries.ReleaseSourceContextObjectIntent(releaseCtx, db.ReleaseSourceContextObjectIntentParams{
+ LastError: pgtype.Text{String: cause.Error(), Valid: true}, StorageKey: intent.StorageKey,
+ WorkspaceID: intent.WorkspaceID, LeaseToken: leaseToken,
+ }); err != nil {
+ slog.Warn("source context cleanup: failed to record object intent retry backoff",
+ "storage_key", intent.StorageKey, "error", err)
+ }
+}
+
// CleanupAbandonedSourceContexts abandons terminal quick-create captures only
// after their 30-day retry window. Retry creation transfers origin_task_id to
// the successor, so the terminal row selected here is the latest attempt.
@@ -713,6 +752,11 @@ func (s *TaskService) CleanupAbandonedSourceContexts(ctx context.Context, limit
}
removed := 0
for _, sourceContext := range abandoned {
+ // Stop cleanly when the round budget is gone. Every deletion below is
+ // idempotent, so the next round resumes from whatever is still abandoned.
+ if ctx.Err() != nil {
+ return removed, nil
+ }
attachments, err := s.Queries.ListAttachmentsBySourceContext(ctx, db.ListAttachmentsBySourceContextParams{
WorkspaceID: sourceContext.WorkspaceID, SourceContextID: sourceContext.ID,
})
@@ -721,8 +765,14 @@ func (s *TaskService) CleanupAbandonedSourceContexts(ctx context.Context, limit
}
deleteFailed := false
for _, attachment := range attachments {
+ if ctx.Err() != nil {
+ return removed, nil
+ }
key := s.SourceContextStorage.KeyFromURL(attachment.Url)
- if err := s.SourceContextStorage.DeleteObject(ctx, key); err != nil {
+ deleteCtx, cancel := context.WithTimeout(ctx, sourceContextObjectDeleteTimeout)
+ err := s.SourceContextStorage.DeleteObject(deleteCtx, key)
+ cancel()
+ if err != nil {
deleteFailed = true
slog.Warn("source context cleanup: object delete failed; retained row for retry",
"source_context_id", util.UUIDToString(sourceContext.ID), "attachment_id", util.UUIDToString(attachment.ID), "error", err)
diff --git a/server/internal/service/source_context_cleanup_budget_test.go b/server/internal/service/source_context_cleanup_budget_test.go
new file mode 100644
index 0000000000..5fecd1aed3
--- /dev/null
+++ b/server/internal/service/source_context_cleanup_budget_test.go
@@ -0,0 +1,227 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/dbid"
+)
+
+// sourceContextCleanupTestLock serializes every cleanup-oracle test against the
+// other packages that sweep the same integration database.
+const sourceContextCleanupTestLock = int64(0x53434f4e54455854)
+
+// failingSourceContextObjectStore records the context each delete received and
+// always fails, standing in for an object store that is down or throttling.
+type failingSourceContextObjectStore struct {
+ mu sync.Mutex
+ attempts []string
+ deadlineBounded []bool
+ onDelete func()
+}
+
+func (s *failingSourceContextObjectStore) KeyFromURL(rawURL string) string { return rawURL }
+
+func (s *failingSourceContextObjectStore) DeleteObject(ctx context.Context, key string) error {
+ s.mu.Lock()
+ s.attempts = append(s.attempts, key)
+ deadline, ok := ctx.Deadline()
+ s.deadlineBounded = append(s.deadlineBounded, ok && time.Until(deadline) <= sourceContextObjectDeleteTimeout)
+ onDelete := s.onDelete
+ s.mu.Unlock()
+ if onDelete != nil {
+ onDelete()
+ }
+ return errors.New("object store unavailable")
+}
+
+func (s *failingSourceContextObjectStore) attemptCount() int {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ return len(s.attempts)
+}
+
+// TestCleanupSourceContextObjectIntentsBoundsAttemptsNotSuccesses locks the
+// batch semantics that made this sweeper dangerous: the loop used to stop after
+// `limit` SUCCESSES, so a failing object store — the case that produces a
+// backlog of due intents in the first place — let one round keep claiming rows
+// for as long as due intents existed. The bound is on attempts.
+func TestCleanupSourceContextObjectIntentsBoundsAttemptsNotSuccesses(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ lockConn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire cleanup test lock: %v", err)
+ }
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock($1)`, sourceContextCleanupTestLock); err != nil {
+ lockConn.Release()
+ t.Fatalf("lock source-context cleanup tests: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, sourceContextCleanupTestLock)
+ lockConn.Release()
+ })
+
+ workspaceID, _, _, _ := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+
+ // The whole fixture lives in a rolled-back transaction: the sweeper is
+ // global, so seeding due rows outside one would let a developer server (or
+ // the next test) claim them mid-assertion.
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatalf("begin isolated intent batch: %v", err)
+ }
+ defer tx.Rollback(ctx)
+ if _, err := tx.Exec(ctx, `LOCK TABLE issue_source_context_object_intent IN SHARE ROW EXCLUSIVE MODE`); err != nil {
+ t.Fatalf("lock object intent table: %v", err)
+ }
+ // Park any pre-existing due row so the claim order below is exactly the
+ // three intents this test seeds.
+ if _, err := tx.Exec(ctx, `
+ UPDATE issue_source_context_object_intent
+ SET next_attempt_at = now() + interval '1 hour'
+ WHERE next_attempt_at <= now()
+ `); err != nil {
+ t.Fatalf("park pre-existing due intents: %v", err)
+ }
+
+ qtx := db.New(pool).WithTx(tx)
+ keys := make([]string, 0, 3)
+ for _, name := range []string{"a", "b", "c"} {
+ attachmentID := dbid.NewV7()
+ key := "source-context-budget/" + name + "-" + util.UUIDToString(attachmentID)
+ keys = append(keys, key)
+ if _, err := qtx.RecordSourceContextObjectIntent(ctx, db.RecordSourceContextObjectIntentParams{
+ StorageKey: key, WorkspaceID: workspaceUUID, SourceContextID: dbid.NewV7(),
+ AttachmentID: attachmentID, ObjectUrl: "https://objects.example/" + key,
+ }); err != nil {
+ t.Fatalf("record intent %s: %v", name, err)
+ }
+ }
+ if _, err := tx.Exec(ctx, `
+ UPDATE issue_source_context_object_intent
+ SET created_at = now() - interval '2 hours', next_attempt_at = '-infinity'::timestamptz
+ WHERE storage_key = ANY($1::text[])
+ `, keys); err != nil {
+ t.Fatalf("age seeded intents: %v", err)
+ }
+
+ store := &failingSourceContextObjectStore{}
+ svc := &TaskService{Queries: qtx, SourceContextStorage: store}
+ cleaned, err := svc.CleanupSourceContextObjectIntents(ctx, 2)
+ if err != nil {
+ t.Fatalf("cleanup intents: %v", err)
+ }
+ if cleaned != 0 {
+ t.Fatalf("cleaned intents = %d, want 0 while every delete fails", cleaned)
+ }
+ if got := store.attemptCount(); got != 2 {
+ t.Fatalf("delete attempts = %d, want the batch size of 2 (a failing store must not extend the round)", got)
+ }
+ for i, bounded := range store.deadlineBounded {
+ if !bounded {
+ t.Fatalf("delete attempt %d ran without a bounded deadline", i)
+ }
+ }
+
+ var due int
+ if err := tx.QueryRow(ctx, `
+ SELECT count(*) FROM issue_source_context_object_intent
+ WHERE storage_key = ANY($1::text[]) AND next_attempt_at <= now()
+ `, keys).Scan(&due); err != nil {
+ t.Fatalf("count remaining due intents: %v", err)
+ }
+ if due != 1 {
+ t.Fatalf("still-due seeded intents = %d, want 1 (the two attempted rows carry a retry backoff)", due)
+ }
+}
+
+// TestCleanupAbandonedSourceContextsStopsWhenTheRoundBudgetEnds proves the
+// second stage is both per-object bounded and budget-aware: it stops between
+// captures instead of walking the rest of the batch with a dead context.
+func TestCleanupAbandonedSourceContextsStopsWhenTheRoundBudgetEnds(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ lockConn, err := pool.Acquire(ctx)
+ if err != nil {
+ t.Fatalf("acquire cleanup test lock: %v", err)
+ }
+ if _, err := lockConn.Exec(ctx, `SELECT pg_advisory_lock($1)`, sourceContextCleanupTestLock); err != nil {
+ lockConn.Release()
+ t.Fatalf("lock source-context cleanup tests: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = lockConn.Exec(context.Background(), `SELECT pg_advisory_unlock($1)`, sourceContextCleanupTestLock)
+ lockConn.Release()
+ })
+
+ workspaceID, userID, _, sourceIssueID := seedAttributionFixture(t, pool)
+ workspaceUUID := util.MustParseUUID(workspaceID)
+ userUUID := util.MustParseUUID(userID)
+ sourceIssueUUID := util.MustParseUUID(sourceIssueID)
+
+ contextIDs := make([]pgtype.UUID, 0, 2)
+ for i, age := range []string{"120 days", "119 days"} {
+ contextID := dbid.NewV7()
+ contextIDs = append(contextIDs, contextID)
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO issue_source_context (
+ id, workspace_id, source_issue_id, anchor_comment_id, captured_by_user_id,
+ snapshot_version, snapshot, capture_digest, state, captured_at
+ ) VALUES ($1, $2, $3, gen_random_uuid(), $4, 1, '{}'::jsonb, 'digest', 'abandoned',
+ now() - $5::interval)
+ `, contextID, workspaceUUID, sourceIssueUUID, userUUID, age); err != nil {
+ t.Fatalf("insert abandoned context %d: %v", i, err)
+ }
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO attachment (
+ id, workspace_id, source_context_id, uploader_type, uploader_id,
+ filename, url, content_type, size_bytes
+ ) VALUES (gen_random_uuid(), $1, $2, 'member', $3, 'clone.txt', $4, 'text/plain', 7)
+ `, workspaceUUID, contextID, userUUID,
+ "source-context-budget/abandoned-"+util.UUIDToString(contextID)); err != nil {
+ t.Fatalf("insert abandoned clone %d: %v", i, err)
+ }
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM attachment WHERE source_context_id = ANY($1::uuid[])`, contextIDs)
+ _, _ = pool.Exec(context.Background(), `DELETE FROM issue_source_context WHERE id = ANY($1::uuid[])`, contextIDs)
+ })
+
+ roundCtx, cancelRound := context.WithCancel(ctx)
+ defer cancelRound()
+ // Model the round budget expiring inside the first object delete.
+ store := &failingSourceContextObjectStore{onDelete: cancelRound}
+ svc := &TaskService{Queries: db.New(pool), TxStarter: pool, SourceContextStorage: store}
+
+ removed, err := svc.CleanupAbandonedSourceContexts(roundCtx, 10)
+ if err != nil {
+ t.Fatalf("abandoned cleanup after budget exhaustion = %v, want a clean stop", err)
+ }
+ if removed != 0 {
+ t.Fatalf("removed captures = %d, want 0 when no object could be deleted", removed)
+ }
+ if got := store.attemptCount(); got != 1 {
+ t.Fatalf("delete attempts = %d, want 1: the round must stop instead of walking the rest of the batch", got)
+ }
+ if len(store.deadlineBounded) != 1 || !store.deadlineBounded[0] {
+ t.Fatalf("object delete ran without a per-object deadline: %#v", store.deadlineBounded)
+ }
+
+ var surviving int
+ if err := pool.QueryRow(ctx, `
+ SELECT count(*) FROM issue_source_context WHERE id = ANY($1::uuid[]) AND state = 'abandoned'
+ `, contextIDs).Scan(&surviving); err != nil {
+ t.Fatalf("count surviving abandoned captures: %v", err)
+ }
+ if surviving != 2 {
+ t.Fatalf("surviving abandoned captures = %d, want 2 retained for the next round", surviving)
+ }
+}