Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6880 fix(daemon): wait for the previous run to let go of the workdir (#7818)
Bohan Jiang4cf5a2ca9c2b
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 5ffb089807..2d9143fe4c 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -602,6 +602,11 @@ type Daemon struct {runner taskRunner // executes agent tasks; set to d.runTask by New(), overridable in testscancelPollInterval time.Duration // how often handleTask polls for server-side cancellation; overridable in tests+ // envRootBusyWait is how long a task that is entitled to a prior env root+ // waits for the previous run to let go of it before giving up and preparing+ // a fresh one. New() sets it; the zero value means "do not wait", which is+ // what focused unit tests want. See lockReusablePriorEnvRoot (MUL-6880).+ envRootBusyWait time.Duration// executionEnvironmentCommand resolves the killable helper used for// Prepare/Reuse. New always sets it; nil keeps focused unit tests in-process.executionEnvironmentCommand executionEnvironmentCommand@@ -654,6 +659,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {reregisterNextAttempt: make(map[string]time.Time),reregisterLastCompletedAt: make(map[string]time.Time),cancelPollInterval: 5 * time.Second,+ envRootBusyWait: 15 * time.Second,taskPrepareTimeout: defaultTaskPrepareTimeout,reconcile: newReconcileBroadcaster(),workspaceChanges: newWorkspaceChangeSignal(),@@ -6322,7 +6328,12 @@ func (d *Daemon) startTaskPrepareLeaseExtender(ctx context.Context, task Task, t// The re-check under the lock closes the gap between proving eligibility and// acting on it. Declining is always safe: the caller falls back to a fresh// Prepare, which costs session continuity, not correctness.-func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirectoryAssignment, heldRoot string) (*execenv.EnvRootClaim, string, os.FileInfo, bool) {+//+// The error return is the one outcome that is NOT "decline and carry on": it is+// non-nil only when the run was cancelled while waiting for the prior env root,+// and it carries the context's cause so the caller can end the task instead of+// preparing an environment for work that no longer exists.+func (d *Daemon) lockReusablePriorEnvRoot(ctx context.Context, task Task, localAssignment *localDirectoryAssignment, heldRoot string) (*execenv.EnvRootClaim, string, os.FileInfo, bool, error) {// Pin the workspaces root BEFORE validating anything. Opening it after,// from a name validation just approved, would re-resolve that name: rename// the root aside, leave a symlink to a look-alike tree, and os.Root@@ -6331,13 +6342,13 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirec// first makes that ordering impossible.wsRoot, err := os.OpenRoot(d.cfg.WorkspacesRoot)if err != nil {- return nil, "", nil, false+ return nil, "", nil, false, nil}defer wsRoot.Close()workDir, ok := shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot)if !ok {- return nil, "", nil, false+ return nil, "", nil, false, nil}priorRoot := filepath.Dir(workDir)// workDir came back through EvalSymlinks, so the root it is measured@@ -6346,17 +6357,17 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirec// makes the two look unrelated and every reuse is refused.canonicalWorkspacesRoot, err := filepath.EvalSymlinks(d.cfg.WorkspacesRoot)if err != nil {- return nil, "", nil, false+ return nil, "", nil, false, nil}rel, err := filepath.Rel(canonicalWorkspacesRoot, priorRoot)if err != nil || !filepath.IsLocal(rel) {- return nil, "", nil, false+ return nil, "", nil, false, nil}// Already covered by this run's own claim (a task re-dispatched onto its// own directory); taking a second lock on it would only deadlock against// ourselves.if priorRoot == heldRoot {- return nil, workDir, nil, true+ return nil, workDir, nil, true, nil}// Pin the identity of the directory that just passed validation. Every@@ -6365,7 +6376,7 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirec// apart from "a different directory now answering to that name".validatedInfo, err := os.Stat(priorRoot)if err != nil {- return nil, "", nil, false+ return nil, "", nil, false, nil}// Deterministic seam for the TOCTOU regressions: tests swap the validated@@ -6374,25 +6385,31 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirecreuseLockTestHook()}- claim, lockedInfo, err := execenv.LockEnvRootForReuse(wsRoot, rel, priorRoot)+ lockStartedAt := time.Now()+ claim, lockedInfo, err := d.lockEnvRootForReuseWaitingOutTheBusyWindow(ctx, wsRoot, rel, priorRoot, task)switch {+ case errors.Is(err, errPriorEnvRootWaitAborted):+ // The run is over. Declining reuse would hand the caller on to a fresh+ // Prepare, which is the one thing that must not happen here.+ return nil, "", nil, false, context.Cause(ctx)case errors.Is(err, execenv.ErrEnvRootBusy):- d.logger.Info("prior workdir is in use by another execution; starting a fresh environment",- "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot))- return nil, "", nil, false+ d.logger.Info("prior workdir is still in use after waiting for it; starting a fresh environment",+ "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "waited", time.Since(lockStartedAt).Round(time.Millisecond), "budget", d.envRootBusyWait)+ return nil, "", nil, false, nilcase err != nil:d.logger.Warn("could not lock prior workdir; starting a fresh environment","task", shortID(task.ID), "error", err)- return nil, "", nil, false+ return nil, "", nil, false, nilcase claim == nil:- return nil, "", nil, false+ return nil, "", nil, false, nil}// The lock has to have landed on the directory validation approved.if !os.SameFile(validatedInfo, lockedInfo) {d.logger.Info("prior workdir changed identity before it could be claimed; starting a fresh environment","task", shortID(task.ID))claim.Release()- return nil, "", nil, false+ return nil, "", nil, false, nil}// Re-validate while holding the lock, and require the answer to be the SAME@@ -6404,7 +6421,7 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirecrecheckedWorkDir, stillOK := shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot)if !stillOK || recheckedWorkDir != workDir {claim.Release()- return nil, "", nil, false+ return nil, "", nil, false, nil}// ...and the directory we are about to hand to Reuse has to be that same// one, so the object locked and the object used cannot diverge.@@ -6413,9 +6430,85 @@ func (d *Daemon) lockReusablePriorEnvRoot(task Task, localAssignment *localDirecd.logger.Info("prior workdir changed identity while being claimed; starting a fresh environment","task", shortID(task.ID))claim.Release()- return nil, "", nil, false+ return nil, "", nil, false, nil+ }+ return claim, workDir, lockedInfo, true, nil+}++// envRootBusyRetryInterval is how often the wait below re-tries the lock. The+// window it is covering is seconds long, so this only has to be small relative+// to that, not tight.+const envRootBusyRetryInterval = 250 * time.Millisecond++// errPriorEnvRootWaitAborted marks the wait as ended by the run itself rather+// than by the lock. It wraps the context's cause so the task can be failed with+// the real reason.+var errPriorEnvRootWaitAborted = errors.New("waiting for the prior env root was aborted")++// lockEnvRootForReuseWaitingOutTheBusyWindow takes the reuse lock, waiting out+// a lock the PREVIOUS run of this (issue, agent) has not let go of yet.+//+// A busy lock here has one cause in a healthy system: the server hands a task+// to a daemon only when no other task for the same (issue, agent) is dispatched+// or running (ClaimAgentTask's serialization), so by the time this task exists+// its predecessor is already finished as far as the server is concerned. The+// process is not: it learns of its cancellation from its own poll tick and+// takes a few seconds to exit, and it holds .task_lock until it does. That is+// the whole of the gap — a machine-local fact, visible right here.+//+// Giving up immediately costs the workdir, and with it the provider session+// living in it: the agent restarts with no memory of the conversation the user+// was in the middle of editing (MUL-6880). Waiting costs a few seconds of one+// task slot, which is far less than the fresh Prepare — including a repo+// checkout — that declining forces instead.+//+// The wait is bounded and gives up into exactly the old behaviour, so a+// predecessor that is genuinely wedged, or a lock held by something else on a+// shared workspaces root, still ends in a fresh environment rather than a+// stuck task.+func (d *Daemon) lockEnvRootForReuseWaitingOutTheBusyWindow(+ ctx context.Context,+ wsRoot *os.Root,+ rel, priorRoot string,+ task Task,+) (*execenv.EnvRootClaim, os.FileInfo, error) {+ start := time.Now()+ deadline := start.Add(d.envRootBusyWait)+ waited := false+ for {+ claim, info, err := execenv.LockEnvRootForReuse(wsRoot, rel, priorRoot)+ if !errors.Is(err, execenv.ErrEnvRootBusy) || !time.Now().Before(deadline) {+ // The wait's real duration is logged, not the budget: 15s is a+ // reasoned guess (one cancel-poll interval plus the agent's exit),+ // and these lines are how it gets checked against production+ // instead of staying a guess.+ if waited && err == nil {+ d.logger.Info("prior workdir freed while waiting for the previous run to exit",+ "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "waited", time.Since(start).Round(time.Millisecond))+ }+ return claim, info, err+ }+ if !waited {+ waited = true+ d.logger.Info("prior workdir is still held by the previous run; waiting for it",+ "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "budget", d.envRootBusyWait)+ }+ select {+ case <-ctx.Done():+ d.logger.Info("stopped waiting for the prior workdir: the run was cancelled",+ "task", shortID(task.ID), "prior_root", filepath.Base(priorRoot),+ "waited", time.Since(start).Round(time.Millisecond))+ // NOT the busy error the loop was carrying. A cancelled run is a+ // third outcome, and collapsing it into "still busy" would send the+ // caller on to a fresh Prepare for work nobody is waiting for, and+ // would file one cancellation under both "cancelled" and "budget+ // exhausted" in the very logs the budget is meant to be judged by.+ return nil, nil, fmt.Errorf("%w: %w", errPriorEnvRootWaitAborted, context.Cause(ctx))+ case <-time.After(envRootBusyRetryInterval):+ }}- return claim, workDir, lockedInfo, true}// reuseLockTestHook runs between reuse eligibility validation and taking the@@ -7060,7 +7153,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}}envReused := false- if priorClaim, priorWorkDir, lockedPriorInfo, ok := d.lockReusablePriorEnvRoot(task, localAssignment, envClaim.RootDir()); ok {+ priorClaim, priorWorkDir, lockedPriorInfo, reusable, reuseErr := d.lockReusablePriorEnvRoot(ctx, task, localAssignment, envClaim.RootDir())+ if reuseErr != nil {+ // Cancelled while waiting for the previous run to let go of its+ // directory. Ending here IS the behaviour: falling through would+ // prepare a whole environment — repo checkout included — for a task+ // nobody is waiting for any more.+ return TaskResult{}, reuseErr+ }+ if reusable {defer priorClaim.Release()// Deterministic seam for the last-window regression: tests swap the// directory here, after the claim is settled and before Reuse resolvesdiff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.goindex 88010f2cd7..26ee54021c 100644--- a/server/internal/daemon/leader_workdir_reuse_test.go+++ b/server/internal/daemon/leader_workdir_reuse_test.go@@ -1,7 +1,9 @@package daemonimport (+ "bytes""context"+ "errors""io""io/fs""log/slog"@@ -469,7 +471,7 @@ func TestLockReusablePriorEnvRootNeverWritesOutsideWorkspacesRoot(t *testing.T)d := &Daemon{logger: discardLogger()}d.cfg.WorkspacesRoot = workspacesRoot- claim, _, _, ok := d.lockReusablePriorEnvRoot(Task{+ claim, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), Task{ID: "01a01ec0-e69d-7000-8000-0123456789ab",WorkspaceID: "ws-1",AgentID: "agent-1",@@ -533,7 +535,7 @@ func TestLockReusablePriorEnvRootLocksAValidatedRoot(t *testing.T) {d := &Daemon{logger: discardLogger()}d.cfg.WorkspacesRoot = root- claim, canonical, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")+ claim, canonical, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")if !ok {t.Fatal("a fully provenanced managed workdir was refused for reuse")}@@ -559,19 +561,217 @@ func TestLockReusablePriorEnvRootLocksAValidatedRoot(t *testing.T) {}// A concurrent continuation of the same task must not get the same root.- if second, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, ""); ok {+ if second, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, ""); ok {second.Release()t.Fatal("two continuations locked the same prior workdir at once")}claim.Release()- again, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")+ again, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")if !ok {t.Fatal("prior workdir stayed locked after release")}again.Release()}+// TestLockReusablePriorEnvRootWaitsOutTheDyingPredecessor is MUL-6880.+//+// Editing a comment cancels the run it triggered and enqueues the replacement+// in the same request. The server considers the predecessor finished the moment+// it writes 'cancelled', and its serialization fence lets the replacement be+// claimed; the PROCESS is still exiting, and it holds .task_lock for another+// few seconds. Declining on sight cost the workdir, and with it the provider+// session living in it — the agent came back with no memory of the+// conversation being edited.+//+// The predecessor here lets go while the successor is waiting, which is what+// happens in production once the daemon's cancel poll fires.+func TestLockReusablePriorEnvRootWaitsOutTheDyingPredecessor(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ workDir := filepath.Join(root, "ws-leader", "0123456789ab", "workdir")+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")++ task := leaderReuseTestTask("task-reuse")+ task.PriorWorkDir = workDir++ d := &Daemon{logger: discardLogger(), envRootBusyWait: 10 * time.Second}+ d.cfg.WorkspacesRoot = root++ // The predecessor, still holding its lock when the successor starts.+ predecessor, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ if !ok {+ t.Fatal("could not set up the predecessor's claim")+ }++ const exitAfter = 300 * time.Millisecond+ go func() {+ time.Sleep(exitAfter)+ predecessor.Release()+ }()++ start := time.Now()+ claim, canonical, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ waited := time.Since(start)+ if !ok {+ t.Fatal("the successor abandoned the workdir its predecessor was still exiting from: that is the lost session")+ }+ defer claim.Release()+ if canonical == "" {+ t.Fatal("accepted reuse without returning the canonical workdir")+ }+ if waited < exitAfter {+ t.Fatalf("took the lock after %s, before the predecessor let go of it — the test is not exercising the wait", waited)+ }+}++// The other half: the wait is a budget, not a promise. A predecessor that never+// lets go — wedged, SIGKILL lost, or a lock held by something else on a shared+// workspaces root — must end in the same fresh environment as before, a few+// seconds later, and never in a task that waits forever.+func TestLockReusablePriorEnvRootStopsWaitingWhenTheLockNeverFrees(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ workDir := filepath.Join(root, "ws-leader", "0123456789ab", "workdir")+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")++ task := leaderReuseTestTask("task-reuse")+ task.PriorWorkDir = workDir++ const budget = 300 * time.Millisecond+ d := &Daemon{logger: discardLogger(), envRootBusyWait: budget}+ d.cfg.WorkspacesRoot = root++ held, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ if !ok {+ t.Fatal("could not set up the holder's claim")+ }+ defer held.Release()++ start := time.Now()+ second, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ waited := time.Since(start)+ if ok {+ second.Release()+ t.Fatal("two continuations locked the same prior workdir at once")+ }+ if waited < budget {+ t.Fatalf("gave up after %s, before spending the %s budget", waited, budget)+ }+}++// A daemon shutting down must not be held up by the wait.+func TestLockReusablePriorEnvRootStopsWaitingWhenTheContextEnds(t *testing.T) {+ t.Parallel()++ root := t.TempDir()+ workDir := filepath.Join(root, "ws-leader", "0123456789ab", "workdir")+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")++ task := leaderReuseTestTask("task-reuse")+ task.PriorWorkDir = workDir++ d := &Daemon{logger: discardLogger(), envRootBusyWait: time.Hour}+ d.cfg.WorkspacesRoot = root++ held, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")+ if !ok {+ t.Fatal("could not set up the holder's claim")+ }+ defer held.Release()++ ctx, cancel := context.WithCancel(context.Background())+ go func() {+ time.Sleep(100 * time.Millisecond)+ cancel()+ }()+ start := time.Now()+ second, _, _, ok, err := d.lockReusablePriorEnvRoot(ctx, task, nil, "")+ if ok {+ second.Release()+ t.Fatal("took a lock that was never released")+ }+ if waited := time.Since(start); waited > 30*time.Second {+ t.Fatalf("waited %s after the context ended", waited)+ }+ // A cancelled run is its own outcome. Reported as a plain "no reuse" it+ // reads as "the lock stayed busy", which sends the caller on to prepare a+ // fresh environment for a task that no longer exists.+ if !errors.Is(err, context.Canceled) {+ t.Fatalf("cancellation reported as %v, want it to carry context.Canceled", err)+ }+ cancel()+}++// TestRunTaskCancelledWaitingForThePriorWorkdirStopsInsteadOfPreparing is the+// caller-level half of the same rule. The inner function reporting the+// cancellation only matters if runTask acts on it: flattened into "no reuse", a+// cancelled run would go on to prepare a whole fresh environment — repo+// checkout included — for work nobody is waiting for, and would file the one+// cancellation under "budget exhausted" in the very logs the 15s budget is+// meant to be judged by.+func TestRunTaskCancelledWaitingForThePriorWorkdirStopsInsteadOfPreparing(t *testing.T) {+ d, _, cleanup := newLeaderReuseTestDaemon(t)+ defer cleanup()++ first := leaderReuseTestTask("task-first")+ firstResult, err := d.runTask(context.Background(), first, "claude", 0, d.logger)+ if err != nil {+ t.Fatalf("first runTask: %v", err)+ }++ // The predecessor, still holding its env root when the successor starts.+ d.envRootBusyWait = time.Hour+ second := leaderReuseTestTask("task-second")+ second.PriorSessionID = firstResult.SessionID+ second.PriorWorkDir = firstResult.WorkDir+ held, _, _, ok, err := d.lockReusablePriorEnvRoot(context.Background(), second, nil, "")+ if err != nil || !ok {+ t.Fatalf("could not hold the prior env root: ok=%v err=%v", ok, err)+ }+ defer held.Release()++ var logs bytes.Buffer+ d.logger = slog.New(slog.NewTextHandler(&logs, nil))++ ctx, cancel := context.WithCancel(context.Background())+ go func() {+ time.Sleep(150 * time.Millisecond)+ cancel()+ }()+ defer cancel()++ if _, err = d.runTask(ctx, second, "claude", 0, d.logger); !errors.Is(err, context.Canceled) {+ t.Fatalf("runTask returned %v, want the cancellation that ended the wait", err)+ }++ // Prepare writes .managed_env.json into the env root it builds, so its+ // absence is the proof that no fresh environment was prepared.+ freshRoot, err := execenv.ResolveRootDir(taskRootDirParams(d.cfg.WorkspacesRoot, second))+ if err != nil {+ t.Fatalf("resolve the successor's env root: %v", err)+ }+ switch _, statErr := os.Stat(filepath.Join(freshRoot, ".managed_env.json")); {+ case statErr == nil:+ t.Fatal("prepared a fresh environment for a cancelled run")+ case !os.IsNotExist(statErr):+ t.Fatalf("stat managed env provenance: %v", statErr)+ }++ got := logs.String()+ if strings.Contains(got, "still in use after waiting for it") {+ t.Fatalf("a cancelled run was logged as budget exhausted, which is the number the budget is judged by:\n%s", got)+ }+ if !strings.Contains(got, "the run was cancelled") {+ t.Fatalf("the cancellation went unlogged:\n%s", got)+ }+}+// TestLockReusablePriorEnvRootSurvivesRetargetAfterValidation is the TOCTOU// half review found: the canonical path returned by validation is a string,// not a handle. Between proving eligibility and opening the lock, the@@ -610,7 +810,7 @@ func TestLockReusablePriorEnvRootSurvivesRetargetAfterValidation(t *testing.T) {}t.Cleanup(func() { reuseLockTestHook = nil })- claim, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")+ claim, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")if claim != nil {claim.Release()}@@ -656,7 +856,7 @@ func TestLockReusablePriorEnvRootRejectsIdentitySwap(t *testing.T) {}t.Cleanup(func() { reuseLockTestHook = nil })- claim, used, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")+ claim, used, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")if claim != nil {claim.Release()}@@ -724,7 +924,7 @@ func TestLockReusablePriorEnvRootSurvivesWorkspacesRootSwap(t *testing.T) {}t.Cleanup(func() { reuseLockTestHook = nil })- claim, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")+ claim, _, _, ok, _ := d.lockReusablePriorEnvRoot(context.Background(), task, nil, "")if claim != nil {claim.Release()}