Skip to content

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

Go

MUL-6491 fix(daemon): fence env-root resets on a live execution, not a task id (#7356)

Bohan Jiangd2532f766b15
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index 580270c3c5..4ab851d6a1 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5705,8 +5705,31 @@ func providerNeedsInlineSystemPrompt(provider string) bool {
// the conversation's session store got mounted (execenv.Environment
// HermesSessionStore) — and false drops the resume with the same disclosure as
// a workdir mismatch.
+// sameExistingDir reports whether two paths name the same existing directory.
+// False when either cannot be stat'd, which is the safe answer here: an absent
+// prior workdir means there is nothing to resume from.
+func sameExistingDir(a, b string) bool {
+ if a == "" || b == "" {
+ return false
+ }
+ ai, err := os.Stat(a)
+ if err != nil {
+ return false
+ }
+ bi, err := os.Stat(b)
+ if err != nil {
+ return false
+ }
+ return os.SameFile(ai, bi)
+}
+
func gateResumeToReusedWorkdir(task *Task, taskCtx *execenv.TaskContextForEnv, envWorkDir string, sessionHomeReachable bool, taskLog *slog.Logger) bool {
- reused := task.PriorWorkDir != "" && envWorkDir == task.PriorWorkDir && sessionHomeReachable
+ // Compare the directories, not the spelling. Reuse runs in the canonical
+ // path it validated and locked, which need not be character-identical to
+ // the PriorWorkDir the server sent — a symlinked workspaces root is enough
+ // to make them differ. A string compare would then silently drop the prior
+ // session on every follow-up task in that installation.
+ reused := task.PriorWorkDir != "" && sameExistingDir(envWorkDir, task.PriorWorkDir) && sessionHomeReachable
if !reused && task.PriorSessionID != "" {
taskLog.Info("dropping prior session: session store not reachable from this run",
"session_id", task.PriorSessionID,
@@ -5774,33 +5797,33 @@ func sessionHomeReachable(provider string, env *execenv.Environment, envReused b
// terminal file raced and dropped the session (MUL-4886). Both proofs this
// function reads — the env-root provenance and the workdir task-context marker
// — are written at Prepare time, so neither depends on completion ordering.
-func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignment, workspacesRoot string) bool {
+func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignment, workspacesRoot string) (string, bool) {
if task.PriorWorkDir == "" || localAssignment != nil {
- return false
+ return "", false
}
root, err := filepath.EvalSymlinks(workspacesRoot)
if err != nil {
- return false
+ return "", false
}
workdir, err := filepath.EvalSymlinks(task.PriorWorkDir)
if err != nil {
- return false
+ return "", false
}
info, err := os.Stat(workdir)
if err != nil || !info.IsDir() {
- return false
+ return "", false
}
rel, err := filepath.Rel(root, workdir)
if err != nil || !filepath.IsLocal(rel) {
- return false
+ return "", false
}
parts := strings.Split(rel, string(filepath.Separator))
if len(parts) != 3 || parts[0] != task.WorkspaceID || parts[1] == "" || parts[2] != "workdir" {
- return false
+ return "", false
}
if task.AgentID == "" || (task.IssueID == "" && task.ChatSessionID == "") {
- return false
+ return "", false
}
// Managed-env provenance is written only for non-local resumable envs, so
// its presence (plus the workspace/scope/agent match) proves this is a
@@ -5809,12 +5832,12 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
if err != nil || prov.ManagedBy != execenv.ManagedEnvProvenanceManagedBy ||
prov.WorkspaceID != task.WorkspaceID ||
prov.AgentID != task.AgentID {
- return false
+ return "", false
}
data, err := os.ReadFile(filepath.Join(workdir, execenv.TaskContextMarkerRelPath))
if err != nil {
- return false
+ return "", false
}
var marker struct {
ManagedBy string `json:"managed_by"`
@@ -5823,15 +5846,21 @@ func shouldReusePriorWorkdir(task Task, localAssignment *localDirectoryAssignmen
ChatSessionID string `json:"chat_session_id"`
}
if json.Unmarshal(data, &marker) != nil {
- return false
+ return "", false
}
if marker.ManagedBy != execenv.TaskContextMarkerManagedBy || marker.AgentID != task.AgentID {
- return false
+ return "", false
}
if task.IssueID != "" {
- return prov.IssueID == task.IssueID && marker.IssueID == task.IssueID
+ if prov.IssueID != task.IssueID || marker.IssueID != task.IssueID {
+ return "", false
+ }
+ return workdir, true
+ }
+ if prov.ChatSessionID != task.ChatSessionID || marker.ChatSessionID != task.ChatSessionID {
+ return "", false
}
- return prov.ChatSessionID == task.ChatSessionID && marker.ChatSessionID == task.ChatSessionID
+ return workdir, true
}
// gateCodexResumeToRolloutPresence drops the prior Codex session when its
@@ -6099,6 +6128,126 @@ func (d *Daemon) startTaskPrepareLeaseExtender(ctx context.Context, task Task, t
}
}
+// lockReusablePriorEnvRoot decides whether this task may continue in a prior
+// task's env root and, if so, takes the exclusion lock on it.
+//
+// Order matters and is the point of this function. The lock WRITES a file into
+// the directory, so eligibility has to be proven first:
+// shouldReusePriorWorkdir resolves symlinks, checks the
+// {workspace}/{task}/workdir shape and verifies managed provenance, and only
+// the canonical path it returns is ever opened. Locking on
+// filepath.Dir(task.PriorWorkDir) before that would drop .task_lock into
+// whatever the path happened to point at — a symlink target outside the
+// workspaces root, or a user's own local_directory.
+//
+// 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) {
+ // 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
+ // faithfully pins the replacement. Root promises you cannot escape the tree
+ // it opened — not that it opened the tree you meant. Holding the handle
+ // first makes that ordering impossible.
+ wsRoot, err := os.OpenRoot(d.cfg.WorkspacesRoot)
+ if err != nil {
+ return nil, "", nil, false
+ }
+ defer wsRoot.Close()
+
+ workDir, ok := shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot)
+ if !ok {
+ return nil, "", nil, false
+ }
+ priorRoot := filepath.Dir(workDir)
+ // workDir came back through EvalSymlinks, so the root it is measured
+ // against has to be resolved the same way — otherwise a symlinked
+ // workspaces root (macOS /tmp -> /private/tmp, a home on a linked volume)
+ // makes the two look unrelated and every reuse is refused.
+ canonicalWorkspacesRoot, err := filepath.EvalSymlinks(d.cfg.WorkspacesRoot)
+ if err != nil {
+ return nil, "", nil, false
+ }
+ rel, err := filepath.Rel(canonicalWorkspacesRoot, priorRoot)
+ if err != nil || !filepath.IsLocal(rel) {
+ return nil, "", nil, false
+ }
+ // 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
+ }
+
+ // Pin the identity of the directory that just passed validation. Every
+ // later step is checked against THIS, not against whatever the name
+ // resolves to next: a path string cannot tell "the directory I validated"
+ // apart from "a different directory now answering to that name".
+ validatedInfo, err := os.Stat(priorRoot)
+ if err != nil {
+ return nil, "", nil, false
+ }
+
+ // Deterministic seam for the TOCTOU regressions: tests swap the validated
+ // directory here, between proving eligibility and taking the lock.
+ if reuseLockTestHook != nil {
+ reuseLockTestHook()
+ }
+
+ claim, lockedInfo, err := execenv.LockEnvRootForReuse(wsRoot, rel, priorRoot)
+ switch {
+ 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
+ case err != nil:
+ d.logger.Warn("could not lock prior workdir; starting a fresh environment",
+ "task", shortID(task.ID), "error", err)
+ return nil, "", nil, false
+ case claim == nil:
+ return nil, "", nil, false
+ }
+ // 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
+ }
+
+ // Re-validate while holding the lock, and require the answer to be the SAME
+ // directory. Equality of the canonical path is not enough on its own: the
+ // tree can be rearranged so a different-but-equally-valid env root now
+ // answers to that name, which would leave us holding a lock on one
+ // directory while handing another to Reuse. os.SameFile compares identity,
+ // not spelling.
+ recheckedWorkDir, stillOK := shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot)
+ if !stillOK || recheckedWorkDir != workDir {
+ claim.Release()
+ return nil, "", nil, false
+ }
+ // ...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.
+ currentInfo, err := os.Stat(filepath.Dir(recheckedWorkDir))
+ if err != nil || !os.SameFile(lockedInfo, currentInfo) {
+ d.logger.Info("prior workdir changed identity while being claimed; starting a fresh environment",
+ "task", shortID(task.ID))
+ claim.Release()
+ return nil, "", nil, false
+ }
+ return claim, workDir, lockedInfo, true
+}
+
+// reuseLockTestHook runs between reuse eligibility validation and taking the
+// prior-root lock. Nil outside tests; the TOCTOU regressions use it to make the
+// swap deterministic instead of racing it.
+var reuseLockTestHook func()
+
+// reuseBeforeUseTestHook runs after the prior-root claim is settled and before
+// Reuse resolves that path by name. Nil outside tests.
+var reuseBeforeUseTestHook func()
+
func (d *Daemon) prepareExecutionEnvironment(ctx context.Context, params execenv.PrepareParams) (*execenv.Environment, error) {
if d.executionEnvironmentCommand == nil {
// Focused runTask tests construct a zero-valued Daemon and keep setup
@@ -6492,6 +6641,21 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
}
+ // Claim the env root HERE, in the daemon parent, and hold it for the whole
+ // task run — the same lifetime as unmarkActiveEnvRoot above.
+ //
+ // It cannot be claimed inside preparation: production preparation runs in a
+ // short-lived helper process (prepareExecutionEnvironment ->
+ // PrepareIsolated), so a lock taken there dies with the helper and the
+ // *os.File cannot cross its JSON response back to us. Claiming there would
+ // leave the agent running with no protection at all — which is exactly the
+ // re-dispatch window this guards.
+ envClaim, err := execenv.ClaimEnvRoot(d.cfg.WorkspacesRoot, task.WorkspaceID, task.ID)
+ if err != nil {
+ return TaskResult{}, fmt.Errorf("claim execution environment: %w", err)
+ }
+ defer envClaim.Release()
+
// Try to reuse the workdir from a previous task on the same (agent, issue) pair.
var env *execenv.Environment
// For a built-in codex task, use the version paired with the resolved path
@@ -6712,12 +6876,22 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
}
}
envReused := false
- if shouldReusePriorWorkdir(task, localAssignment, d.cfg.WorkspacesRoot) {
+ if priorClaim, priorWorkDir, lockedPriorInfo, ok := d.lockReusablePriorEnvRoot(task, localAssignment, envClaim.RootDir()); ok {
+ defer priorClaim.Release()
+ // Deterministic seam for the last-window regression: tests swap the
+ // directory here, after the claim is settled and before Reuse resolves
+ // the path by name.
+ if reuseBeforeUseTestHook != nil {
+ reuseBeforeUseTestHook()
+ }
var err error
env, err = d.reuseExecutionEnvironment(prepareCtx, execenv.ReuseParams{
- WorkspacesRoot: d.cfg.WorkspacesRoot,
- Profile: d.cfg.Profile,
- WorkDir: task.PriorWorkDir,
+ WorkspacesRoot: d.cfg.WorkspacesRoot,
+ Profile: d.cfg.Profile,
+ // The canonical path the lock was taken on. Handing Reuse the raw
+ // PriorWorkDir instead would re-resolve it, so the directory we
+ // locked and the directory we use could differ.
+ WorkDir: priorWorkDir,
Provider: provider,
CodexVersion: codexVersion,
ResumeSessionID: task.PriorSessionID,
@@ -6737,6 +6911,20 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if err != nil {
return TaskResult{}, fmt.Errorf("reuse execution environment: %w", err)
}
+ // Reuse resolves priorWorkDir by name, so confirm what it actually
+ // opened is still the directory we hold the lock on. An fd cannot cross
+ // into the preparation helper process, so the name is the only thing
+ // that can be handed over; this turns "silently ran somewhere else"
+ // into "declined and started clean". See lockReusablePriorEnvRoot for
+ // what remains uncovered.
+ if env != nil && lockedPriorInfo != nil {
+ usedInfo, statErr := os.Stat(filepath.Dir(env.WorkDir))
+ if statErr != nil || !os.SameFile(lockedPriorInfo, usedInfo) {
+ taskLog.Info("reused workdir is not the directory that was claimed; starting a fresh environment",
+ "task", shortID(task.ID))
+ env = nil
+ }
+ }
// Reuse can decline (nil) and fall through to a fresh Prepare below.
// Whether it did decides whether an env-root-scoped session store — the
// Hermes overlay's task-local state.db — carried over from the prior task.
@@ -6745,11 +6933,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if env == nil {
var err error
prepParams := execenv.PrepareParams{
- WorkspacesRoot: d.cfg.WorkspacesRoot,
- Profile: d.cfg.Profile,
- WorkspaceID: task.WorkspaceID,
- TaskID: task.ID,
- AgentName: agentName,
+ WorkspacesRoot: d.cfg.WorkspacesRoot,
+ Profile: d.cfg.Profile,
+ WorkspaceID: task.WorkspaceID,
+ TaskID: task.ID,
+ AgentName: agentName,
+ // This run already holds the claim (envClaim above) and the reset
+ // it implies; preparation must not try to take it again.
+ EnvRootPreclaimed: true,
Provider: provider,
CodexVersion: codexVersion,
OpenclawBin: openclawBin,
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index 155b2a2095..4234aa7653 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -2019,10 +2019,27 @@ func TestGateResumeToReusedWorkdir(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: tt.priorDir}
+ // gateResumeToReusedWorkdir compares directory IDENTITY, not path
+ // spelling, so the table's paths have to exist on disk. Mapping
+ // them under one temp root preserves each case's same/different
+ // relationship while making them real.
+ base := t.TempDir()
+ realize := func(p string) string {
+ if p == "" {
+ return ""
+ }
+ real := filepath.Join(base, filepath.FromSlash(strings.TrimPrefix(p, "/")))
+ if err := os.MkdirAll(real, 0o755); err != nil {
+ t.Fatalf("create %s: %v", real, err)
+ }
+ return real
+ }
+ priorDir, envDir := realize(tt.priorDir), realize(tt.envDir)
+
+ task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: priorDir}
taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}
- reused := gateResumeToReusedWorkdir(&task, &taskCtx, tt.envDir, !tt.sessionHomeUnreachable, slog.Default())
+ reused := gateResumeToReusedWorkdir(&task, &taskCtx, envDir, !tt.sessionHomeUnreachable, slog.Default())
if reused != tt.wantReused {
t.Fatalf("reused = %v, want %v", reused, tt.wantReused)
diff --git a/server/internal/daemon/execenv/envlock_unix.go b/server/internal/daemon/execenv/envlock_unix.go
new file mode 100644
index 0000000000..25091f24e1
--- /dev/null
+++ b/server/internal/daemon/execenv/envlock_unix.go
@@ -0,0 +1,37 @@
+//go:build !windows
+
+package execenv
+
+import (
+ "os"
+
+ "golang.org/x/sys/unix"
+)
+
+// lockFileExclusiveNonBlocking takes an exclusive advisory lock on f without
+// waiting. ok is false when another process already holds it.
+//
+// The lock is released by the kernel when the file is closed OR when the
+// holding process dies, which is the whole reason this is a lock and not
+// another marker file: it answers "is the previous execution still alive?"
+// without a heartbeat, a PID table, or a stale-state cleanup path.
+func openEnvRootLockFile(path string) (*os.File, error) {
+ return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)
+}
+
+func lockFileExclusiveNonBlocking(f *os.File) (ok bool, err error) {
+ err = unix.Flock(int(f.Fd()), unix.LOCK_EX|unix.LOCK_NB)
+ if err == nil {
+ return true, nil
+ }
+ if err == unix.EWOULDBLOCK {
+ return false, nil
+ }
+ return false, err
+}
+
+// unlockFile drops the advisory lock. Closing the file would do it too; this
+// makes the release explicit at the call site.
+func unlockFile(f *os.File) error {
+ return unix.Flock(int(f.Fd()), unix.LOCK_UN)
+}
diff --git a/server/internal/daemon/execenv/envlock_windows.go b/server/internal/daemon/execenv/envlock_windows.go
new file mode 100644
index 0000000000..68c2af2e46
--- /dev/null
+++ b/server/internal/daemon/execenv/envlock_windows.go
@@ -0,0 +1,66 @@
+//go:build windows
+
+package execenv
+
+import (
+ "errors"
+ "os"
+
+ "golang.org/x/sys/windows"
+)
+
+// lockFileExclusiveNonBlocking takes an exclusive lock on f without waiting.
+// ok is false when another process already holds it.
+//
+// Windows releases the lock when the handle closes, including on abnormal
+// process termination, giving the same crash-safe liveness answer as flock on
+// unix — see the unix build of this file for why that property matters.
+// openEnvRootLockFile opens (creating if needed) the lock file with
+// FILE_SHARE_DELETE, which os.OpenFile does not request.
+//
+// Without it Windows refuses to delete a file that anyone still has open, so a
+// held lock would pin the whole env root: the GC could not reclaim the
+// directory, and neither could a test's temp-dir teardown. Unix already allows
+// unlinking an open file, and this is what makes Windows behave the same. The
+// lock coordinates executions; it is not meant to pin the directory.
+func openEnvRootLockFile(path string) (*os.File, error) {
+ p, err := windows.UTF16PtrFromString(path)
+ if err != nil {
+ return nil, err
+ }
+ h, err := windows.CreateFile(
+ p,
+ windows.GENERIC_READ|windows.GENERIC_WRITE,
+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE,
+ nil,
+ windows.OPEN_ALWAYS,
+ windows.FILE_ATTRIBUTE_NORMAL,
+ 0,
+ )
+ if err != nil {
+ return nil, err
+ }
+ return os.NewFile(uintptr(h), path), nil
+}
+
+func lockFileExclusiveNonBlocking(f *os.File) (ok bool, err error) {
+ overlapped := new(windows.Overlapped)
+ err = windows.LockFileEx(
+ windows.Handle(f.Fd()),
+ windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY,
+ 0, 1, 0, overlapped,
+ )
+ if err == nil {
+ return true, nil
+ }
+ if errors.Is(err, windows.ERROR_LOCK_VIOLATION) || errors.Is(err, windows.ERROR_IO_PENDING) {
+ return false, nil
+ }
+ return false, err
+}
+
+// unlockFile drops the lock.
+func unlockFile(f *os.File) error {
+ overlapped := new(windows.Overlapped)
+ return windows.UnlockFileEx(windows.Handle(f.Fd()), 0, 1, 0, overlapped)
+}
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 02f430f8ec..edac666351 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -41,6 +41,15 @@ type PrepareParams struct {
WorkspaceID string // workspace UUID — tasks are grouped under this
TaskID string // task UUID — used for directory name
AgentName string // for git branch naming only
+ // EnvRootPreclaimed says the CALLER already holds this env root's claim
+ // (see ClaimEnvRoot) and has already reset it. Prepare then skips claiming.
+ //
+ // This exists because production preparation runs in a short-lived helper
+ // process (PrepareIsolated): a lock taken here would be released by the
+ // kernel the moment that helper exits, and the *os.File cannot cross the
+ // JSON boundary back to the daemon. The claim therefore has to be held by
+ // the parent, whose lifetime is the task run.
+ EnvRootPreclaimed bool
// Profile is the daemon's profile name (empty = default). It namespaces the
// per-issue Codex session store so a second profile-daemon sharing the same
// ~/.codex cannot see or GC this daemon's stores (MUL-4424).
@@ -311,6 +320,9 @@ type Environment struct {
QwenpawWorkspace string
logger *slog.Logger // for cleanup logging
+ // lockFile holds the env root's exclusive execution lock for as long as
+ // this Environment is alive. Released by Cleanup. See claimEnvRoot.
+ lockFile *os.File
}
// PredictRootDir returns the env root path that Prepare would create for the
@@ -363,17 +375,36 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// the rest of Prepare — the reset below clears the directory's CONTENTS and
// leaves the marker in place, so there is never a moment where the env root
// looks unowned to a racing task.
- fresh, err := claimEnvRoot(envRoot, params.TaskID)
- if err != nil {
- return nil, fmt.Errorf("execenv: %w", err)
- }
- // Not fresh means this task already owned the directory — a rerun, which is
- // meant to start from a clean tree. Reuse of a PRIOR task's directory never
- // reaches here; that is Reuse, which takes an explicit WorkDir and deletes
- // nothing.
- if !fresh {
- if err := resetEnvRootContents(envRoot); err != nil {
- return nil, fmt.Errorf("execenv: reset existing env: %w", err)
+ var lockFile *os.File
+ lockClaimed := false
+ if params.EnvRootPreclaimed {
+ // The caller holds the claim and already reset the root; just make sure
+ // the directory is there before populating it.
+ if err := os.MkdirAll(envRoot, 0o755); err != nil {
+ return nil, fmt.Errorf("execenv: create env root %s: %w", envRoot, err)
+ }
+ } else {
+ lock, reset, err := claimEnvRoot(envRoot, params.TaskID)
+ if err != nil {
+ return nil, fmt.Errorf("execenv: %w", err)
+ }
+ lockFile = lock
+ // Release the lock on every failure path below. The successful path
+ // hands it to the Environment.
+ lockClaimed = true
+ defer func() {
+ if lockClaimed {
+ releaseEnvRootLock(lockFile)
+ }
+ }()
+ // reset means this task already owned the directory and the execution
+ // that left it there is gone — a rerun, which is meant to start from a
+ // clean tree. Reuse of a PRIOR task's directory never reaches here;
+ // that is Reuse, which takes an explicit WorkDir and deletes nothing.
+ if reset {
+ if err := resetEnvRootContents(envRoot); err != nil {
+ return nil, fmt.Errorf("execenv: reset existing env: %w", err)
+ }
}
}
@@ -446,6 +477,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
LocalWorktree: localWorktree,
MulticaConfigRoot: multicaConfigRoot,
logger: logger,
+ lockFile: lockFile,
}
// Write context files into workdir (skills go to provider-native paths).
@@ -622,6 +654,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
logger.Info("execenv: prepared env", "root", envRoot, "repos_available", len(params.Task.Repos))
prepareSucceeded = true
+ lockClaimed = false // ownership of any lock passes to the Environment
return env, nil
}
@@ -1091,6 +1124,11 @@ func (env *Environment) Cleanup(removeAll bool) error {
if env == nil {
return nil
}
+ // Drop the execution lock first. Until it is released the env root still
+ // reads as "a live execution owns this", which would make a legitimate
+ // rerun fail closed. The daemon also defers ReleaseLock for the task run;
+ // both paths are idempotent.
+ env.ReleaseLock()
if env.LocalDirectory {
// Never touch the user's directory. RootDir is the daemon's own
@@ -1121,100 +1159,260 @@ func (env *Environment) Cleanup(removeAll bool) error {
return nil
}
-// envRootOwnerFile records which task an env root belongs to. Creating it with
-// O_EXCL is the atomic step that decides which of two same-key tasks owns the
-// directory, and it is the proof Prepare needs before wiping a directory that
-// another task may still be executing in (#7326).
-const envRootOwnerFile = ".task_owner"
+// EnvRootClaim is a held claim on a task's env root. It exists so the claim can
+// outlive the code that prepares the directory.
+//
+// Production preparation runs in a short-lived helper process
+// (PrepareIsolated / ReuseIsolated). A lock taken inside that helper is
+// released by the kernel as soon as it exits, and *os.File cannot travel back
+// through the helper's JSON response — so a claim taken there protects
+// nothing by the time the agent actually runs. The daemon parent takes the
+// claim instead and holds it for the whole task run.
+type EnvRootClaim struct {
+ rootDir string
+ lock *os.File
+}
+
+// RootDir is the env root this claim covers.
+func (c *EnvRootClaim) RootDir() string {
+ if c == nil {
+ return ""
+ }
+ return c.rootDir
+}
+
+// Release drops the claim. Safe on nil and safe to call twice.
+func (c *EnvRootClaim) Release() {
+ if c == nil || c.lock == nil {
+ return
+ }
+ releaseEnvRootLock(c.lock)
+ c.lock = nil
+}
-// claimEnvRoot atomically establishes that taskID owns envRoot.
+// ClaimEnvRoot takes the full claim for a fresh preparation of taskID: it
+// proves ownership, refuses a root a live execution or another task holds, and
+// resets a stale root this task owns so the caller receives a clean directory.
//
-// fresh is true when this call created the claim and the directory is the
-// caller's to populate; false when taskID already owned it, i.e. a rerun that
-// may reset its own tree. Any other owner is an error, and so is a directory
-// that holds content but names no owner — refusing to guess is the whole point
-// of the marker.
+// Callers that pass the claim to Prepare must also set
+// PrepareParams.EnvRootPreclaimed, or Prepare will try to take a lock this
+// claim already holds and fail.
+func ClaimEnvRoot(workspacesRoot, workspaceID, taskID string) (*EnvRootClaim, error) {
+ envRoot := PredictRootDir(workspacesRoot, workspaceID, taskID)
+ if envRoot == "" {
+ return nil, fmt.Errorf("execenv: claim env root: workspaces root, workspace ID and task ID are all required")
+ }
+ lock, reset, err := claimEnvRoot(envRoot, taskID)
+ if err != nil {
+ return nil, fmt.Errorf("execenv: %w", err)
+ }
+ if reset {
+ if err := resetEnvRootContents(envRoot); err != nil {
+ releaseEnvRootLock(lock)
+ return nil, fmt.Errorf("execenv: reset existing env: %w", err)
+ }
+ }
+ return &EnvRootClaim{rootDir: envRoot, lock: lock}, nil
+}
+
+// ErrEnvRootBusy reports that a live execution already holds an env root. On
+// the reuse path it is a reason to fall back to a fresh Prepare, not to fail
+// the task.
+var ErrEnvRootBusy = errors.New("env root is held by a running execution")
+
+// LockEnvRootForReuse takes the exclusion half of a claim, without the identity
+// half, for a task continuing in a PRIOR task's directory.
+//
+// Reuse adopts another task's env root on purpose, so the owner marker names
+// that earlier task and must not be reinterpreted or overwritten — but two
+// continuations of the same task still must not refresh and run the same
+// directory at once.
+//
+// wsRoot must be a Root the CALLER opened before it validated anything, and
+// rel the env root's path within it. Both matter:
//
-// Atomicity comes from two filesystem primitives rather than a lock: os.Mkdir
-// fails if the directory exists, and O_EXCL fails if the marker exists. Exactly
-// one racing caller can win each, and a caller that wins neither never reaches
-// the destructive path. The emptiness check below only decides whether a
-// caller may ATTEMPT a claim; O_EXCL alone decides who gets it.
-func claimEnvRoot(envRoot, taskID string) (fresh bool, err error) {
- if err := os.MkdirAll(filepath.Dir(envRoot), 0o755); err != nil {
- return false, fmt.Errorf("create workspace directory: %w", err)
- }
-
- switch err := os.Mkdir(envRoot, 0o755); {
- case err == nil:
- // We created the directory, so nothing of anyone's can be inside it.
- if err := writeEnvRootOwnerExclusive(envRoot, taskID); err != nil {
- return false, err
+// - Opening the Root here, from a name the caller validated a moment ago,
+// would re-resolve that name. Renaming the whole workspaces root aside and
+// leaving a symlink to a look-alike tree in its place would have os.Root
+// faithfully pin the replacement — Root guarantees you cannot escape the
+// tree it opened, not that it opened the tree you meant.
+// - Every operation below goes through ONE sub-Root pinned on the env root,
+// so the directory whose identity is returned and the directory the lock
+// file is created in cannot be two different directories. Resolving rel
+// twice from wsRoot would allow exactly that: A on the first resolution,
+// B on the second.
+//
+// It returns that directory's FileInfo so the caller can confirm it is the one
+// validation approved; Root still follows symlinks that stay inside the tree,
+// so "locked A, reused B" has to be ruled out by identity, not containment.
+//
+// Returns a nil claim and no error when the env root is missing, and
+// ErrEnvRootBusy when another execution holds it — both mean "fall back to a
+// fresh Prepare".
+func LockEnvRootForReuse(wsRoot *os.Root, rel, envRoot string) (*EnvRootClaim, os.FileInfo, error) {
+ if wsRoot == nil || rel == "" || !filepath.IsLocal(rel) {
+ return nil, nil, fmt.Errorf("execenv: env root %s is not inside the workspaces root", envRoot)
+ }
+
+ // Pin the env root itself. From here on nothing is resolved by name again.
+ envRootHandle, err := wsRoot.OpenRoot(rel)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ return nil, nil, nil
}
- return true, nil
- case !errors.Is(err, os.ErrExist):
- return false, fmt.Errorf("create env root %s: %w", envRoot, err)
+ return nil, nil, fmt.Errorf("execenv: open env root %s: %w", envRoot, err)
}
+ defer envRootHandle.Close()
+
+ info, err := envRootHandle.Stat(".")
+ if err != nil {
+ return nil, nil, fmt.Errorf("execenv: inspect env root %s: %w", envRoot, err)
+ }
+ if !info.IsDir() {
+ return nil, nil, nil
+ }
+
+ lock, err := envRootHandle.OpenFile(envRootLockFile, os.O_CREATE|os.O_RDWR, 0o644)
+ if err != nil {
+ return nil, nil, fmt.Errorf("execenv: open env root lock for %s: %w", envRoot, err)
+ }
+ locked, err := lockFileExclusiveNonBlocking(lock)
+ if err != nil {
+ lock.Close()
+ return nil, nil, fmt.Errorf("execenv: lock env root %s: %w", envRoot, err)
+ }
+ if !locked {
+ lock.Close()
+ return nil, nil, fmt.Errorf("execenv: reuse %s: %w", envRoot, ErrEnvRootBusy)
+ }
+ return &EnvRootClaim{rootDir: envRoot, lock: lock}, info, nil
+}
+
+// envRootOwnerFile records which task an env root belongs to: WHO owns it.
+const envRootOwnerFile = ".task_owner"
+
+// envRootLockFile carries the env root's exclusive execution lock: whether the
+// owner is STILL RUNNING. The two answer different questions and both are
+// needed — a dead task's directory still holds its work, and a live task's
+// directory must not be reset even by another execution of the same task.
+const envRootLockFile = ".task_lock"
+
+// claimEnvRoot takes exclusive ownership of envRoot for taskID.
+//
+// It returns the held lock file — the caller owns it until Cleanup — and
+// whether the directory needs resetting before use.
+//
+// The lock is an OS advisory lock, and the kernel releases it when the holding
+// process exits for any reason. That is what makes it a lock rather than a
+// third marker file: it answers "is the previous execution still alive?"
+// across processes, with no heartbeat, no PID table and no stale-state cleanup
+// path. An identity marker alone cannot answer it, which is how the previous
+// design let a re-dispatched execution of the SAME task id wipe the directory
+// of an execution that was still running (#7326 follow-up):
+//
+// - The server re-delivers a task row whose prepare lease expired
+// (ReclaimStaleDispatchedTaskForRuntime) using the same task id.
+// - A failing lease renewal only logs; it does not cancel the Prepare that
+// is still in flight.
+// - So two Prepare calls for one task id could overlap, and "owner == mine"
+// read as "my own rerun, safe to reset".
+//
+// Holding the lock also serialises everything below it, which is what makes
+// repairing a torn marker safe: no other execution can be mid-claim.
+func claimEnvRoot(envRoot, taskID string) (lockFile *os.File, reset bool, err error) {
+ if err := os.MkdirAll(envRoot, 0o755); err != nil {
+ return nil, false, fmt.Errorf("create env root %s: %w", envRoot, err)
+ }
+
+ lockFile, err = openEnvRootLockFile(filepath.Join(envRoot, envRootLockFile))
+ if err != nil {
+ return nil, false, fmt.Errorf("open env root lock for %s: %w", envRoot, err)
+ }
+ locked, err := lockFileExclusiveNonBlocking(lockFile)
+ if err != nil {
+ lockFile.Close()
+ return nil, false, fmt.Errorf("lock env root %s: %w", envRoot, err)
+ }
+ if !locked {
+ lockFile.Close()
+ return nil, false, fmt.Errorf("env root %s is held by a running execution; refusing to reset it for task %s", envRoot, taskID)
+ }
+ // Past this point we are the only execution touching this env root, in this
+ // process or any other, so the checks below cannot race.
+ defer func() {
+ if err != nil {
+ releaseEnvRootLock(lockFile)
+ lockFile = nil
+ }
+ }()
- // The directory already existed. Who owns it?
owner, err := readEnvRootOwner(envRoot)
if err != nil {
- return false, fmt.Errorf("read env root owner for %s: %w", envRoot, err)
+ return nil, false, fmt.Errorf("read env root owner for %s: %w", envRoot, err)
}
switch {
case owner == taskID:
- return false, nil
+ // Ours, and the execution that left it is provably gone — we hold the
+ // lock it would still be holding.
+ return lockFile, true, nil
case owner != "":
- return false, fmt.Errorf("env root %s belongs to task %s; refusing to reset it for task %s", envRoot, owner, taskID)
+ return nil, false, fmt.Errorf("env root %s belongs to task %s; refusing to reset it for task %s", envRoot, owner, taskID)
}
- // No owner. A directory holding work is never ours to take — the marker is
- // written before any content, so the only unowned directory that can be
- // safely claimed is an empty one (a crash between Mkdir and the marker
- // write). Anything else fails closed and waits for a human.
- empty, err := dirIsEmpty(envRoot)
+ // No owner recorded. Either the directory is new, or a crash tore the
+ // marker before it named anyone. Work with no owner is never ours to
+ // delete; an env root with nothing in it costs nothing to adopt.
+ hasWork, err := envRootHoldsWork(envRoot)
if err != nil {
- return false, fmt.Errorf("inspect env root %s: %w", envRoot, err)
+ return nil, false, fmt.Errorf("inspect env root %s: %w", envRoot, err)
}
- if !empty {
- return false, fmt.Errorf("env root %s already holds files but names no owning task; refusing to delete it", envRoot)
+ if hasWork {
+ return nil, false, fmt.Errorf("env root %s already holds files but names no owning task; refusing to delete it", envRoot)
}
- if err := writeEnvRootOwnerExclusive(envRoot, taskID); err != nil {
- // Lost the race for an empty directory: whoever won owns it now.
- return false, err
+ if err := writeEnvRootOwner(envRoot, taskID); err != nil {
+ return nil, false, err
}
- return true, nil
+ return lockFile, false, nil
}
-// writeEnvRootOwnerExclusive creates the owner marker, failing if one already
-// exists. This is the atomic arbiter between two racing claims.
-func writeEnvRootOwnerExclusive(envRoot, taskID string) error {
- path := filepath.Join(envRoot, envRootOwnerFile)
- f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o644)
- if errors.Is(err, os.ErrExist) {
- owner, readErr := readEnvRootOwner(envRoot)
- if readErr != nil {
- return fmt.Errorf("read env root owner for %s: %w", envRoot, readErr)
- }
- if owner == taskID {
- return nil
- }
- return fmt.Errorf("env root %s was claimed by task %s while task %s was starting", envRoot, owner, taskID)
- }
- if err != nil {
- return fmt.Errorf("claim env root %s: %w", envRoot, err)
+// ReleaseLock drops the env root's execution lock. The daemon defers this for
+// the duration of a task run: the lock's lifetime is the EXECUTION, not this
+// value. Cleanup is not the right place on its own — production never calls it
+// (the GC reclaims env roots later), so a lock released only there would be
+// held until the daemon exits and would fail-closed every legitimate rerun of
+// that task. Safe on nil and safe to call twice.
+func (env *Environment) ReleaseLock() {
+ if env == nil || env.lockFile == nil {
+ return
+ }
+ releaseEnvRootLock(env.lockFile)
+ env.lockFile = nil
+}
+
+// releaseEnvRootLock drops the execution lock and closes the file. Safe on nil.
+func releaseEnvRootLock(f *os.File) {
+ if f == nil {
+ return
}
- if _, err := f.WriteString(taskID); err != nil {
- f.Close()
+ _ = unlockFile(f)
+ _ = f.Close()
+}
+
+// writeEnvRootOwner records taskID as the owner. Callers must hold the env
+// root lock, which is what lets this overwrite a marker torn by an earlier
+// crash without racing another execution mid-claim.
+func writeEnvRootOwner(envRoot, taskID string) error {
+ path := filepath.Join(envRoot, envRootOwnerFile)
+ if err := os.WriteFile(path, []byte(taskID), 0o644); err != nil {
return fmt.Errorf("record env root owner for %s: %w", envRoot, err)
}
- return f.Close()
+ return nil
}
// readEnvRootOwner returns the task id that owns envRoot, or "" when no marker
-// is present. An unreadable marker is an error, not an empty owner: treating it
-// as unowned would hand the caller a licence to delete the very directory it
-// could not identify.
+// is present or it was never written through. An unreadable marker is an
+// error, not an empty owner: treating it as unowned would hand the caller a
+// licence to delete the very directory it could not identify.
func readEnvRootOwner(envRoot string) (string, error) {
b, err := os.ReadFile(filepath.Join(envRoot, envRootOwnerFile))
if errors.Is(err, os.ErrNotExist) {
@@ -1226,17 +1424,17 @@ func readEnvRootOwner(envRoot string) (string, error) {
return strings.TrimSpace(string(b)), nil
}
-// resetEnvRootContents empties an env root the caller already owns, keeping the
-// directory and its owner marker. Removing and recreating the directory instead
-// would drop the claim for as long as the recreate takes, which is exactly the
-// window claimEnvRoot exists to close.
+// resetEnvRootContents empties an env root the caller already owns and holds
+// the lock on, keeping the bookkeeping files. Removing and recreating the
+// directory instead would drop both the claim and the lock for as long as the
+// recreate takes, which is exactly the window claimEnvRoot exists to close.
func resetEnvRootContents(envRoot string) error {
entries, err := os.ReadDir(envRoot)
if err != nil {
return err
}
for _, e := range entries {
- if e.Name() == envRootOwnerFile {
+ if isEnvRootBookkeeping(e.Name()) {
continue
}
if err := os.RemoveAll(filepath.Join(envRoot, e.Name())); err != nil {
@@ -1246,11 +1444,21 @@ func resetEnvRootContents(envRoot string) error {
return nil
}
-// dirIsEmpty reports whether dir has no entries at all.
-func dirIsEmpty(dir string) (bool, error) {
- entries, err := os.ReadDir(dir)
+// envRootHoldsWork reports whether envRoot contains anything beyond the owner
+// marker and the lock file — that is, anything a task could lose.
+func envRootHoldsWork(envRoot string) (bool, error) {
+ entries, err := os.ReadDir(envRoot)
if err != nil {
return false, err
}
- return len(entries) == 0, nil
+ for _, e := range entries {
+ if !isEnvRootBookkeeping(e.Name()) {
+ return true, nil
+ }
+ }
+ return false, nil
+}
+
+func isEnvRootBookkeeping(name string) bool {
+ return name == envRootOwnerFile || name == envRootLockFile
}
diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.go
index a83d27f0fd..54fae3b1b8 100644
--- a/server/internal/daemon/execenv/execenv_test.go
+++ b/server/internal/daemon/execenv/execenv_test.go
@@ -6284,7 +6284,7 @@ func TestPrepareRefusesEnvRootOwnedByAnotherTask(t *testing.T) {
if err := os.MkdirAll(filepath.Join(envRoot, "workdir"), 0o755); err != nil {
t.Fatalf("seed env root: %v", err)
}
- if err := writeEnvRootOwnerExclusive(envRoot, "11111111-2222-3333-4444-555555555555"); err != nil {
+ if err := writeEnvRootOwner(envRoot, "11111111-2222-3333-4444-555555555555"); err != nil {
t.Fatalf("seed owner: %v", err)
}
survivor := filepath.Join(envRoot, "workdir", "other-task-work.txt")
@@ -6331,6 +6331,10 @@ func TestPrepareResetsItsOwnEnvRoot(t *testing.T) {
if err := os.WriteFile(stale, []byte("from the previous run"), 0o644); err != nil {
t.Fatalf("seed stale file: %v", err)
}
+ // End the first execution. A rerun only reaches the reset path once the
+ // previous execution has released the env root; an overlapping one is
+ // refused, which TestPrepareRefusesOverlappingExecutionOfSameTask covers.
+ first.ReleaseLock()
second, err := Prepare(PrepareParams{
WorkspacesRoot: workspacesRoot,
@@ -6435,7 +6439,7 @@ func TestClaimEnvRootRefusesUnownedDirectoryWithContent(t *testing.T) {
t.Fatalf("seed: %v", err)
}
- if _, err := claimEnvRoot(envRoot, "aaaaaaaa-1111-2222-3333-0123456789ab"); err == nil {
+ if _, _, err := claimEnvRoot(envRoot, "aaaaaaaa-1111-2222-3333-0123456789ab"); err == nil {
t.Fatal("claimEnvRoot took a directory holding files with no owner")
} else if !strings.Contains(err.Error(), "names no owning task") {
t.Fatalf("error = %v, want it to explain the missing owner", err)
@@ -6455,14 +6459,160 @@ func TestClaimEnvRootAdoptsEmptyDirectory(t *testing.T) {
t.Fatalf("seed: %v", err)
}
const id = "aaaaaaaa-1111-2222-3333-0123456789ab"
- fresh, err := claimEnvRoot(envRoot, id)
+ lock, reset, err := claimEnvRoot(envRoot, id)
if err != nil {
t.Fatalf("claimEnvRoot on an empty directory: %v", err)
}
- if !fresh {
- t.Fatal("adopting an empty directory should report a fresh claim")
+ defer releaseEnvRootLock(lock)
+ if reset {
+ t.Fatal("adopting an empty directory should not ask for a reset")
}
if owner, _ := readEnvRootOwner(envRoot); owner != id {
t.Fatalf("owner = %q, want %q", owner, id)
}
}
+
+// prepareSameTask is a helper for the stale-dispatch regressions below: two
+// executions of ONE task id, which is what the server actually re-delivers.
+func prepareSameTask(t *testing.T, workspacesRoot, taskID string) (*Environment, error) {
+ t.Helper()
+ return Prepare(PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: "ws-redispatch",
+ TaskID: taskID,
+ AgentName: "Redispatch",
+ Task: TaskContextForEnv{IssueID: taskID},
+ }, testLogger())
+}
+
+// TestPrepareRefusesOverlappingExecutionOfSameTask covers the gap review found
+// after the identity marker landed: the marker answers WHO owns an env root,
+// not whether that owner is still running, so "owner == my task id" was read as
+// "my own rerun, safe to reset".
+//
+// That is reachable, not theoretical. ReclaimStaleDispatchedTaskForRuntime
+// re-delivers a task row whose prepare lease expired using the SAME task id,
+// and a failing lease renewal only logs — it does not cancel the Prepare still
+// in flight. The re-delivered execution would then wipe the running one's
+// workdir, config and worktree: the very cross-execution deletion the env-root
+// claim exists to prevent, arriving through the one door it left open.
+func TestPrepareRefusesOverlappingExecutionOfSameTask(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ const taskID = "01a01ec0-e69d-7000-8000-0123456789ab"
+
+ live, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err != nil {
+ t.Fatalf("first execution: %v", err)
+ }
+ defer live.Cleanup(true)
+
+ inFlight := filepath.Join(live.WorkDir, "in-flight.txt")
+ if err := os.WriteFile(inFlight, []byte("still running"), 0o644); err != nil {
+ t.Fatalf("seed in-flight work: %v", err)
+ }
+
+ // The stale-dispatch reclaim arrives while the first execution is running.
+ second, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err == nil {
+ second.Cleanup(true)
+ t.Fatal("a second execution of the same task took over a live env root")
+ }
+ if !strings.Contains(err.Error(), "running execution") {
+ t.Fatalf("error = %v, want it to name the live execution", err)
+ }
+ if _, statErr := os.Stat(inFlight); statErr != nil {
+ t.Fatalf("the re-dispatched execution destroyed live work: %v", statErr)
+ }
+}
+
+// TestPrepareResetsAfterPriorExecutionEnded is the other half: once the earlier
+// execution is gone, the same task id must still be able to recover. The lock
+// is what distinguishes the two cases, and the kernel drops it when the holder
+// exits, so no stale-state cleanup path is needed for a crashed execution.
+func TestPrepareResetsAfterPriorExecutionEnded(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ const taskID = "01a01ec0-e69d-7000-8000-0123456789ab"
+
+ first, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err != nil {
+ t.Fatalf("first execution: %v", err)
+ }
+ stale := filepath.Join(first.WorkDir, "stale.txt")
+ if err := os.WriteFile(stale, []byte("left behind"), 0o644); err != nil {
+ t.Fatalf("seed stale work: %v", err)
+ }
+ // The execution ends without tearing the directory down — a crash, from the
+ // next execution's point of view.
+ first.ReleaseLock()
+
+ second, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err != nil {
+ t.Fatalf("recovery execution refused a released env root: %v", err)
+ }
+ defer second.Cleanup(true)
+ if _, statErr := os.Stat(stale); !os.IsNotExist(statErr) {
+ t.Fatalf("recovery did not reset the env root; stale file still present (%v)", statErr)
+ }
+}
+
+// TestClaimEnvRootRepairsTornOwnerMarker covers the reliability note from the
+// same review: the marker used to be created empty and written a moment later,
+// so a crash in between left a zero-length marker. That read back as "no
+// owner", while the marker itself counted as directory content — so the env
+// root could never be adopted OR reset, and stayed wedged until someone
+// deleted it by hand.
+//
+// Holding the lock before reading the marker is what makes repair safe: no
+// other execution can be mid-claim, so an unnamed marker can simply be
+// rewritten.
+func TestClaimEnvRootRepairsTornOwnerMarker(t *testing.T) {
+ t.Parallel()
+ envRoot := filepath.Join(t.TempDir(), "ws", "0123456789ab")
+ if err := os.MkdirAll(envRoot, 0o755); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(envRoot, envRootOwnerFile), nil, 0o644); err != nil {
+ t.Fatalf("seed torn marker: %v", err)
+ }
+
+ const id = "aaaaaaaa-1111-2222-3333-0123456789ab"
+ lock, _, err := claimEnvRoot(envRoot, id)
+ if err != nil {
+ t.Fatalf("claimEnvRoot wedged on a torn marker: %v", err)
+ }
+ defer releaseEnvRootLock(lock)
+ if owner, _ := readEnvRootOwner(envRoot); owner != id {
+ t.Fatalf("owner = %q, want the repairing task %q", owner, id)
+ }
+}
+
+// TestReleaseLockFreesEnvRootForALaterDispatch pins the lifetime rule that
+// Windows CI surfaced: the lock belongs to the task EXECUTION, and nothing in
+// production calls Environment.Cleanup — the GC reclaims env roots on its own
+// schedule. A lock released only by Cleanup would therefore be held until the
+// daemon exited, fail-closing every later dispatch of that task and, on
+// Windows, pinning the directory against removal. The daemon defers
+// ReleaseLock for the task run; this covers the contract it relies on.
+func TestReleaseLockFreesEnvRootForALaterDispatch(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ const taskID = "01a01ec0-e69d-7000-8000-0123456789ab"
+
+ first, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err != nil {
+ t.Fatalf("first execution: %v", err)
+ }
+ first.ReleaseLock()
+ first.ReleaseLock() // idempotent: Cleanup may release the same lock again
+
+ second, err := prepareSameTask(t, workspacesRoot, taskID)
+ if err != nil {
+ t.Fatalf("later dispatch was refused after the lock was released: %v", err)
+ }
+ // Cleanup must stay safe on an already-released lock.
+ if err := second.Cleanup(true); err != nil {
+ t.Fatalf("cleanup after release: %v", err)
+ }
+}
diff --git a/server/internal/daemon/execenv/isolation_test.go b/server/internal/daemon/execenv/isolation_test.go
index 381fc0d794..17d3beb465 100644
--- a/server/internal/daemon/execenv/isolation_test.go
+++ b/server/internal/daemon/execenv/isolation_test.go
@@ -258,3 +258,146 @@ func TestRehydratePreparationErrorUnknownKind(t *testing.T) {
t.Errorf("preparationErrorKind(timeout) = %q, want %q", kind, preparationErrorKindOpenclawCLITimeout)
}
}
+
+// TestPrepareIsolatedKeepsTheClaimWithTheParent is the production-path
+// regression. Every real daemon prepares through PrepareIsolated, and the
+// helper is a short-lived child process: a lock taken inside it is released by
+// the kernel the instant it exits, and *os.File cannot travel back through the
+// helper's JSON response. An env-root claim taken during preparation therefore
+// protects nothing by the time the agent runs — the in-process Prepare tests
+// cannot see this, because there the "helper" never exits.
+//
+// The parent takes the claim and keeps it, so a second execution of the same
+// task must still be refused after PrepareIsolated has returned.
+func TestPrepareIsolatedKeepsTheClaimWithTheParent(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ const (
+ workspaceID = "ws-isolated"
+ taskID = "01a01ec0-e69d-7000-8000-0123456789ab"
+ )
+
+ claim, err := ClaimEnvRoot(workspacesRoot, workspaceID, taskID)
+ if err != nil {
+ t.Fatalf("parent claim: %v", err)
+ }
+ defer claim.Release()
+
+ env, err := PrepareIsolated(context.Background(), preparationHelperTestCommand(), PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: workspaceID,
+ TaskID: taskID,
+ AgentName: "Isolated",
+ EnvRootPreclaimed: true,
+ Task: TaskContextForEnv{IssueID: taskID},
+ }, nil)
+ if err != nil {
+ t.Fatalf("PrepareIsolated: %v", err)
+ }
+ if env == nil || env.WorkDir == "" {
+ t.Fatal("PrepareIsolated returned no environment")
+ }
+
+ // The helper has exited. If the claim had been taken inside it, the lock
+ // would be gone and this second claim would succeed.
+ if second, err := ClaimEnvRoot(workspacesRoot, workspaceID, taskID); err == nil {
+ second.Release()
+ t.Fatal("production PrepareIsolated returned without retaining the execution lock")
+ }
+
+ // And releasing it must hand the env root back for a later dispatch.
+ claim.Release()
+ next, err := ClaimEnvRoot(workspacesRoot, workspaceID, taskID)
+ if err != nil {
+ t.Fatalf("env root stayed locked after release: %v", err)
+ }
+ next.Release()
+}
+
+// TestLockEnvRootForReuseExcludesConcurrentContinuations covers the lock
+// primitive the reuse path is built on. The composed decision — validate the
+// prior workdir, then lock only the canonical root — is pinned by
+// TestLockReusablePriorEnvRoot* in the daemon package, which is where the
+// ordering lives.
+func TestLockEnvRootForReuseExcludesConcurrentContinuations(t *testing.T) {
+ t.Parallel()
+ priorRoot := filepath.Join(t.TempDir(), "ws", "0123456789ab")
+ if err := os.MkdirAll(filepath.Join(priorRoot, "workdir"), 0o755); err != nil {
+ t.Fatalf("seed prior root: %v", err)
+ }
+
+ wsRoot, err := os.OpenRoot(filepath.Dir(filepath.Dir(priorRoot)))
+ if err != nil {
+ t.Fatalf("open workspaces root: %v", err)
+ }
+ defer wsRoot.Close()
+ rel := filepath.Join(filepath.Base(filepath.Dir(priorRoot)), filepath.Base(priorRoot))
+
+ first, _, err := LockEnvRootForReuse(wsRoot, rel, priorRoot)
+ if err != nil {
+ t.Fatalf("first continuation: %v", err)
+ }
+ if first == nil {
+ t.Fatal("expected a claim for an existing prior root")
+ }
+
+ if second, _, err := LockEnvRootForReuse(wsRoot, rel, priorRoot); err == nil {
+ second.Release()
+ t.Fatal("two continuations locked the same prior workdir at once")
+ }
+
+ first.Release()
+ again, _, err := LockEnvRootForReuse(wsRoot, rel, priorRoot)
+ if err != nil {
+ t.Fatalf("prior root stayed locked after release: %v", err)
+ }
+ again.Release()
+
+ // A missing root is not an error — the caller falls through to a fresh
+ // Prepare, and there is nothing to exclude on.
+ base := t.TempDir()
+ baseRoot, err := os.OpenRoot(base)
+ if err != nil {
+ t.Fatalf("open base: %v", err)
+ }
+ defer baseRoot.Close()
+ missing, _, err := LockEnvRootForReuse(baseRoot, "absent", filepath.Join(base, "absent"))
+ if err != nil || missing != nil {
+ t.Fatalf("missing prior root: claim=%v err=%v, want nil/nil", missing, err)
+ }
+}
+
+// TestPrepareIsolatedFailsLoudlyWhenPreclaimIsNotDeclared pins what happens if
+// a caller ever holds the claim but forgets EnvRootPreclaimed. Parent and
+// helper then contend for the same lock, and the important property is that
+// this fails immediately and says so, rather than proceeding with preparation
+// that silently believes it is protected.
+func TestPrepareIsolatedFailsLoudlyWhenPreclaimIsNotDeclared(t *testing.T) {
+ t.Parallel()
+ workspacesRoot := t.TempDir()
+ const (
+ workspaceID = "ws-preclaim"
+ taskID = "01a01ec0-e69d-7000-8000-0123456789ab"
+ )
+
+ claim, err := ClaimEnvRoot(workspacesRoot, workspaceID, taskID)
+ if err != nil {
+ t.Fatalf("parent claim: %v", err)
+ }
+ defer claim.Release()
+
+ _, err = PrepareIsolated(context.Background(), preparationHelperTestCommand(), PrepareParams{
+ WorkspacesRoot: workspacesRoot,
+ WorkspaceID: workspaceID,
+ TaskID: taskID,
+ AgentName: "Forgetful",
+ // EnvRootPreclaimed deliberately left false while the parent holds it.
+ Task: TaskContextForEnv{IssueID: taskID},
+ }, nil)
+ if err == nil {
+ t.Fatal("preparation ran without declaring the parent's claim")
+ }
+ if !strings.Contains(err.Error(), "running execution") {
+ t.Fatalf("error = %v, want it to name the held claim", err)
+ }
+}
diff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.go
index 88ffa52e1c..c695f224d5 100644
--- a/server/internal/daemon/leader_workdir_reuse_test.go
+++ b/server/internal/daemon/leader_workdir_reuse_test.go
@@ -3,6 +3,7 @@ package daemon
import (
"context"
"io"
+ "io/fs"
"log/slog"
"net/http"
"net/http/httptest"
@@ -52,7 +53,10 @@ func TestRunTaskSquadLeaderReusesWorkdirBeforeGCMetaWritten(t *testing.T) {
if err != nil {
t.Fatalf("second runTask: %v", err)
}
- if secondResult.WorkDir != firstResult.WorkDir {
+ // Compare resolved paths: reuse runs in the canonical directory it locked,
+ // and on macOS the test root itself is a symlink (/tmp -> /private/tmp), so
+ // the two spellings name one directory.
+ if !sameDir(t, secondResult.WorkDir, firstResult.WorkDir) {
t.Fatalf("second WorkDir = %q, want reused leader workdir %q", secondResult.WorkDir, firstResult.WorkDir)
}
args, err := os.ReadFile(argsFile)
@@ -94,7 +98,7 @@ func TestShouldReusePriorWorkdirNonLeaderRequiresProvenance(t *testing.T) {
task := leaderReuseTestTask("task-non-leader")
task.IsLeaderTask = false
task.PriorWorkDir = filepath.Join(root, "anything", "workdir")
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatal("non-leader task reused a prior workdir without any ownership provenance")
}
}
@@ -114,12 +118,12 @@ func TestShouldReusePriorWorkdirChatAcceptsMatchingConversation(t *testing.T) {
task.AgentID = "agent-chat"
task.IsLeaderTask = false
task.PriorWorkDir = workDir
- if !shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); !ok {
t.Fatalf("chat task did not reuse its fully-provenanced conversation workdir %q", workDir)
}
task.ChatSessionID = "another-chat"
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatal("chat task reused a workdir belonging to another conversation")
}
}
@@ -136,7 +140,7 @@ func TestShouldReusePriorWorkdirSquadLeaderAcceptsManagedProvenance(t *testing.T
task := leaderReuseTestTask("task-accept")
task.PriorWorkDir = workDir
- if !shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); !ok {
t.Fatalf("leader did not reuse a fully-provenanced managed workdir %q", workDir)
}
}
@@ -152,7 +156,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsNonManagedPathUnderRoot(t *tes
task := leaderReuseTestTask("task-contained-user-dir")
task.PriorWorkDir = userDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused non-managed path %q merely because it is under WorkspacesRoot", userDir)
}
}
@@ -172,7 +176,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsManagedShapeWithoutProvenance(
task := leaderReuseTestTask("task-without-provenance")
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused marked workdir %q without managed-env provenance", workDir)
}
}
@@ -190,7 +194,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsMismatchedProvenanceOwner(t *t
task := leaderReuseTestTask("task-mismatched-provenance")
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused workdir %q with provenance owned by another agent", workDir)
}
}
@@ -208,7 +212,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsMismatchedTaskMarker(t *testin
task := leaderReuseTestTask("task-mismatched-marker")
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused workdir %q with a marker for another agent", workDir)
}
}
@@ -227,7 +231,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsRegularFile(t *testing.T) {
task := leaderReuseTestTask("task-file-workdir")
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused regular file %q as a workdir", workDir)
}
}
@@ -243,7 +247,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsEmptyAgentID(t *testing.T) {
task := leaderReuseTestTask("task-empty-agent")
task.AgentID = ""
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatal("leader with an empty AgentID must not reuse a prior workdir")
}
}
@@ -267,7 +271,7 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsSymlinkEscape(t *testing.T) {
task := leaderReuseTestTask("task-symlink-escape")
task.PriorWorkDir = workDir
- if shouldReusePriorWorkdir(task, nil, root) {
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
t.Fatalf("leader reused a workdir symlinked outside WorkspacesRoot (%q -> %q)", workDir, external)
}
}
@@ -385,3 +389,447 @@ func leaderReuseTestTask(id string) Task {
},
}
}
+
+// TestLockReusablePriorEnvRootNeverWritesOutsideWorkspacesRoot pins the
+// ordering that makes the reuse lock safe. Taking the lock writes .task_lock
+// INTO the directory, so it must happen only after the prior workdir is proven
+// to be a canonical managed env root.
+//
+// An earlier revision locked filepath.Dir(task.PriorWorkDir) up front, guarded
+// only by a lexical containment check. filepath.Rel does not resolve symlinks,
+// so a link inside the workspaces root pointing anywhere else passed the guard
+// and the lock file was created in the target — a user's directory, or any
+// path outside the root entirely.
+func TestLockReusablePriorEnvRootNeverWritesOutsideWorkspacesRoot(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ name string
+ // build returns the PriorWorkDir to offer, plus the directory tree that
+ // must come back untouched.
+ build func(t *testing.T, workspacesRoot, outside string) string
+ }{
+ {
+ name: "symlink inside the root pointing outside it",
+ build: func(t *testing.T, workspacesRoot, outside string) string {
+ target := filepath.Join(outside, "someone-elses-repo")
+ if err := os.MkdirAll(filepath.Join(target, "workdir"), 0o755); err != nil {
+ t.Fatalf("seed target: %v", err)
+ }
+ link := filepath.Join(workspacesRoot, "ws-1", "escape")
+ if err := os.MkdirAll(filepath.Dir(link), 0o755); err != nil {
+ t.Fatalf("seed link parent: %v", err)
+ }
+ if err := os.Symlink(target, link); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ return filepath.Join(link, "workdir")
+ },
+ },
+ {
+ name: "plain path outside the root",
+ build: func(t *testing.T, workspacesRoot, outside string) string {
+ dir := filepath.Join(outside, "local-project", "workdir")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ return dir
+ },
+ },
+ {
+ name: "managed-looking shape but no provenance",
+ build: func(t *testing.T, workspacesRoot, outside string) string {
+ dir := filepath.Join(workspacesRoot, "ws-1", "0123456789ab", "workdir")
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+ return dir
+ },
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ t.Parallel()
+ base := t.TempDir()
+ workspacesRoot := filepath.Join(base, "workspaces")
+ outside := filepath.Join(base, "outside")
+ if err := os.MkdirAll(workspacesRoot, 0o755); err != nil {
+ t.Fatalf("seed root: %v", err)
+ }
+ if err := os.MkdirAll(outside, 0o755); err != nil {
+ t.Fatalf("seed outside: %v", err)
+ }
+
+ priorWorkDir := tc.build(t, workspacesRoot, outside)
+ d := &Daemon{logger: discardLogger()}
+ d.cfg.WorkspacesRoot = workspacesRoot
+
+ claim, _, _, ok := d.lockReusablePriorEnvRoot(Task{
+ ID: "01a01ec0-e69d-7000-8000-0123456789ab",
+ WorkspaceID: "ws-1",
+ AgentID: "agent-1",
+ IssueID: "issue-1",
+ PriorWorkDir: priorWorkDir,
+ }, nil, "")
+ if ok {
+ claim.Release()
+ t.Fatal("unvalidated prior workdir was accepted for reuse")
+ }
+ if claim != nil {
+ claim.Release()
+ t.Fatal("declined reuse still returned a claim")
+ }
+ if found := findTaskLocks(t, outside); len(found) > 0 {
+ t.Fatalf("prior-workdir guard wrote the lock outside workspaces root: %v", found)
+ }
+ })
+ }
+}
+
+// findTaskLocks returns every .task_lock under dir.
+func findTaskLocks(t *testing.T, dir string) []string {
+ t.Helper()
+ var found []string
+ err := filepath.WalkDir(dir, func(path string, e fs.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ if !e.IsDir() && e.Name() == ".task_lock" {
+ found = append(found, path)
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("walk %s: %v", dir, err)
+ }
+ return found
+}
+
+func discardLogger() *slog.Logger {
+ return slog.New(slog.NewTextHandler(io.Discard, nil))
+}
+
+// TestLockReusablePriorEnvRootLocksAValidatedRoot is the positive half: a fully
+// provenanced managed workdir IS accepted, the lock lands inside the workspaces
+// root, and a second continuation of the same task is excluded from it while
+// the first holds it. Declining is then correct rather than fatal — the caller
+// falls back to a fresh Prepare.
+func TestLockReusablePriorEnvRootLocksAValidatedRoot(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()}
+ d.cfg.WorkspacesRoot = root
+
+ claim, canonical, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")
+ if !ok {
+ t.Fatal("a fully provenanced managed workdir was refused for reuse")
+ }
+ if claim == nil {
+ t.Fatal("accepted reuse without taking the lock")
+ }
+ if canonical == "" {
+ t.Fatal("accepted reuse without returning the canonical workdir")
+ }
+ // The lock must be inside the env root we validated, and nowhere else.
+ // Compare resolved paths: canonical comes back through EvalSymlinks, and on
+ // macOS the temp root itself is a symlink (/tmp -> /private/tmp).
+ locks := findTaskLocks(t, root)
+ if len(locks) != 1 {
+ t.Fatalf("found %v .task_lock files, want exactly one", locks)
+ }
+ gotDir, err := filepath.EvalSymlinks(filepath.Dir(locks[0]))
+ if err != nil {
+ t.Fatalf("resolve lock dir: %v", err)
+ }
+ if wantDir := filepath.Dir(canonical); gotDir != wantDir {
+ t.Fatalf("lock landed in %s, want %s", gotDir, wantDir)
+ }
+
+ // A concurrent continuation of the same task must not get the same root.
+ if second, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, ""); ok {
+ second.Release()
+ t.Fatal("two continuations locked the same prior workdir at once")
+ }
+
+ claim.Release()
+ again, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")
+ if !ok {
+ t.Fatal("prior workdir stayed locked after release")
+ }
+ again.Release()
+}
+
+// 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
+// validated env root can be renamed away and a symlink to somewhere outside
+// dropped in its place; an ordinary open follows it and creates .task_lock out
+// there, and no later re-check can undo a write that already happened.
+//
+// The swap is made deterministic with reuseLockTestHook rather than raced.
+func TestLockReusablePriorEnvRootSurvivesRetargetAfterValidation(t *testing.T) {
+ base := t.TempDir()
+ root := filepath.Join(base, "workspaces")
+ outside := filepath.Join(base, "outside")
+ if err := os.MkdirAll(outside, 0o755); err != nil {
+ t.Fatalf("seed outside: %v", err)
+ }
+
+ workDir := filepath.Join(root, "ws-leader", "0123456789ab", "workdir")
+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")
+ envRoot := filepath.Dir(workDir)
+
+ task := leaderReuseTestTask("task-retarget")
+ task.PriorWorkDir = workDir
+
+ d := &Daemon{logger: discardLogger()}
+ d.cfg.WorkspacesRoot = root
+
+ // Validation has already passed by the time this runs.
+ reuseLockTestHook = func() {
+ if err := os.Rename(envRoot, envRoot+"-moved"); err != nil {
+ t.Fatalf("retarget rename: %v", err)
+ }
+ if err := os.Symlink(outside, envRoot); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ }
+ t.Cleanup(func() { reuseLockTestHook = nil })
+
+ claim, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")
+ if claim != nil {
+ claim.Release()
+ }
+ if ok {
+ t.Fatal("reuse was accepted after the validated root was retargeted")
+ }
+ if locks := findTaskLocks(t, outside); len(locks) > 0 {
+ t.Fatalf("validated canonical root was retargeted and the lock was written outside: %v", locks)
+ }
+}
+
+// TestLockReusablePriorEnvRootRejectsIdentitySwap is the other half, and the
+// reason comparing canonical path STRINGS is not sufficient. Here the
+// validated root is moved aside and a brand new, equally well-provenanced
+// directory is created at exactly the same path. Every name-based check still
+// agrees — the canonical path is character-for-character what validation
+// returned — but it is a different directory. Accepting it would leave the
+// daemon holding a lock on the old inode while Reuse ran in the new one, i.e.
+// unprotected in a directory another execution may own. Only comparing
+// identity (os.SameFile) can tell them apart.
+func TestLockReusablePriorEnvRootRejectsIdentitySwap(t *testing.T) {
+ root := t.TempDir()
+
+ workDir := filepath.Join(root, "ws-leader", "aaaa56789abc", "workdir")
+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")
+ envRoot := filepath.Dir(workDir)
+
+ task := leaderReuseTestTask("task-swap")
+ task.PriorWorkDir = workDir
+
+ d := &Daemon{logger: discardLogger()}
+ d.cfg.WorkspacesRoot = root
+
+ // After validation, swap in a different directory at the SAME path, just
+ // as legitimate: same workspace, agent and issue.
+ reuseLockTestHook = func() {
+ if err := os.Rename(envRoot, envRoot+"-moved"); err != nil {
+ t.Fatalf("move the validated root aside: %v", err)
+ }
+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")
+ }
+ t.Cleanup(func() { reuseLockTestHook = nil })
+
+ claim, used, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")
+ if claim != nil {
+ claim.Release()
+ }
+ if ok {
+ t.Fatalf("accepted reuse after the validated directory was replaced at the same path (would use %s)", used)
+ }
+}
+
+// sameDir reports whether two paths name the same directory, independent of
+// how they spell it.
+func sameDir(t *testing.T, a, b string) bool {
+ t.Helper()
+ ai, err := os.Stat(a)
+ if err != nil {
+ return false
+ }
+ bi, err := os.Stat(b)
+ if err != nil {
+ return false
+ }
+ return os.SameFile(ai, bi)
+}
+
+// TestLockReusablePriorEnvRootSurvivesWorkspacesRootSwap covers the subtler
+// half of the pinning problem. os.Root guarantees you cannot escape the tree
+// it opened — it does not guarantee it opened the tree you meant. Opening the
+// workspaces root from a name AFTER validation would let the whole root be
+// renamed aside and a symlink to a look-alike tree left behind: Root then
+// faithfully pins the replacement, and the lock file is created out there.
+//
+// Pinning the root before any validation runs is what makes that ordering
+// impossible.
+func execenvLockForTest(wsRoot *os.Root, rel, envRoot string) (*execenv.EnvRootClaim, os.FileInfo, error) {
+ return execenv.LockEnvRootForReuse(wsRoot, rel, envRoot)
+}
+
+func TestLockReusablePriorEnvRootSurvivesWorkspacesRootSwap(t *testing.T) {
+ base := t.TempDir()
+ root := filepath.Join(base, "workspaces")
+ outside := filepath.Join(base, "outside")
+
+ workDir := filepath.Join(root, "ws-leader", "0123456789ab", "workdir")
+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")
+
+ // A look-alike tree with the same relative shape, outside the root.
+ decoy := filepath.Join(outside, "ws-leader", "0123456789ab")
+ if err := os.MkdirAll(decoy, 0o755); err != nil {
+ t.Fatalf("seed decoy: %v", err)
+ }
+
+ task := leaderReuseTestTask("task-rootswap")
+ task.PriorWorkDir = workDir
+
+ d := &Daemon{logger: discardLogger()}
+ d.cfg.WorkspacesRoot = root
+
+ reuseLockTestHook = func() {
+ if err := os.Rename(root, root+"-moved"); err != nil {
+ t.Fatalf("move the workspaces root aside: %v", err)
+ }
+ if err := os.Symlink(outside, root); err != nil {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ }
+ t.Cleanup(func() { reuseLockTestHook = nil })
+
+ claim, _, _, ok := d.lockReusablePriorEnvRoot(task, nil, "")
+ if claim != nil {
+ claim.Release()
+ }
+ if ok {
+ t.Fatal("reuse was accepted after the workspaces root itself was replaced")
+ }
+ if locks := findTaskLocks(t, outside); len(locks) > 0 {
+ t.Fatalf("OpenRoot pinned the replacement tree and wrote the lock outside: %v", locks)
+ }
+}
+
+// TestLockEnvRootForReuseTakesIdentityAndLockFromOneHandle pins that the
+// directory whose identity is reported and the directory the lock file lands
+// in are the same one. Resolving the env root's relative path twice from the
+// workspaces Root — once to stat, once to create — would let it be A on the
+// first resolution and B on the second, reporting A's identity while holding
+// B's lock. Both now come from a single sub-Root pinned on the env root.
+func TestLockEnvRootForReuseTakesIdentityAndLockFromOneHandle(t *testing.T) {
+ t.Parallel()
+ root := t.TempDir()
+ rel := filepath.Join("ws-leader", "0123456789ab")
+ envRoot := filepath.Join(root, rel)
+ if err := os.MkdirAll(envRoot, 0o755); err != nil {
+ t.Fatalf("seed: %v", err)
+ }
+
+ wsRoot, err := os.OpenRoot(root)
+ if err != nil {
+ t.Fatalf("open workspaces root: %v", err)
+ }
+ defer wsRoot.Close()
+
+ claim, info, err := execenvLockForTest(wsRoot, rel, envRoot)
+ if err != nil {
+ t.Fatalf("lock: %v", err)
+ }
+ if claim == nil || info == nil {
+ t.Fatal("expected a claim and the locked directory identity")
+ }
+ defer claim.Release()
+
+ // The reported identity must be the directory the lock file is actually in.
+ lockDirInfo, err := os.Stat(filepath.Dir(findTaskLocks(t, root)[0]))
+ if err != nil {
+ t.Fatalf("stat lock dir: %v", err)
+ }
+ if !os.SameFile(info, lockDirInfo) {
+ t.Fatal("reported identity is not the directory holding the lock file")
+ }
+}
+
+// TestRunTaskDeclinesReuseWhenTheClaimedDirectoryIsSwappedBeforeUse covers the
+// last window: the claim is settled, and only THEN does Reuse resolve the
+// prior workdir by name. A file descriptor cannot cross into the preparation
+// helper process, so a name is the only thing that can be handed over — which
+// means this window cannot be closed by pinning alone. What it can be is
+// detected: the environment Reuse produced is checked back against the
+// directory the lock is held on, so a substitution ends the run in a fresh
+// environment instead of executing in a directory nothing holds.
+func TestRunTaskDeclinesReuseWhenTheClaimedDirectoryIsSwappedBeforeUse(t *testing.T) {
+ d, argsFile, cleanup := newLeaderReuseTestDaemon(t)
+ defer cleanup()
+ _ = argsFile
+
+ first := leaderReuseTestTask("task-first")
+ firstResult, err := d.runTask(context.Background(), first, "claude", 0, d.logger)
+ if err != nil {
+ t.Fatalf("first runTask: %v", err)
+ }
+ envRoot := filepath.Dir(firstResult.WorkDir)
+
+ // Swap the claimed directory for an equally valid one after the claim is
+ // settled and before Reuse opens it by name.
+ var swapped bool
+ reuseBeforeUseTestHook = func() {
+ if swapped {
+ return
+ }
+ swapped = true
+ // The replacement must be one Reuse would happily accept, or the test
+ // passes because Reuse declined on its own merits rather than because
+ // the identity check caught the substitution.
+ replacement := envRoot + "-replacement"
+ replacementWorkDir := filepath.Join(replacement, "workdir")
+ writeLeaderTaskMarker(t, replacementWorkDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, replacementWorkDir, "ws-leader", "issue-leader", "agent-leader")
+ if err := os.Rename(envRoot, envRoot+"-moved"); err != nil {
+ t.Fatalf("move claimed dir aside: %v", err)
+ }
+ if err := os.Rename(replacement, envRoot); err != nil {
+ t.Fatalf("install replacement: %v", err)
+ }
+ }
+ t.Cleanup(func() { reuseBeforeUseTestHook = nil })
+
+ second := leaderReuseTestTask("task-second")
+ second.PriorSessionID = firstResult.SessionID
+ second.PriorWorkDir = firstResult.WorkDir
+ secondResult, err := d.runTask(context.Background(), second, "claude", 0, d.logger)
+ if err != nil {
+ t.Fatalf("second runTask: %v", err)
+ }
+ if !swapped {
+ t.Fatal("the swap hook never ran; the test proved nothing")
+ }
+ // envRoot's NAME now resolves to the replacement, so a run that reused it
+ // lands there. Compare the env root the second task actually ran in.
+ if sameDir(t, filepath.Dir(secondResult.WorkDir), envRoot) {
+ t.Fatal("ran in the substituted directory instead of declining to a fresh environment")
+ }
+ if secondResult.WorkDir == "" {
+ t.Fatal("second task produced no environment at all")
+ }
+}