Skip to content

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

Go

fix(daemon): prevent runtime update starvation (#6123)

hvejsel423d86da0467
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index ed6bc694b9..41699b4878 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -3151,12 +3151,29 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
return
}
- // Prevent concurrent update attempts.
- if !d.updating.CompareAndSwap(false, true) {
- d.logger.Warn("update already in progress, ignoring", "runtime_id", runtimeID, "update_id", update.ID)
+ switch d.tryBeginServerUpdate(ctx) {
+ case serverUpdateAlreadyRunning:
+ d.logger.Warn("update deferred: another update is already in progress", "runtime_id", runtimeID, "update_id", update.ID)
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": "another runtime update is already in progress on this machine",
+ })
+ return
+ case serverUpdateRuntimeBusy:
+ d.logger.Info("update deferred: task or claim in progress", "runtime_id", runtimeID, "update_id", update.ID)
+ d.reportUpdateResult(ctx, runtimeID, update.ID, map[string]any{
+ "status": "failed",
+ "error": "runtime update deferred because agent work is starting or still active; retry when the machine is idle",
+ })
return
}
- defer d.updating.Store(false)
+ restarting := false
+ defer func() {
+ if !restarting {
+ d.releaseClaimBarrier()
+ d.updating.Store(false)
+ }
+ }()
d.logger.Info("CLI update requested", "runtime_id", runtimeID, "update_id", update.ID, "target_version", update.TargetVersion)
@@ -3183,6 +3200,59 @@ func (d *Daemon) handleUpdate(ctx context.Context, runtimeID string, update *Pen
// Trigger daemon restart with the new binary.
d.triggerRestart()
+ restarting = d.RestartBinary() != ""
+}
+
+type serverUpdateAcquireResult uint8
+
+const (
+ serverUpdateAcquired serverUpdateAcquireResult = iota
+ serverUpdateAlreadyRunning
+ serverUpdateRuntimeBusy
+)
+
+// tryBeginServerUpdate atomically claims update ownership, pauses new claims,
+// and lets any claim already in flight finish its handoff. An empty claim can
+// therefore never starve an update; a claim that returns work increments
+// activeTasks before exitClaim, so the final check still defers safely.
+func (d *Daemon) tryBeginServerUpdate(ctx context.Context) serverUpdateAcquireResult {
+ if !d.updating.CompareAndSwap(false, true) {
+ return serverUpdateAlreadyRunning
+ }
+
+ d.claimMu.Lock()
+ if d.pauseClaims || d.activeTasks.Load() > 0 {
+ d.claimMu.Unlock()
+ d.updating.Store(false)
+ return serverUpdateRuntimeBusy
+ }
+ d.pauseClaims = true
+ d.claimMu.Unlock()
+
+ ticker := time.NewTicker(10 * time.Millisecond)
+ defer ticker.Stop()
+ for {
+ d.claimMu.Lock()
+ if d.claimsInFlight == 0 {
+ if d.activeTasks.Load() == 0 {
+ d.claimMu.Unlock()
+ return serverUpdateAcquired
+ }
+ d.pauseClaims = false
+ d.claimMu.Unlock()
+ d.updating.Store(false)
+ return serverUpdateRuntimeBusy
+ }
+ d.claimMu.Unlock()
+
+ select {
+ case <-ctx.Done():
+ d.releaseClaimBarrier()
+ d.updating.Store(false)
+ return serverUpdateRuntimeBusy
+ case <-ticker.C:
+ }
+ }
}
// runUpdate executes the brew-or-download upgrade against targetVersion and
diff --git a/server/internal/daemon/server_update_test.go b/server/internal/daemon/server_update_test.go
new file mode 100644
index 0000000000..c230cd9266
--- /dev/null
+++ b/server/internal/daemon/server_update_test.go
@@ -0,0 +1,239 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func TestHandleUpdateReportsWhyItWasDeferred(t *testing.T) {
+ tests := []struct {
+ name string
+ arrange func(*Daemon)
+ wantError string
+ }{
+ {
+ name: "another update owns the daemon",
+ arrange: func(d *Daemon) {
+ d.updating.Store(true)
+ },
+ wantError: "another runtime update is already in progress on this machine",
+ },
+ {
+ name: "agent task is active",
+ arrange: func(d *Daemon) {
+ d.activeTasks.Store(1)
+ },
+ wantError: "runtime update deferred because agent work is starting or still active; retry when the machine is idle",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ var payload map[string]any
+ d, reportCalls := updateReportDaemon(t, func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode update report: %v", err)
+ }
+ w.WriteHeader(http.StatusOK)
+ })
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatal("runUpdateFn must not run while the update is deferred")
+ return "", nil
+ }
+ tt.arrange(d)
+
+ d.handleUpdate(context.Background(), "runtime-1", &PendingUpdate{
+ ID: "update-1",
+ TargetVersion: "v0.4.14",
+ })
+
+ if got := atomic.LoadInt32(reportCalls); got != 1 {
+ t.Fatalf("update reports = %d, want 1", got)
+ }
+ if got := payload["status"]; got != "failed" {
+ t.Fatalf("status = %v, want failed", got)
+ }
+ if got := payload["error"]; got != tt.wantError {
+ t.Fatalf("error = %v, want %q", got, tt.wantError)
+ }
+ })
+ }
+}
+
+func TestHandleUpdateWaitsForEmptyClaimInsteadOfStarving(t *testing.T) {
+ originalResolveSelfExecutable := resolveSelfExecutable
+ originalIsBrewInstall := isBrewInstall
+ resolveSelfExecutable = func() (string, error) {
+ return "/tmp/multica-next", nil
+ }
+ isBrewInstall = func() bool { return false }
+ t.Cleanup(func() {
+ resolveSelfExecutable = originalResolveSelfExecutable
+ isBrewInstall = originalIsBrewInstall
+ })
+
+ d, _ := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+ d.claimsInFlight = 1
+ updateStarted := make(chan struct{})
+ d.runUpdateFn = func(string) (string, error) {
+ close(updateStarted)
+ return "upgraded", nil
+ }
+ done := make(chan struct{})
+ go func() {
+ d.handleUpdate(context.Background(), "runtime-1", &PendingUpdate{
+ ID: "update-1",
+ TargetVersion: "v0.4.14",
+ })
+ close(done)
+ }()
+
+ waitForServerUpdateBarrier(t, d)
+ select {
+ case <-updateStarted:
+ t.Fatal("update started before the in-flight claim finished")
+ default:
+ }
+
+ d.exitClaim()
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("update did not continue after the empty claim finished")
+ }
+ select {
+ case <-updateStarted:
+ default:
+ t.Fatal("update never started after the empty claim finished")
+ }
+}
+
+func TestHandleUpdateReportsBusyWhenClaimBecomesTask(t *testing.T) {
+ var payload map[string]any
+ d, _ := updateReportDaemon(t, func(w http.ResponseWriter, r *http.Request) {
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode update report: %v", err)
+ }
+ w.WriteHeader(http.StatusOK)
+ })
+ d.claimsInFlight = 1
+ d.runUpdateFn = func(string) (string, error) {
+ t.Fatal("runUpdateFn must not run after the claim hands off an active task")
+ return "", nil
+ }
+ done := make(chan struct{})
+ go func() {
+ d.handleUpdate(context.Background(), "runtime-1", &PendingUpdate{
+ ID: "update-1",
+ TargetVersion: "v0.4.14",
+ })
+ close(done)
+ }()
+
+ waitForServerUpdateBarrier(t, d)
+ d.activeTasks.Add(1)
+ d.exitClaim()
+ defer d.activeTasks.Add(-1)
+
+ select {
+ case <-done:
+ case <-time.After(time.Second):
+ t.Fatal("update did not return after the claim handed off a task")
+ }
+ if got := payload["status"]; got != "failed" {
+ t.Fatalf("status = %v, want failed", got)
+ }
+ if got := payload["error"]; got != "runtime update deferred because agent work is starting or still active; retry when the machine is idle" {
+ t.Fatalf("error = %v", got)
+ }
+}
+
+func waitForServerUpdateBarrier(t *testing.T, d *Daemon) {
+ t.Helper()
+ deadline := time.Now().Add(time.Second)
+ for time.Now().Before(deadline) {
+ d.claimMu.Lock()
+ paused := d.pauseClaims
+ d.claimMu.Unlock()
+ if paused {
+ return
+ }
+ time.Sleep(time.Millisecond)
+ }
+ t.Fatal("server update did not pause new claims")
+}
+
+func TestHandleUpdateKeepsBarrierOnlyWhenRestartWasScheduled(t *testing.T) {
+ tests := []struct {
+ name string
+ resolveExecutable func() (string, error)
+ wantUpdating bool
+ wantClaimsPaused bool
+ wantRestartCalls int32
+ }{
+ {
+ name: "restart scheduled",
+ resolveExecutable: func() (string, error) {
+ return "/tmp/multica-next", nil
+ },
+ wantUpdating: true,
+ wantClaimsPaused: true,
+ wantRestartCalls: 1,
+ },
+ {
+ name: "restart could not be scheduled",
+ resolveExecutable: func() (string, error) {
+ return "", errors.New("executable unavailable")
+ },
+ wantUpdating: false,
+ wantClaimsPaused: false,
+ wantRestartCalls: 0,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ originalResolveSelfExecutable := resolveSelfExecutable
+ originalIsBrewInstall := isBrewInstall
+ resolveSelfExecutable = tt.resolveExecutable
+ isBrewInstall = func() bool { return false }
+ t.Cleanup(func() {
+ resolveSelfExecutable = originalResolveSelfExecutable
+ isBrewInstall = originalIsBrewInstall
+ })
+
+ d, _ := updateReportDaemon(t, func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ })
+ d.runUpdateFn = func(string) (string, error) {
+ return "upgraded", nil
+ }
+ var restartCalls atomic.Int32
+ d.cancelFunc = func() {
+ restartCalls.Add(1)
+ }
+
+ d.handleUpdate(context.Background(), "runtime-1", &PendingUpdate{
+ ID: "update-1",
+ TargetVersion: "v0.4.14",
+ })
+
+ if got := d.updating.Load(); got != tt.wantUpdating {
+ t.Fatalf("updating = %v, want %v", got, tt.wantUpdating)
+ }
+ if got := d.pauseClaims; got != tt.wantClaimsPaused {
+ t.Fatalf("pauseClaims = %v, want %v", got, tt.wantClaimsPaused)
+ }
+ if got := restartCalls.Load(); got != tt.wantRestartCalls {
+ t.Fatalf("restart calls = %d, want %d", got, tt.wantRestartCalls)
+ }
+ })
+ }
+}