Skip to content

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

Go

MUL-8453: fix(daemon): retry tasks interrupted by shutdown (#9778)

沙雕的小鱼儿 boyfeiyu1c82a5b3f1a8
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 37c5d125c4..baee8accd2 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5803,13 +5803,18 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
err = nil // Cleanup uncertainty must outrank worktree-finalization errors.
}
+ // Shutdown cancels ctx before the runner returns. Keep the final usage,
+ // server-cancellation check and acknowledgement deliverable during cleanup.
+ finalCtx, finalCancel := context.WithTimeout(context.WithoutCancel(ctx), terminalTaskReportTimeout)
+ defer finalCancel()
+
// Report usage before any early return — the agent accumulates tokens
// whether the task completes, errors, or is cancelled mid-run by the poll
// goroutine. Both claude.go and codex.go populate result.Usage even when
// runCtx is cancelled, so dropping this on the cancelled path silently
// under-reports billing.
if len(result.Usage) > 0 {
- if usageErr := d.client.ReportTaskUsage(ctx, task.ID, result.Usage); usageErr != nil {
+ if usageErr := d.client.ReportTaskUsage(finalCtx, task.ID, result.Usage); usageErr != nil {
taskLog.Warn("report task usage failed", "error", usageErr)
}
}
@@ -5833,7 +5838,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// got a single message out of must not stay this issue's resume
// pointer (MUL-8188).
ack := taskCancelAcknowledgement(result, err, provider)
- if ackErr := d.client.AckTaskCancelled(ctx, task.ID, ack); ackErr != nil {
+ if ackErr := d.client.AckTaskCancelled(finalCtx, task.ID, ack); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
return
@@ -5864,14 +5869,14 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
return
}
- _ = d.client.ReportProgress(ctx, task.ID, "Finishing task", 2, 2)
+ _ = d.client.ReportProgress(finalCtx, task.ID, "Finishing task", 2, 2)
// Final pre-completion check: if the server already moved the task to a
// terminal state (completed/failed/cancelled) or deleted the row
// outright, skip reporting — the complete/fail callbacks would fail
// anyway. Reuse shouldInterruptAgent so this guard honors the same
// signals as the in-flight watcher.
- if status, err := d.client.GetTaskStatus(ctx, task.ID); shouldInterruptAgent(status, err) {
+ if status, err := d.client.GetTaskStatus(finalCtx, task.ID); shouldInterruptAgent(status, err) {
taskLog.Info("task cancelled during execution, discarding result",
"status", status, "error", err, "branch_name", result.BranchName)
// Same contract as the poll-cancelled path above: the transcript is
@@ -5883,12 +5888,22 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// completed/failed rows the complete/fail callback is the
// authoritative channel and a stale run's late ack must not touch
// them.
- if ackErr := d.client.AckTaskCancelled(ctx, task.ID, taskCancelAcknowledgement(result, nil, provider)); ackErr != nil {
+ if ackErr := d.client.AckTaskCancelled(finalCtx, task.ID, taskCancelAcknowledgement(result, nil, provider)); ackErr != nil {
taskLog.Warn("cancel ack failed; server sweeper will finalize", "error", ackErr)
}
return
}
+ // Only the parent (daemon) context identifies shutdown. A cancelled agent
+ // with a live parent remains a deliberate cancellation; server terminal
+ // states and poll cancellation have already taken precedence above.
+ // Infrastructure interruptions carry a diagnostic, matching server-side orphan
+ // recovery; deliberate cancellation relies on its localized reason label.
+ if result.Status == "cancelled" && result.FailureReason == "" && errors.Is(ctx.Err(), context.Canceled) {
+ result.FailureReason = taskfailure.ReasonRuntimeRecovery.String()
+ result.Comment = "daemon shut down while task was in flight"
+ }
+
d.reportTaskResult(ctx, task.ID, result, taskLog)
// Write GC metadata after the task finishes so the periodic GC loop
@@ -6241,13 +6256,26 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
}
taskLog.Error("local_directory: lock acquire failed", "error", err)
failureReason := "local_directory_error"
+ errorMessage := fmt.Sprintf("local_directory wait cancelled: %s", err.Error())
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
failureReason = "cancelled"
+ if errors.Is(ctx.Err(), context.Canceled) {
+ // Shutdown can stop the wait poller before it observes a user
+ // cancellation. Honor server terminal state before enabling retry.
+ finalCtx, finalCancel := context.WithTimeout(context.WithoutCancel(ctx), terminalTaskReportTimeout)
+ defer finalCancel()
+ if status, statusErr := d.client.GetTaskStatus(finalCtx, task.ID); shouldInterruptAgent(status, statusErr) {
+ taskLog.Info("local_directory: wait aborted by server-side terminal state", "status", status, "error", statusErr)
+ return nil, true
+ }
+ failureReason = taskfailure.ReasonRuntimeRecovery.String()
+ errorMessage = "daemon shut down while task was waiting for its local directory lock"
+ }
}
if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
kind: terminalTaskReportFail,
taskID: task.ID,
- errorMessage: fmt.Sprintf("local_directory wait cancelled: %s", err.Error()),
+ errorMessage: errorMessage,
failureReason: failureReason,
}); failErr != nil {
taskLog.Error("fail task after local_directory lock cancel", "error", failErr)
@@ -9155,21 +9183,10 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
Usage: usageEntries,
}, nil
case "cancelled":
- // The daemon's own context was cancelled (server cancel or daemon
- // shutdown): the parent context cancellation propagates here as
- // context.Canceled and the fail callback runs. A user cancel or issue
- // reassignment is discarded earlier by handleTask's cancelledByPoll
- // branch, so this case is mainly defensive — and preserves the
- // "cancelled" status string for the "agent finished" log line so
- // operators can distinguish a server cancellation from a real timeout.
- //
- // Comment stays empty on purpose. reportTaskResult forwards it as the
- // task's `error`, which the UI shows verbatim under "Technical
- // details", so a sentence written here would reach the reader
- // untranslated. The status alone already yields failure_reason
- // "cancelled", whose label is localized in every shipped locale, and
- // it says the same thing — an English sentence beside it would only
- // be a worse copy of it.
+ // handleTask distinguishes daemon shutdown from explicit cancellation
+ // using its parent context, after checking the server's terminal state.
+ // Keep deliberate cancellation's comment empty: its localized reason
+ // already explains the outcome without untranslated duplicate prose.
return TaskResult{
Status: "cancelled",
SessionID: result.SessionID,
diff --git a/server/internal/daemon/shutdown_lock_wait_test.go b/server/internal/daemon/shutdown_lock_wait_test.go
new file mode 100644
index 0000000000..a0c6236ff0
--- /dev/null
+++ b/server/internal/daemon/shutdown_lock_wait_test.go
@@ -0,0 +1,177 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+// Give a manually signalled context the same Err contract as an expired deadline.
+type shutdownWaitDeadlineContext struct{ context.Context }
+
+func (c shutdownWaitDeadlineContext) Err() error {
+ if c.Context.Err() != nil {
+ return context.DeadlineExceeded
+ }
+ return nil
+}
+
+func TestHandleTask_LocalDirectoryWaitCancellation(t *testing.T) {
+ for _, tc := range []struct {
+ name, serverStatus, wantReason string
+ shutdown, deadline bool
+ }{
+ {name: "shutdown", serverStatus: "running", wantReason: "runtime_recovery", shutdown: true},
+ {name: "user cancellation", serverStatus: "cancelled"},
+ {name: "server cancellation during shutdown", serverStatus: "cancelled", shutdown: true},
+ {name: "server completion during shutdown", serverStatus: "completed", shutdown: true},
+ {name: "server failure during shutdown", serverStatus: "failed", shutdown: true},
+ {name: "server deletion during shutdown", serverStatus: "deleted", shutdown: true},
+ {name: "parent deadline", serverStatus: "running", wantReason: "cancelled", deadline: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ dir := t.TempDir()
+ realDir, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ locker := NewLocalPathLocker()
+ release, err := locker.Acquire(context.Background(), realDir, "holder", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer release()
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var parent context.Context = ctx
+ if tc.deadline {
+ parent = shutdownWaitDeadlineContext{ctx}
+ }
+ parked := make(chan struct{}, 1)
+ leaseStarted := make(chan struct{}, 1)
+ leaseStopped := make(chan struct{}, 1)
+ reports := make(chan map[string]any, 2)
+ var stopped atomic.Bool
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/wait-local-directory"):
+ parked <- struct{}{}
+ case strings.HasSuffix(r.URL.Path, "/prepare-lease"):
+ _, _ = io.Copy(io.Discard, r.Body)
+ select {
+ case leaseStarted <- struct{}{}:
+ default:
+ }
+ <-r.Context().Done()
+ select {
+ case leaseStopped <- struct{}{}:
+ default:
+ }
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ status := "running"
+ if stopped.Load() {
+ status = tc.serverStatus
+ }
+ if status == "deleted" {
+ http.Error(w, "task not found", http.StatusNotFound)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": status})
+ case strings.HasSuffix(r.URL.Path, "/fail"):
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ reports <- body
+ default:
+ t.Errorf("unexpected callback: %s", r.URL.Path)
+ }
+ }))
+ defer func() { cancel(); srv.CloseClientConnections(); srv.Close() }()
+ poll := time.Hour
+ if !tc.shutdown && !tc.deadline {
+ poll = time.Millisecond
+ }
+ d := &Daemon{client: NewClient(srv.URL), logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ cfg: Config{DaemonID: "daemon"}, localPathLocks: locker,
+ runtimeIndex: map[string]Runtime{"rt": {ID: "rt", Provider: "codex"}},
+ cancelPollInterval: poll, prepareLeaseRefresh: time.Millisecond}
+ d.runner = taskRunnerFunc(func(context.Context, Task, string, int, *slog.Logger) (TaskResult, error) {
+ t.Error("runner started while lock held")
+ return TaskResult{}, nil
+ })
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: "daemon"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ task := Task{ID: "waiter", RuntimeID: "rt", ProjectResources: []ProjectResourceData{{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: ref}}}
+ done := make(chan struct{})
+ go func() { defer close(done); d.handleTask(parent, task, 0) }()
+ wait := func(ch <-chan struct{}, what string) {
+ t.Helper()
+ select {
+ case <-ch:
+ case <-time.After(3 * time.Second):
+ t.Fatalf("timed out waiting for %s", what)
+ }
+ }
+ wait(parked, "directory wait")
+ if got := d.resourceWaitTasks.Load(); got != 1 {
+ t.Fatalf("wait count=%d", got)
+ }
+ wait(leaseStarted, "prepare lease request")
+ stopped.Store(true)
+ if tc.shutdown || tc.deadline {
+ cancel()
+ }
+ wait(done, "handleTask cleanup")
+ wait(leaseStopped, "lease cancellation")
+ if got := d.resourceWaitTasks.Load(); got != 0 {
+ t.Errorf("wait count after return=%d", got)
+ }
+ if got := locker.Holder(realDir); got != "holder" {
+ t.Errorf("cancelled waiter disturbed holder: %q", got)
+ }
+ if tc.wantReason == "" {
+ select {
+ case report := <-reports:
+ t.Errorf("terminal server task received fail: %v", report)
+ default:
+ }
+ } else {
+ select {
+ case report := <-reports:
+ if report["failure_reason"] != tc.wantReason {
+ t.Errorf("failure_reason=%v, want %s", report["failure_reason"], tc.wantReason)
+ }
+ if tc.wantReason == "runtime_recovery" && report["error"] != "daemon shut down while task was waiting for its local directory lock" {
+ t.Errorf("shutdown diagnostic=%v", report["error"])
+ }
+ default:
+ t.Error("missing fail callback")
+ }
+ }
+ select {
+ case report := <-reports:
+ t.Errorf("duplicate callback: %v", report)
+ default:
+ }
+ release()
+ nextCtx, nextCancel := context.WithTimeout(context.Background(), 3*time.Second)
+ defer nextCancel()
+ nextRelease, err := locker.Acquire(nextCtx, realDir, "next", nil)
+ if err != nil {
+ t.Fatalf("cancelled waiter leaked lock: %v", err)
+ }
+ nextRelease()
+ })
+ }
+}
diff --git a/server/internal/daemon/shutdown_provider_unix_test.go b/server/internal/daemon/shutdown_provider_unix_test.go
new file mode 100644
index 0000000000..dd22cf30d9
--- /dev/null
+++ b/server/internal/daemon/shutdown_provider_unix_test.go
@@ -0,0 +1,148 @@
+//go:build !windows
+
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "syscall"
+ "testing"
+ "time"
+)
+
+type shutdownProviderLog struct {
+ lockedBuffer
+ stopped chan struct{}
+ once sync.Once
+}
+
+func (l *shutdownProviderLog) Write(p []byte) (int, error) {
+ n, err := l.lockedBuffer.Write(p)
+ if strings.Contains(string(p), "opencode finished") {
+ l.once.Do(func() { close(l.stopped) })
+ }
+ return n, err
+}
+
+// Run a test-owned provider through runTask, then verify handleTask delivers
+// shutdown as retryable recovery. The provider blocks on a FIFO, not a timer.
+func TestHandleTask_ShutdownThroughRunTask(t *testing.T) {
+ redirectTestHome(t, t.TempDir())
+ t.Setenv("MULTICA_OPENCODE_TRANSPORT", "run")
+ dir := t.TempDir()
+ gate := filepath.Join(dir, "gate")
+ if err := syscall.Mkfifo(gate, 0600); err != nil {
+ t.Fatal(err)
+ }
+ bin := filepath.Join(dir, "opencode")
+ script := `#!/bin/sh
+case "$1" in
+--version) echo 1.18.31; exit 0;;
+models) exit 0;;
+run)
+ cat >/dev/null
+ printf '%s\n' '{"type":"step_start","sessionID":"ses-shutdown","part":{"type":"step-start"}}'
+ printf '%s\n' '{"type":"text","sessionID":"ses-shutdown","part":{"type":"text","text":"shutdown-ready"}}'
+ exec cat "$SHUTDOWN_GATE";;
+esac
+exit 1
+`
+ if err := os.WriteFile(bin, []byte(script), 0700); err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ ready := make(chan struct{})
+ var once sync.Once
+ reports := make(chan map[string]any, 2)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/messages"):
+ var body struct {
+ Messages []TaskMessageData `json:"messages"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ for _, msg := range body.Messages {
+ if strings.Contains(msg.Content, "shutdown-ready") {
+ once.Do(func() { close(ready); cancel() })
+ }
+ }
+ case strings.HasSuffix(r.URL.Path, "/fail"), strings.HasSuffix(r.URL.Path, "/complete"), strings.HasSuffix(r.URL.Path, "/cancel-ack"):
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Error(err)
+ }
+ body["endpoint"] = r.URL.Path
+ reports <- body
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": "running"})
+ }))
+ defer srv.Close()
+ logs := &shutdownProviderLog{stopped: make(chan struct{})}
+ logger := slog.New(slog.NewTextHandler(logs, nil))
+ d := New(Config{ServerBaseURL: srv.URL, WorkspacesRoot: t.TempDir(), AgentTimeout: 20 * time.Second, Agents: map[string]AgentEntry{"opencode": {Path: bin}}}, logger)
+ d.executionEnvironmentCommand = nil
+ d.cancelPollInterval = time.Hour
+ d.runtimeIndex["rt-shutdown"] = Runtime{ID: "rt-shutdown", Provider: "opencode"}
+ d.setAgentVersion("opencode", "1.18.31")
+ task := Task{ID: "task-shutdown", WorkspaceID: "ws-shutdown", RuntimeID: "rt-shutdown", IssueID: "issue-shutdown", AgentID: "agent-shutdown", AuthToken: "mat_test_shutdown", Agent: &AgentData{ID: "agent-shutdown", Name: "shutdown fixture", CustomEnv: map[string]string{"SHUTDOWN_GATE": gate}}}
+ done := make(chan struct{})
+ go func() { defer close(done); d.handleTask(ctx, task, 0) }()
+ select {
+ case <-ready:
+ case <-time.After(10 * time.Second):
+ cancel()
+ <-done
+ t.Fatalf("fake provider never reported readiness; logs: %s", logs.String())
+ }
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("shutdown did not finish handleTask")
+ }
+ select {
+ case report := <-reports:
+ if !strings.HasSuffix(report["endpoint"].(string), "/fail") || report["failure_reason"] != "runtime_recovery" {
+ t.Fatalf("shutdown callback: %v", report)
+ }
+ if report["error"] != "daemon shut down while task was in flight" {
+ t.Errorf("shutdown diagnostic: %v", report)
+ }
+ workDir, ok := report["work_dir"].(string)
+ if !ok || workDir == "" {
+ t.Fatalf("workdir lost: %v", report)
+ }
+ if _, err := os.Stat(workDir); err != nil {
+ t.Errorf("delivered workdir: %v", err)
+ }
+ default:
+ t.Fatal("missing shutdown terminal callback")
+ }
+ select {
+ case report := <-reports:
+ t.Errorf("duplicate terminal callback: %v", report)
+ default:
+ }
+ select {
+ case <-logs.stopped:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("provider process cleanup did not finish: %s", logs.String())
+ }
+ d.activeEnvRootsMu.Lock()
+ defer d.activeEnvRootsMu.Unlock()
+ if len(d.activeEnvRoots) != 0 {
+ t.Errorf("active environment guard leaked: %v", d.activeEnvRoots)
+ }
+ if stats, err := d.terminalReports.stats(); err != nil || stats.PendingCount != 0 {
+ t.Errorf("acknowledged callback still queued: %+v", stats)
+ }
+}
diff --git a/server/internal/daemon/shutdown_retry_test.go b/server/internal/daemon/shutdown_retry_test.go
new file mode 100644
index 0000000000..a80a705f9c
--- /dev/null
+++ b/server/internal/daemon/shutdown_retry_test.go
@@ -0,0 +1,107 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// Exercise handleTask's real disposition and HTTP delivery without launching a
+// provider or stopping a daemon. Cancellation happens while the runner is active.
+func TestHandleTask_ShutdownDisposition(t *testing.T) {
+ for _, tc := range []struct {
+ name, status, reason, serverStatus, wantEndpoint, wantReason string
+ shutdown bool
+ }{
+ {"shutdown", "cancelled", "", "running", "/fail", "runtime_recovery", true},
+ {"explicit agent cancellation", "cancelled", "", "running", "/fail", "cancelled", false},
+ {"server cancellation during shutdown", "cancelled", "", "cancelled", "/cancel-ack", "", true},
+ {"timeout during shutdown", "blocked", "timeout", "running", "/fail", "timeout", true},
+ {"completed before shutdown", "completed", "", "running", "/complete", "", true},
+ {"cleanup uncertainty", "cancelled", "process_cleanup_unconfirmed", "running", "/fail", "process_cleanup_unconfirmed", true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var mu sync.Mutex
+ var endpoint string
+ var terminal, usage map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ defer mu.Unlock()
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/status"):
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": tc.serverStatus})
+ case strings.HasSuffix(r.URL.Path, "/usage"):
+ if err := json.NewDecoder(r.Body).Decode(&usage); err != nil {
+ t.Error(err)
+ }
+ case strings.HasSuffix(r.URL.Path, "/progress"):
+ default:
+ endpoint = r.URL.Path
+ if err := json.NewDecoder(r.Body).Decode(&terminal); err != nil {
+ t.Error(err)
+ }
+ }
+ }))
+ defer srv.Close()
+ d := &Daemon{
+ client: NewClient(srv.URL), logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ runtimeIndex: map[string]Runtime{"rt": {ID: "rt", Provider: "codex"}},
+ cancelPollInterval: time.Hour,
+ }
+ d.runner = taskRunnerFunc(func(runCtx context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ if runCtx.Err() != nil {
+ t.Fatal("run started with cancelled context")
+ }
+ if tc.shutdown {
+ cancel()
+ <-runCtx.Done()
+ }
+ return TaskResult{
+ Status: tc.status, FailureReason: tc.reason,
+ SessionID: "session", WorkDir: "/workdir", BranchName: "agent/work",
+ Usage: []TaskUsageEntry{{Provider: "openai", Model: "test", InputTokens: 100, OutputTokens: 50}},
+ }, nil
+ })
+ d.handleTask(ctx, Task{ID: "task", RuntimeID: "rt"}, 0)
+ mu.Lock()
+ defer mu.Unlock()
+ if !strings.HasSuffix(endpoint, tc.wantEndpoint) {
+ t.Fatalf("endpoint = %q, want %q", endpoint, tc.wantEndpoint)
+ }
+ if tc.wantReason != "" && terminal["failure_reason"] != tc.wantReason {
+ t.Errorf("reason = %v, want %s", terminal["failure_reason"], tc.wantReason)
+ }
+ if tc.wantReason == "runtime_recovery" && terminal["error"] != "daemon shut down while task was in flight" {
+ t.Errorf("missing shutdown diagnostic: %v", terminal)
+ }
+ if tc.wantReason == "cancelled" && terminal["error"] != "" {
+ t.Errorf("explicit cancellation has untranslated error: %v", terminal)
+ }
+ if tc.wantEndpoint != "/cancel-ack" {
+ for k, want := range map[string]string{"session_id": "session", "work_dir": "/workdir", "branch_name": "agent/work"} {
+ if terminal[k] != want {
+ t.Errorf("%s = %v, want %s", k, terminal[k], want)
+ }
+ }
+ }
+ entries, ok := usage["usage"].([]any)
+ if !ok || len(entries) != 1 {
+ t.Fatalf("usage lost: %v", usage)
+ }
+ entry := entries[0].(map[string]any)
+ if entry["input_tokens"] != float64(100) || entry["output_tokens"] != float64(50) {
+ t.Errorf("usage changed: %v", entry)
+ }
+ })
+ }
+}
diff --git a/server/internal/service/shutdown_retry_test.go b/server/internal/service/shutdown_retry_test.go
new file mode 100644
index 0000000000..ad83cbc543
--- /dev/null
+++ b/server/internal/service/shutdown_retry_test.go
@@ -0,0 +1,32 @@
+package service
+
+import (
+ "testing"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestShutdownRetryUsesExistingBudgetAndSessionPolicy(t *testing.T) {
+ for _, tc := range []struct {
+ reason string
+ attempt, max int32
+ want bool
+ }{
+ {"runtime_recovery", 1, 2, true},
+ {"runtime_recovery", 2, 2, false},
+ {"runtime_recovery", 1, 1, false},
+ {"cancelled", 1, 2, false},
+ } {
+ task := db.AgentTaskQueue{Attempt: tc.attempt, MaxAttempts: tc.max, IssueID: pgtype.UUID{Valid: true}}
+ if got := retryEligible(tc.reason, task); got != tc.want {
+ t.Errorf("retryEligible(%s, %d/%d) = %v, want %v", tc.reason, tc.attempt, tc.max, got, tc.want)
+ }
+ if ceiling := retryAttemptCeiling(tc.reason, tc.max); ceiling != tc.max {
+ t.Errorf("%s widened budget to %d", tc.reason, ceiling)
+ }
+ }
+ if resumeUnsafeFailureReason("runtime_recovery") {
+ t.Fatal("shutdown must preserve the resumable session")
+ }
+}