Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6895, MUL-6586: fix(daemon,tasks): force a server-side re-check for woken runtimes to clear a stale empty-claim stall (#7824)
Danila Katalshovc07c978407e4
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex a88799979d..add81377ba 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -204,6 +204,7 @@ func daemonHTTPClientCapabilities() string {func daemonCommonCapabilities() []string {return []string{+ protocol.DaemonCapabilityForceRecheckV1,protocol.DaemonCapabilitySkillBundlesV1,protocol.DaemonCapabilityCoalescedCommentsV1,protocol.DaemonCapabilityLocalWorktreeV1,@@ -277,11 +278,24 @@ const batchClaimRequestTimeout = protocol.DaemonBatchClaimRequestTimeout// daemons advertising claim-poll-hints-v1. A zero-value result is deliberately// conservative: it makes the poller retain PollInterval, which protects new// daemons talking to old servers and claims whose WS outcome was uncertain.+//+// ForceRecheckedRuntimeIDs is the server's force_rechecked_runtime_ids+// acknowledgement (#7452): the forced runtimes the server observed genuinely+// idle this cycle (a zero-candidate scan, cache re-armed). It is a POINTER so absence is distinguishable from emptiness:+// a non-nil empty slice means an upgraded server acknowledged nothing, so the+// caller keeps every drained runtime forced; nil means the server omitted the+// field (it predates #7452, or the legacy per-runtime fallback ran), so the+// caller drops the drained hints as before #7452 and the empty-claim TTL stays+// the outer bound. The WS transport also synthesizes values: the cooldown+// branch returns present-but-empty (nothing was sent) and the uncertain-after-+// send branch acknowledges the whole drained set (a frame went out, so+// replaying the hint could double-claim).type claimTasksResult struct {- Tasks []*Task `json:"tasks"`- ClaimPollHintSupported bool `json:"claim_poll_hint_supported,omitempty"`- NextDeferredTaskAfterMillis int64 `json:"next_deferred_task_after_ms,omitempty"`- ClaimedOverWS bool `json:"-"`+ Tasks []*Task `json:"tasks"`+ ClaimPollHintSupported bool `json:"claim_poll_hint_supported,omitempty"`+ NextDeferredTaskAfterMillis int64 `json:"next_deferred_task_after_ms,omitempty"`+ ForceRecheckedRuntimeIDs *[]string `json:"force_rechecked_runtime_ids,omitempty"`+ ClaimedOverWS bool `json:"-"`}// ClaimTasks is the machine-level (MUL-4257) batch counterpart of ClaimTask:@@ -299,18 +313,36 @@ func (c *Client) ClaimTasks(ctx context.Context, daemonID string, runtimeIDs []sreturn result.Tasks, err}-func (c *Client) claimTasksWithHints(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) (claimTasksResult, error) {+// claimTasksWithHints issues the HTTP batch claim and returns the full+// claimTasksResult, including any scheduling hints and the #7452+// force_rechecked_runtime_ids acknowledgement. forceRecheckIDs are the runtimes+// woken since the last claim; they ride along in the request body so the server+// bypasses their cached "empty" verdict for exactly this claim.+func (c *Client) claimTasksWithHints(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int, forceRecheckIDs ...string) (claimTasksResult, error) {reqCtx, cancel := context.WithTimeout(ctx, batchClaimRequestTimeout)defer cancel()var resp claimTasksResult- if err := c.postJSON(reqCtx, "/api/daemon/tasks/claim", map[string]any{+ if err := c.postJSON(reqCtx, "/api/daemon/tasks/claim", claimTasksBody(daemonID, runtimeIDs, maxTasks, forceRecheckIDs...), &resp); err != nil {+ return claimTasksResult{}, err+ }+ return resp, nil+}++// claimTasksBody builds the batch-claim request body shared by the HTTP and+// WS-first transports so both stay byte-identical. force_recheck_runtime_ids+// (#7452) is an optional, additive field: it is omitted when no runtime was+// woken so a steady-state poll is exactly the pre-#7452 request, and an older+// server that does not know the field simply ignores it.+func claimTasksBody(daemonID string, runtimeIDs []string, maxTasks int, forceRecheckIDs ...string) map[string]any {+ body := map[string]any{"daemon_id": daemonID,"runtime_ids": runtimeIDs,"max_tasks": maxTasks,- }, &resp); err != nil {- return claimTasksResult{}, err}- return resp, nil+ if len(forceRecheckIDs) > 0 {+ body["force_recheck_runtime_ids"] = forceRecheckIDs+ }+ return body}// isBatchClaimUnsupported reports whether err is a 404 from the batch claimdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 2dcb051c4f..6e7bffa769 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -648,6 +648,14 @@ type Daemon struct {pendingWorkInflight map[string]struct{} // runtime_id -> hint-driven heartbeat in flightpendingWorkLastRun map[string]time.Time // runtime_id -> when the last hint-driven heartbeat started+ // forceRecheckMu guards forceRecheckRuntimes, the set of runtimes woken by a+ // targeted `task_available` since the last batch claim (#7452). The next+ // claim carries them so the server bypasses their cached "empty" verdict,+ // repairing a stale verdict left by a lost EmptyClaim.Bump instead of+ // stalling the queued task until the 3-minute TTL.+ forceRecheckMu sync.Mutex+ forceRecheckRuntimes map[string]struct{} // runtime_id -> woken since last claim+cancelFunc context.CancelFunc // set by Run(); called by triggerRestartrootCtx context.Context // set by Run(); used by long-running recoveries that must survive per-runtime ctx cancellation// restartMu guards restartBinary. Two goroutines can reach triggerRestart —@@ -5503,9 +5511,13 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er// The batch poller re-derives allRuntimeIDs() each cycle; nudge it to// pick up a registered/removed runtime promptly.nudge()- case <-taskWakeups:+ case wk := <-taskWakeups:// Targeted-runtime and catch-up wakeups both trigger one batch claim- // across the whole runtime set.+ // across the whole runtime set. A targeted wakeup also records its+ // runtime so the next claim forces a server-side re-check that bypasses+ // a stale cached "empty" verdict (#7452); a catch-up wakeup has no+ // runtime id and only nudges.+ d.noteWokenRuntime(wk.runtimeID)nudge()}}@@ -5572,10 +5584,22 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan icontinue}- claimResult, err := d.claimTasksWSFirst(pollerCtx, d.cfg.DaemonID, runtimeIDs, len(slots))+ // Drain the runtimes woken since the last claim and force a server-side+ // re-check for them so a stale cached "empty" verdict cannot strand their+ // queued task until the TTL (#7452). Intersect with the live runtime set+ // so a runtime deleted since it was woken (#7969) is never force-rechecked.+ forceRecheck := d.filterLiveRuntimes(d.drainWokenRuntimes())+ claimResult, err := d.claimTasksWSFirst(pollerCtx, d.cfg.DaemonID, runtimeIDs, len(slots), forceRecheck...)if err != nil {d.exitClaim()releaseSlots(slots)+ // Preserve the force signal across a transient claim failure so the+ // woken runtime is still re-checked on the next cycle. Re-filter+ // against the live set so a runtime deleted during the in-flight claim+ // is dropped instead of re-forced.+ for _, rid := range d.filterLiveRuntimes(forceRecheck) {+ d.noteWokenRuntime(rid)+ }if pollerCtx.Err() == nil {d.logger.Warn("batch claim failed", "error", err)}@@ -5586,6 +5610,10 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i}tasks := claimResult.Tasks+ // Re-filter before consuming so a runtime deleted during the in-flight+ // claim is dropped from the re-note rather than re-forced next cycle.+ d.consumeForceRecheckHints(d.filterLiveRuntimes(forceRecheck), claimResult.ForceRecheckedRuntimeIDs)+// Dispatch each claimed task into a slot. activeTasks is incremented for// every dispatched task BEFORE exitClaim so the auto-update barrier never// sees a zero-claims / zero-active window between claim and dispatch.@@ -5645,6 +5673,107 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i}}+// noteWokenRuntime records a runtime woken by a targeted `task_available` so the+// next batch claim forces a server-side re-check that bypasses its cached+// "empty" verdict (#7452). A catch-up wakeup carries no runtime id and is a+// no-op here — it still nudges the poller, which polls the whole set normally.+func (d *Daemon) noteWokenRuntime(runtimeID string) {+ if runtimeID == "" {+ return+ }+ d.forceRecheckMu.Lock()+ if d.forceRecheckRuntimes == nil {+ d.forceRecheckRuntimes = make(map[string]struct{})+ }+ d.forceRecheckRuntimes[runtimeID] = struct{}{}+ d.forceRecheckMu.Unlock()+}++// consumeForceRecheckHints decides which drained force-recheck runtimes stay+// forced after a claim (#7452). acknowledged is the server's+// force_rechecked_runtime_ids, as a pointer so absence is distinguishable from+// emptiness:+// - acknowledged == nil: the server never returned the field, so it is older+// than #7452 and can never act on the hint. Drop the drained hints (the+// pre-#7452 behaviour) rather than re-forcing forever; the empty-claim TTL+// remains the outer bound.+// - acknowledged non-nil: an upgraded server spoke. It lists only the forced+// runtimes it observed genuinely idle (a zero-candidate scan, cache+// re-armed). Every other drained runtime is re-noted and forced again next+// cycle, including when the list is empty. A forced runtime whose scan found+// candidates is deliberately in that group: it keeps its stale cached+// verdict until a scan comes back empty, so the fix never depends on a+// Redis repair write succeeding.+//+// The caller passes a set already intersected with the live runtime set+// (filterLiveRuntimes), so a runtime deleted since it was woken is never+// re-forced here — see runBatchPoller.+func (d *Daemon) consumeForceRecheckHints(drained []string, acknowledged *[]string) {+ if len(drained) == 0 || acknowledged == nil {+ return+ }+ acked := make(map[string]struct{}, len(*acknowledged))+ for _, rid := range *acknowledged {+ acked[rid] = struct{}{}+ }+ for _, rid := range drained {+ if _, ok := acked[rid]; !ok {+ d.noteWokenRuntime(rid)+ }+ }+}++// drainWokenRuntimes returns and clears the runtimes woken since the last claim.+// The poller calls it immediately before issuing a claim; on a claim error the+// caller re-notes them so a transient failure does not drop the force signal.+func (d *Daemon) drainWokenRuntimes() []string {+ d.forceRecheckMu.Lock()+ defer d.forceRecheckMu.Unlock()+ if len(d.forceRecheckRuntimes) == 0 {+ return nil+ }+ out := make([]string, 0, len(d.forceRecheckRuntimes))+ for id := range d.forceRecheckRuntimes {+ out = append(out, id)+ }+ d.forceRecheckRuntimes = nil+ return out+}++// filterLiveRuntimes intersects ids with the daemon's current live runtime set+// (#7452, #7969). A runtime deleted after being woken can never appear in the+// server's force_rechecked_runtime_ids ack — the server filters the request down+// to authorized runtimes — so without this intersection its id would be re-noted+// and re-sent on every cycle forever. The poller re-derives liveness at each use+// (drain-before-claim, error re-note, consume), so a deletion that races an+// in-flight claim is dropped on the very next use rather than persisting.+func (d *Daemon) filterLiveRuntimes(ids []string) []string {+ if len(ids) == 0 {+ return ids+ }+ live := make(map[string]struct{})+ for _, id := range d.allRuntimeIDs() {+ live[id] = struct{}{}+ }+ out := make([]string, 0, len(ids))+ for _, id := range ids {+ if _, ok := live[id]; ok {+ out = append(out, id)+ }+ }+ return out+}++// hasPendingForceRecheck reports whether any runtime is still awaiting a forced+// server-side re-check (#7452). taskClaimPollInterval consults it after a claim+// that took work, so a woken runtime's remaining same-agent task is not left+// behind the ~3-minute WS safety interval.+func (d *Daemon) hasPendingForceRecheck() bool {+ d.forceRecheckMu.Lock()+ defer d.forceRecheckMu.Unlock()+ return len(d.forceRecheckRuntimes) > 0+}+// taskClaimPollInterval returns the next missed-event safety poll. The longer// cadence is only safe when this exact claim response came from a server that// opted into scheduling hints; a missing hint covers old servers and uncertain@@ -5652,11 +5781,37 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i// jitter keeps the default below the server's 3-minute empty-claim cache TTL// while preventing an idle fleet from polling in lockstep.func (d *Daemon) taskClaimPollInterval(result claimTasksResult) time.Duration {- if !d.wsRPC.supportsRPCV1() || !result.ClaimedOverWS || !result.ClaimPollHintSupported {- if d.cfg.PollInterval > 0 {- return d.cfg.PollInterval+ interval := d.baseTaskClaimPollInterval(result)+ // A forced claim that claimed work while a force-recheck hint is still+ // pending (#7452) must not wait out the long WS safety interval: the+ // server keeps a runtime forced while it still has candidates, and the+ // one-attempt-per-agent rule can leave a second same-agent task queued+ // behind the stale cached verdict. Cap the wait at the normal poll so the+ // next forced claim takes it. The cap applies only while claims make+ // progress: a runtime whose remaining candidates are blocked (agent or+ // runtime capacity, per-(issue, agent) serialization, a stale heartbeat, a+ // locked row) stays forced but goes back to the normal cadence, and the+ // terminal transition that clears a capacity or serialization barrier sends+ // its own targeted wakeup. Capping instead of returning keeps a sooner+ // deferred-task deadline.+ if len(result.Tasks) > 0 && d.hasPendingForceRecheck() {+ if poll := d.normalTaskClaimPollInterval(); interval > poll {+ interval = poll}- return DefaultPollInterval+ }+ return interval+}++func (d *Daemon) normalTaskClaimPollInterval() time.Duration {+ if d.cfg.PollInterval > 0 {+ return d.cfg.PollInterval+ }+ return DefaultPollInterval+}++func (d *Daemon) baseTaskClaimPollInterval(result claimTasksResult) time.Duration {+ if !d.wsRPC.supportsRPCV1() || !result.ClaimedOverWS || !result.ClaimPollHintSupported {+ return d.normalTaskClaimPollInterval()}upperBound := d.cfg.WSClaimPollIntervalif upperBound <= 0 {diff --git a/server/internal/daemon/daemon_legacy_fallback_test.go b/server/internal/daemon/daemon_legacy_fallback_test.goindex 81128b67ef..b794d3f91f 100644--- a/server/internal/daemon/daemon_legacy_fallback_test.go+++ b/server/internal/daemon/daemon_legacy_fallback_test.go@@ -42,7 +42,7 @@ func TestClaimTasksWSFirst_LegacyFallbackWhenBatchRouteMissing(t *testing.T) {d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))- tasks, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5)+ tasks, _, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5)if err != nil {t.Fatalf("ClaimTasksWSFirst: %v", err)}@@ -64,7 +64,7 @@ func TestClaimTasksWSFirst_LegacyFallbackWhenBatchRouteMissing(t *testing.T) {}// Second poll must skip the batch route entirely and go straight to legacy.- if _, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5); err != nil {+ if _, _, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1", "rt2"}, 5); err != nil {t.Fatalf("second ClaimTasksWSFirst: %v", err)}if batchCalls.Load() != 1 {@@ -110,7 +110,7 @@ func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {var tasks []*Taskvar err errorgo func() {- tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)+ tasks, _, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)close(done)}()@@ -178,7 +178,7 @@ func TestClaimTasksWSFirst_HTTPFallbackAfterUncertainCooldown(t *testing.T) {var tasks []*Taskvar err errorgo func() {- tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)+ tasks, _, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)close(done)}()@@ -213,7 +213,7 @@ func TestClaimTasksWSFirst_HTTPFallbackAfterUncertainCooldown(t *testing.T) {})d.wsRPC.markRPCV1Supported(reconnectGeneration)- tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)+ tasks, _, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)if err != nil {t.Fatalf("cooldown ClaimTasksWSFirst: %v", err)}@@ -225,7 +225,7 @@ func TestClaimTasksWSFirst_HTTPFallbackAfterUncertainCooldown(t *testing.T) {}time.Sleep(2 * wsClaimUncertainFallbackDelay)- tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)+ tasks, _, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)if err != nil {t.Fatalf("post-cooldown ClaimTasksWSFirst: %v", err)}@@ -266,7 +266,7 @@ func TestClaimTasksWSFirst_ReconnectToOldServerSkipsWSRPC(t *testing.T) {return &wsOutbound{data: frame}, nil})- tasks, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 1)+ tasks, _, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 1)if err != nil {t.Fatalf("ClaimTasksWSFirst: %v", err)}diff --git a/server/internal/daemon/force_recheck_consume_test.go b/server/internal/daemon/force_recheck_consume_test.gonew file mode 100644index 0000000000..a81d69e4c1--- /dev/null+++ b/server/internal/daemon/force_recheck_consume_test.go@@ -0,0 +1,292 @@+package daemon++import (+ "context"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "sort"+ "sync"+ "testing"+ "time"+)++// TestConsumeForceRecheckHints_ReNotesEverythingUnacknowledged pins the+// acknowledgement contract (#7452). The server acknowledges only the forced+// runtimes it observed genuinely idle; every other drained runtime stays forced+// so the next claim forces it again.+func TestConsumeForceRecheckHints_ReNotesEverythingUnacknowledged(t *testing.T) {+ // A partial acknowledgement: rt-1's scan came back empty, rt-2's did not+ // (either it found candidates or it was never scanned). rt-2 stays forced.+ d := &Daemon{}+ d.consumeForceRecheckHints([]string{"rt-1", "rt-2"}, &[]string{"rt-1"})+ got := d.drainWokenRuntimes()+ sort.Strings(got)+ if len(got) != 1 || got[0] != "rt-2" {+ t.Fatalf("re-noted set = %v, want [rt-2] (only the unacknowledged runtime)", got)+ }++ // A full acknowledgement: every drained runtime was confirmed idle, so+ // nothing stays forced.+ d = &Daemon{}+ d.consumeForceRecheckHints([]string{"rt-1", "rt-2"}, &[]string{"rt-1", "rt-2"})+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("full acknowledgement re-noted %v, want nothing", got)+ }+}++// TestConsumeForceRecheckHints_PresentButEmptyKeepsAllForced covers refinement 2+// (#7452): a PRESENT but empty acknowledged set means an upgraded server+// explicitly acknowledged nothing — reclaim filled the batch before the scan, or+// every forced scan found candidates — so every drained runtime stays forced.+func TestConsumeForceRecheckHints_PresentButEmptyKeepsAllForced(t *testing.T) {+ d := &Daemon{}+ drained := []string{"rt-1", "rt-2", "rt-3"}+ d.consumeForceRecheckHints(drained, &[]string{})+ got := d.drainWokenRuntimes()+ sort.Strings(got)+ want := []string{"rt-1", "rt-2", "rt-3"}+ if len(got) != len(want) {+ t.Fatalf("re-noted set = %v, want all drained %v", got, want)+ }+ for i := range want {+ if got[i] != want[i] {+ t.Fatalf("re-noted set = %v, want all drained %v", got, want)+ }+ }+}++// TestConsumeForceRecheckHints_AbsentFieldConsumesHints is the other half of+// refinement 2 (#7452): an ABSENT acknowledged set means a pre-#7452 server that+// cannot act on the hint at all. Re-forcing it forever would be pointless churn,+// so the drained hints are consumed and the empty-claim TTL stays the outer+// bound — exactly the pre-#7452 behaviour.+func TestConsumeForceRecheckHints_AbsentFieldConsumesHints(t *testing.T) {+ d := &Daemon{}+ d.consumeForceRecheckHints([]string{"rt-1", "rt-2"}, nil)+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("absent acknowledgement re-noted %v, want nothing (legacy server)", got)+ }+}++// TestClaimTasksWSFirst_UncertainCooldownAcknowledgesNothing is the "targeted+// wakeup during the uncertain-claim cooldown still forces a re-check next cycle"+// regression (#7452). While the send-nothing cooldown is open ClaimTasksWSFirst+// scans nothing, so it must return a PRESENT but empty acknowledgement —+// driving the daemon to keep the whole drained set forced — even though a frame+// went out on the earlier uncertain attempt.+func TestClaimTasksWSFirst_UncertainCooldownAcknowledgesNothing(t *testing.T) {+ originalDelay := wsClaimUncertainFallbackDelay+ wsClaimUncertainFallbackDelay = time.Hour // keep the cooldown open for the test+ t.Cleanup(func() { wsClaimUncertainFallbackDelay = originalDelay })++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[]}`))+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ // Drive one uncertain sent-frame outcome so the HTTP-fallback cooldown opens.+ var mu sync.Mutex+ var item *wsOutbound+ frameQueued := make(chan struct{})+ generation := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ close(frameQueued)+ return item, nil+ })+ d.wsRPC.markRPCV1Supported(generation)++ done := make(chan struct{})+ go func() {+ d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2, "rt1")+ close(done)+ }()+ select {+ case <-frameQueued:+ case <-time.After(time.Second):+ t.Fatal("WS claim frame was not queued")+ }+ mu.Lock()+ item.beginWrite()+ mu.Unlock()+ d.wsRPC.attach(nil)+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("uncertain ClaimTasksWSFirst did not return")+ }++ // The cooldown is now open. A claim that names a woken runtime scans nothing+ // and must echo an empty force-rechecked set.+ drained := []string{"rt1"}+ tasks, acknowledged, err := d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2, drained...)+ if err != nil {+ t.Fatalf("cooldown ClaimTasksWSFirst: %v", err)+ }+ if len(tasks) != 0 {+ t.Fatalf("cooldown claim returned %d tasks, want 0", len(tasks))+ }+ if acknowledged == nil {+ t.Fatal("cooldown acknowledgement is absent, want present but empty so the force set is kept")+ }+ if len(*acknowledged) != 0 {+ t.Fatalf("cooldown acknowledgement = %v, want empty so the daemon keeps the force set", *acknowledged)+ }++ // End to end: feeding that empty acknowledgement back keeps the runtime forced.+ d.consumeForceRecheckHints(drained, acknowledged)+ if got := d.drainWokenRuntimes(); len(got) != 1 || got[0] != "rt1" {+ t.Fatalf("re-noted set after cooldown = %v, want [rt1]", got)+ }+}++// TestClaimTasksWSFirst_UncertainAfterSendAcknowledgesFullForceSet pins the opposite+// branch (#7452): when a claim frame actually went out and its outcome is+// uncertain, ClaimTasksWSFirst acknowledges the FULL drained force set so the+// daemon re-notes nothing — replaying the hint could double-claim a task the WS frame+// may have already committed.+func TestClaimTasksWSFirst_UncertainAfterSendAcknowledgesFullForceSet(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[]}`))+ }))+ defer srv.Close()++ d := New(Config{ServerBaseURL: srv.URL, MaxConcurrentTasks: 4}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ var mu sync.Mutex+ var item *wsOutbound+ frameQueued := make(chan struct{})+ generation := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {+ mu.Lock()+ defer mu.Unlock()+ item = &wsOutbound{data: frame}+ close(frameQueued)+ return item, nil+ })+ d.wsRPC.markRPCV1Supported(generation)++ drained := []string{"rt1", "rt2"}+ done := make(chan struct{})+ var acknowledged *[]string+ go func() {+ _, acknowledged, _ = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2, drained...)+ close(done)+ }()+ select {+ case <-frameQueued:+ case <-time.After(time.Second):+ t.Fatal("WS claim frame was not queued")+ }+ mu.Lock()+ item.beginWrite() // frame on the wire — outcome is genuinely uncertain+ mu.Unlock()+ d.wsRPC.attach(nil)+ select {+ case <-done:+ case <-time.After(3 * time.Second):+ t.Fatal("uncertain ClaimTasksWSFirst did not return")+ }++ if acknowledged == nil {+ t.Fatal("uncertain-after-send acknowledgement is absent, want the full drained set")+ }+ sort.Strings(*acknowledged)+ if len(*acknowledged) != 2 || (*acknowledged)[0] != "rt1" || (*acknowledged)[1] != "rt2" {+ t.Fatalf("uncertain-after-send acknowledgement = %v, want the full drained set [rt1 rt2]", *acknowledged)+ }+ // Feeding it back re-notes nothing.+ d.consumeForceRecheckHints(drained, acknowledged)+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("uncertain-after-send re-noted %v, want nothing", got)+ }+}++// TestSignalTaskWakeup_FullChannelCoalescesRuntimeID is the "wakeup channel full+// → runtime id not lost" regression (#7452). signalTaskWakeup drops on a full+// channel, but a targeted wakeup's runtime id is the force-recheck signal, so it+// must be coalesced into the woken set instead of silently lost; the pending+// nudge already queued still drives the next claim.+func TestSignalTaskWakeup_FullChannelCoalescesRuntimeID(t *testing.T) {+ d := New(Config{MaxConcurrentTasks: 1}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))++ // An unbuffered channel with no receiver is always "full" for a non-blocking+ // send, so the coalesce path runs.+ full := make(chan taskWakeup)+ d.signalTaskWakeup(full, "rt-burst")++ got := d.drainWokenRuntimes()+ if len(got) != 1 || got[0] != "rt-burst" {+ t.Fatalf("woken set after dropped wakeup = %v, want [rt-burst]", got)+ }++ // A catch-up wakeup (empty runtime id) has nothing to preserve and must not+ // enter the set.+ d.signalTaskWakeup(full, "")+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("empty-id wakeup coalesced %v, want nothing", got)+ }+}++// TestClaimTasks_AcknowledgementPresenceOverTheWire is the wire half of+// refinement 2 (#7452): the acknowledged set must survive JSON decoding as+// PRESENT-but-empty when an upgraded server returns an empty array, and as+// ABSENT when an older server omits the field, so the daemon can tell the two+// apart.+func TestClaimTasks_AcknowledgementPresenceOverTheWire(t *testing.T) {+ for _, tc := range []struct {+ name string+ body string+ present bool+ }{+ {name: "upgraded server acknowledges nothing", body: `{"tasks":[],"force_rechecked_runtime_ids":[]}`, present: true},+ {name: "upgraded server acknowledges one", body: `{"tasks":[],"force_rechecked_runtime_ids":["rt1"]}`, present: true},+ {name: "legacy server omits the field", body: `{"tasks":[]}`, present: false},+ {name: "legacy server sends null", body: `{"tasks":[],"force_rechecked_runtime_ids":null}`, present: false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(tc.body))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ c.SetToken("tok")+ result, err := c.claimTasksWithHints(context.Background(), "daemon-x", []string{"rt1"}, 1, "rt1")+ if err != nil {+ t.Fatalf("claimTasksWithHints: %v", err)+ }+ acknowledged := result.ForceRecheckedRuntimeIDs+ if tc.present != (acknowledged != nil) {+ t.Fatalf("acknowledged presence = %v, want %v (body %s)", acknowledged != nil, tc.present, tc.body)+ }++ // The daemon's decision follows from that presence alone: absent consumes+ // the drained hints, present keeps every unacknowledged runtime forced.+ d := &Daemon{}+ d.consumeForceRecheckHints([]string{"rt1", "rt2"}, acknowledged)+ got := d.drainWokenRuntimes()+ sort.Strings(got)+ switch {+ case !tc.present:+ if got != nil {+ t.Fatalf("absent acknowledgement kept %v forced, want nothing", got)+ }+ case len(*acknowledged) == 0:+ if len(got) != 2 {+ t.Fatalf("present-but-empty acknowledgement kept %v forced, want both runtimes", got)+ }+ default:+ if len(got) != 1 || got[0] != "rt2" {+ t.Fatalf("partial acknowledgement kept %v forced, want [rt2]", got)+ }+ }+ })+ }+}diff --git a/server/internal/daemon/force_recheck_rebase_test.go b/server/internal/daemon/force_recheck_rebase_test.gonew file mode 100644index 0000000000..4235032e43--- /dev/null+++ b/server/internal/daemon/force_recheck_rebase_test.go@@ -0,0 +1,180 @@+package daemon++import (+ "log/slog"+ "sort"+ "sync"+ "testing"+ "time"+)++func silentDaemonLogger() *slog.Logger {+ return slog.New(slog.NewTextHandler(noopWriter{}, nil))+}++// TestSignalTaskWakeup_RecordsRuntimeBeforeSend pins refinement 1 (#7452): the+// woken runtime must be recorded in the force-recheck set BEFORE the channel+// send is attempted, not only on the full-channel default branch. If recording+// trailed the send, a poller that consumed the already-queued nudge and drained+// between the failed send and the note would strand the id in a set nobody+// drains, with no nudge left to drive a claim.+//+// The observable proof is a channel with room: on the pre-fix ordering the send+// succeeds and the producer never records the runtime (it relied on the+// consumer noting it after receipt), so the set is empty right after the call.+// Recording first makes the runtime present regardless of the send outcome.+func TestSignalTaskWakeup_RecordsRuntimeBeforeSend(t *testing.T) {+ d := &Daemon{logger: silentDaemonLogger()}+ taskWakeups := make(chan taskWakeup, 1) // room available, so the send succeeds++ d.signalTaskWakeup(taskWakeups, "rt-1")++ if !d.hasPendingForceRecheck() {+ t.Fatal("runtime not recorded before the send; a racing drain could strand it")+ }+ got := d.drainWokenRuntimes()+ if len(got) != 1 || got[0] != "rt-1" {+ t.Fatalf("woken set = %v, want [rt-1]", got)+ }+}++// TestSignalTaskWakeup_ConcurrentDrainNeverStrands stresses the drop-on-full+// path against a concurrent drainer (#7452): the runtime id must always end up+// either drained by the racer or still pending for the next drain — never lost.+func TestSignalTaskWakeup_ConcurrentDrainNeverStrands(t *testing.T) {+ logger := silentDaemonLogger()+ for i := 0; i < 100_000; i++ {+ d := &Daemon{logger: logger}+ full := make(chan taskWakeup) // unbuffered, no receiver: every send hits default++ var wg sync.WaitGroup+ wg.Add(1)+ var raced []string+ go func() {+ defer wg.Done()+ raced = d.drainWokenRuntimes()+ }()+ d.signalTaskWakeup(full, "rt-burst")+ wg.Wait()++ drainedByRacer := len(raced) == 1 && raced[0] == "rt-burst"+ if !drainedByRacer && !d.hasPendingForceRecheck() {+ t.Fatalf("iteration %d: runtime neither drained (%v) nor pending — lost", i, raced)+ }+ }+}++// TestForceRecheckFiltersDeletedRuntimeBeforeClaim covers refinement 2 (#7452,+// #7969): a runtime woken and then deleted before the claim is intersected out+// by filterLiveRuntimes, so its id never reaches the request. Without the+// filter it would be sent every cycle forever, because the server filters the+// request down to authorized runtimes and can never acknowledge a deleted one.+func TestForceRecheckFiltersDeletedRuntimeBeforeClaim(t *testing.T) {+ d := &Daemon{+ logger: silentDaemonLogger(),+ workspaces: map[string]*workspaceState{"ws-1": {runtimeIDs: []string{"rt-live"}}},+ }+ d.noteWokenRuntime("rt-live")+ d.noteWokenRuntime("rt-gone") // woken, then its runtime was removed++ forceRecheck := d.filterLiveRuntimes(d.drainWokenRuntimes())+ if len(forceRecheck) != 1 || forceRecheck[0] != "rt-live" {+ t.Fatalf("force-recheck set = %v, want only the live runtime [rt-live]", forceRecheck)+ }+}++// TestForceRecheckFiltersDeletionRacingInFlightClaim covers the interleaving+// half of refinement 2 (#7452, #7969): a runtime still live when the claim goes+// out but deleted while it is in flight must be dropped from the re-note, not+// re-forced next cycle. The poller re-filters against the live set at consume+// time, so the deletion is honoured even mid-request.+func TestForceRecheckFiltersDeletionRacingInFlightClaim(t *testing.T) {+ ws := &workspaceState{runtimeIDs: []string{"rt-live", "rt-gone"}}+ d := &Daemon{+ logger: silentDaemonLogger(),+ workspaces: map[string]*workspaceState{"ws-1": ws},+ }+ d.noteWokenRuntime("rt-live")+ d.noteWokenRuntime("rt-gone")++ // Both runtimes are live when the claim is issued.+ forceRecheck := d.filterLiveRuntimes(d.drainWokenRuntimes())+ sort.Strings(forceRecheck)+ if len(forceRecheck) != 2 {+ t.Fatalf("force-recheck set at claim time = %v, want both runtimes", forceRecheck)+ }++ // rt-gone is deleted while the claim is in flight; the server acknowledged+ // nothing (present-but-empty), so every unacknowledged runtime would normally+ // be re-forced.+ ws.runtimeIDs = []string{"rt-live"}+ d.consumeForceRecheckHints(d.filterLiveRuntimes(forceRecheck), &[]string{})++ remaining := d.drainWokenRuntimes()+ if len(remaining) != 1 || remaining[0] != "rt-live" {+ t.Fatalf("re-forced set = %v, want only [rt-live] (rt-gone dropped after deletion)", remaining)+ }+}++// TestTaskClaimPollInterval_PendingForceKeepsNormalCadence pins refinement 3 of+// the rebase (#7452 vs #7983): a claim over a healthy WS with poll hints would+// otherwise take the long (~3-minute) safety interval, but a still-pending+// force-recheck hint must keep the poller on the normal PollInterval so the next+// same-agent task is not stranded for the exact window this fix targets.+func TestTaskClaimPollInterval_PendingForceKeepsNormalCadence(t *testing.T) {+ d := New(Config{+ PollInterval: 30 * time.Second,+ WSClaimPollInterval: 3 * time.Minute,+ MaxConcurrentTasks: 1,+ }, silentDaemonLogger())+ gen := d.wsRPC.attach(func([]byte) (*wsOutbound, error) { return nil, nil })+ d.wsRPC.markRPCV1Supported(gen)++ result := claimTasksResult{ClaimedOverWS: true, ClaimPollHintSupported: true}++ // No pending force: the healthy-WS path takes the long jittered interval,+ // which sits well above the normal poll.+ if got := d.taskClaimPollInterval(result); got <= d.cfg.PollInterval {+ t.Fatalf("healthy-WS interval = %v, want the long safety interval above PollInterval %v", got, d.cfg.PollInterval)+ }++ // A pending force hint after a claim that took work must collapse the+ // interval back to the normal poll.+ d.noteWokenRuntime("rt-forced")+ progressed := result+ progressed.Tasks = []*Task{{ID: "task-1"}}+ if got := d.taskClaimPollInterval(progressed); got != d.cfg.PollInterval {+ t.Fatalf("interval with pending force after a claim = %v, want normal PollInterval %v", got, d.cfg.PollInterval)+ }++ // A pending force hint after a claim that took nothing (the remaining+ // candidates are blocked) keeps the long interval: the poller must not+ // re-scan every PollInterval for as long as the blocker runs.+ if got := d.taskClaimPollInterval(result); got <= d.cfg.PollInterval {+ t.Fatalf("interval with pending force after an empty claim = %v, want the long safety interval", got)+ }+}++// TestTaskClaimPollInterval_PendingForceKeepsSoonerDeferredDeadline: the+// pending-force cap must not override a deferred task that is due sooner than+// the normal poll.+func TestTaskClaimPollInterval_PendingForceKeepsSoonerDeferredDeadline(t *testing.T) {+ d := New(Config{+ PollInterval: 30 * time.Second,+ WSClaimPollInterval: 3 * time.Minute,+ MaxConcurrentTasks: 5,+ }, silentDaemonLogger())+ gen := d.wsRPC.attach(func([]byte) (*wsOutbound, error) { return nil, nil })+ d.wsRPC.markRPCV1Supported(gen)+ d.noteWokenRuntime("rt-forced")++ result := claimTasksResult{+ Tasks: []*Task{{ID: "task-1"}},+ ClaimedOverWS: true,+ ClaimPollHintSupported: true,+ NextDeferredTaskAfterMillis: 1000,+ }+ if got := d.taskClaimPollInterval(result); got != time.Second {+ t.Fatalf("interval = %v, want the 1s deferred deadline", got)+ }+}diff --git a/server/internal/daemon/force_recheck_test.go b/server/internal/daemon/force_recheck_test.gonew file mode 100644index 0000000000..cf139a8a83--- /dev/null+++ b/server/internal/daemon/force_recheck_test.go@@ -0,0 +1,61 @@+package daemon++import (+ "sort"+ "testing"+)++// TestDaemon_WokenRuntimeTracking pins the daemon side of #7452: a targeted+// `task_available` records its runtime so the next claim can force a server-side+// re-check, an empty wakeup (catch-up) is ignored, and draining clears the set+// so a runtime is forced exactly once per wakeup.+func TestDaemon_WokenRuntimeTracking(t *testing.T) {+ d := &Daemon{}++ // Nothing woken yet.+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("drain on empty set = %v, want nil", got)+ }++ // A catch-up wakeup carries no runtime id and must not enter the set.+ d.noteWokenRuntime("")+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("drain after empty wakeup = %v, want nil", got)+ }++ // Two targeted wakeups (with a duplicate) collapse to the distinct set.+ d.noteWokenRuntime("rt-1")+ d.noteWokenRuntime("rt-2")+ d.noteWokenRuntime("rt-1")+ got := d.drainWokenRuntimes()+ sort.Strings(got)+ if len(got) != 2 || got[0] != "rt-1" || got[1] != "rt-2" {+ t.Fatalf("drain = %v, want [rt-1 rt-2]", got)+ }++ // Draining clears the set: the same runtime is not force-rechecked again+ // until it is woken anew.+ if got := d.drainWokenRuntimes(); got != nil {+ t.Fatalf("drain after clear = %v, want nil", got)+ }+}++// TestClaimTasksBody_ForceRecheckIsOptional pins the request-compat contract of+// #7452: with no woken runtime the body is byte-for-byte the pre-#7452 request+// (so an older server sees no new field), and the field appears only when a+// runtime was actually woken.+func TestClaimTasksBody_ForceRecheckIsOptional(t *testing.T) {+ base := claimTasksBody("daemon-x", []string{"rt-1"}, 3)+ if _, present := base["force_recheck_runtime_ids"]; present {+ t.Fatalf("force_recheck_runtime_ids must be omitted when no runtime is woken; body = %v", base)+ }+ if base["daemon_id"] != "daemon-x" || base["max_tasks"] != 3 {+ t.Fatalf("base body lost its existing fields: %v", base)+ }++ withForce := claimTasksBody("daemon-x", []string{"rt-1"}, 3, "rt-1")+ ids, ok := withForce["force_recheck_runtime_ids"].([]string)+ if !ok || len(ids) != 1 || ids[0] != "rt-1" {+ t.Fatalf("force_recheck_runtime_ids = %v, want [rt-1]", withForce["force_recheck_runtime_ids"])+ }+}diff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex fffb88614e..b0c118cc3d 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -143,7 +143,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strindefer d.clearWSHeartbeatAcks()d.logger.Info("task wakeup websocket connected", "runtimes", len(runtimeIDs))- signalTaskWakeup(taskWakeups, "")+ d.signalTaskWakeup(taskWakeups, "")// A healthy reconnect is the strongest signal that a terminal callback// stranded during an outage may now succeed. The buffered wakeup also// preserves a connect that races replay-loop startup.@@ -239,7 +239,7 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// A healthy WS connection lets the claim poller use a longer fallback// interval. Wake it as soon as the connection drops so it immediately// observes the detach and resumes the configured HTTP cadence.- signalTaskWakeup(taskWakeups, "")+ d.signalTaskWakeup(taskWakeups, "")sendMu.Lock()sendClosed = truesendMu.Unlock()@@ -406,7 +406,7 @@ func (d *Daemon) readTaskWakeupMessagesForConnection(conn *websocket.Conn, taskWif payload.RuntimeID != "" {d.logger.Debug("task wakeup received", "runtime_id", payload.RuntimeID, "task_id", payload.TaskID)}- signalTaskWakeup(taskWakeups, payload.RuntimeID)+ d.signalTaskWakeup(taskWakeups, payload.RuntimeID)case protocol.EventDaemonTaskSupplementAvailable:var payload protocol.TaskAvailablePayloadif err := json.Unmarshal(msg.Payload, &payload); err != nil {@@ -496,10 +496,28 @@ func (d *Daemon) handleRuntimeProfilesChanged(payload protocol.RuntimeProfilesCh}}-func signalTaskWakeup(taskWakeups chan<- taskWakeup, runtimeID string) {+// signalTaskWakeup delivers a targeted (or catch-up) task wakeup to the poller.+// For a targeted wakeup the runtime id is the #7452 force-recheck signal, so it+// is recorded in the woken set BEFORE the send is attempted. Recording after the+// send would race: the `default` branch is only reached because a nudge is+// already queued, and between a failed send and a late note the poller can+// consume that queued nudge AND drain the woken set — stranding the id in a set+// nobody will drain, with no nudge left to trigger a claim, until the next+// scheduled poll. Recording first is strictly safe: if a drain races in, it+// picks the id up and the subsequent nudge is merely redundant. The channel is a+// coalescing nudge, so a full channel already carries a pending wakeup that will+// drive the next claim, where the runtime is now forced. A catch-up wakeup+// (empty runtimeID) has nothing to preserve.+func (d *Daemon) signalTaskWakeup(taskWakeups chan<- taskWakeup, runtimeID string) {+ if runtimeID != "" {+ d.noteWokenRuntime(runtimeID)+ }select {case taskWakeups <- taskWakeup{runtimeID: runtimeID}:default:+ if runtimeID != "" {+ d.logger.Debug("task wakeup channel full; coalesced runtime into force-recheck set", "runtime_id", runtimeID)+ }}}diff --git a/server/internal/daemon/wsrpc.go b/server/internal/daemon/wsrpc.goindex 2458cddaab..3a1cef063f 100644--- a/server/internal/daemon/wsrpc.go+++ b/server/internal/daemon/wsrpc.go@@ -312,17 +312,38 @@ func (c *wsRPCClient) deliver(resp protocol.RPCResponsePayload) {// retried over HTTP only after a short safety window. The request/response bodies// are identical to the HTTP endpoint so both transports are interchangeable.// Wired into the claim poller as part of the poller cutover.-func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) ([]*Task, error) {- result, err := d.claimTasksWSFirst(ctx, daemonID, runtimeIDs, maxTasks)- return result.Tasks, err+// forceRecheckIDs (#7452) names runtimes woken by a targeted `task_available`+// since the last claim; it is forwarded unchanged over whichever transport+// wins so the server bypasses their cached "empty" verdict. The legacy+// per-runtime fallback ignores it (an un-upgraded server has no such route).+//+// The exported wrapper returns the server's acknowledgement of the forced+// runtimes (#7452) as a POINTER (claimTasksResult.ForceRecheckedRuntimeIDs) so+// the caller can tell an explicit empty acknowledgement from a missing one:+// - a normal WS/HTTP claim passes the server's force_rechecked_runtime_ids+// through verbatim: present (possibly empty) from an upgraded server,+// absent from an older one that does not know the field;+// - the send-nothing cooldown branch acknowledges nothing (present, empty),+// so the caller keeps the whole drained set forced and re-forces next cycle;+// - the uncertain-after-send branch acknowledges the full forced set, so the+// caller re-notes nothing: a frame DID go out and replaying the hint could+// double-claim, so recovery falls to the next wakeup or the TTL;+// - the legacy/unsupported fallbacks report ABSENT, so the caller drops the+// hint the way it did before #7452 instead of re-forcing a server that can+// never acknowledge it.+func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int, forceRecheckIDs ...string) ([]*Task, *[]string, error) {+ result, err := d.claimTasksWSFirst(ctx, daemonID, runtimeIDs, maxTasks, forceRecheckIDs...)+ return result.Tasks, result.ForceRecheckedRuntimeIDs, err}-func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) (claimTasksResult, error) {+func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int, forceRecheckIDs ...string) (claimTasksResult, error) {// Un-upgraded server without the batch route: a prior poll already learned// this (via a 404), so go straight to the legacy per-runtime claim and skip// the WS + batch attempts each cycle.if d.batchClaimUnsupported.Load() {tasks, err := d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ // The legacy route cannot honour the hint, so report ABSENT (nil): the+ // caller drops it instead of re-forcing a server that will never ack.return claimTasksResult{Tasks: tasks}, err}bypassWSOnce := false@@ -332,7 +353,11 @@ func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimeif now.Before(retryAfter) {d.logger.Debug("ws claim outcome uncertain; delaying http fallback until safety window elapses","retry_after", retryAfter.Sub(now).Round(time.Millisecond))- return claimTasksResult{}, nil+ // Nothing was sent and nothing scanned this cycle: acknowledge nothing+ // (present but empty) so the caller keeps the whole drained force set and+ // re-forces next cycle. Unlike the uncertain-after-send branch below, no+ // frame went out, so replaying the hint cannot double-claim.+ return claimTasksResult{ForceRecheckedRuntimeIDs: ackNone()}, nil}if d.wsClaimHTTPFallbackAfter.CompareAndSwap(retryAfterNanos, 0) {bypassWSOnce = true@@ -343,11 +368,7 @@ func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimevar resp claimTasksResult// batchClaimRequestTimeout is the server-side execution budget; the// daemon waits that plus the client's grace margin for the response.- _, err := d.wsRPC.CallIfRPCV1Supported(ctx, "tasks.claim", batchClaimRequestTimeout, map[string]any{- "daemon_id": daemonID,- "runtime_ids": runtimeIDs,- "max_tasks": maxTasks,- }, &resp)+ _, err := d.wsRPC.CallIfRPCV1Supported(ctx, "tasks.claim", batchClaimRequestTimeout, claimTasksBody(daemonID, runtimeIDs, maxTasks, forceRecheckIDs...), &resp)if err == nil {resp.ClaimedOverWS = truereturn resp, nil@@ -359,17 +380,22 @@ func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtime// execution budget plus response grace has elapsed. If the WS claim// committed, the task is already dispatched and stale reclaim owns// recovery; if it did not, HTTP regains liveness for the queued task.+ // The drained forceRecheck set (#7452) is intentionally not re-noted+ // here: a frame DID go out and may have committed server-side, so+ // replaying the hint immediately could double-claim. Echo the full+ // forced set as "confirmed" so the caller re-notes nothing; recovery+ // falls to the next targeted wakeup or the empty-claim TTL.delay := wsClaimUncertainFallbackDelayif delay < 0 {delay = 0}d.wsClaimHTTPFallbackAfter.Store(time.Now().Add(delay).UnixNano())d.logger.Debug("ws claim outcome uncertain after disconnect; delaying http fallback", "retry_after", delay)- return claimTasksResult{}, nil+ return claimTasksResult{ForceRecheckedRuntimeIDs: ackAll(forceRecheckIDs)}, nil}d.logger.Debug("ws claim failed; falling back to http", "error", err)}- result, err := d.client.claimTasksWithHints(ctx, daemonID, runtimeIDs, maxTasks)+ result, err := d.client.claimTasksWithHints(ctx, daemonID, runtimeIDs, maxTasks, forceRecheckIDs...)if err == nil {return result, nil}@@ -380,7 +406,26 @@ func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimed.batchClaimUnsupported.Store(true)d.logger.Info("batch claim route unsupported by server; using legacy per-runtime claim")tasks, legacyErr := d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ // An old server without the batch route can never acknowledge the hint,+ // so report ABSENT (nil) and let the caller drop it (pre-#7452 behaviour)+ // rather than re-force it forever.return claimTasksResult{Tasks: tasks}, legacyErr}return claimTasksResult{}, err}++// ackNone is a present-but-empty acknowledgement (#7452): the transport knows+// the server scanned nothing this cycle, so the caller keeps every drained+// runtime forced. Distinct from a nil acknowledgement, which means the server+// never spoke about the hint at all.+func ackNone() *[]string {+ acked := []string{}+ return &acked+}++// ackAll acknowledges the whole drained set (#7452), so the caller re-notes+// nothing.+func ackAll(ids []string) *[]string {+ acked := append([]string{}, ids...)+ return &acked+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex f38212000d..88cd442b7c 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -2107,6 +2107,14 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {DaemonID string `json:"daemon_id"`RuntimeIDs []string `json:"runtime_ids"`MaxTasks int `json:"max_tasks"`+ // ForceRecheckRuntimeIDs is an optional, additive signal (#7452): the+ // daemon lists the runtimes woken by a targeted `task_available` since its+ // last claim so the server bypasses their cached "empty" verdict and runs+ // the real candidate SELECT, repairing a stale verdict left by a lost+ // EmptyClaim.Bump. Absent/unknown on an older daemon → behaves exactly as+ // before (TTL fallback). Parsed defensively; ids not in the authorized set+ // are dropped.+ ForceRecheckRuntimeIDs []string `json:"force_recheck_runtime_ids"`}if err := json.NewDecoder(r.Body).Decode(&req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body")@@ -2129,6 +2137,16 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {return}+ // An explicit force list also opts in for clients that predate the header.+ wantAck := len(req.ForceRecheckRuntimeIDs) > 0 || requestHasClientCapability(r, protocol.DaemonCapabilityForceRecheckV1)+ respondEmpty := func() {+ response := map[string]any{"tasks": []AgentTaskResponse{}}+ if wantAck {+ response["force_rechecked_runtime_ids"] = []string{}+ }+ writeMeasuredJSON(w, http.StatusOK, response)+ }+// max_tasks semantics (MUL-4257 review): a negative count is malformed; zero// is a valid "no free slots" poll that must claim nothing — never coerce to// 1, which would dispatch a task the daemon cannot run and strand it until@@ -2139,7 +2157,7 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {return}if req.MaxTasks == 0 {- writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})+ respondEmpty()return}maxTasks := req.MaxTasks@@ -2161,7 +2179,7 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {idByKey[util.UUIDToString(ruid)] = ruid}if len(idByKey) == 0 {- writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})+ respondEmpty()return}ids := make([]pgtype.UUID, 0, len(idByKey))@@ -2221,11 +2239,27 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {authorized = append(authorized, rt.ID)}if len(authorized) == 0 {- writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": []AgentTaskResponse{}})+ respondEmpty()return}- claimed, err := h.TaskService.ClaimTasksForRuntimes(r.Context(), authorized, maxTasks)+ // Restrict the force-recheck set (#7452) to runtimes this daemon is+ // authorized for: an unknown or malformed id is skipped (matching this+ // endpoint's "unknown id skipped" semantics), and an id for another daemon's+ // runtime cannot force a cross-machine cache bypass.+ forceRecheck := make([]pgtype.UUID, 0, len(req.ForceRecheckRuntimeIDs))+ for _, rid := range req.ForceRecheckRuntimeIDs {+ ruid, err := util.ParseUUID(rid)+ if err != nil {+ continue+ }+ if _, ok := runtimeByID[util.UUIDToString(ruid)]; !ok {+ continue+ }+ forceRecheck = append(forceRecheck, ruid)+ }++ claimed, forceRechecked, err := h.TaskService.ClaimTasksForRuntimes(r.Context(), authorized, maxTasks, forceRecheck...)if err != nil {slog.Warn("claim tasks failed", append(logger.RequestAttrs(r), "error", err)...)writeError(w, http.StatusInternalServerError, "failed to claim tasks")@@ -2324,6 +2358,14 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {"total_ms", time.Since(start).Milliseconds())}response := map[string]any{"tasks": out}+ if wantAck {+ // An explicit empty list keeps outstanding hints pending. Absence+ // tells the client to fall back to legacy polling.+ if forceRechecked == nil {+ forceRechecked = []string{}+ }+ response["force_rechecked_runtime_ids"] = forceRechecked+ }// Only opted-in daemons understand this additive response metadata. Query// after the claim so a future fire_at can shorten the long healthy-WS safety// poll; a task that crossed fire_at during this request yields a boundeddiff --git a/server/internal/handler/daemon_batch_claim_finalize_test.go b/server/internal/handler/daemon_batch_claim_finalize_test.goindex 7068e3df13..c1729d860f 100644--- a/server/internal/handler/daemon_batch_claim_finalize_test.go+++ b/server/internal/handler/daemon_batch_claim_finalize_test.go@@ -6,6 +6,8 @@ import ("net/http""net/http/httptest""testing"++ "github.com/multica-ai/multica/server/pkg/protocol")type batchClaimReceiptResponse struct {@@ -347,3 +349,37 @@ func TestClaimTasksByRuntime_RepairsStaleCommentPlan(t *testing.T) {t.Fatalf("expected the surviving comment rebuilt into a new trigger task, found %d", rebuilt)}}++func TestClaimTasksByRuntime_EmptyPollAcknowledgesNoRechecks(t *testing.T) {+ rt := createClaimReclaimRuntime(t, context.Background(), "Empty poll")+ for _, tc := range []struct {+ name string+ ids []string+ slots int+ }{+ {"no slots", []string{rt}, 0},+ {"no runtime IDs", nil, 1},+ {"unknown runtime", []string{"07a50d10-3e8d-4e48-a74b-6a176c34865e"}, 1},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := postBatchClaimWithCapabilities(t, testWorkspaceID, tc.ids, tc.slots, protocol.DaemonCapabilityForceRecheckV1)+ var resp struct {+ Acknowledged []string `json:"force_rechecked_runtime_ids"`+ }+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &resp) != nil || resp.Acknowledged == nil || len(resp.Acknowledged) != 0 {+ t.Fatalf("expected 200 with an explicit empty acknowledgement, got %d %s", w.Code, w.Body.String())+ }+ })+ }+}++func TestClaimTasksByRuntime_LegacyPollOmitsRecheckAck(t *testing.T) {+ rt := createClaimReclaimRuntime(t, context.Background(), "Legacy poll")+ for _, slots := range []int{0, 1} {+ w := postBatchClaim(t, testWorkspaceID, []string{rt}, slots)+ var resp map[string]json.RawMessage+ if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &resp) != nil || resp["tasks"] == nil || resp["force_rechecked_runtime_ids"] != nil {+ t.Fatalf("unexpected response to legacy poll: %d %s", w.Code, w.Body.String())+ }+ }+}diff --git a/server/internal/service/issue_wakeup_capacity_test.go b/server/internal/service/issue_wakeup_capacity_test.goindex 25a941122a..dc0c4ce984 100644--- a/server/internal/service/issue_wakeup_capacity_test.go+++ b/server/internal/service/issue_wakeup_capacity_test.go@@ -59,6 +59,13 @@ func TestIssueWakeupBusyRuleDoesNotBlockOtherWorkspace(t *testing.T) {if ctx.Err() != nil {t.Fatal("busy rule consumed batch deadline")}+ // The blocker is only needed during TickWorkspaces. Release it before+ // reading through another connection: a parallel test's DROP TRIGGER+ // can queue an exclusive table lock behind holder and block that read,+ // preventing the deferred rollback from ever running.+ if err := holder.Rollback(context.Background()); err != nil {+ t.Fatal(err)+ }if got := other.Count(t, "SELECT count(*) FROM agent_task_queue WHERE context->>'wakeup_id'=$1", util.UUIDToString(second.ID)); got != 1 {t.Fatalf("unrelated rule not dispatched: %d", got)}diff --git a/server/internal/service/runtime_claim_access_test.go b/server/internal/service/runtime_claim_access_test.goindex a43c254220..cf9e0ee3aa 100644--- a/server/internal/service/runtime_claim_access_test.go+++ b/server/internal/service/runtime_claim_access_test.go@@ -364,7 +364,7 @@ func TestClaimTasksForRuntimesKeepsOwnerlessPrivateAgentClaimable(t *testing.T)}svc := NewTaskService(db.New(fixture.pool), fixture.pool, nil, events.New())- claimed, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{fixture.runtimeID}, 1)+ claimed, _, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{fixture.runtimeID}, 1)if err != nil {t.Fatalf("claim tasks: %v", err)}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex c07ae4964e..d172baea08 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -4166,9 +4166,48 @@ func (s *TaskService) RequeueTaskAfterClaimFailure(ctx context.Context, task db.// The returned slice contains both reclaimed and freshly-claimed tasks, each// already carrying its runtime_id so the daemon routes it to the matching// runtime locally.-func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgtype.UUID, maxTasks int) ([]db.AgentTaskQueue, error) {+// forceRecheckRuntimeIDs, when non-empty, names runtimes whose empty-claim+// verdict must be ignored for THIS call: a targeted daemon `task_available`+// wakeup carries them so a queued task becomes claimable immediately even if a+// prior enqueue's EmptyClaim.Bump was lost to a transient Redis failure and the+// stale "empty" verdict would otherwise survive to its TTL (GitHub #7452). The+// forced runtimes still MarkEmpty-repair on a zero-candidate result (step 5),+// so a genuinely-idle runtime re-arms the cache instead of polling Postgres+// every cycle. It is an optional, additive signal: an empty set reproduces the+// exact pre-#7452 behavior, and ids not in runtimeIDs are ignored.+//+// The second return value ACKNOWLEDGES the subset of forceRecheckRuntimeIDs+// whose candidate SELECT came back with ZERO candidates this cycle, as+// canonical uuid strings. A forced runtime is acknowledged only once it has+// been observed genuinely idle and MarkEmpty-repaired (step 5): its cache entry+// is then freshly authoritative, so the hint has done its job and the daemon+// can drop it.+//+// Everything else is deliberately NOT acknowledged, so the daemon keeps the+// runtime forced and re-forces it next cycle:+// - a forced runtime whose SELECT found candidates. The batch's+// one-attempt-per-agent rule can claim one of two same-agent tasks and leave+// the second queued, and the stale verdict that made the runtime need+// forcing is still cached. Acknowledging here would depend on a repair write+// (a Bump/invalidate) succeeding, and that write can fail in the very Redis+// outage that lost the enqueue-side Bump, silently restoring the stale+// verdict. Staying forced until a scan is empty needs no such write.+// - a forced runtime the server never scanned, because reclaim already filled+// the batch (step 2 early return) or an error cut the cycle short.+//+// The set is meaningful even when empty, and the handler always emits the field,+// so a daemon can tell "this server acknowledged nothing" from "this server does+// not know the field at all".+func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgtype.UUID, maxTasks int, forceRecheckRuntimeIDs ...pgtype.UUID) ([]db.AgentTaskQueue, []string, error) {if len(runtimeIDs) == 0 || maxTasks <= 0 {- return nil, nil+ return nil, nil, nil+ }++ // Runtimes whose cached empty verdict is bypassed for this call. Keyed by+ // canonical uuid string so it matches the per-runtime bookkeeping below.+ forceRecheck := make(map[string]struct{}, len(forceRecheckRuntimeIDs))+ for _, rid := range forceRecheckRuntimeIDs {+ forceRecheck[util.UUIDToString(rid)] = struct{}{}}// De-dup runtime IDs defensively so MarkEmpty/version bookkeeping stays@@ -4210,7 +4249,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgpromoted = nil} else if err != nil {s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "error_promote_deferred", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})- return nil, fmt.Errorf("promote deferred tasks: %w", err)+ return nil, nil, fmt.Errorf("promote deferred tasks: %w", err)}for _, task := range promoted {slog.Info("deferred task promoted (batch)",@@ -4246,7 +4285,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg})if err != nil {s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "error_reclaim_dispatched", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})- return nil, fmt.Errorf("reclaim stale dispatched tasks: %w", err)+ return nil, 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@@ -4269,15 +4308,31 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg)}if len(claimed) >= maxTasks {- return claimed[:maxTasks], nil+ // Reclaim (step 2) already filled the batch, so step 3 never runs and a+ // forceRecheck runtime not among the reclaimed tasks keeps its stale+ // "empty" verdict this cycle. That is self-healing: the daemon re-drives+ // the same free slots on the next poll (and the wakeup that set the force+ // signal recurs), so the bypass lands then; the TTL is the outer bound.+ // Nothing was scanned, so nothing is acknowledged: the daemon keeps every+ // forced runtime forced and the bypass lands on the next poll.+ return claimed[:maxTasks], nil, nil}// 3. Empty-cache short-circuit + version sampling for the remaining runtimes.+ // A runtime named in forceRecheck skips the IsEmpty short-circuit and always+ // runs the real candidate SELECT (step 4), repairing a stale "empty" verdict+ // left by a lost Bump (#7452). It still samples the version so step 5 can+ // MarkEmpty-repair it, and acknowledge it, when the SELECT confirms it is+ // genuinely idle.nonEmpty := make([]pgtype.UUID, 0, len(uniqueIDs))versions := make(map[string]int64, len(uniqueIDs))+ // forceRechecked acknowledges the forced runtimes that step 5 confirms idle,+ // so every other forced runtime stays forced (see the doc comment).+ forceRechecked := make([]string, 0, len(forceRecheck))for _, rid := range uniqueIDs {key := util.UUIDToString(rid)- if s.EmptyClaim.IsEmpty(ctx, key) {+ _, forced := forceRecheck[key]+ if !forced && s.EmptyClaim.IsEmpty(ctx, key) {continue}versions[key] = s.EmptyClaim.CurrentVersion(ctx, key)@@ -4286,7 +4341,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgif len(nonEmpty) == 0 {s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "empty_cache_hit", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})slog.Debug("batch claim: all runtimes empty-cached", "runtimes", len(uniqueIDs))- return claimed, nil+ return claimed, forceRechecked, nil}// 4. One candidate SELECT across the non-empty set.@@ -4304,9 +4359,11 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgif len(claimed) > 0 {slog.Error("batch claim: candidate query failed after partial success; returning claimed tasks to avoid loss","error", err, "claimed", len(claimed))- return claimed, nil+ // The SELECT errored, so no forced runtime was observed idle:+ // acknowledge none of them and let the daemon keep them forced.+ return claimed, nil, nil}- return nil, fmt.Errorf("list queued claim candidates: %w", err)+ return nil, nil, fmt.Errorf("list queued claim candidates: %w", err)}// 5. Mark runtimes with zero candidates empty so their next idle poll skips@@ -4321,6 +4378,15 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgkey := util.UUIDToString(rid)if _, ok := withCandidates[key]; !ok {s.EmptyClaim.MarkEmpty(ctx, key, versions[key])+ // The runtime is confirmed idle and its cache entry has just been+ // re-armed from a real SELECT, so the force hint has done its job:+ // acknowledge it and let the daemon drop it (#7452). A forced runtime+ // that DID yield candidates is intentionally left unacknowledged: it+ // stays forced until a later scan comes back empty, which is what makes+ // the contract independent of any Redis repair write succeeding.+ if _, forced := forceRecheck[key]; forced {+ forceRechecked = append(forceRechecked, key)+ }}}if len(candidates) == 0 {@@ -4329,7 +4395,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pg// agent/runtime binding, so this is about visible candidates, not// about the queue being empty).s.recordClaimDecision(pgtype.UUID{}, pgtype.UUID{}, "empty_db", claimScope{claimPath: claimPathBatch}, claimDecisionDetail{})- return claimed, nil+ return claimed, forceRechecked, nil}// 6. Claim per distinct agent through the runtime-scoped helper, preserving@@ -4368,9 +4434,11 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgif len(claimed) > 0 {slog.Error("batch claim: claim task failed after partial success; returning claimed tasks to avoid loss","error", err, "claimed", len(claimed))- return claimed, nil+ // Step 5 already ran, so any forced runtime it confirmed idle is+ // safely acknowledged; the rest stay forced.+ return claimed, forceRechecked, nil}- return nil, fmt.Errorf("claim task: %w", err)+ return nil, nil, fmt.Errorf("claim task: %w", err)}if task == nil {continue@@ -4388,7 +4456,7 @@ func (s *TaskService) ClaimTasksForRuntimes(ctx context.Context, runtimeIDs []pgclaimed = append(claimed, *task)}- return claimed, nil+ return claimed, forceRechecked, nil}// cancelSupersededDeferredRetries drops deferred auto-retry rows that an activediff --git a/server/internal/service/task_batch_claim_deferred_test.go b/server/internal/service/task_batch_claim_deferred_test.goindex b5dbcc3bdd..6368718642 100644--- a/server/internal/service/task_batch_claim_deferred_test.go+++ b/server/internal/service/task_batch_claim_deferred_test.go@@ -45,7 +45,7 @@ func TestClaimTasksForRuntimes_PromotesDeferredAndEmitsQueuedEvent(t *testing.T)svc := NewTaskService(db.New(pool), pool, nil, bus)rt, deferredTaskID := deferredBatchFixture(t, ctx, pool)- got, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt)}, 5)+ got, _, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt)}, 5)if err != nil {t.Fatalf("claim: %v", err)}diff --git a/server/internal/service/task_batch_claim_force_recheck_test.go b/server/internal/service/task_batch_claim_force_recheck_test.gonew file mode 100644index 0000000000..c509e5af56--- /dev/null+++ b/server/internal/service/task_batch_claim_force_recheck_test.go@@ -0,0 +1,257 @@+package service++import (+ "context"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// TestClaimTasksForRuntimes_ForceRecheckBypassesStaleEmptyVerdict is the #7452+// regression: a runtime with a queued task but a stale cached "empty" verdict+// (as if the enqueue's EmptyClaim.Bump was lost to a transient Redis failure)+// is stranded on a normal claim, yet a claim that names it in the force set+// bypasses the short-circuit and claims the task immediately. A second runtime+// that is NOT forced still short-circuits, proving the bypass is targeted.+func TestClaimTasksForRuntimes_ForceRecheckBypassesStaleEmptyVerdict(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ rdb := newRedisTestClient(t)++ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.EmptyClaim = NewEmptyClaimCache(rdb)++ rt1, rt2 := batchClaimFixture(t, ctx, pool)+ rt1Key, rt2Key := rt1, rt2+ ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}++ // Simulate the missed-invalidation state on BOTH runtimes: a verdict tagged+ // with the current version, so IsEmpty trusts it even though rows are queued.+ svc.EmptyClaim.MarkEmpty(ctx, rt1Key, svc.EmptyClaim.CurrentVersion(ctx, rt1Key))+ svc.EmptyClaim.MarkEmpty(ctx, rt2Key, svc.EmptyClaim.CurrentVersion(ctx, rt2Key))+ if !svc.EmptyClaim.IsEmpty(ctx, rt1Key) || !svc.EmptyClaim.IsEmpty(ctx, rt2Key) {+ t.Fatal("precondition: both runtimes must read as cached-empty")+ }++ // No force set: both runtimes short-circuit on the stale verdict → nothing+ // is claimed even though tasks are queued.+ got, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ if err != nil {+ t.Fatalf("unforced claim: %v", err)+ }+ if len(got) != 0 {+ t.Fatalf("unforced claim returned %d tasks, want 0 (stale empty verdict must short-circuit)", len(got))+ }++ // Force only rt1: it bypasses the short-circuit and claims its queued task,+ // while rt2 (not forced) stays short-circuited.+ got, _, err = svc.ClaimTasksForRuntimes(ctx, ids, 5, util.MustParseUUID(rt1))+ if err != nil {+ t.Fatalf("forced claim: %v", err)+ }+ if len(got) != 1 {+ t.Fatalf("forced claim returned %d tasks, want exactly 1 (only rt1 bypassed)", len(got))+ }+ if util.UUIDToString(got[0].RuntimeID) != rt1 {+ t.Fatalf("forced claim routed to %s, want rt1", util.UUIDToString(got[0].RuntimeID))+ }+}++// TestClaimTasksForRuntimes_ForceRecheckReArmsCacheOnZeroCandidates pins the+// other half of #7452: forcing a re-check on a genuinely-idle runtime must not+// leave the cache disabled — a zero-candidate result re-arms the empty verdict+// (MarkEmpty), so subsequent idle polls skip Postgres again.+func TestClaimTasksForRuntimes_ForceRecheckReArmsCacheOnZeroCandidates(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ rdb := newRedisTestClient(t)++ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.EmptyClaim = NewEmptyClaimCache(rdb)++ _, rt2 := batchClaimFixture(t, ctx, pool)+ rt2ID := util.MustParseUUID(rt2)++ // Drain rt2's single queued task so it becomes genuinely idle in the DB.+ if got, _, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt2ID}, 5); err != nil {+ t.Fatalf("drain claim: %v", err)+ } else if len(got) != 1 {+ t.Fatalf("drain claim returned %d tasks, want 1", len(got))+ }++ // Invalidate any cached verdict so IsEmpty is false going into the forced call.+ svc.EmptyClaim.Bump(ctx, rt2)+ if svc.EmptyClaim.IsEmpty(ctx, rt2) {+ t.Fatal("precondition: rt2 must not read as cached-empty after Bump")+ }++ // Force a re-check on the now-idle runtime: nothing to claim, but the empty+ // verdict must be re-armed for the next idle poll.+ got, acknowledged, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt2ID}, 5, rt2ID)+ if err != nil {+ t.Fatalf("forced idle claim: %v", err)+ }+ if len(got) != 0 {+ t.Fatalf("forced idle claim returned %d tasks, want 0", len(got))+ }+ if !svc.EmptyClaim.IsEmpty(ctx, rt2) {+ t.Fatal("forced re-check on a zero-candidate runtime must re-arm the empty verdict")+ }+ // A zero-candidate scan is the ONLY thing that acknowledges a forced runtime+ // (#7452): the runtime is confirmed idle and its cache entry was just re-armed+ // from a real SELECT, so the daemon may drop the hint.+ if len(acknowledged) != 1 || acknowledged[0] != rt2 {+ t.Fatalf("acknowledged set = %v, want [rt2] after a zero-candidate forced scan", acknowledged)+ }+}++// TestClaimTasksForRuntimes_ForcedPositiveIsNotAcknowledged pins refinement 1 of+// #7452: a forced runtime whose SELECT returns candidates is NOT acknowledged,+// so the daemon keeps it forced and re-forces it next cycle. The batch claims at+// most one task per agent per call, so a forced claim on a runtime with TWO+// queued tasks for the same agent takes only the first and leaves the second+// queued behind a stale "empty" verdict. Acknowledging here would have made+// correctness depend on a Redis repair write landing — and that write can fail in+// the very outage that lost the enqueue-side Bump. Staying forced until a scan+// comes back empty needs no such write: the next forced claim takes the second+// task immediately, without waiting for the ~3 minute TTL.+func TestClaimTasksForRuntimes_ForcedPositiveIsNotAcknowledged(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ rdb := newRedisTestClient(t)++ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.EmptyClaim = NewEmptyClaimCache(rdb)++ // batchClaimFixture gives rt1 an agent with TWO queued tasks on two issues.+ rt1, _ := batchClaimFixture(t, ctx, pool)+ rt1ID := util.MustParseUUID(rt1)++ // Simulate the lost-Bump state: a verdict tagged with the current version, so+ // IsEmpty trusts it even though two tasks are queued on rt1.+ svc.EmptyClaim.MarkEmpty(ctx, rt1, svc.EmptyClaim.CurrentVersion(ctx, rt1))+ if !svc.EmptyClaim.IsEmpty(ctx, rt1) {+ t.Fatal("precondition: rt1 must read as cached-empty")+ }++ // Forced claim: bypasses the short-circuit and claims exactly one of the two+ // same-agent tasks. Because the scan found candidates, rt1 is NOT acknowledged.+ forced, acknowledged, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt1ID}, 5, rt1ID)+ if err != nil {+ t.Fatalf("forced claim: %v", err)+ }+ if len(forced) != 1 || util.UUIDToString(forced[0].RuntimeID) != rt1 {+ t.Fatalf("forced claim = %d tasks on %v, want exactly 1 on rt1", len(forced), forced)+ }+ if len(acknowledged) != 0 {+ t.Fatalf("acknowledged set = %v, want empty: a forced scan that found candidates must stay forced", acknowledged)+ }++ // A NORMAL poll still short-circuits on the stale verdict, which is exactly+ // why the runtime must stay forced rather than be acknowledged here.+ if stranded, _, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt1ID}, 5); err != nil {+ t.Fatalf("normal follow-up claim: %v", err)+ } else if len(stranded) != 0 {+ t.Fatalf("normal follow-up claim = %d tasks, want 0 (the stale verdict still short-circuits)", len(stranded))+ }++ // The daemon kept rt1 forced, so the next FORCED claim takes the second+ // same-agent task instead of stranding it until the TTL.+ second, secondAck, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt1ID}, 5, rt1ID)+ if err != nil {+ t.Fatalf("second forced claim: %v", err)+ }+ if len(second) != 1 || util.UUIDToString(second[0].RuntimeID) != rt1 {+ t.Fatalf("second forced claim = %d tasks on %v, want the second task on rt1", len(second), second)+ }+ if forced[0].ID == second[0].ID {+ t.Fatal("second forced claim returned the same task, want the distinct second same-agent task")+ }+ if len(secondAck) != 0 {+ t.Fatalf("acknowledged set = %v, want empty: this scan also found candidates", secondAck)+ }++ // Once the queue really is drained, a forced scan comes back empty and only+ // THEN is rt1 acknowledged, so the daemon finally drops the hint.+ drained, drainedAck, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{rt1ID}, 5, rt1ID)+ if err != nil {+ t.Fatalf("drained forced claim: %v", err)+ }+ if len(drained) != 0 {+ t.Fatalf("drained forced claim = %d tasks, want 0", len(drained))+ }+ if len(drainedAck) != 1 || drainedAck[0] != rt1 {+ t.Fatalf("acknowledged set = %v, want [rt1] once the forced scan is empty", drainedAck)+ }+}++// TestClaimTasksForRuntimes_TransientIneligibilityKeepsForce: a forced scan that+// sees a candidate it cannot claim for a reason nothing will announce (a stale+// runtime heartbeat, a row locked by another transaction and skipped by SKIP+// LOCKED) must not acknowledge the runtime. Once the condition clears, an+// ordinary claim still short-circuits on the stale verdict and only a forced+// claim takes the task.+func TestClaimTasksForRuntimes_TransientIneligibilityKeepsForce(t *testing.T) {+ for _, condition := range []string{"stale_heartbeat", "locked_candidate"} {+ t.Run(condition, func(t *testing.T) {+ ctx := context.Background()+ pool := newTaskClaimRacePool(t)+ rdb := newRedisTestClient(t)+ svc := NewTaskService(db.New(pool), pool, nil, events.New())+ svc.EmptyClaim = NewEmptyClaimCache(rdb)+ _, rid := batchClaimFixture(t, ctx, pool)+ runtimeID := util.MustParseUUID(rid)+ ids := []pgtype.UUID{runtimeID}+ svc.EmptyClaim.MarkEmpty(ctx, rid, svc.EmptyClaim.CurrentVersion(ctx, rid))+ if !svc.EmptyClaim.IsEmpty(ctx, rid) {+ t.Fatal("precondition: runtime must read as cached-empty")+ }++ var restore func()+ switch condition {+ case "stale_heartbeat":+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET last_seen_at = now() - interval '10 minutes' WHERE id = $1`, rid); err != nil {+ t.Fatal(err)+ }+ restore = func() {+ if _, err := pool.Exec(ctx, `UPDATE agent_runtime SET last_seen_at = now() WHERE id = $1`, rid); err != nil {+ t.Fatal(err)+ }+ }+ case "locked_candidate":+ tx, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = tx.Rollback(ctx) })+ var taskID string+ if err := tx.QueryRow(ctx, `SELECT id FROM agent_task_queue WHERE runtime_id = $1 AND status = 'queued' FOR UPDATE`, rid).Scan(&taskID); err != nil {+ t.Fatal(err)+ }+ restore = func() {+ if err := tx.Rollback(ctx); err != nil {+ t.Fatal(err)+ }+ }+ }++ got, ack, err := svc.ClaimTasksForRuntimes(ctx, ids, 5, runtimeID)+ if err != nil || len(got) != 0 {+ t.Fatalf("forced claim while %s: tasks=%d err=%v, want 0 tasks", condition, len(got), err)+ }+ if len(ack) != 0 {+ t.Fatalf("acknowledged set while %s = %v, want empty: the runtime must stay forced", condition, ack)+ }+ restore()+ if ordinary, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5); err != nil || len(ordinary) != 0 {+ t.Fatalf("ordinary claim after recovery: tasks=%d err=%v, want 0 (stale verdict)", len(ordinary), err)+ }+ if forced, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5, runtimeID); err != nil || len(forced) != 1 {+ t.Fatalf("forced claim after recovery: tasks=%d err=%v, want 1", len(forced), err)+ }+ })+ }+}diff --git a/server/internal/service/task_batch_claim_partial_test.go b/server/internal/service/task_batch_claim_partial_test.goindex e5d7475c27..b39dbd22b0 100644--- a/server/internal/service/task_batch_claim_partial_test.go+++ b/server/internal/service/task_batch_claim_partial_test.go@@ -69,7 +69,7 @@ func TestClaimTasksForRuntimes_PartialSuccessOnSecondAgentClaimFailure(t *testinrt1, rt2 := batchClaimFixture(t, ctx, pool)ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}- claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ claimed, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("expected partial success (nil error), got %v", err)}@@ -129,7 +129,7 @@ func TestClaimTasksForRuntimes_PartialSuccessOnCandidateQueryFailureAfterReclaim})ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}- claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ claimed, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("expected partial success (nil error) despite candidate query failure, got %v", err)}diff --git a/server/internal/service/task_batch_claim_test.go b/server/internal/service/task_batch_claim_test.goindex 84b6ebc366..d628c6ad40 100644--- a/server/internal/service/task_batch_claim_test.go+++ b/server/internal/service/task_batch_claim_test.go@@ -108,7 +108,7 @@ func TestClaimTasksForRuntimes_MultiRuntimeDrain(t *testing.T) {ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}// Call 1: one task per agent (agent1→rt1, agent2→rt2) => 2 tasks, one per runtime.- got1, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ got1, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("call1: %v", err)}@@ -125,7 +125,7 @@ func TestClaimTasksForRuntimes_MultiRuntimeDrain(t *testing.T) {// Call 2: agent1 still has a second queued task (different issue, capacity 5);// agent2 is drained => exactly 1 task, on rt1.- got2, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ got2, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("call2: %v", err)}@@ -137,7 +137,7 @@ func TestClaimTasksForRuntimes_MultiRuntimeDrain(t *testing.T) {}// Call 3: everything dispatched => empty.- got3, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ got3, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("call3: %v", err)}@@ -156,7 +156,7 @@ func TestClaimTasksForRuntimes_MaxTasksCap(t *testing.T) {rt1, rt2 := batchClaimFixture(t, ctx, pool)ids := []pgtype.UUID{util.MustParseUUID(rt1), util.MustParseUUID(rt2)}- got, err := svc.ClaimTasksForRuntimes(ctx, ids, 1)+ got, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 1)if err != nil {t.Fatalf("claim: %v", err)}@@ -211,7 +211,7 @@ func TestClaimTasksForRuntimes_AnyDueRuntimeChecksTheCompleteSet(t *testing.T) {t.Fatalf("precondition due runtimes = %v, want [%s]", due, rt1)}- claimed, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)+ claimed, _, err := svc.ClaimTasksForRuntimes(ctx, ids, 5)if err != nil {t.Fatalf("batch claim: %v", err)}@@ -270,7 +270,7 @@ func TestClaimTasksForRuntimes_EmptyReclaimDefersHintForRetry(t *testing.T) {t.Fatalf("precondition due runtimes = %v, want [%s]", due, rt1)}- if claimed, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{runtimeID}, 5); err != nil {+ 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)@@ -305,11 +305,11 @@ func TestClaimTasksForRuntimes_EmptyInputs(t *testing.T) {pool := newTaskClaimRacePool(t)svc := NewTaskService(db.New(pool), pool, nil, events.New())- if got, err := svc.ClaimTasksForRuntimes(ctx, nil, 5); err != nil || got != nil {+ if got, _, err := svc.ClaimTasksForRuntimes(ctx, nil, 5); err != nil || got != nil {t.Fatalf("nil runtimes: got=%v err=%v, want nil,nil", got, err)}rt1, _ := batchClaimFixture(t, ctx, pool)- if got, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt1)}, 0); err != nil || got != nil {+ if got, _, err := svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{util.MustParseUUID(rt1)}, 0); err != nil || got != nil {t.Fatalf("maxTasks=0: got=%v err=%v, want nil,nil", got, err)}}diff --git a/server/internal/service/task_claim_decision_db_test.go b/server/internal/service/task_claim_decision_db_test.goindex 3316becdff..1a119b95dd 100644--- a/server/internal/service/task_claim_decision_db_test.go+++ b/server/internal/service/task_claim_decision_db_test.go@@ -197,7 +197,7 @@ func TestClaimDecisionDBBatchClaimed(t *testing.T) {f := newClaimDecisionFixture(t, 5)f.insertTask(t, "queued")- claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)+ claimed, _, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("ClaimTasksForRuntimes: %v", err)}@@ -215,7 +215,7 @@ func TestClaimDecisionDBBatchClaimed(t *testing.T) {func TestClaimDecisionDBBatchNoVisibleCandidates(t *testing.T) {f := newClaimDecisionFixture(t, 5)- claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)+ claimed, _, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("ClaimTasksForRuntimes: %v", err)}@@ -241,7 +241,7 @@ func TestClaimDecisionDBBatchCandidatesUnclaimed(t *testing.T) {t.Fatalf("take runtime offline: %v", err)}- claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)+ claimed, _, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("ClaimTasksForRuntimes: %v", err)}diff --git a/server/internal/service/task_runtime_concurrency_db_test.go b/server/internal/service/task_runtime_concurrency_db_test.goindex 3c6868de19..b45ed2ec53 100644--- a/server/internal/service/task_runtime_concurrency_db_test.go+++ b/server/internal/service/task_runtime_concurrency_db_test.go@@ -59,7 +59,7 @@ func TestRuntimeConcurrencyCapLimitsAcrossAgents(t *testing.T) {f.setRuntimeCap(t, int32Ptr(1))ctx := context.Background()- claimed, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)+ claimed, _, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("ClaimTasksForRuntimes: %v", err)}@@ -70,7 +70,7 @@ func TestRuntimeConcurrencyCapLimitsAcrossAgents(t *testing.T) {t.Fatalf("claim_decision_total{batch,runtime_no_capacity,runtime_concurrency_cap} = %v, want 1", got)}- again, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)+ again, _, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("second ClaimTasksForRuntimes: %v", err)}@@ -83,7 +83,7 @@ func TestRuntimeConcurrencyCapLimitsAcrossAgents(t *testing.T) {); err != nil {t.Fatalf("complete first task: %v", err)}- next, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)+ next, _, err := f.svc.ClaimTasksForRuntimes(ctx, []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("third ClaimTasksForRuntimes: %v", err)}@@ -102,7 +102,7 @@ func TestRuntimeConcurrencyCapNullIsUnlimited(t *testing.T) {f.insertTask(t, "queued")f.addRuntimeAgentWithTask(t, "runtime-nocap-agent-b")- claimed, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)+ claimed, _, err := f.svc.ClaimTasksForRuntimes(context.Background(), []pgtype.UUID{f.runtimeID}, 8)if err != nil {t.Fatalf("ClaimTasksForRuntimes: %v", err)}diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 17ba60f441..431b1e1b85 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -32,6 +32,9 @@ const (// the extra deferred-task lookup for clients that opt in, and an older// server's missing fields make a newer daemon retain its short fallback.DaemonCapabilityClaimPollHintsV1 = "claim-poll-hints-v1"+ // DaemonCapabilityForceRecheckV1 requests presence-aware batch claim+ // acknowledgements on both HTTP and WebSocket.+ DaemonCapabilityForceRecheckV1 = "force-recheck-v1"// DaemonCapabilityPlatformSkillV1 advertises that the daemon's runtime// brief names the merged `multica-platform` skill instead of the