Skip to content

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

Go

fix(daemon): recover from uncertain ws claims

ZIce92676fbe515f
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 6f5e13e14d..f4300c353d 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -229,6 +229,10 @@ type Daemon struct {
// directly. Reset when the WS (re)connects, so a server upgrade that
// bounces the connection re-probes the batch route (MUL-4257).
batchClaimUnsupported atomic.Bool
+ // wsClaimHTTPFallbackAfter is set after an uncertain WS claim outcome. Once
+ // the safety delay elapses, the next claim bypasses WS once and uses HTTP so
+ // a flaky reconnecting WS cannot starve queued tasks indefinitely.
+ wsClaimHTTPFallbackAfter atomic.Int64
// runtimeGoneMu guards runtimeGoneInflight, reregisterNextAttempt, and
// reregisterLastCompletedAt. The state lets heartbeat / poller / WS-ack
diff --git a/server/internal/daemon/daemon_legacy_fallback_test.go b/server/internal/daemon/daemon_legacy_fallback_test.go
index b0e54dd2ab..91d8c5ace9 100644
--- a/server/internal/daemon/daemon_legacy_fallback_test.go
+++ b/server/internal/daemon/daemon_legacy_fallback_test.go
@@ -74,10 +74,9 @@ func TestClaimTasksWSFirst_LegacyFallbackWhenBatchRouteMissing(t *testing.T) {
// TestClaimTasksWSFirst_NoDoubleClaimOnDetach pins the Sol-Boy review fix: if
// the WS connection detaches while a tasks.claim RPC is in flight (its frame
-// already sent), ClaimTasksWSFirst must NOT fall back to an HTTP claim for the
-// same free slots — the WS claim may have committed server-side, and a second
-// HTTP claim would double-claim. It returns no tasks; reclaim / the next poll
-// recovers.
+// already sent), ClaimTasksWSFirst must NOT fall back to an HTTP claim in the
+// same call — the WS claim may have committed server-side, and an immediate
+// second HTTP claim would double-claim.
func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {
var httpClaims atomic.Int64
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -133,6 +132,106 @@ func TestClaimTasksWSFirst_NoDoubleClaimOnDetach(t *testing.T) {
}
}
+// TestClaimTasksWSFirst_HTTPFallbackAfterUncertainCooldown covers #5404: a
+// flaky WS can reconnect and advertise rpc-v1 before the next poll. After one
+// uncertain sent-frame outcome, the daemon must not immediately HTTP fallback,
+// but it must bypass WS once after the safety window so queued tasks cannot wedge
+// behind repeated uncertain WS attempts.
+func TestClaimTasksWSFirst_HTTPFallbackAfterUncertainCooldown(t *testing.T) {
+ originalDelay := wsClaimUncertainFallbackDelay
+ wsClaimUncertainFallbackDelay = 25 * time.Millisecond
+ t.Cleanup(func() { wsClaimUncertainFallbackDelay = originalDelay })
+
+ var httpClaims, wsClaims atomic.Int64
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if strings.Contains(r.URL.Path, "/claim") {
+ httpClaims.Add(1)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"tasks":[{"id":"http-t","runtime_id":"rt1","agent":{"name":"a"}}]}`))
+ }))
+ 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)
+
+ done := make(chan struct{})
+ var tasks []*Task
+ var err error
+ go func() {
+ tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)
+ 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("ClaimTasksWSFirst did not return after detach")
+ }
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if len(tasks) != 0 {
+ t.Fatalf("expected no tasks on uncertain WS outcome, got %d", len(tasks))
+ }
+ if httpClaims.Load() != 0 {
+ t.Fatalf("HTTP fallback claimed immediately after uncertain WS outcome; calls=%d", httpClaims.Load())
+ }
+
+ reconnectGeneration := d.wsRPC.attach(func(frame []byte) (*wsOutbound, error) {
+ wsClaims.Add(1)
+ return &wsOutbound{data: frame}, nil
+ })
+ d.wsRPC.markRPCV1Supported(reconnectGeneration)
+
+ tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)
+ 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 httpClaims.Load() != 0 || wsClaims.Load() != 0 {
+ t.Fatalf("cooldown attempted claims: http=%d ws=%d, want 0/0", httpClaims.Load(), wsClaims.Load())
+ }
+
+ time.Sleep(2 * wsClaimUncertainFallbackDelay)
+ tasks, err = d.ClaimTasksWSFirst(context.Background(), "daemon-x", []string{"rt1"}, 2)
+ if err != nil {
+ t.Fatalf("post-cooldown ClaimTasksWSFirst: %v", err)
+ }
+ if len(tasks) != 1 || tasks[0].ID != "http-t" {
+ t.Fatalf("tasks = %#v, want one HTTP fallback task", tasks)
+ }
+ if httpClaims.Load() != 1 {
+ t.Fatalf("HTTP fallback claims = %d, want 1", httpClaims.Load())
+ }
+ if wsClaims.Load() != 0 {
+ t.Fatalf("WS claims after uncertain cooldown = %d, want 0", wsClaims.Load())
+ }
+}
+
// TestClaimTasksWSFirst_ReconnectToOldServerSkipsWSRPC pins compatibility when
// a daemon moves from an rpc-v1 server to an older server. The replacement
// connection must not inherit the first connection's negotiated capability;
diff --git a/server/internal/daemon/wsrpc.go b/server/internal/daemon/wsrpc.go
index e35bf77763..4e9356a222 100644
--- a/server/internal/daemon/wsrpc.go
+++ b/server/internal/daemon/wsrpc.go
@@ -29,6 +29,8 @@ var errWSRPCUncertain = errors.New("ws rpc: sent but outcome unknown (connection
// daemon gives up (MUL-4257).
const wsRPCResponseGrace = 2 * time.Second
+var wsClaimUncertainFallbackDelay = batchClaimRequestTimeout + wsRPCResponseGrace
+
// errWSRPCWriteBufferFull is returned when the connection's write buffer is
// saturated; the caller falls back to HTTP rather than blocking the socket.
var errWSRPCWriteBufferFull = errors.New("ws rpc: write buffer full")
@@ -304,10 +306,12 @@ func (c *wsRPCClient) deliver(resp protocol.RPCResponsePayload) {
// ClaimTasksWSFirst is the WS-first claim policy (MUL-4257): it issues the
// tasks.claim RPC over the WS control connection when one is attached, and
-// falls back to the HTTP claim endpoint on any transport failure (no
-// connection, write-buffer full, timeout) or server error. 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.
+// falls back to the HTTP claim endpoint on transport failures that are known not
+// to have reached the server (no connection, write-buffer full, unsent timeout)
+// or server error. A sent-frame disconnect/timeout is uncertain, so it is
+// 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) {
// 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
@@ -315,7 +319,21 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtime
if d.batchClaimUnsupported.Load() {
return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)
}
- if d.wsRPC.supportsRPCV1() {
+ bypassWSOnce := false
+ if retryAfterNanos := d.wsClaimHTTPFallbackAfter.Load(); retryAfterNanos > 0 {
+ retryAfter := time.Unix(0, retryAfterNanos)
+ now := time.Now()
+ if 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 nil, nil
+ }
+ if d.wsClaimHTTPFallbackAfter.CompareAndSwap(retryAfterNanos, 0) {
+ bypassWSOnce = true
+ d.logger.Debug("previous ws claim outcome uncertain; using http fallback for this claim cycle")
+ }
+ }
+ if !bypassWSOnce && d.wsRPC.supportsRPCV1() {
var resp struct {
Tasks []*Task `json:"tasks"`
}
@@ -331,10 +349,17 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtime
}
if errors.Is(err, errWSRPCUncertain) {
// The WS claim may have committed server-side; claiming the same
- // free slots again over HTTP would double-claim. Skip this cycle —
- // an orphaned server-side claim is recovered by stale reclaim and
- // the next poll picks up anything still queued.
- d.logger.Debug("ws claim outcome uncertain after disconnect; skipping fallback this cycle")
+ // free slots again over HTTP immediately would double-claim. Skip
+ // this cycle, then force one HTTP batch claim after the server-side
+ // 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.
+ delay := wsClaimUncertainFallbackDelay
+ if 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 nil, nil
}
d.logger.Debug("ws claim failed; falling back to http", "error", err)