Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6518 fix(daemon): reclaim orphaned per-task temp dirs in the GC (#7391)
Bohan Jiang520359a2c9aa
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex cd63251df9..44c3d6e8fd 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -715,6 +715,20 @@ jobs:go test ./internal/daemon/execenv -v -run '^(TestSeedUserCodexSkills|TestHydrateCodexSkills)' -count=1 -timeout=5mgo test ./internal/daemon -v -run '^(TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction|TestTaskSize_DoesNotCountDirectoryJunction)$' -count=1 -timeout=5m+ - name: Test Windows task temp dir sweep survives a sharing violation+ if: ${{ needs.changes.outputs.backend == 'true' }}+ working-directory: server+ # The GC's task temp sweep has to cope with a file it cannot delete: a+ # leftover child process holding one open is what left 174 directories+ # behind in #7364. Only a real Windows filesystem produces that sharing+ # violation — on unix an open file unlinks fine — so this is the only+ # place we can prove the two things that matter: the failed cleanup+ # keeps .task_lock (without it the directory reads as a pre-lock+ # leftover and stops being reclaimable on liveness), and the next cycle+ # removes the directory once the handle closes.+ # -v so a skip is visible instead of passing silently as "ok".+ run: go test ./internal/daemon/execenv -v -run '^TestPruneTaskTempDirsSurvivesRealSharingViolation$' -count=1 -timeout=5m+- name: Test Windows agent executable junction resolutionif: ${{ needs.changes.outputs.backend == 'true' }}working-directory: serverdiff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 2b9e8c9676..daaf075562 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -266,6 +266,7 @@ Daemon behavior is configured via flags or environment variables:| GC repo maintenance | — | `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` (set `false`/`0` to disable heavy Git maintenance only) || GC Hermes memory TTL (per-agent `memories/`) | — | `MULTICA_GC_HERMES_MEMORY_TTL` | `2160h` (90d; set `0` to disable) || GC Hermes session TTL (per-conversation `state.db`) | — | `MULTICA_GC_HERMES_SESSION_TTL` | `336h` (14d; set `0` to disable) |+| GC task temp legacy TTL (pre-lock `multica-task-*`) | — | `MULTICA_GC_TASK_TEMP_LEGACY_TTL` | `0` (disabled; set a duration to opt in) |#### Workspace garbage collection@@ -285,6 +286,7 @@ The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and applies several disk- **Hermes session store reclamation** — a conversation's Hermes transcript (`state.db`) lives at `<profile dir>/hermes-sessions/<agent-id>/<hermes-profile>/<conversation>/`, outside any task directory, so a follow-up turn can resume it (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_SESSION_TTL` is removed. The default matches the Codex session store rather than the memory store above: these hold full transcripts, and reclaiming an idle one costs a thread that starts fresh (with a continuity notice), not an agent that forgot what it learned. A store a running task holds is never reclaimed.- **Hermes memory store reclamation** — a Hermes agent's long-term memory (`memories/`) lives at `<profile dir>/hermes-state/<agent-id>/<hermes-profile>/`, outside any task directory, so it survives across tasks and issues (see [Hermes agent memory](#hermes-agent-memory)). A store untouched for `MULTICA_GC_HERMES_MEMORY_TTL` is removed, giving a deleted agent's memory an eventual-reclamation guarantee. The default is deliberately long: these are a handful of markdown files, and reclaiming one is user-visible amnesia rather than a cache miss. A store a running task holds is never reclaimed.+- **Task temp dir reclamation** — every task gets a private temp directory (`multica-task-*`) under the system temp base (`/tmp`, or `MULTICA_AGENT_TEMP_BASE`), exported to the agent as `TMPDIR`/`TMP`/`TEMP`. It is removed when the run ends, but that removal never happens when the daemon is killed and does not succeed while a file inside is still open — common on Windows, where an open handle makes the delete fail outright. These directories live outside `MULTICA_WORKSPACES_ROOT`, so nothing else reclaimed them and whatever the end-of-run removal missed accumulated forever. Every GC cycle now sweeps the temp base. Liveness is decided by the directory's `.task_lock` — the same OS advisory lock an env root uses, which the kernel releases when the holding process dies — not by age: a directory still in use is never removed however old it is, including one owned by a different daemon sharing the same temp base, and a directory whose owner is gone is removed on the next cycle however new it is. Directories left by a daemon predating that lock carry no lock file, so nothing can be proven about them and age is the only signal available. Reclaiming those is an operator's explicit decision: `MULTICA_GC_TASK_TEMP_LEGACY_TTL` defaults to `0`, which leaves them in place. Set it to a duration only once you know no pre-lock daemon is still running tasks on this machine — a task may legitimately run for weeks (there is no default agent timeout), a daemon on another profile can still be on the old binary, and every daemon on the machine shares one temp base, so a TTL here can delete a `TMPDIR` that is still in use. Each GC cycle logs how many such directories it left alone. Even with a TTL set, a directory holding no task content is never reclaimed on age — an old empty leftover, or a shell left by a daemon that died between creating the directory and publishing its lock — because holding no content is exactly what a directory currently being published looks like, and deleting one of those would take the `TMPDIR` of a task that is starting. Those shells are a few bytes each. Only entries carrying the `multica-task-` prefix are ever considered — the temp base itself is usually shared with other programs — and a directory this sweep cannot read is never touched.Configured patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The managed Codex cache is matched by its exact relative path, so a repository's own `.sandbox-bin` is not removed unless an operator explicitly adds that basename to `MULTICA_GC_ARTIFACT_PATTERNS`. The default list (`node_modules`, `.next`, `.turbo`) is intentionally narrow; extend it per deployment if your repos consistently produce other regenerable directories (for example, `MULTICA_GC_ARTIFACT_PATTERNS=node_modules,.next,.turbo,target,__pycache__`). To disable artifact cleanup entirely, including the managed Codex cache, set `MULTICA_GC_ARTIFACT_TTL=0`.diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex fe33ab6e61..707bbd726a 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -76,7 +76,16 @@ const (DefaultGCHermesMemoryTTL = 90 * 24 * time.Hour // 90 days — reclaim per-agent Hermes memory stores untouched this long (long: reclaiming these is visible amnesia, and they are a few markdown files)DefaultGCHermesSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-conversation Hermes session stores untouched this long (matches Codex: these hold transcripts, and losing an idle one restarts the thread rather than the agent's notes)DefaultGCRepoTTL = 30 * 24 * time.Hour // 30 days — evict a bare repo cache no task has checked out this long- DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release+ // DefaultGCTaskTempLegacyTTL is 0 — disabled. Per-task temp dirs left by a+ // daemon predating the temp dir execution lock carry no liveness signal at+ // all, and age cannot supply one: a task may legitimately run for weeks+ // (DefaultAgentTimeout is 0), a pre-lock daemon on another profile can+ // still be running one, and every daemon on the machine shares the temp+ // base. Reclaiming those is therefore an operator's explicit call, made+ // when no pre-lock daemon is running here. Dirs that DO carry the lock are+ // reclaimed on liveness and never touch this knob.+ DefaultGCTaskTempLegacyTTL = time.Duration(0)+ DefaultAutoUpdateCheckInterval = 6 * time.Hour // how often the daemon polls GitHub for a newer CLI release)// DefaultGCArtifactPatterns lists basename matches that the GC loop treats as@@ -114,6 +123,7 @@ type Config struct {GCCodexSessionTTL time.Duration // reclaim a per-issue Codex session store (~/.codex/multica-sessions/<agent>/<issue>) untouched for at least this long, so a done/abandoned issue's conversation history does not accumulate forever (default: 14d, set 0 to disable)GCHermesMemoryTTL time.Duration // reclaim a per-agent Hermes memory store (<profile dir>/hermes-state/<agent>/<profile>) untouched for at least this long, so a deleted agent's memory does not sit on disk forever (default: 90d, set 0 to disable)GCHermesSessionTTL time.Duration // reclaim a per-conversation Hermes session store (<profile dir>/hermes-sessions/<agent>/<profile>/<conversation>) untouched for at least this long, so a done or abandoned conversation's transcript does not accumulate forever (default: 14d, set 0 to disable)+ GCTaskTempLegacyTTL time.Duration // reclaim a per-task temp dir (<temp base>/multica-task-*) that carries no execution lock — i.e. left by a daemon predating the lock — once nothing inside it has been touched for this long. Dirs that DO carry the lock are reclaimed on liveness, never on age, so this knob does not apply to them. Neither does it reclaim a dir holding no task content — an old empty leftover, or a shell left by a daemon that died between creating the dir and publishing its lock — because holding no content is exactly what a dir currently being published looks like (default: 0, disabled — see DefaultGCTaskTempLegacyTTL)AutoUpdateEnabled bool // periodically check for a newer CLI release and self-update when idle (default: true on Multica Cloud, false on self-host)AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)AutoReloadEnabled bool // restart when the multica binary on disk no longer matches the running version (default: true for CLI-launched daemons)@@ -471,6 +481,10 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcTaskTempLegacyTTL, err := durationFromEnv("MULTICA_GC_TASK_TEMP_LEGACY_TTL", DefaultGCTaskTempLegacyTTL)+ if err != nil {+ return Config{}, err+ }gcHermesMemoryTTL, err := durationFromEnv("MULTICA_GC_HERMES_MEMORY_TTL", DefaultGCHermesMemoryTTL)if err != nil {return Config{}, err@@ -540,6 +554,7 @@ func LoadConfig(overrides Overrides) (Config, error) {GCCodexSessionTTL: gcCodexSessionTTL,GCHermesMemoryTTL: gcHermesMemoryTTL,GCHermesSessionTTL: gcHermesSessionTTL,+ GCTaskTempLegacyTTL: gcTaskTempLegacyTTL,AutoUpdateEnabled: autoUpdateEnabled,AutoUpdateCheckInterval: autoUpdateInterval,AutoReloadEnabled: autoReloadEnabled,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 4ab851d6a1..afcac82848 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -7158,12 +7158,23 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}}()}- taskTempDir, err := ensureTaskTempDir(env.RootDir, task.WorkspaceID, task.ID)+ taskTempDir, taskTempLock, err := ensureTaskTempDir(env.RootDir, task.WorkspaceID, task.ID)if err != nil {return TaskResult{}, fmt.Errorf("prepare task temp dir: %w", err)}defer func() {- if cerr := os.RemoveAll(taskTempDir); cerr != nil {+ // Drop the execution lock before removing the directory: while it is+ // held the GC sweep correctly refuses to touch this directory, so a+ // removal that fails here (a file inside still open — the Windows case+ // in #7364) would otherwise leave the directory pinned until the daemon+ // exits. Released first, the next GC cycle acquires the lock, sees the+ // owner is gone and reclaims it. Nothing waits on the task path.+ //+ // RemoveTaskTempDir rather than os.RemoveAll so that a cleanup which+ // fails here leaves the .task_lock marker intact — without it the next+ // sweep could not tell this directory from a pre-lock leftover.+ execenv.ReleaseTaskTempLock(taskTempLock)+ if cerr := execenv.RemoveTaskTempDir(taskTempDir); cerr != nil {taskLog.Warn("task temp dir cleanup failed", "path", taskTempDir, "error", cerr)}}()@@ -8747,34 +8758,44 @@ func composeOpenclawIncludeRoots(addRoot, userValue string) (string, bool) {return strings.Join(parts, string(os.PathListSeparator)), true}-func ensureTaskTempDir(envRoot string, workspaceID string, taskID string) (string, error) {+// ensureTaskTempDir creates this task's private temp directory and returns it+// with its execution lock held. The caller owns the lock for the lifetime of+// the run and must release it before removing the directory — see the cleanup+// defer in runTask, and execenv.PruneTaskTempDirs for what the lock buys.+func ensureTaskTempDir(envRoot string, workspaceID string, taskID string) (string, *os.File, error) {envRoot = strings.TrimSpace(envRoot)if envRoot == "" {- return "", errors.New("env root is empty")+ return "", nil, errors.New("env root is empty")}workspaceID = strings.TrimSpace(workspaceID)if workspaceID == "" {- return "", errors.New("workspace id is empty")+ return "", nil, errors.New("workspace id is empty")}taskID = strings.TrimSpace(taskID)if taskID == "" {- return "", errors.New("task id is empty")+ return "", nil, errors.New("task id is empty")}base, overrideConfigured, err := taskTempBaseDir()if err != nil {- return "", err+ return "", nil, err}- dir, err := os.MkdirTemp(base, "multica-task-")+ dir, err := os.MkdirTemp(base, execenv.TaskTempDirPrefix)if err != nil {if overrideConfigured {- return "", fmt.Errorf("MULTICA_AGENT_TEMP_BASE: create task temp dir: %w", err)+ return "", nil, fmt.Errorf("MULTICA_AGENT_TEMP_BASE: create task temp dir: %w", err)}- return "", err+ return "", nil, err}if err := os.Chmod(dir, 0o700); err != nil {- return "", err+ _ = os.RemoveAll(dir)+ return "", nil, err+ }+ lock, err := execenv.LockTaskTempDir(dir)+ if err != nil {+ _ = os.RemoveAll(dir)+ return "", nil, err}- return dir, nil+ return dir, lock, nil}// taskTempBaseDir resolves the parent directory for private per-task tempdiff --git a/server/internal/daemon/execenv/codex_home.go b/server/internal/daemon/execenv/codex_home.goindex b8a19d47e8..a5ed3948f4 100644--- a/server/internal/daemon/execenv/codex_home.go+++ b/server/internal/daemon/execenv/codex_home.go@@ -480,7 +480,7 @@ func PruneCodexSessionStores(profile string, retention time.Duration, now time.Tcontinue}storeDir := filepath.Join(agentDir, is.Name())- newest, size := codexStoreStat(storeDir)+ newest, size := dirStat(storeDir)if newest.IsZero() || now.Sub(newest) <= retention {kept++continue@@ -518,9 +518,10 @@ func PruneCodexSessionStores(profile string, retention time.Duration, now time.Treturn removed, bytesFreed}-// codexStoreStat walks dir once, returning the newest modification time seen-// (the store's last activity) and its total byte size (for GC accounting).-func codexStoreStat(dir string) (newest time.Time, size int64) {+// dirStat walks dir once, returning the newest modification time seen (the+// directory's last activity) and its total byte size (for GC accounting).+// Shared by the store pruners and the task temp sweep.+func dirStat(dir string) (newest time.Time, size int64) {_ = filepath.WalkDir(dir, func(_ string, d os.DirEntry, err error) error {if err != nil {return nil@@ -665,7 +666,7 @@ func linkCodexSessionsToStore(dst, storeDir, sharedSessions, resumeID string, lo}// touchCodexSessionStore refreshes storeDir's modification time to now — the-// signal codexStoreStat reads as the store's last activity. Best-effort: a+// signal dirStat reads as the store's last activity. Best-effort: a// failed touch only risks an over-eager prune, which the active-store guard// still prevents.func touchCodexSessionStore(storeDir string, logger *slog.Logger) {diff --git a/server/internal/daemon/execenv/envlock_unix.go b/server/internal/daemon/execenv/envlock_unix.goindex 25091f24e1..d044a0973a 100644--- a/server/internal/daemon/execenv/envlock_unix.go+++ b/server/internal/daemon/execenv/envlock_unix.go@@ -15,7 +15,7 @@ import (// 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) {+func openLockFile(path string) (*os.File, error) {return os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o644)}diff --git a/server/internal/daemon/execenv/envlock_windows.go b/server/internal/daemon/execenv/envlock_windows.goindex 68c2af2e46..b085e27c39 100644--- a/server/internal/daemon/execenv/envlock_windows.go+++ b/server/internal/daemon/execenv/envlock_windows.go@@ -15,7 +15,7 @@ import (// 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+// openLockFile 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@@ -23,7 +23,7 @@ import (// 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) {+func openLockFile(path string) (*os.File, error) {p, err := windows.UTF16PtrFromString(path)if err != nil {return nil, errdiff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex edac666351..942e26eeac 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -394,7 +394,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {lockClaimed = truedefer func() {if lockClaimed {- releaseEnvRootLock(lockFile)+ releaseLockFile(lockFile)}}()// reset means this task already owned the directory and the execution@@ -1186,7 +1186,7 @@ func (c *EnvRootClaim) Release() {if c == nil || c.lock == nil {return}- releaseEnvRootLock(c.lock)+ releaseLockFile(c.lock)c.lock = nil}@@ -1208,7 +1208,7 @@ func ClaimEnvRoot(workspacesRoot, workspaceID, taskID string) (*EnvRootClaim, er}if reset {if err := resetEnvRootContents(envRoot); err != nil {- releaseEnvRootLock(lock)+ releaseLockFile(lock)return nil, fmt.Errorf("execenv: reset existing env: %w", err)}}@@ -1324,7 +1324,7 @@ func claimEnvRoot(envRoot, taskID string) (lockFile *os.File, reset bool, err erreturn nil, false, fmt.Errorf("create env root %s: %w", envRoot, err)}- lockFile, err = openEnvRootLockFile(filepath.Join(envRoot, envRootLockFile))+ lockFile, err = openLockFile(filepath.Join(envRoot, envRootLockFile))if err != nil {return nil, false, fmt.Errorf("open env root lock for %s: %w", envRoot, err)}@@ -1341,7 +1341,7 @@ func claimEnvRoot(envRoot, taskID string) (lockFile *os.File, reset bool, err er// process or any other, so the checks below cannot race.defer func() {if err != nil {- releaseEnvRootLock(lockFile)+ releaseLockFile(lockFile)lockFile = nil}}()@@ -1385,12 +1385,12 @@ func (env *Environment) ReleaseLock() {if env == nil || env.lockFile == nil {return}- releaseEnvRootLock(env.lockFile)+ releaseLockFile(env.lockFile)env.lockFile = nil}-// releaseEnvRootLock drops the execution lock and closes the file. Safe on nil.-func releaseEnvRootLock(f *os.File) {+// releaseLockFile drops the execution lock and closes the file. Safe on nil.+func releaseLockFile(f *os.File) {if f == nil {return}diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 54fae3b1b8..4bc2b3d302 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -6463,7 +6463,7 @@ func TestClaimEnvRootAdoptsEmptyDirectory(t *testing.T) {if err != nil {t.Fatalf("claimEnvRoot on an empty directory: %v", err)}- defer releaseEnvRootLock(lock)+ defer releaseLockFile(lock)if reset {t.Fatal("adopting an empty directory should not ask for a reset")}@@ -6582,7 +6582,7 @@ func TestClaimEnvRootRepairsTornOwnerMarker(t *testing.T) {if err != nil {t.Fatalf("claimEnvRoot wedged on a torn marker: %v", err)}- defer releaseEnvRootLock(lock)+ defer releaseLockFile(lock)if owner, _ := readEnvRootOwner(envRoot); owner != id {t.Fatalf("owner = %q, want the repairing task %q", owner, id)}diff --git a/server/internal/daemon/execenv/task_temp.go b/server/internal/daemon/execenv/task_temp.gonew file mode 100644index 0000000000..75d1055aba--- /dev/null+++ b/server/internal/daemon/execenv/task_temp.go@@ -0,0 +1,332 @@+package execenv++import (+ "errors"+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "time"+)++// TaskTempDirPrefix is the basename prefix os.MkdirTemp stamps on every+// per-task temp directory the daemon creates under the task temp base. The+// sweep below removes nothing without it, so the base itself — usually a+// shared /tmp holding other programs' files — is never at risk.+const TaskTempDirPrefix = "multica-task-"++// taskTempLockClaimFile is the name the marker is locked under before being+// renamed into place, so .task_lock never exists unlocked while its owner is+// still starting up.+const taskTempLockClaimFile = envRootLockFile + ".claiming"++// LockTaskTempDir takes the temp directory's execution lock and returns the+// held file; the caller owns it for the lifetime of the task run.+//+// This is the same .task_lock an env root uses, for the same reason: the+// kernel releases it when the holding process dies, so it answers "is the+// execution that owns this directory still alive?" across processes without a+// heartbeat, a PID table, or a stale-state cleanup path. That is what lets+// PruneTaskTempDirs reclaim a directory the moment its owner is gone while+// never touching one that is still in use — including a directory owned by a+// different daemon sharing the same temp base, which no in-memory active set+// could ever see, and including a live task in this very process, because a+// lock is held by an open file description rather than by a process.+func LockTaskTempDir(dir string) (*os.File, error) {+ // Lock the marker under a name the sweep does not read, then publish it+ // with a rename. Creating .task_lock first and locking it second would+ // leave a window — however short — in which a concurrent sweep sees a+ // marker it can lock, concludes the owner is dead, and deletes the+ // directory out from under a task that is about to start using it. Rename+ // within one directory is atomic, and the lock rides on the open file+ // description rather than the name, so the marker becomes visible and+ // held in the same step.+ //+ // Before that rename the directory carries no published marker, so the+ // sweep can only reach it through the legacy branch. What keeps it safe+ // there is not its age — legacyTTL takes any duration, down to a+ // nanosecond, and a stalled owner can outlast any TTL — but the fact that+ // it holds no task content yet. The legacy branch reclaims only+ // directories that do; see taskTempDirHoldsContent.+ claim := filepath.Join(dir, taskTempLockClaimFile)+ lock, err := openLockFile(claim)+ if err != nil {+ return nil, fmt.Errorf("open task temp dir lock for %s: %w", dir, err)+ }+ locked, err := lockFileExclusiveNonBlocking(lock)+ if err != nil {+ lock.Close()+ _ = os.Remove(claim)+ return nil, fmt.Errorf("lock task temp dir %s: %w", dir, err)+ }+ if !locked {+ // Unreachable in practice: the directory was just created by+ // os.MkdirTemp under a name nobody else knows yet.+ lock.Close()+ _ = os.Remove(claim)+ return nil, fmt.Errorf("task temp dir %s is already locked", dir)+ }+ if err := os.Rename(claim, filepath.Join(dir, envRootLockFile)); err != nil {+ releaseLockFile(lock)+ _ = os.Remove(claim)+ return nil, fmt.Errorf("publish task temp dir lock for %s: %w", dir, err)+ }+ return lock, nil+}++// ReleaseTaskTempLock drops the temp directory's execution lock and closes the+// file. Safe on nil and safe to call twice.+func ReleaseTaskTempLock(f *os.File) {+ releaseLockFile(f)+}++// RemoveTaskTempDir removes dir's contents first, then its lock marker, then+// dir itself — and stops at the first content it cannot remove, leaving the+// marker behind.+//+// That ordering is the whole point, and it is why this is not os.RemoveAll.+// RemoveAll walks the directory and keeps going after a failure, so a payload+// Windows will not let go of still costs the .task_lock sitting next to it:+// the removal fails having deleted exactly the file the NEXT sweep needs to+// recognise this directory as a lock-bearing one. It would come back as a+// directory with no marker — indistinguishable from a pre-lock leftover, and+// so reclaimable only on age, if at all.+//+// Leaving the marker means a failed cleanup costs nothing: the directory is+// still lock-bearing, still unlocked, and the next GC cycle takes the lock and+// retries, however many cycles it takes for the holder to let go.+//+// That holds for every way this can fail, not just the content walk. The+// marker has to be gone before the directory itself can be removed, so when+// that last removal fails the marker is put back — otherwise the one case+// where cleanup gets furthest would be the one case that leaks permanently.+//+// Callers must release their own lock before calling this — the marker is+// deleted here, and on Windows removing a file this process still holds open+// only marks it for deletion, which would then block the directory's removal.+func RemoveTaskTempDir(dir string) error {+ entries, err := os.ReadDir(dir)+ if err != nil {+ if errors.Is(err, os.ErrNotExist) {+ return nil+ }+ return err+ }+ for _, e := range entries {+ if e.Name() == envRootLockFile {+ continue // last, and only once everything else is gone+ }+ if err := os.RemoveAll(filepath.Join(dir, e.Name())); err != nil {+ return err+ }+ }+ lockPath := filepath.Join(dir, envRootLockFile)+ if err := os.Remove(lockPath); err != nil && !errors.Is(err, os.ErrNotExist) {+ return err+ }+ if err := os.Remove(dir); err != nil {+ // The directory outlived its marker: a Windows process holding a handle+ // to the directory itself, or content an orphaned child recreated after+ // the sweep above walked past it. Put an unlocked marker back, or the+ // directory reads as a pre-lock leftover from here on — which, with the+ // legacy branch disabled by default, means it never gets reclaimed at+ // all. Restoring it keeps the retry available for the next cycle.+ if restored, rerr := openLockFile(lockPath); rerr == nil {+ restored.Close()+ }+ return err+ }+ return nil+}++// taskTempVerdict is what a single directory under the temp base is, as far as+// this sweep can prove.+type taskTempVerdict int++const (+ // taskTempInUse: an execution still holds the lock, or something stopped+ // this sweep from finding out. Both mean "do not touch" — the sweep fails+ // closed, since being wrong here deletes a running task's TMPDIR.+ taskTempInUse taskTempVerdict = iota+ // taskTempDead: this sweep acquired the lock the owner would still be+ // holding, so the kernel has already proven that execution is gone.+ taskTempDead+ // taskTempLegacy: no lock file at all — left by a daemon predating+ // LockTaskTempDir, about which nothing can be proven.+ taskTempLegacy+)++// PruneTaskTempDirs reclaims per-task temp directories whose owning execution+// is gone, under the base returned by the daemon's task temp base resolution.+//+// These directories are the agent process's TMPDIR. They live outside+// WorkspacesRoot — the task GC's scan root — so nothing else ever reclaims+// them: their only other exit is the cleanup the daemon defers at the end of+// runTask, which does not run when the daemon is killed and does not finish+// when a file inside is still open (the Windows case in #7364). Whatever that+// misses accumulates on disk forever.+//+// Liveness comes from the lock, not from the clock. A directory is removed+// only once this sweep has itself acquired the .task_lock its owner would+// still be holding, which the kernel grants only after that owner is gone.+//+// The lock is held by the daemon, not by the agent process, so it answers "is+// the owning EXECUTION still alive?" and not "is every child it spawned gone?".+// A daemon killed while agent processes survive it releases the lock on the+// spot, and this sweep may then reclaim a directory such an orphan is still+// writing to. That is the same exposure an env root's .task_lock already+// carries, and from the platform's point of view the task is dead either way;+// closing it properly is a job for process-group teardown, not for the GC.+//+// legacyTTL applies to the one case the lock cannot answer: directories left+// by a daemon predating LockTaskTempDir, which carry no lock file at all. For+// those, age is the only available signal — and age cannot establish liveness,+// which is why legacyTTL defaults to 0 (leave them alone) and reclaiming them+// is an operator's explicit decision. See DefaultGCTaskTempLegacyTTL.+func PruneTaskTempDirs(base string, legacyTTL time.Duration, now time.Time, logger *slog.Logger) (removed int, bytesFreed int64) {+ entries, err := os.ReadDir(base)+ if err != nil {+ return 0, 0 // missing or unreadable base — nothing to prune+ }+ legacyKept := 0+ for _, e := range entries {+ if !e.IsDir() || !strings.HasPrefix(e.Name(), TaskTempDirPrefix) {+ continue+ }+ dir := filepath.Join(base, e.Name())++ switch classifyTaskTempDir(dir, logger) {+ case taskTempInUse:+ continue+ case taskTempLegacy:+ if legacyTTL <= 0 {+ legacyKept+++ continue+ }+ // Age is the only signal here, and age cannot tell a pre-lock+ // leftover from a directory this daemon is in the middle of+ // publishing: both carry no .task_lock, legacyTTL accepts any+ // duration down to a nanosecond, and an owner stalled between+ // MkdirTemp and the rename outlasts any TTL at all. Content can+ // tell them apart. A directory being published holds nothing but+ // its own claim file — the task has not been handed the path yet,+ // so it cannot have written anything — while a leftover worth+ // reclaiming is by definition one with something in it.+ //+ // So this branch never touches a directory with no task content.+ // The cost is that a pre-lock daemon which crashed before its task+ // wrote anything leaves an empty directory nothing reclaims; the+ // alternative is deleting the temp dir of a task that is starting.+ if !taskTempDirHoldsContent(dir) {+ continue+ }+ newest, _ := dirStat(dir)+ if newest.IsZero() || now.Sub(newest) <= legacyTTL {+ continue+ }+ // Everything above is a series of separate observations, not one+ // snapshot: the classify that said "legacy" happened before the+ // content walk, and the owner may have finished publishing in+ // between — leaving a held .task_lock this branch has not looked+ // at, on a directory whose task is now writing to it.+ //+ // Re-reading the classification here closes that, and closes it+ // completely rather than narrowing it. Content is only ever there+ // because a task was handed this path, which happens only after+ // LockTaskTempDir has returned and therefore after the marker is+ // published and held. So content observed at the top plus no+ // marker seen here means no live task owns this directory — and a+ // task cannot appear afterwards either, since MkdirTemp only ever+ // hands out a fresh empty directory under a new name.+ if taskTempSweepBeforeRecheck != nil {+ taskTempSweepBeforeRecheck(dir)+ }+ if classifyTaskTempDir(dir, logger) != taskTempLegacy {+ continue+ }+ }++ _, size := dirStat(dir)+ if err := RemoveTaskTempDir(dir); err != nil {+ // Not worth escalating: the marker is still there, so the next+ // cycle re-acquires the lock and retries. This is the whole reason+ // the fix belongs in the GC rather than in a bounded retry on the+ // task-completion path — here, failing costs nothing and repeats+ // for free.+ if logger != nil {+ logger.Debug("execenv: prune task temp dir failed", "dir", dir, "error", err)+ }+ continue+ }+ removed+++ bytesFreed += size+ }+ if legacyKept > 0 && logger != nil {+ // Say it plainly rather than reclaiming them silently: these are the+ // directories this daemon cannot prove anything about, and an operator+ // who knows no pre-lock daemon is running can opt in.+ logger.Info("gc: pre-lock task temp dirs left in place",+ "base", base,+ "count", legacyKept,+ "hint", "set MULTICA_GC_TASK_TEMP_LEGACY_TTL to reclaim them on age",+ )+ }+ return removed, bytesFreed+}++// taskTempSweepBeforeRecheck is a test seam, nil in production. The sweep's+// correctness depends on what can happen BETWEEN its decision and its removal,+// and that interleaving cannot be produced reliably from the outside.+var taskTempSweepBeforeRecheck func(dir string)++// taskTempDirHoldsContent reports whether dir holds anything a task put there,+// as opposed to only the lock files this package maintains. It is what+// separates a pre-lock leftover from a directory mid-publication, without+// consulting the clock.+func taskTempDirHoldsContent(dir string) bool {+ entries, err := os.ReadDir(dir)+ if err != nil {+ return false // unreadable: not ours to delete+ }+ for _, e := range entries {+ if e.Name() == envRootLockFile || e.Name() == taskTempLockClaimFile {+ continue+ }+ return true+ }+ return false+}++// classifyTaskTempDir decides what can be proven about one directory.+func classifyTaskTempDir(dir string, logger *slog.Logger) taskTempVerdict {+ lockPath := filepath.Join(dir, envRootLockFile)+ if _, err := os.Stat(lockPath); err != nil {+ if !errors.Is(err, os.ErrNotExist) {+ // A directory we cannot even look into is not a directory we may+ // delete. Another user's temp dir under a shared /tmp lands here.+ if logger != nil {+ logger.Debug("execenv: task temp dir lock unreadable; leaving it alone", "dir", dir, "error", err)+ }+ return taskTempInUse+ }+ return taskTempLegacy+ }++ lock, err := openLockFile(lockPath)+ if err != nil {+ return taskTempInUse+ }+ locked, err := lockFileExclusiveNonBlocking(lock)+ if err != nil || !locked {+ lock.Close()+ return taskTempInUse+ }+ // Release immediately: RemoveTaskTempDir deletes this very file, and on+ // Windows deleting a file this process still has open only marks it for+ // deletion, which would then block the directory's own removal. Nothing can+ // claim the directory in between — its name is random and its owner is+ // dead — and a second sweep racing us just loses the removal to ENOENT.+ releaseLockFile(lock)+ return taskTempDead+}diff --git a/server/internal/daemon/execenv/task_temp_test.go b/server/internal/daemon/execenv/task_temp_test.gonew file mode 100644index 0000000000..6882346931--- /dev/null+++ b/server/internal/daemon/execenv/task_temp_test.go@@ -0,0 +1,387 @@+package execenv++import (+ "os"+ "path/filepath"+ "testing"+ "time"+)++// makeTaskTempDir creates a temp dir the way ensureTaskTempDir does, optionally+// without the execution lock so a pre-lock daemon's leftovers can be modelled.+func makeTaskTempDir(t *testing.T, base, suffix string, withLock bool) string {+ t.Helper()+ dir := filepath.Join(base, TaskTempDirPrefix+suffix)+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatalf("create task temp dir: %v", err)+ }+ if withLock {+ lock, err := LockTaskTempDir(dir)+ if err != nil {+ t.Fatalf("LockTaskTempDir(): %v", err)+ }+ ReleaseTaskTempLock(lock)+ }+ return dir+}++// TestPruneTaskTempDirsHoldsOffLiveDirThenReclaimsIt is the core contract: a+// directory whose owner still holds the lock is never removed, and the same+// sweep reclaims it as soon as that lock is gone.+//+// The lock here is held by THIS process, which is the case an in-memory active+// set would be needed for and the case the lock covers for free: flock and+// LockFileEx are held by an open file description, not by a process, so the+// sweep's own probe loses to it exactly as another daemon's would.+func TestPruneTaskTempDirsHoldsOffLiveDirThenReclaimsIt(t *testing.T) {+ base := t.TempDir()+ dir := filepath.Join(base, TaskTempDirPrefix+"live")+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatalf("create task temp dir: %v", err)+ }+ lock, err := LockTaskTempDir(dir)+ if err != nil {+ t.Fatalf("LockTaskTempDir(): %v", err)+ }++ // legacyTTL 0 so nothing here can be reclaimed on age: the lock is the only+ // thing under test. `now` is far in the future for the same reason.+ future := time.Now().Add(365 * 24 * time.Hour)+ if removed, _ := PruneTaskTempDirs(base, 0, future, testLogger()); removed != 0 {+ t.Fatalf("prune removed %d dirs while the lock was held, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("live task temp dir was removed: %v", err)+ }++ ReleaseTaskTempLock(lock)++ removed, _ := PruneTaskTempDirs(base, 0, future, testLogger())+ if removed != 1 {+ t.Fatalf("prune removed %d dirs after the lock was released, want 1", removed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("task temp dir still present after prune: %v", err)+ }+}++// TestPruneTaskTempDirsReclaimsUnlockedDirImmediately pins that age plays no+// part once liveness is answerable: a directory released seconds ago is gone on+// the next cycle, no TTL wait. This is what makes the end-of-task RemoveAll+// failing (the Windows sharing violation in #7364) cost nothing.+func TestPruneTaskTempDirsReclaimsUnlockedDirImmediately(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "released", true)+ payload := filepath.Join(dir, "node-compile-cache")+ if err := os.WriteFile(payload, make([]byte, 4096), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }++ removed, bytesFreed := PruneTaskTempDirs(base, 0, time.Now(), testLogger())+ if removed != 1 {+ t.Fatalf("prune removed %d dirs, want 1", removed)+ }+ if bytesFreed < 4096 {+ t.Fatalf("prune reported %d bytes freed, want at least 4096", bytesFreed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("task temp dir still present after prune: %v", err)+ }+}++// TestPruneTaskTempDirsLegacyDirsFallBackToTTL covers directories left by a+// daemon predating the lock: nothing recorded liveness for them, so age is the+// only signal available. They carry task content — that is both what makes them+// worth reclaiming and what distinguishes them from a directory mid-publication+// (see TestPruneTaskTempDirsLegacyBranchNeedsContent).+func TestPruneTaskTempDirsLegacyDirsFallBackToTTL(t *testing.T) {+ const legacyTTL = 72 * time.Hour++ legacyDir := func(t *testing.T, base string) string {+ t.Helper()+ dir := makeTaskTempDir(t, base, "legacy", false)+ if err := os.WriteFile(filepath.Join(dir, "payload"), make([]byte, 1024), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }+ return dir+ }++ t.Run("young legacy dir is kept", func(t *testing.T) {+ base := t.TempDir()+ dir := legacyDir(t, base)+ if removed, _ := PruneTaskTempDirs(base, legacyTTL, time.Now(), testLogger()); removed != 0 {+ t.Fatalf("prune removed %d young legacy dirs, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("young legacy dir was removed: %v", err)+ }+ })++ t.Run("legacy dir past the TTL is reclaimed", func(t *testing.T) {+ base := t.TempDir()+ dir := legacyDir(t, base)+ if removed, _ := PruneTaskTempDirs(base, legacyTTL, time.Now().Add(legacyTTL+time.Hour), testLogger()); removed != 1 {+ t.Fatalf("prune removed %d expired legacy dirs, want 1", removed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("expired legacy dir still present: %v", err)+ }+ })++ t.Run("zero TTL disables the legacy branch", func(t *testing.T) {+ base := t.TempDir()+ dir := legacyDir(t, base)+ if removed, _ := PruneTaskTempDirs(base, 0, time.Now().Add(10*365*24*time.Hour), testLogger()); removed != 0 {+ t.Fatalf("prune removed %d legacy dirs with the TTL disabled, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("legacy dir was removed with the TTL disabled: %v", err)+ }+ })+}++// TestPruneTaskTempDirsOnlyTouchesOwnDirs guards the blast radius: the temp base+// is usually a shared /tmp, so anything without our prefix — and the base+// itself — has to survive a sweep that is otherwise willing to delete on age.+func TestPruneTaskTempDirsOnlyTouchesOwnDirs(t *testing.T) {+ base := t.TempDir()+ foreignDir := filepath.Join(base, "someone-elses-dir")+ if err := os.Mkdir(foreignDir, 0o700); err != nil {+ t.Fatalf("create foreign dir: %v", err)+ }+ foreignFile := filepath.Join(base, "unrelated.sock")+ if err := os.WriteFile(foreignFile, []byte("x"), 0o600); err != nil {+ t.Fatalf("write foreign file: %v", err)+ }+ // A FILE carrying our prefix is not one of our directories either.+ prefixedFile := filepath.Join(base, TaskTempDirPrefix+"not-a-dir")+ if err := os.WriteFile(prefixedFile, []byte("x"), 0o600); err != nil {+ t.Fatalf("write prefixed file: %v", err)+ }++ removed, _ := PruneTaskTempDirs(base, time.Hour, time.Now().Add(10*365*24*time.Hour), testLogger())+ if removed != 0 {+ t.Fatalf("prune removed %d entries, want 0", removed)+ }+ for _, path := range []string{base, foreignDir, foreignFile, prefixedFile} {+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("prune touched %s: %v", path, err)+ }+ }+}++// TestPruneTaskTempDirsMissingBaseIsNotAnError: the base may not exist yet on a+// daemon that has never run a task, and a GC cycle must not care.+func TestPruneTaskTempDirsMissingBaseIsNotAnError(t *testing.T) {+ removed, bytesFreed := PruneTaskTempDirs(filepath.Join(t.TempDir(), "nope"), time.Hour, time.Now(), testLogger())+ if removed != 0 || bytesFreed != 0 {+ t.Fatalf("prune over a missing base = (%d, %d), want (0, 0)", removed, bytesFreed)+ }+}++// TestLockTaskTempDirPublishesAnAlreadyHeldMarker pins the publication order:+// when LockTaskTempDir returns, .task_lock exists AND is held, with no claim+// file left behind. If the marker were created first and locked second, a sweep+// landing in between would lock it, read the owner as dead, and delete the+// directory a task is about to start using.+func TestLockTaskTempDirPublishesAnAlreadyHeldMarker(t *testing.T) {+ base := t.TempDir()+ dir := filepath.Join(base, TaskTempDirPrefix+"publishing")+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatalf("create task temp dir: %v", err)+ }+ lock, err := LockTaskTempDir(dir)+ if err != nil {+ t.Fatalf("LockTaskTempDir(): %v", err)+ }+ t.Cleanup(func() { ReleaseTaskTempLock(lock) })++ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err != nil {+ t.Fatalf("marker not published: %v", err)+ }+ if _, err := os.Stat(filepath.Join(dir, taskTempLockClaimFile)); !os.IsNotExist(err) {+ t.Fatalf("claim file left behind, stat err = %v", err)+ }+ if got := classifyTaskTempDir(dir, testLogger()); got != taskTempInUse {+ t.Fatalf("classify = %v, want taskTempInUse", got)+ }+}++// TestPruneTaskTempDirsSpareDirMidClaim covers the window itself: a directory+// whose owner has taken the claim but not yet published it must survive a sweep+// under every legacy setting, including ones whose TTL the directory has+// already outlived. Age must play no part in what protects it.+func TestPruneTaskTempDirsSpareDirMidClaim(t *testing.T) {+ for _, legacyTTL := range []time.Duration{0, time.Nanosecond, time.Millisecond, time.Hour, 72 * time.Hour} {+ t.Run(legacyTTL.String(), func(t *testing.T) {+ base := t.TempDir()+ dir := filepath.Join(base, TaskTempDirPrefix+"claiming")+ if err := os.Mkdir(dir, 0o700); err != nil {+ t.Fatalf("create task temp dir: %v", err)+ }+ // Exactly the on-disk state between claim and publish.+ claim, err := openLockFile(filepath.Join(dir, taskTempLockClaimFile))+ if err != nil {+ t.Fatalf("open claim: %v", err)+ }+ if ok, err := lockFileExclusiveNonBlocking(claim); err != nil || !ok {+ t.Fatalf("lock claim: ok=%v err=%v", ok, err)+ }+ t.Cleanup(func() { releaseLockFile(claim) })++ // now is pushed past the TTL on purpose: what protects this state+ // must not be that it is younger than the TTL, because legacyTTL+ // accepts any duration and an owner can stall between MkdirTemp+ // and the rename.+ now := time.Now().Add(legacyTTL + time.Second)+ if removed, _ := PruneTaskTempDirs(base, legacyTTL, now, testLogger()); removed != 0 {+ t.Fatalf("prune removed %d dirs mid-claim, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("prune removed a directory whose owner was mid-claim: %v", err)+ }+ })+ }+}++// TestLockTaskTempDirRacesPruneCleanly is the concurrency regression: a sweep+// running flat out against tasks publishing their temp dirs must never hand a+// task a directory that has been deleted underneath it.+func TestLockTaskTempDirRacesPruneCleanly(t *testing.T) {+ base := t.TempDir()+ stop := make(chan struct{})+ swept := make(chan struct{})+ go func() {+ defer close(swept)+ for {+ select {+ case <-stop:+ return+ default:+ PruneTaskTempDirs(base, 0, time.Now(), testLogger())+ }+ }+ }()++ for i := 0; i < 200; i++ {+ dir, err := os.MkdirTemp(base, TaskTempDirPrefix)+ if err != nil {+ t.Fatalf("MkdirTemp(): %v", err)+ }+ lock, err := LockTaskTempDir(dir)+ if err != nil {+ t.Fatalf("LockTaskTempDir() on iteration %d: %v", i, err)+ }+ // What the task does next: write into the TMPDIR it was handed.+ if err := os.WriteFile(filepath.Join(dir, "payload"), []byte("x"), 0o600); err != nil {+ t.Fatalf("task temp dir vanished under its owner on iteration %d: %v", i, err)+ }+ ReleaseTaskTempLock(lock)+ _ = RemoveTaskTempDir(dir)+ }++ close(stop)+ <-swept+}++// TestPruneTaskTempDirsSparesDirBeforeItsClaimExists covers the other half of+// the publication window — the instant between os.MkdirTemp and the claim file+// appearing, when the directory is simply empty. Nothing can be locked yet, so+// the only thing that can protect it is that it holds no task content.+func TestPruneTaskTempDirsSparesDirBeforeItsClaimExists(t *testing.T) {+ for _, legacyTTL := range []time.Duration{time.Nanosecond, time.Millisecond, 72 * time.Hour} {+ t.Run(legacyTTL.String(), func(t *testing.T) {+ base := t.TempDir()+ dir, err := os.MkdirTemp(base, TaskTempDirPrefix)+ if err != nil {+ t.Fatalf("MkdirTemp(): %v", err)+ }+ now := time.Now().Add(legacyTTL + time.Second)+ if removed, _ := PruneTaskTempDirs(base, legacyTTL, now, testLogger()); removed != 0 {+ t.Fatalf("prune removed %d dirs before their claim existed, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("prune removed a directory whose owner had not claimed it yet: %v", err)+ }+ })+ }+}++// TestPruneTaskTempDirsLegacyBranchNeedsContent states the invariant the two+// tests above depend on, so that relaxing it fails here rather than in a race:+// the age branch reclaims a leftover holding task content, and nothing else.+func TestPruneTaskTempDirsLegacyBranchNeedsContent(t *testing.T) {+ base := t.TempDir()+ empty := makeTaskTempDir(t, base, "empty-legacy", false)+ withContent := makeTaskTempDir(t, base, "used-legacy", false)+ if err := os.WriteFile(filepath.Join(withContent, "payload"), make([]byte, 1024), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }++ removed, _ := PruneTaskTempDirs(base, time.Hour, time.Now().Add(48*time.Hour), testLogger())+ if removed != 1 {+ t.Fatalf("prune removed %d dirs, want 1 (only the one holding content)", removed)+ }+ if _, err := os.Stat(withContent); !os.IsNotExist(err) {+ t.Fatalf("expired legacy dir with content survived: %v", err)+ }+ if _, err := os.Stat(empty); err != nil {+ t.Fatalf("empty legacy dir was reclaimed on age: %v", err)+ }+}++// TestPruneTaskTempDirsRechecksLockBeforeRemoving is the TOCTOU regression: the+// sweep's legacy decision is several separate observations, and a directory can+// finish publishing in the middle of them. The barrier below reproduces exactly+// that interleaving — sweep classifies the directory as legacy, then the owner+// publishes its marker and the task writes — and the sweep must notice before+// it removes anything.+//+// Age deliberately cannot save this one: `now` is far past the TTL, and the+// write inside the barrier would normally refresh the directory's mtime, which+// is precisely the implicit timing crutch this pins against.+func TestPruneTaskTempDirsRechecksLockBeforeRemoving(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "publishing-mid-sweep", false)+ // Content at the top of the sweep, so the legacy branch's content and age+ // gates both pass and it commits to removing this directory.+ if err := os.WriteFile(filepath.Join(dir, "payload"), make([]byte, 1024), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }++ var lock *os.File+ barrierRuns := 0+ taskTempSweepBeforeRecheck = func(swept string) {+ if swept != dir {+ return+ }+ barrierRuns+++ // The owner wins the race: it publishes, and its task starts writing.+ var err error+ if lock, err = LockTaskTempDir(dir); err != nil {+ t.Errorf("LockTaskTempDir() at the barrier: %v", err)+ return+ }+ if err := os.WriteFile(filepath.Join(dir, "task-output"), []byte("live"), 0o600); err != nil {+ t.Errorf("task write at the barrier: %v", err)+ }+ }+ t.Cleanup(func() {+ taskTempSweepBeforeRecheck = nil+ ReleaseTaskTempLock(lock)+ })++ removed, _ := PruneTaskTempDirs(base, time.Hour, time.Now().Add(72*time.Hour), testLogger())+ if barrierRuns != 1 {+ t.Fatalf("barrier ran %d times, want 1 — the sweep never reached the removal decision", barrierRuns)+ }+ if removed != 0 {+ t.Fatalf("sweep removed %d dirs after the owner published mid-decision, want 0", removed)+ }+ if _, err := os.Stat(filepath.Join(dir, "task-output")); err != nil {+ t.Fatalf("sweep destroyed a live task's temp dir: %v", err)+ }+ if got := classifyTaskTempDir(dir, testLogger()); got != taskTempInUse {+ t.Fatalf("classify = %v, want taskTempInUse", got)+ }+}diff --git a/server/internal/daemon/execenv/task_temp_unix_test.go b/server/internal/daemon/execenv/task_temp_unix_test.gonew file mode 100644index 0000000000..b01552152e--- /dev/null+++ b/server/internal/daemon/execenv/task_temp_unix_test.go@@ -0,0 +1,169 @@+//go:build !windows++package execenv++import (+ "os"+ "path/filepath"+ "testing"+ "time"+)++// blockContentRemoval plants a payload inside dir that cannot be unlinked,+// standing in for the Windows sharing violation this sweep has to survive:+// unlinking needs write+execute on the PARENT, so a read-only subdirectory+// makes RemoveAll fail after it has already walked the rest of the tree.+// The returned func lifts the obstruction.+func blockContentRemoval(t *testing.T, dir string) func() {+ t.Helper()+ sub := filepath.Join(dir, "held")+ if err := os.Mkdir(sub, 0o755); err != nil {+ t.Fatalf("create blocked subdir: %v", err)+ }+ if err := os.WriteFile(filepath.Join(sub, "payload"), make([]byte, 2048), 0o600); err != nil {+ t.Fatalf("write blocked payload: %v", err)+ }+ if err := os.Chmod(sub, 0o555); err != nil {+ t.Fatalf("chmod blocked subdir: %v", err)+ }+ unblocked := false+ unblock := func() {+ if unblocked {+ return+ }+ unblocked = true+ _ = os.Chmod(sub, 0o755)+ }+ t.Cleanup(unblock)+ return unblock+}++// TestRemoveTaskTempDirKeepsMarkerWhenContentSurvives is the regression for the+// reason this is not os.RemoveAll: RemoveAll keeps walking after a failure, so+// it deletes the .task_lock sitting next to the payload it could not remove.+// The directory would come back as one with no marker — indistinguishable from+// a pre-lock leftover, and so no longer reclaimable on liveness at all.+func TestRemoveTaskTempDirKeepsMarkerWhenContentSurvives(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "held", true)+ unblock := blockContentRemoval(t, dir)++ if err := RemoveTaskTempDir(dir); err == nil {+ t.Skip("process can unlink through a read-only directory (running as root?)")+ }+ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err != nil {+ t.Fatalf("cleanup destroyed the lock marker the next sweep needs: %v", err)+ }+ // Contrast: what the previous implementation did to the same directory.+ if err := os.RemoveAll(dir); err == nil {+ t.Fatal("os.RemoveAll unexpectedly succeeded")+ }+ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); !os.IsNotExist(err) {+ t.Fatalf("os.RemoveAll was expected to destroy the marker, stat err = %v", err)+ }++ unblock()+}++// TestPruneTaskTempDirsRetriesUntilContentCanBeRemoved walks the whole failure+// path the way the GC does: a cycle that cannot finish the removal leaves the+// directory reclaimable on liveness, and a later cycle finishes the job with no+// TTL involved at any point.+func TestPruneTaskTempDirsRetriesUntilContentCanBeRemoved(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "held", true)+ unblock := blockContentRemoval(t, dir)++ // legacyTTL 0 throughout: if the marker were lost, the directory would be+ // classified legacy and this sweep would never remove it at all.+ if removed, _ := PruneTaskTempDirs(base, 0, time.Now(), testLogger()); removed != 0 {+ if _, err := os.Stat(filepath.Join(dir, "held", "payload")); os.IsNotExist(err) {+ t.Skip("process can unlink through a read-only directory (running as root?)")+ }+ t.Fatalf("prune reported %d removals despite the blocked payload, want 0", removed)+ }+ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err != nil {+ t.Fatalf("failed prune destroyed the lock marker: %v", err)+ }++ unblock()++ removed, bytesFreed := PruneTaskTempDirs(base, 0, time.Now(), testLogger())+ if removed != 1 {+ t.Fatalf("prune removed %d dirs once the payload was releasable, want 1", removed)+ }+ if bytesFreed < 2048 {+ t.Fatalf("prune reported %d bytes freed, want at least 2048", bytesFreed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("task temp dir still present: %v", err)+ }+}++// TestPruneTaskTempDirsFailsClosedOnUnreadableDir: a directory this sweep+// cannot inspect is one it must not delete. Another user's temp dir under a+// shared /tmp arrives here.+func TestPruneTaskTempDirsFailsClosedOnUnreadableDir(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "opaque", true)+ if err := os.Chmod(dir, 0o000); err != nil {+ t.Fatalf("chmod: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })++ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err == nil {+ t.Skip("process can stat through a 0000 directory (running as root?)")+ }++ // An ancient legacy TTL that would otherwise fire: the point is that an+ // unreadable directory is never classified legacy in the first place.+ removed, _ := PruneTaskTempDirs(base, time.Hour, time.Now().Add(10*365*24*time.Hour), testLogger())+ if removed != 0 {+ t.Fatalf("prune removed %d unreadable dirs, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("prune removed an unreadable dir: %v", err)+ }+}++// TestRemoveTaskTempDirRestoresMarkerWhenDirCannotBeRemoved is the second+// failure branch: the contents come away cleanly, the marker is deleted so the+// directory can go — and then the directory itself cannot be removed. Without+// restoring the marker this is the worst case of all, because the cleanup that+// got furthest is the one that leaves a directory nothing can classify again.+//+// A read-only BASE blocks removing the directory while still allowing its+// contents (and marker) to be removed, since unlinking is governed by the+// parent.+func TestRemoveTaskTempDirRestoresMarkerWhenDirCannotBeRemoved(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "undeletable", true)+ if err := os.WriteFile(filepath.Join(dir, "payload"), []byte("x"), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }+ if err := os.Chmod(base, 0o555); err != nil {+ t.Fatalf("chmod base: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(base, 0o700) })++ if err := RemoveTaskTempDir(dir); err == nil {+ t.Skip("process can unlink through a read-only directory (running as root?)")+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("directory unexpectedly removed: %v", err)+ }+ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err != nil {+ t.Fatalf("marker was not restored after the directory removal failed: %v", err)+ }+ // The restored marker must be unlocked, so the next cycle can claim it.+ if got := classifyTaskTempDir(dir, testLogger()); got != taskTempDead {+ t.Fatalf("classify after restore = %v, want taskTempDead", got)+ }++ if err := os.Chmod(base, 0o700); err != nil {+ t.Fatalf("restore base perms: %v", err)+ }+ if removed, _ := PruneTaskTempDirs(base, 0, time.Now(), testLogger()); removed != 1 {+ t.Fatalf("next sweep removed %d dirs, want 1", removed)+ }+}diff --git a/server/internal/daemon/execenv/task_temp_windows_test.go b/server/internal/daemon/execenv/task_temp_windows_test.gonew file mode 100644index 0000000000..b40a29cc8d--- /dev/null+++ b/server/internal/daemon/execenv/task_temp_windows_test.go@@ -0,0 +1,84 @@+//go:build windows++package execenv++import (+ "os"+ "path/filepath"+ "testing"+ "time"++ "golang.org/x/sys/windows"+)++// TestPruneTaskTempDirsSurvivesRealSharingViolation is the Windows regression+// for #7364's actual failure mode, with a real sharing violation rather than a+// simulated one: a payload opened WITHOUT FILE_SHARE_DELETE cannot be deleted+// while the handle is open, which is exactly what a task's leftover child+// process does to its node compile cache.+//+// What has to hold: the failed cleanup leaves .task_lock intact, so the+// directory stays reclaimable on liveness, and the cycle after the handle+// closes removes it — with the legacy TTL disabled throughout, proving no part+// of this depends on age.+func TestPruneTaskTempDirsSurvivesRealSharingViolation(t *testing.T) {+ base := t.TempDir()+ dir := makeTaskTempDir(t, base, "sharing-violation", true)++ payload := filepath.Join(dir, "node-compile-cache")+ if err := os.WriteFile(payload, make([]byte, 2048), 0o600); err != nil {+ t.Fatalf("write payload: %v", err)+ }+ payloadPtr, err := windows.UTF16PtrFromString(payload)+ if err != nil {+ t.Fatalf("UTF16PtrFromString(): %v", err)+ }+ // No FILE_SHARE_DELETE: Windows now refuses to delete this file.+ handle, err := windows.CreateFile(+ payloadPtr,+ windows.GENERIC_READ,+ windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE,+ nil,+ windows.OPEN_EXISTING,+ windows.FILE_ATTRIBUTE_NORMAL,+ 0,+ )+ if err != nil {+ t.Fatalf("CreateFile(): %v", err)+ }+ handleClosed := false+ closeHandle := func() {+ if handleClosed {+ return+ }+ handleClosed = true+ _ = windows.CloseHandle(handle)+ }+ t.Cleanup(closeHandle)++ // Establish that the sharing violation is real before asserting anything+ // about how the sweep copes with it.+ if err := os.Remove(payload); err == nil {+ t.Skip("this Windows build allowed deleting an open file; nothing to regress against")+ }++ if removed, _ := PruneTaskTempDirs(base, 0, time.Now(), testLogger()); removed != 0 {+ t.Fatalf("prune reported %d removals while the payload was held, want 0", removed)+ }+ if _, err := os.Stat(filepath.Join(dir, envRootLockFile)); err != nil {+ t.Fatalf("failed prune destroyed the lock marker the next cycle needs: %v", err)+ }++ closeHandle()++ removed, bytesFreed := PruneTaskTempDirs(base, 0, time.Now(), testLogger())+ if removed != 1 {+ t.Fatalf("prune removed %d dirs after the handle closed, want 1", removed)+ }+ if bytesFreed < 2048 {+ t.Fatalf("prune reported %d bytes freed, want at least 2048", bytesFreed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("task temp dir still present after prune: %v", err)+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 204186001a..48d35294df 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -72,6 +72,7 @@ type gcStats struct {hermesMemoryStoresReclaimed int // per-agent Hermes memory stores reclaimed past their TTLhermesSessionStoresReclaimed int // per-conversation Hermes session stores reclaimed past their TTLrepoCachesReclaimed int // bare repo caches under .repos evicted past their TTL+ taskTempDirsReclaimed int // per-task temp dirs under the temp base reclaimed after their owning execution endedbytesReclaimed int64 // total bytes freed in this cyclebyPattern map[string]int // configured basename or managed path label -> reclaim count}@@ -134,7 +135,22 @@ func (d *Daemon) runGC(ctx context.Context) {stats.bytesReclaimed += storeBytes}- if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.hermesSessionStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 {+ // Reclaim per-task temp dirs whose owning execution is gone. These are the+ // agent process's TMPDIR and live under the system temp base, not under+ // WorkspacesRoot, so the task walk above has never seen them and the only+ // other thing that removes them is the RemoveAll runTask defers — which+ // does not run at all when the daemon is killed, and does not succeed when+ // a file inside is still open (#7364). Unlike every other pruner here this+ // one asks the kernel, not the clock: it removes a directory only once it+ // has acquired the .task_lock the owner would still be holding.+ if base, _, err := taskTempBaseDir(); err == nil {+ if tempRemoved, tempBytes := execenv.PruneTaskTempDirs(base, d.cfg.GCTaskTempLegacyTTL, time.Now(), d.logger); tempRemoved > 0 {+ stats.taskTempDirsReclaimed += tempRemoved+ stats.bytesReclaimed += tempBytes+ }+ }++ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 || stats.storesReclaimed > 0 || stats.hermesMemoryStoresReclaimed > 0 || stats.hermesSessionStoresReclaimed > 0 || stats.repoCachesReclaimed > 0 || stats.taskTempDirsReclaimed > 0 {d.logger.Info("gc: cycle complete","cleaned", stats.cleaned,"orphaned", stats.orphaned,@@ -145,6 +161,7 @@ func (d *Daemon) runGC(ctx context.Context) {"hermes_memory_stores_reclaimed", stats.hermesMemoryStoresReclaimed,"hermes_session_stores_reclaimed", stats.hermesSessionStoresReclaimed,"repo_caches_reclaimed", stats.repoCachesReclaimed,+ "task_temp_dirs_reclaimed", stats.taskTempDirsReclaimed,"bytes_reclaimed", stats.bytesReclaimed,"by_pattern", stats.byPattern,)diff --git a/server/internal/daemon/task_temp_gc_test.go b/server/internal/daemon/task_temp_gc_test.gonew file mode 100644index 0000000000..6009f4f7a3--- /dev/null+++ b/server/internal/daemon/task_temp_gc_test.go@@ -0,0 +1,66 @@+package daemon++import (+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "runtime"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// TestTaskTempDirSurvivesGCWhileTheRunHoldsIt wires the two halves of the fix+// together: the directory ensureTaskTempDir hands a running task is invisible to+// the GC sweep for as long as the run holds its lock, and is reclaimed by the+// very next sweep once the run releases it.+//+// The sweep runs inside the same daemon that owns the live task, so here the+// holder and the sweeper are one process on purpose. That is the case a PID+// marker could not answer and an in-memory active set would have to be built+// for; the lock answers it because it is held by an open file description+// rather than by a process.+//+// `now` is a year ahead throughout, so nothing below can pass or fail on age.+func TestTaskTempDirSurvivesGCWhileTheRunHoldsIt(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("MULTICA_AGENT_TEMP_BASE is ignored on Windows; execenv's task temp tests cover the lock contract there")+ }+ base := t.TempDir()+ t.Setenv("MULTICA_AGENT_TEMP_BASE", base)+ logger := slog.New(slog.NewTextHandler(io.Discard, nil))+ future := time.Now().Add(365 * 24 * time.Hour)++ dir, lock, err := ensureTaskTempDir("root", "ws", "task")+ if err != nil {+ t.Fatalf("ensureTaskTempDir(): %v", err)+ }+ t.Cleanup(func() {+ execenv.ReleaseTaskTempLock(lock)+ _ = os.RemoveAll(dir)+ })++ if _, err := os.Stat(filepath.Join(dir, ".task_lock")); err != nil {+ t.Fatalf("ensureTaskTempDir did not leave an execution lock in %s: %v", dir, err)+ }++ if removed, _ := execenv.PruneTaskTempDirs(base, DefaultGCTaskTempLegacyTTL, future, logger); removed != 0 {+ t.Fatalf("gc sweep removed %d dirs while the run held the lock, want 0", removed)+ }+ if _, err := os.Stat(dir); err != nil {+ t.Fatalf("gc sweep removed a live task's temp dir: %v", err)+ }++ // What the cleanup defer in runTask does at the end of a run.+ execenv.ReleaseTaskTempLock(lock)++ removed, _ := execenv.PruneTaskTempDirs(base, DefaultGCTaskTempLegacyTTL, future, logger)+ if removed != 1 {+ t.Fatalf("gc sweep removed %d dirs after the run released the lock, want 1", removed)+ }+ if _, err := os.Stat(dir); !os.IsNotExist(err) {+ t.Fatalf("task temp dir still present after the sweep: %v", err)+ }+}diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.goindex 652f979996..0700d28e94 100644--- a/server/internal/daemon/workdir_race_test.go+++ b/server/internal/daemon/workdir_race_test.go@@ -344,11 +344,14 @@ func TestTaskTempBaseDir(t *testing.T) {t.Run("configured base creates private 0700 task dir", func(t *testing.T) {t.Setenv("MULTICA_AGENT_TEMP_BASE", validBase)- dir, err := ensureTaskTempDir("root", "ws", "task")+ dir, lock, err := ensureTaskTempDir("root", "ws", "task")if err != nil {t.Fatalf("ensureTaskTempDir(): %v", err)}- t.Cleanup(func() { _ = os.RemoveAll(dir) })+ t.Cleanup(func() {+ execenv.ReleaseTaskTempLock(lock)+ _ = os.RemoveAll(dir)+ })info, err := os.Stat(dir)if err != nil {t.Fatalf("stat task temp dir: %v", err)@@ -379,8 +382,9 @@ func TestTaskTempBaseDir(t *testing.T) {} {t.Run(tc.name, func(t *testing.T) {t.Setenv("MULTICA_AGENT_TEMP_BASE", tc.base)- dir, err := ensureTaskTempDir("root", "ws", "task")+ dir, lock, err := ensureTaskTempDir("root", "ws", "task")if err == nil {+ execenv.ReleaseTaskTempLock(lock)_ = os.RemoveAll(dir)if tc.base == readOnlyBase {t.Skip("process can write to the read-only fixture")