Skip to content

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

Go

MUL-2215: fix(daemon): close handleRuntimeGone success/straggler race (#2623)

Bohan Jiang8572a7995043
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 55b388e88d..44c1fa8b3a 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -82,13 +82,15 @@ type Daemon struct {
wsHBMu sync.RWMutex // guards wsHBLastAck
wsHBLastAck map[string]time.Time // runtime_id -> last successful WS heartbeat ack timestamp
- // runtimeGoneMu guards runtimeGoneInflight and reregisterNextAttempt. The
- // state lets heartbeat / poller / WS-ack handlers converge on a single
- // recovery path when they each detect that a runtime row was deleted
- // server-side without three of them stampeding registerRuntimesForWorkspace.
- runtimeGoneMu sync.Mutex
- runtimeGoneInflight map[string]struct{} // runtime_id -> currently recovering
- reregisterNextAttempt map[string]time.Time // workspace_id -> earliest time the next re-register attempt may run
+ // runtimeGoneMu guards runtimeGoneInflight, reregisterNextAttempt, and
+ // reregisterLastCompletedAt. The state lets heartbeat / poller / WS-ack
+ // handlers converge on a single recovery path when they each detect that a
+ // runtime row was deleted server-side without three of them stampeding
+ // registerRuntimesForWorkspace.
+ runtimeGoneMu sync.Mutex
+ runtimeGoneInflight map[string]struct{} // runtime_id -> currently recovering
+ reregisterNextAttempt map[string]time.Time // workspace_id -> earliest time the next re-register attempt may run
+ reregisterLastCompletedAt map[string]time.Time // workspace_id -> wall-clock at which the last SUCCESSFUL re-register call returned (failures intentionally not stamped — see recordRegisterCompletion)
cancelFunc context.CancelFunc // set by Run(); called by triggerRestart
rootCtx context.Context // set by Run(); used by long-running recoveries that must survive per-runtime ctx cancellation
@@ -115,18 +117,19 @@ func New(cfg Config, logger *slog.Logger) *Daemon {
// server can split logs/metrics by client version (parallel to the CLI).
client.SetVersion(cfg.CLIVersion)
return &Daemon{
- cfg: cfg,
- client: client,
- repoCache: repocache.New(cacheRoot, logger),
- logger: logger,
- workspaces: make(map[string]*workspaceState),
- runtimeIndex: make(map[string]Runtime),
- runtimeSet: newRuntimeSetWatcher(),
- agentVersions: make(map[string]string),
- wsHBLastAck: make(map[string]time.Time),
- activeEnvRoots: make(map[string]int),
- runtimeGoneInflight: make(map[string]struct{}),
- reregisterNextAttempt: make(map[string]time.Time),
+ cfg: cfg,
+ client: client,
+ repoCache: repocache.New(cacheRoot, logger),
+ logger: logger,
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: make(map[string]Runtime),
+ runtimeSet: newRuntimeSetWatcher(),
+ agentVersions: make(map[string]string),
+ wsHBLastAck: make(map[string]time.Time),
+ activeEnvRoots: make(map[string]int),
+ runtimeGoneInflight: make(map[string]struct{}),
+ reregisterNextAttempt: make(map[string]time.Time),
+ reregisterLastCompletedAt: make(map[string]time.Time),
}
}
@@ -170,12 +173,17 @@ const reregisterFailureBackoff = 60 * time.Second
// each other, so this function:
//
// - keys an in-flight set on runtimeID to drop concurrent calls for the same
-// ID after the first one is already cleaning up; and
+// ID after the first one is already cleaning up;
// - keys a per-workspace next-attempt timestamp on workspaceID so that
// concurrent recoveries triggered by the SAME initial event coalesce to a
// single registerRuntimesForWorkspace call. The slot is cleared on success
// so a later distinct runtime deletion in the same workspace can trigger
-// its own recovery without waiting for the coalesce window to expire.
+// its own recovery without waiting for the coalesce window to expire; and
+// - keys a per-workspace last-completed timestamp so that a straggler whose
+// removeStaleRuntime took long enough that a sibling fully ran AND cleared
+// the slot can still recognize itself as same-wave and bail. Without this,
+// the success-case slot clear opens a race where the late caller re-claims
+// an empty slot and double-registers.
//
// On failure of the underlying re-register, the next-attempt timestamp is
// extended by reregisterFailureBackoff so we don't replace a server-side log
@@ -191,6 +199,11 @@ func (d *Daemon) handleRuntimeGone(runtimeID string) {
return
}
+ // entryAt anchors the same-wave-straggler check at the bottom of the
+ // function. Captured at the very top so removeStaleRuntime mutex
+ // contention can't push it past a sibling's register completion.
+ entryAt := time.Now()
+
// Stampede control per runtime ID.
d.runtimeGoneMu.Lock()
if _, inflight := d.runtimeGoneInflight[runtimeID]; inflight {
@@ -216,40 +229,75 @@ func (d *Daemon) handleRuntimeGone(runtimeID string) {
"runtime_id", runtimeID, "workspace_id", workspaceID)
d.notifyRuntimeSetChanged()
- // Per-workspace coalescing: claim the slot atomically. The first caller
- // past this check is the only one that will run
- // registerRuntimesForWorkspace while the coalesce window is open. We
- // clear the slot on success so a separate later deletion in the same
- // workspace is NOT suppressed; the inflight set above is what keeps two
- // callers from racing the same recovery.
- now := time.Now()
- d.runtimeGoneMu.Lock()
- if next, ok := d.reregisterNextAttempt[workspaceID]; ok && now.Before(next) {
- d.runtimeGoneMu.Unlock()
+ if !d.tryClaimRegisterSlot(workspaceID, entryAt, time.Now()) {
d.logger.Debug("skip re-register: coalescing with recent attempt",
"workspace_id", workspaceID)
return
}
- d.reregisterNextAttempt[workspaceID] = now.Add(reregisterCoalesceWindow)
- d.runtimeGoneMu.Unlock()
- if err := d.reregisterWorkspaceAfterRuntimeGone(d.recoveryContext(), workspaceID); err != nil {
- d.runtimeGoneMu.Lock()
- d.reregisterNextAttempt[workspaceID] = time.Now().Add(reregisterFailureBackoff)
- d.runtimeGoneMu.Unlock()
+ err := d.reregisterWorkspaceAfterRuntimeGone(d.recoveryContext(), workspaceID)
+ d.recordRegisterCompletion(workspaceID, time.Now(), err)
+ if err != nil {
// Logged at Warn (not Error) because workspaceSyncLoop retries
// independently every DefaultWorkspaceSyncInterval, so a transient
// failure here is not a stuck state — just an extra wait.
d.logger.Warn("re-register after runtime gone failed",
"workspace_id", workspaceID, "error", err)
- return
}
- // Success: clear the coalesce slot so a future distinct runtime deletion
- // in this workspace can trigger its own recovery immediately. The
- // inflight set on runtimeID still prevents same-event stampedes.
+}
+
+// tryClaimRegisterSlot atomically decides whether the calling goroutine should
+// run registerRuntimesForWorkspace. Returns true and claims the in-flight slot
+// when the caller may proceed; returns false (without mutating state) when the
+// call must be coalesced with a peer.
+//
+// Two gates are checked under runtimeGoneMu:
+//
+// 1. reregisterNextAttempt: a future timestamp means a peer holds the slot or
+// a previous attempt failed and we are inside the failure backoff window.
+// 2. reregisterLastCompletedAt: a timestamp at or after our entryAt means a
+// peer's register SUCCEEDED after we entered handleRuntimeGone, so the
+// workspace state is already covered for our wave and we can bail.
+// Failures intentionally don't stamp this field (see
+// recordRegisterCompletion), so a same-wave straggler whose entryAt
+// predates a failed sibling can still retry once the failure backoff
+// expires — failures don't cover anything.
+//
+// entryAt is the wall-clock captured at the top of handleRuntimeGone. now is
+// passed in (rather than read inside) so tests can drive the gate
+// deterministically without sleeping.
+func (d *Daemon) tryClaimRegisterSlot(workspaceID string, entryAt, now time.Time) bool {
+ d.runtimeGoneMu.Lock()
+ defer d.runtimeGoneMu.Unlock()
+ if next, ok := d.reregisterNextAttempt[workspaceID]; ok && now.Before(next) {
+ return false
+ }
+ if last, ok := d.reregisterLastCompletedAt[workspaceID]; ok && !last.Before(entryAt) {
+ return false
+ }
+ d.reregisterNextAttempt[workspaceID] = now.Add(reregisterCoalesceWindow)
+ return true
+}
+
+// recordRegisterCompletion records the outcome of a register call. On success
+// it stamps lastCompletedAt (which suppresses same-wave stragglers via
+// tryClaimRegisterSlot) and clears the in-flight slot so a genuinely later
+// runtime deletion can claim immediately. On failure it extends
+// reregisterNextAttempt by the failure backoff and intentionally does NOT
+// stamp lastCompletedAt — a failed register did not cover any workspace
+// state, so a same-wave straggler whose entryAt predates the failure must
+// still be allowed to retry once the backoff expires. workspaceSyncLoop only
+// retries when the workspace's runtimeIDs fully drain, so partial-deletion
+// recovery has to come from the straggler path.
+func (d *Daemon) recordRegisterCompletion(workspaceID string, completedAt time.Time, err error) {
d.runtimeGoneMu.Lock()
+ defer d.runtimeGoneMu.Unlock()
+ if err != nil {
+ d.reregisterNextAttempt[workspaceID] = completedAt.Add(reregisterFailureBackoff)
+ return
+ }
+ d.reregisterLastCompletedAt[workspaceID] = completedAt
delete(d.reregisterNextAttempt, workspaceID)
- d.runtimeGoneMu.Unlock()
}
// recoveryContext returns the daemon root context for long-running recovery
diff --git a/server/internal/daemon/runtime_gone_test.go b/server/internal/daemon/runtime_gone_test.go
index 500f8f4b25..0d479b0744 100644
--- a/server/internal/daemon/runtime_gone_test.go
+++ b/server/internal/daemon/runtime_gone_test.go
@@ -3,6 +3,7 @@ package daemon
import (
"context"
"encoding/json"
+ "errors"
"fmt"
"log/slog"
"net/http"
@@ -18,16 +19,17 @@ import (
// so callers can exercise handleRuntimeGone without going through Run.
func freshDaemon(serverURL string) *Daemon {
return &Daemon{
- client: NewClient(serverURL),
- logger: slog.New(slog.NewTextHandler(testNopWriter{}, &slog.HandlerOptions{Level: slog.LevelWarn})),
- workspaces: make(map[string]*workspaceState),
- runtimeIndex: make(map[string]Runtime),
- runtimeSet: newRuntimeSetWatcher(),
- agentVersions: make(map[string]string),
- wsHBLastAck: make(map[string]time.Time),
- activeEnvRoots: make(map[string]int),
- runtimeGoneInflight: make(map[string]struct{}),
- reregisterNextAttempt: make(map[string]time.Time),
+ client: NewClient(serverURL),
+ logger: slog.New(slog.NewTextHandler(testNopWriter{}, &slog.HandlerOptions{Level: slog.LevelWarn})),
+ workspaces: make(map[string]*workspaceState),
+ runtimeIndex: make(map[string]Runtime),
+ runtimeSet: newRuntimeSetWatcher(),
+ agentVersions: make(map[string]string),
+ wsHBLastAck: make(map[string]time.Time),
+ activeEnvRoots: make(map[string]int),
+ runtimeGoneInflight: make(map[string]struct{}),
+ reregisterNextAttempt: make(map[string]time.Time),
+ reregisterLastCompletedAt: make(map[string]time.Time),
}
}
@@ -544,6 +546,145 @@ func TestHandleRuntimeGone_DistinctDeletionsWithinCoalesceWindowBothRecover(t *t
}
}
+func TestTryClaimRegisterSlot_FirstCallerClaims(t *testing.T) {
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+ if !d.tryClaimRegisterSlot("ws-1", t0, t0) {
+ t.Fatalf("first caller should claim the slot, got false")
+ }
+}
+
+func TestTryClaimRegisterSlot_StragglerBailsAfterSiblingSuccess(t *testing.T) {
+ // Deterministic regression for the race the flaky CoalescesConcurrentCallers
+ // test was catching: goroutine B enters at T0, goroutine A enters slightly
+ // later, A claims the slot, runs register to success, clears the slot. B's
+ // removeStaleRuntime then catches up and B reaches the coalesce gate. Without
+ // the lastCompletedAt gate, B would see an empty slot and double-register.
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+
+ // A: enters at T0+1ms, claims slot, register completes at T0+50ms.
+ aEntry := t0.Add(1 * time.Millisecond)
+ if !d.tryClaimRegisterSlot("ws-1", aEntry, aEntry) {
+ t.Fatalf("A: expected to claim, got bail")
+ }
+ d.recordRegisterCompletion("ws-1", t0.Add(50*time.Millisecond), nil)
+
+ // B: entered at T0 (BEFORE A completed and cleared the slot) but only
+ // arrives at the gate after A is done. Must bail on the lastCompletedAt
+ // check.
+ bEntry := t0
+ bArrive := t0.Add(60 * time.Millisecond)
+ if d.tryClaimRegisterSlot("ws-1", bEntry, bArrive) {
+ t.Fatalf("B: same-wave straggler must NOT re-claim the slot after A's success")
+ }
+}
+
+func TestTryClaimRegisterSlot_DistinctLaterEventClaims(t *testing.T) {
+ // Companion to StragglerBailsAfterSiblingSuccess: a deletion event that
+ // happens AFTER a prior register completed must still trigger its own
+ // register. This is the property the on-success delete preserves and that
+ // TestHandleRuntimeGone_DistinctDeletionsWithinCoalesceWindowBothRecover
+ // validates at the integration layer.
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+
+ if !d.tryClaimRegisterSlot("ws-1", t0, t0) {
+ t.Fatalf("first caller should claim")
+ }
+ d.recordRegisterCompletion("ws-1", t0.Add(50*time.Millisecond), nil)
+
+ // A genuinely later event: entered AFTER the prior register completed.
+ laterEntry := t0.Add(100 * time.Millisecond)
+ if !d.tryClaimRegisterSlot("ws-1", laterEntry, laterEntry) {
+ t.Fatalf("genuinely later event must be allowed to claim, got bail")
+ }
+}
+
+func TestTryClaimRegisterSlot_FailureBackoffSuppressesRetries(t *testing.T) {
+ // After a failed register, callers within the failure backoff window must
+ // bail even if their entry time predates the failure (the daemon must not
+ // replace a server-side log flood with a register flood). Callers past the
+ // window are allowed to proceed.
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+
+ if !d.tryClaimRegisterSlot("ws-1", t0, t0) {
+ t.Fatalf("first caller should claim")
+ }
+ failAt := t0.Add(50 * time.Millisecond)
+ d.recordRegisterCompletion("ws-1", failAt, errors.New("boom"))
+
+ within := failAt.Add(reregisterFailureBackoff / 2)
+ if d.tryClaimRegisterSlot("ws-1", within, within) {
+ t.Fatalf("call within failure backoff must be coalesced")
+ }
+
+ past := failAt.Add(reregisterFailureBackoff + time.Second)
+ if !d.tryClaimRegisterSlot("ws-1", past, past) {
+ t.Fatalf("call past failure backoff must be allowed to claim")
+ }
+}
+
+func TestTryClaimRegisterSlot_StragglerAfterFailedSiblingRetriesPastBackoff(t *testing.T) {
+ // Regression for the failure-path semantics gap the second review caught:
+ // recordRegisterCompletion must NOT stamp lastCompletedAt on failure,
+ // because a failed register has not covered any workspace state. A
+ // same-wave straggler whose entryAt predates the failure but who only
+ // reaches the gate after the failure backoff has expired must be allowed
+ // to claim — otherwise the workspace stays unregistered until
+ // workspaceSyncLoop notices, and that loop only fires when the workspace's
+ // runtimeIDs fully drain (partial deletions wouldn't trigger it).
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+
+ // A: enters at T0+1ms, claims slot, register FAILS at T0+50ms. The
+ // failure stamps reregisterNextAttempt = failAt + failureBackoff and
+ // (per the fix) does NOT stamp lastCompletedAt.
+ aEntry := t0.Add(1 * time.Millisecond)
+ if !d.tryClaimRegisterSlot("ws-1", aEntry, aEntry) {
+ t.Fatalf("A: expected to claim, got bail")
+ }
+ failAt := t0.Add(50 * time.Millisecond)
+ d.recordRegisterCompletion("ws-1", failAt, errors.New("boom"))
+
+ // B: entered at T0 (BEFORE A's failure) but was stuck on removeStaleRuntime
+ // mutex contention; arrives at the gate at failAt + failureBackoff + 1s.
+ // nextAttempt has expired; lastCompletedAt is unset; B must claim.
+ bEntry := t0
+ bArrive := failAt.Add(reregisterFailureBackoff + time.Second)
+ if !d.tryClaimRegisterSlot("ws-1", bEntry, bArrive) {
+ t.Fatalf("B: straggler whose entryAt predates a failed sibling must reclaim once failure backoff expires")
+ }
+}
+
+func TestTryClaimRegisterSlot_PeerHoldingSlotForcesCoalesce(t *testing.T) {
+ // While a peer holds an unfinished slot, callers must bail regardless of
+ // the lastCompletedAt state.
+ t.Parallel()
+
+ d := freshDaemon("")
+ t0 := time.Now()
+ if !d.tryClaimRegisterSlot("ws-1", t0, t0) {
+ t.Fatalf("first caller should claim")
+ }
+ // Peer is still running register; lastCompletedAt is not yet set, but
+ // reregisterNextAttempt is t0 + coalesceWindow.
+ if d.tryClaimRegisterSlot("ws-1", t0.Add(time.Millisecond), t0.Add(time.Millisecond)) {
+ t.Fatalf("caller arriving while peer holds the slot must coalesce")
+ }
+}
+
func TestHandleRuntimeGone_RecoveryContextSurvivesCallerCancellation(t *testing.T) {
// Regression for Finding #1: handleRuntimeGone must not use the per-
// runtime heartbeat ctx for the register HTTP call. notifyRuntimeSetChanged