Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6486: reduce stale dispatch reclaim load (#7375)
Multica Eve003a505b87a2
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex b912473f5b..6a1c09c599 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -244,6 +244,7 @@ var concurrentIndexCleanups = map[string]string{"361_issue_last_activity_index": "idx_issue_workspace_last_activity","363_plugin_invocation_installation_index": "idx_plugin_invocation_installation_created","364_plugin_invocation_created_at_index": "idx_plugin_invocation_created_at",+ "390_agent_task_queue_dispatched_reclaim_v2_index": "idx_agent_task_queue_dispatched_reclaim_v2",}// concurrentDownIndexCleanups covers every migration whose down direction@@ -264,6 +265,7 @@ var concurrentDownIndexCleanups = map[string]string{"312_drop_global_plugin_identity_key_index": "idx_plugin_identity_key","371_comment_content_search_index_strategy": "idx_comment_content_trgm","375_drop_issue_last_activity_index": "idx_issue_workspace_last_activity",+ "391_drop_agent_task_queue_dispatched_prepare_index": "idx_agent_task_queue_dispatched_prepare",}var preMigrationHooks = func() map[string]preMigrationHook {diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 4a6c4fe4dc..32d407995e 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1140,6 +1140,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// task. Returns nil when rdb is nil — TaskService treats that// as "no cache, always hit DB" (existing behavior).h.TaskService.EmptyClaim = service.NewEmptyClaimCache(rdb)+ // Stale-dispatch reclaim has a separate schedule because an empty queued+ // verdict cannot represent a claim response lost after commit. Missing or+ // failed Redis state keeps the historical PostgreSQL fallback.+ h.TaskService.ReclaimCheck = service.NewReclaimCheckCache(rdb)// Wire WS heartbeat after stores are finalized so the WS path uses the// same (possibly Redis-backed) stores as the HTTP path.diff --git a/server/internal/service/reclaim_check_cache.go b/server/internal/service/reclaim_check_cache.gonew file mode 100644index 0000000000..b0004032ff--- /dev/null+++ b/server/internal/service/reclaim_check_cache.go@@ -0,0 +1,288 @@+package service++import (+ "context"+ "log/slog"+ "strconv"+ "time"++ "github.com/redis/go-redis/v9"+)++const (+ reclaimCheckSchedulePrefix = "mul:claim:runtime:reclaim-schedule:"+ reclaimCheckBackstopPrefix = "mul:claim:runtime:reclaim-backstop:"+ reclaimCheckRetryBatchSize = 256++ // The backstop remains at or below the PostgreSQL recovery window so a+ // missed dispatch-side Redis write cannot delay recovery beyond one window.+ ReclaimCheckBackstopInterval = claimResponseRecoveryWindow+ // A due hint that produces no reclaimed row is retried at the daemon's next+ // normal polling cadence instead of becoming inert until the backstop.+ ReclaimCheckRetryInterval = 30 * time.Second+ // The Redis hint is captured immediately before the PostgreSQL dispatch+ // command. Leave a small margin for that command to commit so a hint cannot+ // fire just before the database's strict recovery-window predicate does.+ ReclaimCheckHintSafetyMargin = 5 * time.Second+ // A fresh task's first hint is one recovery window plus the safety margin in+ // the future. Keep the containing ZSET alive for another full window so the+ // hint survives its deadline and several bounded retries.+ ReclaimCheckScheduleTTL = 2*claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin+)++// These scripts use only Redis 2.6-era primitives. In particular, they avoid+// ZADD GT (Redis 6.2+) so self-hosted installations do not silently lose the+// scheduling optimization on older Redis versions.+const reclaimCheckTrackLaterScript = `+local current = redis.call('ZSCORE', KEYS[1], ARGV[1])+if not current then+ return 0+end+if tonumber(current) < tonumber(ARGV[2]) then+ redis.call('ZADD', KEYS[1], ARGV[2], ARGV[1])+end+redis.call('PEXPIRE', KEYS[1], ARGV[3])+return 1+`++const reclaimCheckDeferDueScript = `+local members = redis.call('ZRANGEBYSCORE', KEYS[1], '-inf', ARGV[1], 'LIMIT', '0', ARGV[3])+for _, member in ipairs(members) do+ redis.call('ZADD', KEYS[1], ARGV[2], member)+end+return #members+`++// ReclaimCheckCache keeps the batch/singular claim hot paths from issuing a+// stale-dispatch UPDATE when no task can possibly be reclaimed yet.+//+// Each runtime owns a sorted set of task IDs scored by their earliest known+// reclaim time. A separate last-checked timestamp forces a periodic DB check+// for cache loss, pre-deployment rows, or a missed write. Task scores and the+// last-checked timestamp are both application-clock values; PostgreSQL remains+// authoritative for actual eligibility when the query runs. Missing keys and+// Redis errors always mean "check PostgreSQL now", so the cache can only reduce+// load; it is never authoritative for task recovery.+type ReclaimCheckCache struct {+ rdb *redis.Client+}++func NewReclaimCheckCache(rdb *redis.Client) *ReclaimCheckCache {+ if rdb == nil {+ return nil+ }+ return &ReclaimCheckCache{rdb: rdb}+}++func reclaimCheckScheduleKey(runtimeID string) string {+ return reclaimCheckSchedulePrefix + runtimeID+}++func reclaimCheckBackstopKey(runtimeID string) string {+ return reclaimCheckBackstopPrefix + runtimeID+}++func (c *ReclaimCheckCache) bounded(ctx context.Context) (context.Context, context.CancelFunc) {+ return context.WithTimeout(ctx, emptyClaimRedisTimeout)+}++// DueRuntimeIDs returns only runtimes with a due task hint or whose periodic+// backstop has elapsed. It preserves the relative order of non-empty input IDs.+// MarkChecked advances hints seen by a completed DB check to a bounded retry+// deadline, so an unrecovered task is tried again without retriggering every+// poll. The schedule TTL remains a hard bound on stale cleanup hints.+//+// A nil cache, missing/malformed backstop, or Redis failure fails open. Batch+// callers treat any due runtime as a reason to query their complete runtime set.+func (c *ReclaimCheckCache) DueRuntimeIDs(ctx context.Context, runtimeIDs []string, now time.Time) []string {+ if len(runtimeIDs) == 0 {+ return nil+ }+ validRuntimeIDs := make([]string, 0, len(runtimeIDs))+ for _, runtimeID := range runtimeIDs {+ if runtimeID == "" {+ continue+ }+ validRuntimeIDs = append(validRuntimeIDs, runtimeID)+ }+ if len(validRuntimeIDs) == 0 {+ return nil+ }+ if c == nil {+ return validRuntimeIDs+ }++ bctx, cancel := c.bounded(ctx)+ defer cancel()+ backstopKeys := make([]string, 0, len(validRuntimeIDs))+ for _, runtimeID := range validRuntimeIDs {+ backstopKeys = append(backstopKeys, reclaimCheckBackstopKey(runtimeID))+ }+ backstops, err := c.rdb.MGet(bctx, backstopKeys...).Result()+ if err != nil {+ slog.Warn("reclaim_check_cache: backstop read failed; falling back to DB", "error", err)+ return validRuntimeIDs+ }+ if len(backstops) != len(validRuntimeIDs) {+ slog.Warn("reclaim_check_cache: incomplete backstop read; falling back to DB")+ return validRuntimeIDs+ }++ nowMillis := now.UnixMilli()+ type scheduleCommand struct {+ index int+ count *redis.IntCmd+ }+ due := make([]bool, len(validRuntimeIDs))+ pipe := c.rdb.Pipeline()+ scheduleCommands := make([]scheduleCommand, 0, len(validRuntimeIDs))+ for i, runtimeID := range validRuntimeIDs {+ backstop, ok := backstops[i].(string)+ if !ok {+ // A missing or non-string value means this runtime has no trustworthy+ // successful-check marker.+ due[i] = true+ continue+ }+ checkedMillis, err := strconv.ParseInt(backstop, 10, 64)+ if err != nil {+ due[i] = true+ continue+ }+ nextBackstop := checkedMillis + ReclaimCheckBackstopInterval.Milliseconds()+ if nextBackstop < checkedMillis || nextBackstop <= nowMillis {+ due[i] = true+ continue+ }+ scheduleCommands = append(scheduleCommands, scheduleCommand{+ index: i,+ count: pipe.ZCount(+ bctx,+ reclaimCheckScheduleKey(runtimeID),+ "-inf",+ strconv.FormatInt(nowMillis, 10),+ ),+ })+ }+ if len(scheduleCommands) > 0 {+ if _, err := pipe.Exec(bctx); err != nil {+ slog.Warn("reclaim_check_cache: schedule read failed; falling back to DB", "error", err)+ return validRuntimeIDs+ }+ for _, command := range scheduleCommands {+ count, err := command.count.Result()+ if err != nil {+ slog.Warn("reclaim_check_cache: schedule result failed; falling back to DB", "error", err)+ return validRuntimeIDs+ }+ if count > 0 {+ due[command.index] = true+ }+ }+ }+ dueRuntimeIDs := make([]string, 0, len(validRuntimeIDs))+ for i, runtimeID := range validRuntimeIDs {+ if due[i] {+ dueRuntimeIDs = append(dueRuntimeIDs, runtimeID)+ }+ }+ return dueRuntimeIDs+}++// Track records the earliest known reclaim time for one dispatched task. ZADD+// replaces the task's score after a fresh dispatch/reclaim; multiple tasks on+// one runtime remain independent, avoiding a runtime-level timestamp losing a+// second task's earlier recovery deadline.+func (c *ReclaimCheckCache) Track(ctx context.Context, runtimeID, taskID string, checkAfter time.Time) {+ c.track(ctx, runtimeID, taskID, checkAfter, false)+}++// TrackLater advances an existing task hint only when a prepare-lease extension+// protects it beyond its current recovery deadline. It deliberately does not+// create a missing member: without the initial dispatch deadline, a short lease+// could schedule an early failed check and delay recovery until the next+// backstop. Missing state already fails open through that bounded backstop.+func (c *ReclaimCheckCache) TrackLater(ctx context.Context, runtimeID, taskID string, checkAfter time.Time) {+ c.track(ctx, runtimeID, taskID, checkAfter, true)+}++func (c *ReclaimCheckCache) track(ctx context.Context, runtimeID, taskID string, checkAfter time.Time, onlyLater bool) {+ if c == nil || runtimeID == "" || taskID == "" || checkAfter.IsZero() {+ return+ }+ bctx, cancel := c.bounded(ctx)+ defer cancel()+ key := reclaimCheckScheduleKey(runtimeID)+ if onlyLater {+ if err := c.rdb.Eval(+ bctx,+ reclaimCheckTrackLaterScript,+ []string{key},+ taskID,+ checkAfter.UnixMilli(),+ ReclaimCheckScheduleTTL.Milliseconds(),+ ).Err(); err != nil {+ slog.Warn("reclaim_check_cache: extend hint failed; DB fallback remains active", "error", err)+ }+ return+ }+ pipe := c.rdb.Pipeline()+ member := redis.Z{Score: float64(checkAfter.UnixMilli()), Member: taskID}+ pipe.ZAdd(bctx, key, member)+ pipe.Expire(bctx, key, ReclaimCheckScheduleTTL)+ if _, err := pipe.Exec(bctx); err != nil {+ slog.Warn("reclaim_check_cache: track failed; DB fallback remains active", "error", err)+ }+}++// Forget removes a task that can no longer be reclaimed (started, requeued,+// waiting on a local directory, or terminal). Failures are harmless: the stale+// hint can cause one extra DB check but cannot make an ineligible task run.+func (c *ReclaimCheckCache) Forget(ctx context.Context, runtimeID, taskID string) {+ if c == nil || runtimeID == "" || taskID == "" {+ return+ }+ bctx, cancel := c.bounded(ctx)+ defer cancel()+ if err := c.rdb.ZRem(bctx, reclaimCheckScheduleKey(runtimeID), taskID).Err(); err != nil {+ slog.Warn("reclaim_check_cache: forget failed; stale hint will expire", "error", err)+ }+}++// MarkChecked records a successful PostgreSQL reclaim pass for every runtime in+// the machine-level polling set. Hints that actually triggered this pass are+// atomically moved to retryAfter instead of deleted or made inert: SKIP LOCKED+// and runtime-health predicates mean an empty result cannot prove those tasks no+// longer need recovery. Concurrent hints newer than checkedThrough are left+// untouched. The bounded batch prevents a pathological ZSET from monopolizing+// Redis; any excess due hints remain due and fail open to another DB pass.+func (c *ReclaimCheckCache) MarkChecked(ctx context.Context, runtimeIDs []string, checkedThrough, retryAfter time.Time) {+ if c == nil || len(runtimeIDs) == 0 {+ return+ }+ if retryAfter.IsZero() || !retryAfter.After(checkedThrough) {+ retryAfter = checkedThrough.Add(ReclaimCheckRetryInterval)+ }+ bctx, cancel := c.bounded(ctx)+ defer cancel()+ checkedMillis := strconv.FormatInt(checkedThrough.UnixMilli(), 10)+ retryMillis := strconv.FormatInt(retryAfter.UnixMilli(), 10)+ pipe := c.rdb.Pipeline()+ for _, runtimeID := range runtimeIDs {+ if runtimeID == "" {+ continue+ }+ pipe.Eval(+ bctx,+ reclaimCheckDeferDueScript,+ []string{reclaimCheckScheduleKey(runtimeID)},+ checkedMillis,+ retryMillis,+ reclaimCheckRetryBatchSize,+ )+ pipe.Set(bctx, reclaimCheckBackstopKey(runtimeID), checkedMillis, ReclaimCheckBackstopInterval)+ }+ if _, err := pipe.Exec(bctx); err != nil {+ slog.Warn("reclaim_check_cache: mark checked failed; falling back to DB", "error", err)+ }+}diff --git a/server/internal/service/reclaim_check_cache_test.go b/server/internal/service/reclaim_check_cache_test.gonew file mode 100644index 0000000000..5b6b0eee15--- /dev/null+++ b/server/internal/service/reclaim_check_cache_test.go@@ -0,0 +1,251 @@+package service++import (+ "context"+ "errors"+ "strconv"+ "testing"+ "time"++ "github.com/redis/go-redis/v9"+)++func TestReclaimCheckCache_NilFallsBackToEveryRuntime(t *testing.T) {+ var cache *ReclaimCheckCache+ runtimes := []string{"rt-a", "rt-b"}+ due := cache.DueRuntimeIDs(context.Background(), runtimes, time.Now())+ if len(due) != len(runtimes) || due[0] != runtimes[0] || due[1] != runtimes[1] {+ t.Fatalf("nil cache due runtimes = %v, want %v", due, runtimes)+ }+ cache.Track(context.Background(), "rt-a", "task-a", time.Now())+ cache.TrackLater(context.Background(), "rt-a", "task-a", time.Now())+ cache.Forget(context.Background(), "rt-a", "task-a")+ cache.MarkChecked(context.Background(), runtimes, time.Now(), time.Now().Add(ReclaimCheckRetryInterval))+}++func TestNewReclaimCheckCache_NilRedisReturnsNil(t *testing.T) {+ if cache := NewReclaimCheckCache(nil); cache != nil {+ t.Fatalf("NewReclaimCheckCache(nil) = %#v, want nil", cache)+ }+}++func TestReclaimCheckCache_RedisFailureFallsBackToEveryRuntime(t *testing.T) {+ rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:0"})+ if err := rdb.Close(); err != nil {+ t.Fatalf("close Redis client: %v", err)+ }+ cache := NewReclaimCheckCache(rdb)+ runtimes := []string{"rt-a", "rt-b"}+ due := cache.DueRuntimeIDs(context.Background(), runtimes, time.Now())+ if len(due) != len(runtimes) || due[0] != runtimes[0] || due[1] != runtimes[1] {+ t.Fatalf("failed Redis due runtimes = %v, want %v", due, runtimes)+ }+}++func TestReclaimCheckCache_ProductionWindowHintOutlivesDeadline(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()+ hintDistance := claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin+ hint := now.Add(hintDistance)++ // Put the backstop after the task hint so this test exercises the schedule,+ // not the periodic fallback, at the production recovery deadline including+ // its command-commit safety margin.+ cache.MarkChecked(+ ctx,+ []string{"rt-a"},+ now.Add(30*time.Second),+ now.Add(30*time.Second+ReclaimCheckRetryInterval),+ )+ cache.Track(ctx, "rt-a", "task-a", hint)++ ttl, err := rdb.PTTL(ctx, reclaimCheckScheduleKey("rt-a")).Result()+ if err != nil {+ t.Fatalf("schedule PTTL: %v", err)+ }+ if ttl <= hintDistance {+ t.Fatalf("schedule TTL = %v, must strictly outlive %v hint distance", ttl, hintDistance)+ }+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, hint.Add(-time.Millisecond)); len(due) != 0 {+ t.Fatalf("task must not be checked before its recovery time, got %v", due)+ }+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, hint.Add(time.Millisecond)); len(due) != 1 {+ t.Fatalf("production-window hint must remain observable when due, got %v", due)+ }+}++func TestReclaimCheckCache_CheckedHintIsDeferredAndRetriggers(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()++ cache.MarkChecked(ctx, []string{"rt-a"}, now, now.Add(ReclaimCheckRetryInterval))+ cache.Track(ctx, "rt-a", "task-a", now.Add(10*time.Second))+ cache.Track(ctx, "rt-a", "task-b", now.Add(20*time.Second))+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, now.Add(11*time.Second)); len(due) != 1 {+ t.Fatalf("task-a should trigger its first check, got %v", due)+ }+ ttlBefore, err := rdb.PTTL(ctx, reclaimCheckScheduleKey("rt-a")).Result()+ if err != nil {+ t.Fatalf("read schedule TTL before retry: %v", err)+ }+ retryAt := now.Add(11*time.Second + ReclaimCheckRetryInterval)+ cache.MarkChecked(ctx, []string{"rt-a"}, now.Add(11*time.Second), retryAt)+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, now.Add(12*time.Second)); len(due) != 0 {+ t.Fatalf("deferred hint must not retrigger the next poll, got %v", due)+ }+ score, err := rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "task-a").Result()+ if err != nil {+ t.Fatalf("successful check must retain task hint: %v", err)+ }+ if got := int64(score); got != retryAt.UnixMilli() {+ t.Fatalf("checked hint score = %d, want retry at %d", got, retryAt.UnixMilli())+ }+ ttlAfter, err := rdb.PTTL(ctx, reclaimCheckScheduleKey("rt-a")).Result()+ if err != nil {+ t.Fatalf("read schedule TTL after retry: %v", err)+ }+ if ttlAfter > ttlBefore {+ t.Fatalf("retry extended stale-hint lifetime from %v to %v", ttlBefore, ttlAfter)+ }+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, retryAt.Add(time.Millisecond)); len(due) != 1 {+ t.Fatalf("unrecovered hint must retrigger after the bounded retry, got %v", due)+ }++ // A newer hint that existed when the check began is not deferred with the+ // task that actually triggered the query.+ score, err = rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "task-b").Result()+ if err != nil {+ t.Fatalf("read newer task hint: %v", err)+ }+ if got := int64(score); got != now.Add(20*time.Second).UnixMilli() {+ t.Fatalf("newer hint moved to %d, want %d", got, now.Add(20*time.Second).UnixMilli())+ }+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, now.Add(21*time.Second)); len(due) != 1 {+ t.Fatalf("newer task hint should override the backstop, got %v", due)+ }+}++func TestReclaimCheckCache_TrackLaterAndForget(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()++ cache.Track(ctx, "rt-a", "task-a", now.Add(claimResponseRecoveryWindow))+ cache.TrackLater(ctx, "rt-a", "task-a", now.Add(prepareLeaseDuration))+ score, err := rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "task-a").Result()+ if err != nil {+ t.Fatalf("read task score after shorter lease: %v", err)+ }+ if got := int64(score); got != now.Add(claimResponseRecoveryWindow).UnixMilli() {+ t.Fatalf("shorter lease moved hint to %d, want %d", got, now.Add(claimResponseRecoveryWindow).UnixMilli())+ }++ later := now.Add(claimResponseRecoveryWindow + prepareLeaseDuration)+ cache.TrackLater(ctx, "rt-a", "task-a", later)+ score, err = rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "task-a").Result()+ if err != nil {+ t.Fatalf("read task score after later lease: %v", err)+ }+ if got := int64(score); got != later.UnixMilli() {+ t.Fatalf("later lease left hint at %d, want %d", got, later.UnixMilli())+ }++ cache.Forget(ctx, "rt-a", "task-a")+ if _, err := rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "task-a").Result(); !errors.Is(err, redis.Nil) {+ t.Fatalf("forgotten task score error = %v, want redis.Nil", err)+ }+ cache.TrackLater(ctx, "rt-a", "missing-task", later)+ if _, err := rdb.ZScore(ctx, reclaimCheckScheduleKey("rt-a"), "missing-task").Result(); !errors.Is(err, redis.Nil) {+ t.Fatalf("lease-only missing task score error = %v, want redis.Nil", err)+ }+}++func TestReclaimCheckCache_CollectionCheckAlignsBackstops(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()+ runtimes := []string{"rt-a", "rt-b"}++ cache.MarkChecked(ctx, []string{"rt-a"}, now, now.Add(ReclaimCheckRetryInterval))+ cache.MarkChecked(+ ctx,+ []string{"rt-b"},+ now.Add(30*time.Second),+ now.Add(30*time.Second+ReclaimCheckRetryInterval),+ )+ if due := cache.DueRuntimeIDs(ctx, runtimes, now.Add(91*time.Second)); len(due) != 1 || due[0] != "rt-a" {+ t.Fatalf("staggered backstops due = %v, want [rt-a]", due)+ }++ // ClaimTasksForRuntimes queries the complete set when any member is due and+ // records that successful pass for the complete set as well.+ cache.MarkChecked(+ ctx,+ runtimes,+ now.Add(91*time.Second),+ now.Add(91*time.Second+ReclaimCheckRetryInterval),+ )+ if due := cache.DueRuntimeIDs(ctx, runtimes, now.Add(150*time.Second)); len(due) != 0 {+ t.Fatalf("collection backstops drifted after joint check: %v", due)+ }+ if due := cache.DueRuntimeIDs(ctx, runtimes, now.Add(182*time.Second)); len(due) != 2 {+ t.Fatalf("aligned collection backstops due = %v, want both runtimes", due)+ }+}++func TestReclaimCheckCache_DueRuntimeIDsPreservesInputOrder(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()++ cache.MarkChecked(ctx, []string{"rt-b"}, now, now.Add(ReclaimCheckRetryInterval))+ cache.Track(ctx, "rt-b", "task-b", now.Add(time.Second))+ cache.MarkChecked(+ ctx,+ []string{"rt-a"},+ now.Add(-ReclaimCheckBackstopInterval-time.Second),+ now.Add(ReclaimCheckRetryInterval),+ )++ runtimes := []string{"rt-b", "rt-a"}+ if due := cache.DueRuntimeIDs(ctx, runtimes, now.Add(2*time.Second)); len(due) != 2 || due[0] != runtimes[0] || due[1] != runtimes[1] {+ t.Fatalf("due runtimes = %v, want input order %v", due, runtimes)+ }+}++func TestReclaimCheckCache_MarkCheckedBatchLimitFailsOpen(t *testing.T) {+ rdb := newRedisTestClient(t)+ cache := NewReclaimCheckCache(rdb)+ ctx := context.Background()+ now := time.Now()++ members := make([]redis.Z, 0, reclaimCheckRetryBatchSize+1)+ for i := 0; i <= reclaimCheckRetryBatchSize; i++ {+ members = append(members, redis.Z{+ Score: float64(now.Add(-time.Second).UnixMilli()),+ Member: "task-" + strconv.Itoa(i),+ })+ }+ key := reclaimCheckScheduleKey("rt-a")+ if err := rdb.ZAdd(ctx, key, members...).Err(); err != nil {+ t.Fatalf("seed due hints: %v", err)+ }+ if err := rdb.Expire(ctx, key, ReclaimCheckScheduleTTL).Err(); err != nil {+ t.Fatalf("expire due hints: %v", err)+ }+ cache.MarkChecked(ctx, []string{"rt-a"}, now, now.Add(ReclaimCheckRetryInterval))++ // The Lua script deliberately defers only a bounded number of members. Any+ // overflow remains due, forcing another DB pass instead of being hidden by+ // the newly written backstop.+ if due := cache.DueRuntimeIDs(ctx, []string{"rt-a"}, now.Add(time.Second)); len(due) != 1 {+ t.Fatalf("overflow hint did not fail open to another check: %v", due)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 24391e5d6e..8ae772e06e 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -51,6 +51,10 @@ type TaskService struct {// goes through the DB. Wired in router.go from the shared Redis// client.EmptyClaim *EmptyClaimCache+ // ReclaimCheck schedules the next time a runtime can plausibly contain a+ // stale dispatched task. It removes the unconditional reclaim UPDATE from+ // idle claim polls while missing/error states preserve the DB fallback.+ ReclaimCheck *ReclaimCheckCache// Composio computes the per-task MCP overlay (Stage 3 of the Composio// epic, MUL-3721) — the integration's "current user's connected apps// → MCP session URL" hook called from each Enqueue* path. Optional: a@@ -178,6 +182,52 @@ const (prepareLeaseDuration = 45 * time.Second)+func (s *TaskService) trackTaskForReclaim(task db.AgentTaskQueue, checkAfter time.Time) {+ if !task.RuntimeID.Valid || !task.ID.Valid || task.Status != "dispatched" {+ return+ }+ // The Redis hint is advisory and intentionally uses an application-clock+ // elapsed deadline captured beside the DB command. Comparing PostgreSQL's+ // absolute dispatched_at/lease timestamps with time.Now would mix clocks;+ // PostgreSQL remains authoritative when the reclaim query actually runs.+ // A bounded background context lets this best-effort write outlive a request+ // cancellation without allowing Redis to stall the hot path indefinitely.+ s.ReclaimCheck.Track(+ context.Background(),+ util.UUIDToString(task.RuntimeID),+ util.UUIDToString(task.ID),+ checkAfter,+ )+}++func (s *TaskService) extendTaskReclaimHint(task db.AgentTaskQueue, checkAfter time.Time) {+ if !task.RuntimeID.Valid || !task.ID.Valid || task.Status != "dispatched" {+ return+ }+ // Preserve a later initial recovery deadline; a short prepare lease should+ // only move the hint when repeated extensions actually protect the task for+ // longer. See trackTaskForReclaim for the clock/context rationale.+ s.ReclaimCheck.TrackLater(+ context.Background(),+ util.UUIDToString(task.RuntimeID),+ util.UUIDToString(task.ID),+ checkAfter,+ )+}++func (s *TaskService) forgetTaskReclaim(task db.AgentTaskQueue) {+ if !task.RuntimeID.Valid || !task.ID.Valid {+ return+ }+ // This cleanup is best-effort and uses the cache's bounded timeout; request+ // cancellation must not make a committed task transition leave a stale hint.+ s.ReclaimCheck.Forget(+ context.Background(),+ util.UUIDToString(task.RuntimeID),+ util.UUIDToString(task.ID),+ )+}+// buildCommentTriggerSummary fetches the comment content and truncates// it for storage on the task row. Returns an invalid pgtype.Text when// the comment is missing (deleted / wrong workspace / etc) so the column@@ -2998,6 +3048,7 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.Uoutcome := "unknown"var getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs int64var claimed *db.AgentTaskQueue+ var reclaimCheckAfter time.Timedefer func() {s.maybeLogClaimSlow(agentID, outcome, start, getAgentMs, countRunningMs, claimAgentMs, reanchorMs, updateStatusMs, dispatchMs)}()@@ -3033,6 +3084,7 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.U}t0 = time.Now()+ reclaimCheckAfter = t0.Add(claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin)task, err := qtx.ClaimAgentTask(ctx, db.ClaimAgentTaskParams{AgentID: agentID,RuntimeID: claimRuntimeID,@@ -3084,6 +3136,7 @@ func (s *TaskService) claimTask(ctx context.Context, agentID, runtimeID pgtype.Uif claimed == nil {return nil, nil}+ s.trackTaskForReclaim(*claimed, reclaimCheckAfter)slog.Info("task claimed", "task_id", util.UUIDToString(claimed.ID), "agent_id", util.UUIDToString(agentID))s.captureTaskDispatched(ctx, *claimed)@@ -3144,27 +3197,45 @@ func (s *TaskService) ClaimTaskForRuntime(ctx context.Context, runtimeID pgtype.return nil, err}- // Check this before EmptyClaim: a lost claim response moves the task out of- // `queued`, so the empty-queued cache cannot represent recoverability.- stale, err := s.Queries.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{- RuntimeID: runtimeID,- ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),- PrepareLeaseSecs: prepareLeaseDuration.Seconds(),- RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,- })- if err == nil {- outcome = "reclaimed_dispatched"- claimedFlag = true- slog.Info("stale dispatched task reclaimed",- "task_id", util.UUIDToString(stale.ID),- "runtime_id", runtimeKey,- "agent_id", util.UUIDToString(stale.AgentID),+ // Keep stale-response recovery before EmptyClaim because the queued-only+ // cache cannot represent dispatched work. ReclaimCheck independently skips+ // the UPDATE until a task hint or bounded DB backstop is due.+ checkStarted := time.Now()+ if due := s.ReclaimCheck.DueRuntimeIDs(ctx, []string{runtimeKey}, checkStarted); len(due) > 0 {+ reclaimCheckAfter := time.Now().Add(claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin)+ stale, err := s.Queries.ReclaimStaleDispatchedTaskForRuntime(ctx, db.ReclaimStaleDispatchedTaskForRuntimeParams{+ RuntimeID: runtimeID,+ ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ })+ if err == nil {+ s.ReclaimCheck.MarkChecked(+ ctx,+ []string{runtimeKey},+ checkStarted,+ time.Now().Add(ReclaimCheckRetryInterval),+ )+ s.trackTaskForReclaim(stale, reclaimCheckAfter)+ outcome = "reclaimed_dispatched"+ claimedFlag = true+ slog.Info("stale dispatched task reclaimed",+ "task_id", util.UUIDToString(stale.ID),+ "runtime_id", runtimeKey,+ "agent_id", util.UUIDToString(stale.AgentID),+ )+ return &stale, nil+ }+ if !errors.Is(err, pgx.ErrNoRows) {+ outcome = "error_reclaim_dispatched"+ return nil, fmt.Errorf("reclaim stale dispatched task: %w", err)+ }+ s.ReclaimCheck.MarkChecked(+ ctx,+ []string{runtimeKey},+ checkStarted,+ time.Now().Add(ReclaimCheckRetryInterval),)- return &stale, nil- }- if !errors.Is(err, pgx.ErrNoRows) {- outcome = "error_reclaim_dispatched"- return nil, fmt.Errorf("reclaim stale dispatched task: %w", err)}if s.EmptyClaim.IsEmpty(ctx, runtimeKey) {@@ -3293,6 +3364,7 @@ func (s *TaskService) RequeueTaskAfterClaimFailure(ctx context.Context, task db.if err != nil {return nil, fmt.Errorf("requeue task after claim failure: %w", err)}+ s.forgetTaskReclaim(requeued)s.ReconcileAgentStatus(ctx, requeued.AgentID)s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, requeued)s.notifyTaskAvailable(requeued)@@ -3380,18 +3452,43 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgs.NotifyTaskEnqueued(ctx, task)}- // 2. Reclaim lost-response dispatched tasks across the set, up to maxTasks.- reclaimed, err := s.Queries.ReclaimStaleDispatchedTasksForRuntimes(ctx, db.ReclaimStaleDispatchedTasksForRuntimesParams{- RuntimeIds: uniqueIDs,- ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),- PrepareLeaseSecs: prepareLeaseDuration.Seconds(),- RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,- MaxTasks: int32(maxTasks),- })- if err != nil {- return nil, fmt.Errorf("reclaim stale dispatched tasks: %w", err)+ // 2. Reclaim lost-response dispatched tasks when any runtime's task schedule+ // or bounded DB backstop is due. The query always receives the complete+ // machine-level set so per-runtime backstops stay aligned and fixed UPDATE+ // setup/locking cost is paid at a predictable cadence. A nil/missing/failed+ // cache preserves the historical query path.+ runtimeKeys := make([]string, 0, len(uniqueIDs))+ for _, rid := range uniqueIDs {+ runtimeKeys = append(runtimeKeys, util.UUIDToString(rid))+ }+ checkStarted := time.Now()+ dueKeys := s.ReclaimCheck.DueRuntimeIDs(ctx, runtimeKeys, checkStarted)+ var reclaimed []db.AgentTaskQueue+ var reclaimCheckAfter time.Time+ if len(dueKeys) > 0 {+ reclaimCheckAfter = time.Now().Add(claimResponseRecoveryWindow + ReclaimCheckHintSafetyMargin)+ reclaimed, err = s.Queries.ReclaimStaleDispatchedTasksForRuntimes(ctx, db.ReclaimStaleDispatchedTasksForRuntimesParams{+ RuntimeIds: uniqueIDs,+ ClaimRecoverySecs: claimResponseRecoveryWindow.Seconds(),+ PrepareLeaseSecs: prepareLeaseDuration.Seconds(),+ RuntimeStaleSecs: RuntimeClaimFreshnessSeconds,+ MaxTasks: int32(maxTasks),+ })+ if err != nil {+ return nil, fmt.Errorf("reclaim stale dispatched tasks: %w", err)+ }+ // The UPDATE's fixed setup/locking cost dominates array width. Query and+ // advance the complete machine-level set together so per-runtime backstops+ // cannot drift into one UPDATE on almost every daemon poll.+ s.ReclaimCheck.MarkChecked(+ ctx,+ runtimeKeys,+ checkStarted,+ time.Now().Add(ReclaimCheckRetryInterval),+ )}for i := range reclaimed {+ s.trackTaskForReclaim(reclaimed[i], reclaimCheckAfter)claimed = append(claimed, reclaimed[i])slog.Info("stale dispatched task reclaimed (batch)","task_id", util.UUIDToString(reclaimed[i].ID),@@ -3581,6 +3678,7 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Agif err != nil {return nil, fmt.Errorf("start task: %w", err)}+ s.forgetTaskReclaim(task)s.cancelDeferredEscalationsForTask(ctx, task.ID)slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))@@ -3648,6 +3746,15 @@ func (s *TaskService) ExtendTaskPrepareLease(ctx context.Context, taskID, runtimif err != nil {return nil, fmt.Errorf("extend task prepare lease: %w", err)}+ if task.Status == "dispatched" {+ // Use the successful response time as a conservative application-clock+ // approximation of the DB lease start. Scheduling slightly late by query+ // latency is safer than an early failed check suppressing the hint until+ // the next backstop.+ s.extendTaskReclaimHint(task, time.Now().Add(prepareLeaseDuration))+ } else {+ s.forgetTaskReclaim(task)+ }return &task, nil}@@ -3667,6 +3774,7 @@ func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskIDif err != nil {return nil, fmt.Errorf("mark task waiting_local_directory: %w", err)}+ s.forgetTaskReclaim(task)slog.Info("task waiting_local_directory","task_id", util.UUIDToString(task.ID),@@ -6003,6 +6111,7 @@ func (s *TaskService) NotifyTaskEnqueued(ctx context.Context, task db.AgentTaskQ// is not available; the hint only means that a queued successor may have// become claimable because an agent-capacity or serialization barrier cleared.func (s *TaskService) NotifyTaskFinished(task db.AgentTaskQueue) {+ s.forgetTaskReclaim(task)s.notifyRuntimeMayHaveWork(task.RuntimeID, "")}@@ -6015,6 +6124,7 @@ func (s *TaskService) notifyTasksFinished(tasks []db.AgentTaskQueue) {if !task.RuntimeID.Valid {continue}+ s.forgetTaskReclaim(task)runtimeKey := util.UUIDToString(task.RuntimeID)if _, ok := seen[runtimeKey]; ok {continuediff --git a/server/internal/service/task_batch_claim_test.go b/server/internal/service/task_batch_claim_test.goindex d9e556556c..84b6ebc366 100644--- a/server/internal/service/task_batch_claim_test.go+++ b/server/internal/service/task_batch_claim_test.go@@ -165,6 +165,140 @@ func TestClaimTasksForRuntimes_MaxTasksCap(t *testing.T) {}}+// TestClaimTasksForRuntimes_AnyDueRuntimeChecksTheCompleteSet pins MUL-6486's+// collection-level reclaim gate. Per-runtime backstops can begin staggered, but+// one due member must run the single UPDATE over every runtime on that daemon;+// filtering the SQL array to only the due member both misses recoverable work+// and lets fixed query overhead drift back toward one call per poll.+func TestClaimTasksForRuntimes_AnyDueRuntimeChecksTheCompleteSet(t *testing.T) {+ ctx := context.Background()+ rdb := newRedisTestClient(t)+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.ReclaimCheck = NewReclaimCheckCache(rdb)++ rt1, rt2 := batchClaimFixture(t, ctx, pool)+ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}++ var staleTaskID string+ if err := pool.QueryRow(ctx, `+ SELECT id FROM agent_task_queue+ WHERE runtime_id = $1+ ORDER BY created_at+ LIMIT 1+ `, rt2).Scan(&staleTaskID); err != nil {+ t.Fatalf("load rt2 task: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'dispatched', dispatched_at = now() - interval '10 minutes',+ started_at = NULL, prepare_lease_expires_at = NULL+ WHERE id = $1+ `, staleTaskID); err != nil {+ t.Fatalf("make rt2 task stale: %v", err)+ }++ now := time.Now()+ svc.ReclaimCheck.MarkChecked(+ ctx,+ []string{rt1},+ now.Add(-ReclaimCheckBackstopInterval-time.Second),+ now.Add(ReclaimCheckRetryInterval),+ )+ svc.ReclaimCheck.MarkChecked(ctx, []string{rt2}, now, now.Add(ReclaimCheckRetryInterval))+ due := svc.ReclaimCheck.DueRuntimeIDs(ctx, []string{rt1, rt2}, now)+ if len(due) != 1 || due[0] != rt1 {+ t.Fatalf("precondition due runtimes = %v, want [%s]", due, rt1)+ }++ claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("batch claim: %v", err)+ }+ for _, task := range claimed {+ if util.UUIDToString(task.ID) == staleTaskID {+ return+ }+ }+ t.Fatalf("batch claim omitted stale task %s on non-due runtime %s: got %v", staleTaskID, rt2, claimed)+}++// TestClaimTasksForRuntimes_EmptyReclaimDefersHintForRetry covers the recovery+// hole where the task hint was previously made inert after one empty UPDATE.+// A temporarily stale runtime heartbeat is intentionally correlated with a+// lost claim response: the task remains dispatched, and its hint must become+// due again after the short retry rather than waiting for the 90-second+// backstop.+func TestClaimTasksForRuntimes_EmptyReclaimDefersHintForRetry(t *testing.T) {+ ctx := context.Background()+ rdb := newRedisTestClient(t)+ pool := newTaskClaimRacePool(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.ReclaimCheck = NewReclaimCheckCache(rdb)++ rt1, _ := batchClaimFixture(t, ctx, pool)+ runtimeID := util.MustParseUUID(rt1)+ var taskID string+ if err := pool.QueryRow(ctx, `+ SELECT id FROM agent_task_queue+ WHERE runtime_id = $1+ ORDER BY created_at+ LIMIT 1+ `, rt1).Scan(&taskID); err != nil {+ t.Fatalf("load task: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ UPDATE agent_task_queue+ SET status = 'dispatched', dispatched_at = now() - interval '10 minutes',+ started_at = NULL, prepare_lease_expires_at = NULL+ WHERE id = $1+ `, taskID); err != nil {+ t.Fatalf("make task stale: %v", err)+ }+ if _, err := pool.Exec(ctx, `+ UPDATE agent_runtime+ SET status = 'online', last_seen_at = now() - interval '10 minutes'+ WHERE id = $1+ `, rt1); err != nil {+ t.Fatalf("make runtime temporarily ineligible: %v", err)+ }++ now := time.Now()+ svc.ReclaimCheck.MarkChecked(ctx, []string{rt1}, now, now.Add(ReclaimCheckRetryInterval))+ svc.ReclaimCheck.Track(ctx, rt1, taskID, now.Add(-time.Second))+ if due := svc.ReclaimCheck.DueRuntimeIDs(ctx, []string{rt1}, now); len(due) != 1 {+ t.Fatalf("precondition due runtimes = %v, want [%s]", due, rt1)+ }++ if claimed, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{runtimeID}, 5); err != nil {+ t.Fatalf("batch claim: %v", err)+ } else if len(claimed) != 0 {+ t.Fatalf("claimed tasks with stale runtime heartbeat: %v", claimed)+ }+ var status string+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, taskID).Scan(&status); err != nil {+ t.Fatalf("read task after empty reclaim: %v", err)+ }+ if status != "dispatched" {+ t.Fatalf("task status after empty reclaim = %q, want dispatched", status)+ }++ score, err := rdb.ZScore(ctx, reclaimCheckScheduleKey(rt1), taskID).Result()+ if err != nil {+ t.Fatalf("read deferred hint: %v", err)+ }+ retryAt := time.UnixMilli(int64(score))+ if retryAt.Before(now.Add(ReclaimCheckRetryInterval)) || retryAt.After(time.Now().Add(ReclaimCheckRetryInterval+time.Second)) {+ t.Fatalf("retry hint = %v, want approximately one retry interval after the check", retryAt)+ }+ if due := svc.ReclaimCheck.DueRuntimeIDs(ctx, []string{rt1}, retryAt.Add(-time.Millisecond)); len(due) != 0 {+ t.Fatalf("hint retriggered before retry deadline: %v", due)+ }+ if due := svc.ReclaimCheck.DueRuntimeIDs(ctx, []string{rt1}, retryAt.Add(time.Millisecond)); len(due) != 1 {+ t.Fatalf("hint did not retrigger after empty reclaim: %v", due)+ }+}+// TestClaimTasksForRuntimes_EmptyInputs guards the trivial short-circuits.func TestClaimTasksForRuntimes_EmptyInputs(t *testing.T) {ctx := context.Background()diff --git a/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.down.sql b/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.down.sqlnew file mode 100644index 0000000000..cb1b9cc6a3--- /dev/null+++ b/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_dispatched_reclaim_v2;diff --git a/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.up.sql b/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.up.sqlnew file mode 100644index 0000000000..ca6f6324f8--- /dev/null+++ b/server/migrations/390_agent_task_queue_dispatched_reclaim_v2_index.up.sql@@ -0,0 +1,5 @@+-- Put dispatched_at directly after runtime_id so stale-reclaim scans can use+-- both equality and time-range conditions before applying the priority sort.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_dispatched_reclaim_v2+ ON agent_task_queue (runtime_id, dispatched_at ASC, priority DESC)+ WHERE status = 'dispatched' AND started_at IS NULL;diff --git a/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.down.sql b/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.down.sqlnew file mode 100644index 0000000000..4da7ee827f--- /dev/null+++ b/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.down.sql@@ -0,0 +1,3 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_dispatched_prepare+ ON agent_task_queue (runtime_id, priority DESC, dispatched_at ASC)+ WHERE status = 'dispatched' AND started_at IS NULL;diff --git a/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.up.sql b/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.up.sqlnew file mode 100644index 0000000000..a977fd3029--- /dev/null+++ b/server/migrations/391_drop_agent_task_queue_dispatched_prepare_index.up.sql@@ -0,0 +1,3 @@+-- Migration 390 replaces this index with the same partial predicate and a key+-- order that makes dispatched_at usable as a stale-reclaim range condition.+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_dispatched_prepare;