Skip to content

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

Go

MUL-4937: preserve daemon terminal callbacks during shutdown

Multica Eve099e145611a9
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 16e214b1bd..41923cd666 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -92,6 +92,36 @@ func (f taskRunnerFunc) run(ctx context.Context, task Task, provider string, slo
return f(ctx, task, provider, slot, log)
}
+type terminalTaskReportKind uint8
+
+const (
+ terminalTaskReportComplete terminalTaskReportKind = iota + 1
+ terminalTaskReportFail
+
+ // CompleteTask and FailTask can make six 30-second HTTP attempts around
+ // the five backoffs in defaultTerminalRetrySchedule (124 seconds total).
+ // Keep the detached callback's own deadline above that worst-case budget
+ // so it does not silently shorten the client's existing retry contract.
+ // During daemon restart pollLoop still imposes its separate 30-second
+ // process drain boundary.
+ terminalTaskReportTimeout = 6 * time.Minute
+)
+
+// terminalTaskReport is the single daemon-side representation of a terminal
+// callback. Keeping every complete/fail path behind this value and
+// reportTerminalTask gives the durable outbox one insertion point without
+// revisiting every task exit when it is added.
+type terminalTaskReport struct {
+ kind terminalTaskReportKind
+ taskID string
+ output string
+ branchName string
+ errorMessage string
+ sessionID string
+ workDir string
+ failureReason string
+}
+
var (
isBrewInstall = cli.IsBrewInstall
getBrewPrefix = cli.GetBrewPrefix
@@ -3205,7 +3235,12 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// classifier so the failure_reason column reflects the actual
// shape of the failure (provider 5xx, network, process crash,
// …) rather than the coarse legacy "agent_error" bucket.
- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", taskfailure.Classify(err.Error()).String()); failErr != nil {
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: err.Error(),
+ failureReason: taskfailure.Classify(err.Error()).String(),
+ }); failErr != nil {
taskLog.Error("fail task callback failed", "error", failErr)
}
return
@@ -3276,7 +3311,12 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
assignment, err := localDirectoryAssignmentForTask(task, d.cfg.DaemonID)
if err != nil {
taskLog.Error("local_directory: resolve resource failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "local_directory_error"); failErr != nil {
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: err.Error(),
+ failureReason: "local_directory_error",
+ }); failErr != nil {
taskLog.Error("fail task after local_directory resolve error", "error", failErr)
}
return nil, true
@@ -3287,7 +3327,12 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
taskLog = taskLog.With("local_directory", assignment.AbsPath)
if err := validateLocalPath(assignment.AbsPath); err != nil {
taskLog.Error("local_directory: path validation failed", "error", err)
- if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "local_directory_error"); failErr != nil {
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: err.Error(),
+ failureReason: "local_directory_error",
+ }); failErr != nil {
taskLog.Error("fail task after local_directory validation error", "error", failErr)
}
return nil, true
@@ -3369,7 +3414,12 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
failureReason = "cancelled"
}
- if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("local_directory wait cancelled: %s", err.Error()), "", "", failureReason); failErr != nil {
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: task.ID,
+ errorMessage: fmt.Sprintf("local_directory wait cancelled: %s", err.Error()),
+ failureReason: failureReason,
+ }); failErr != nil {
taskLog.Error("fail task after local_directory lock cancel", "error", failErr)
}
return nil, true
@@ -3392,7 +3442,14 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
switch result.Status {
case "completed":
taskLog.Info("task completed", "status", result.Status)
- err := d.client.CompleteTask(ctx, taskID, result.Comment, result.BranchName, result.SessionID, result.WorkDir)
+ err := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportComplete,
+ taskID: taskID,
+ output: result.Comment,
+ branchName: result.BranchName,
+ sessionID: result.SessionID,
+ workDir: result.WorkDir,
+ })
if err == nil {
return
}
@@ -3421,7 +3478,14 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
// which is the canonical replacement for the legacy
// "agent_error" coarse bucket.
fallbackErrMsg := fmt.Sprintf("complete task failed: %s", err.Error())
- if failErr := d.client.FailTask(ctx, taskID, fallbackErrMsg, result.SessionID, result.WorkDir, taskfailure.Classify(fallbackErrMsg).String()); failErr != nil {
+ if failErr := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: taskID,
+ errorMessage: fallbackErrMsg,
+ sessionID: result.SessionID,
+ workDir: result.WorkDir,
+ failureReason: taskfailure.Classify(fallbackErrMsg).String(),
+ }); failErr != nil {
taskLog.Error("fail task fallback also failed", "error", failErr)
}
default:
@@ -3444,12 +3508,38 @@ func (d *Daemon) reportTaskResult(ctx context.Context, taskID string, result Tas
}
}
taskLog.Info("task did not complete, reporting failure", "status", result.Status, "failure_reason", failureReason)
- if err := d.client.FailTask(ctx, taskID, result.Comment, result.SessionID, result.WorkDir, failureReason); err != nil {
+ if err := d.reportTerminalTask(ctx, terminalTaskReport{
+ kind: terminalTaskReportFail,
+ taskID: taskID,
+ errorMessage: result.Comment,
+ sessionID: result.SessionID,
+ workDir: result.WorkDir,
+ failureReason: failureReason,
+ }); err != nil {
taskLog.Error("report failed task failed", "error", err)
}
}
}
+// reportTerminalTask is the only path that sends complete/fail callbacks.
+// It deliberately preserves context values while discarding cancellation and
+// parent deadlines: daemon shutdown cancels the root context before pollLoop's
+// 30-second drain, but terminal callbacks must still use that remaining window.
+// The explicit timeout keeps this detached work bounded during normal runs.
+func (d *Daemon) reportTerminalTask(parentCtx context.Context, report terminalTaskReport) error {
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(parentCtx), terminalTaskReportTimeout)
+ defer cancel()
+
+ switch report.kind {
+ case terminalTaskReportComplete:
+ return d.client.CompleteTask(ctx, report.taskID, report.output, report.branchName, report.sessionID, report.workDir)
+ case terminalTaskReportFail:
+ return d.client.FailTask(ctx, report.taskID, report.errorMessage, report.sessionID, report.workDir, report.failureReason)
+ default:
+ return fmt.Errorf("unsupported terminal task report kind %d", report.kind)
+ }
+}
+
// gcMetaForTask classifies a finished task and produces a GCMeta of the right
// kind. The discriminator order matters: a task carrying both an issue_id
// and a chat_session_id (theoretical, not produced today) should be treated
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 4e6af3ab0a..41f8e7380a 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2549,6 +2549,17 @@ type reportTaskResultRecorder struct {
payload map[string]any
}
+func TestTerminalTaskReportTimeoutCoversRetrySchedule(t *testing.T) {
+ client := NewClient("http://example.invalid")
+ worstCase := time.Duration(len(defaultTerminalRetrySchedule)+1) * client.client.Timeout
+ for _, delay := range defaultTerminalRetrySchedule {
+ worstCase += delay
+ }
+ if terminalTaskReportTimeout < worstCase {
+ t.Fatalf("terminal report timeout = %s, want at least retry worst case %s", terminalTaskReportTimeout, worstCase)
+ }
+}
+
func (r *reportTaskResultRecorder) handler(t *testing.T) http.HandlerFunc {
t.Helper()
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
@@ -2607,6 +2618,63 @@ func TestReportTaskResult_CompletedHitsCompleteEndpoint(t *testing.T) {
}
}
+func TestReportTaskResult_CancelledParentStillReportsTerminalState(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ result TaskResult
+ wantSuffix string
+ }{
+ {
+ name: "complete",
+ result: TaskResult{
+ Status: "completed",
+ Comment: "all good",
+ BranchName: "agent/foo",
+ SessionID: "ses-complete",
+ WorkDir: "/tmp/complete",
+ },
+ wantSuffix: "/complete",
+ },
+ {
+ name: "fail",
+ result: TaskResult{
+ Status: "blocked",
+ Comment: "provider unavailable",
+ SessionID: "ses-fail",
+ WorkDir: "/tmp/fail",
+ FailureReason: "agent_error.provider_unavailable",
+ },
+ wantSuffix: "/fail",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ var calls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if !strings.HasSuffix(req.URL.Path, tc.wantSuffix) {
+ t.Errorf("terminal callback path = %q, want suffix %q", req.URL.Path, tc.wantSuffix)
+ }
+ calls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}
+ d.reportTaskResult(ctx, "task-cancelled-parent", tc.result, slog.Default())
+
+ if got := calls.Load(); got != 1 {
+ t.Fatalf("terminal callback calls = %d, want 1", got)
+ }
+ })
+ }
+}
+
// Pins the GitHub multica#1952 fail-closed behaviour: a task whose
// agent run never produced a real result (blocked, cancelled, or any
// future status we forget to enumerate) MUST go through FailTask, so
@@ -2814,6 +2882,76 @@ func TestReportTaskResult_PermanentCompleteFallsBackToFail(t *testing.T) {
}
}
+func TestReportTaskResult_CancelledParentStillRunsPermanentFailureFallback(t *testing.T) {
+ defer noSleepRetry(t)()
+
+ var completeCalls, failCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch {
+ case strings.HasSuffix(req.URL.Path, "/complete"):
+ completeCalls.Add(1)
+ w.WriteHeader(http.StatusBadRequest)
+ case strings.HasSuffix(req.URL.Path, "/fail"):
+ failCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ default:
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ d := &Daemon{client: NewClient(srv.URL), logger: slog.Default()}
+ d.reportTaskResult(ctx, "task-cancelled-fallback", TaskResult{
+ Status: "completed",
+ Comment: "ok",
+ }, slog.Default())
+
+ if got := completeCalls.Load(); got != 1 {
+ t.Fatalf("complete calls = %d, want 1", got)
+ }
+ if got := failCalls.Load(); got != 1 {
+ t.Fatalf("fallback fail calls = %d, want 1", got)
+ }
+}
+
+func TestHandleTask_BareErrorReportsFailureWithCancelledParent(t *testing.T) {
+ t.Parallel()
+
+ var failCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if !strings.HasSuffix(req.URL.Path, "/fail") {
+ t.Errorf("unexpected daemon call: %s %s", req.Method, req.URL.Path)
+ }
+ failCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.New(slog.NewTextHandler(io.Discard, nil)),
+ runtimeIndex: map[string]Runtime{"rt-1": {ID: "rt-1", Provider: "codex"}},
+ cancelPollInterval: time.Hour,
+ }
+ d.runner = taskRunnerFunc(func(runCtx context.Context, _ Task, _ string, _ int, _ *slog.Logger) (TaskResult, error) {
+ if !errors.Is(runCtx.Err(), context.Canceled) {
+ t.Errorf("runner context error = %v, want context.Canceled", runCtx.Err())
+ }
+ return TaskResult{}, errors.New("runner exited during shutdown")
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ d.handleTask(ctx, Task{ID: "task-bare-error", RuntimeID: "rt-1"}, 0)
+
+ if got := failCalls.Load(); got != 1 {
+ t.Fatalf("fail callback calls = %d, want 1", got)
+ }
+}
+
// TestHandleTask_ReportsUsageBeforeCancel verifies that ReportTaskUsage is called
// even when the server marks the task as cancelled during the post-run status
// check. Regression test for the ordering bug where the cancel check ran before
diff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.go
index a6d1117182..d16f3deada 100644
--- a/server/internal/daemon/local_directory_test.go
+++ b/server/internal/daemon/local_directory_test.go
@@ -631,3 +631,157 @@ func TestAcquireLocalDirectoryLock_CancelDuringWait(t *testing.T) {
t.Errorf("wait-local-directory calls = %d, want 1", got)
}
}
+
+func TestAcquireLocalDirectoryLock_ParentCancellationReportsWaitFailure(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ realDir, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatalf("evalsymlinks: %v", err)
+ }
+
+ parked := make(chan struct{}, 1)
+ var failCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ switch {
+ case strings.HasSuffix(req.URL.Path, "/wait-local-directory"):
+ select {
+ case parked <- struct{}{}:
+ default:
+ }
+ w.WriteHeader(http.StatusOK)
+ case strings.HasSuffix(req.URL.Path, "/status"):
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"status":"running"}`))
+ case strings.HasSuffix(req.URL.Path, "/fail"):
+ failCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ default:
+ t.Errorf("unexpected daemon call: %s %s", req.Method, req.URL.Path)
+ w.WriteHeader(http.StatusOK)
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ const daemonID = "d-test"
+ locker := NewLocalPathLocker()
+ release, err := locker.Acquire(context.Background(), realDir, "task-holder", nil)
+ if err != nil {
+ t.Fatalf("preclaim acquire: %v", err)
+ }
+ t.Cleanup(release)
+
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ localPathLocks: locker,
+ cancelPollInterval: time.Hour,
+ cfg: Config{DaemonID: daemonID},
+ }
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: daemonID})
+ if err != nil {
+ t.Fatalf("marshal ref: %v", err)
+ }
+ task := Task{
+ ID: "task-waiter",
+ ProjectResources: []ProjectResourceData{
+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: ref},
+ },
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ t.Cleanup(cancel)
+ type result struct {
+ release func()
+ abort bool
+ }
+ done := make(chan result, 1)
+ go func() {
+ rel, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default())
+ done <- result{release: rel, abort: abort}
+ }()
+
+ select {
+ case <-parked:
+ cancel()
+ case <-time.After(2 * time.Second):
+ t.Fatal("task never entered local_directory wait")
+ }
+
+ select {
+ case got := <-done:
+ if !got.abort {
+ t.Fatal("expected abort=true after parent cancellation")
+ }
+ if got.release != nil {
+ t.Fatal("expected nil release after parent cancellation")
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("acquireLocalDirectoryLockIfNeeded did not return after parent cancellation")
+ }
+
+ if got := failCalls.Load(); got != 1 {
+ t.Fatalf("fail callback calls = %d, want 1", got)
+ }
+}
+
+func TestAcquireLocalDirectoryLock_EarlyFailureReportsWithCancelledParent(t *testing.T) {
+ t.Parallel()
+
+ var failCalls atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
+ if !strings.HasSuffix(req.URL.Path, "/fail") {
+ t.Errorf("unexpected daemon call: %s %s", req.Method, req.URL.Path)
+ }
+ failCalls.Add(1)
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(srv.Close)
+
+ const daemonID = "d-test"
+ d := &Daemon{
+ client: NewClient(srv.URL),
+ logger: slog.Default(),
+ localPathLocks: NewLocalPathLocker(),
+ cfg: Config{DaemonID: daemonID},
+ }
+ missingPathRef, err := json.Marshal(localDirectoryRef{
+ LocalPath: filepath.Join(t.TempDir(), "missing"),
+ DaemonID: daemonID,
+ })
+ if err != nil {
+ t.Fatalf("marshal ref: %v", err)
+ }
+ tests := []struct {
+ name string
+ ref json.RawMessage
+ }{
+ {name: "resource resolution", ref: json.RawMessage(`{not-json`)},
+ {name: "path validation", ref: missingPathRef},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ task := Task{
+ ID: "task-invalid-local-directory",
+ ProjectResources: []ProjectResourceData{
+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: tc.ref},
+ },
+ }
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default())
+ if !abort {
+ t.Fatal("expected local_directory failure to abort task")
+ }
+ if release != nil {
+ t.Fatal("expected nil release on local_directory failure")
+ }
+ })
+ }
+ if got := failCalls.Load(); got != int32(len(tests)) {
+ t.Fatalf("fail callback calls = %d, want %d", got, len(tests))
+ }
+}