loop-engineering icon indicating copy to clipboard operation
loop-engineering copied to clipboard

bug(loop-worktree): concurrent manifest mutations can lose worktree entries

Open shixi-li opened this issue 4 months ago • 2 comments

Summary

Concurrent loop-worktree manifest mutations can overwrite each other. In the clearest case, two createWorktree() calls can both create their Git worktrees successfully while the manifest records only one of them.

Observed against current main at 98a6766c2e338e2b723d0807dcbf19ce6dbd2a33.

Reproduction

In a temporary Git repository initialized with a main branch and one commit, run two distinct creates concurrently:

const results = await Promise.allSettled([
  createWorktree({ root, runId: 'run-a', pattern: 'ci-sweeper' }),
  createWorktree({ root, runId: 'run-b', pattern: 'ci-sweeper' }),
]);

In 12/12 local runs:

  • both promises fulfilled
  • git worktree list showed the repository root plus both new worktrees
  • .loop-worktrees/manifest.json contained only one of the two run IDs

Cause

createWorktree() currently performs this sequence:

readManifest()
→ git worktree add
→ mutate the previously-read manifest object
→ writeManifest()

Two callers can read the same old snapshot. Both Git operations then succeed, and the last manifest writer drops the sibling entry. See createWorktree.

The same read-modify-write shape also deserves review in markWorktree, cleanupWorktrees, and gc.

Impact

Git state and the loop-worktree control manifest can diverge, leaving a successfully-created worktree untracked by list, mark, and normal cleanup flows. #398 currently serializes worktree creation as a mitigation, but the underlying package API remains unsafe for independent concurrent callers.

Design questions

Before implementing, could we align on the intended transaction model?

  1. Should manifest mutations use a dedicated cross-process mutex, or a reservation/commit/rollback flow?
  2. If using a mutex, should it cover the slower Git operation to preserve Git/manifest consistency?
  3. What stale-lock and crash-recovery behavior should the mutex have?
  4. Should atomic temp-file + rename writes be included here or kept as a separate hardening follow-up?
  5. Should serialized #398 land first and this remain a package-level follow-up, or should this be the prerequisite for restoring parallel creation there?

Proposed acceptance criteria

  • concurrent creates with different run IDs retain both manifest entries
  • concurrent creates with the same run ID produce exactly one success and no orphaned Git worktree
  • concurrent create/mark operations do not lose unrelated entries or fields
  • failures do not leave Git worktrees and manifest state silently divergent
  • a cross-process regression test covers the race; behavior is supported on POSIX and Windows

I am happy to implement once the locking/transaction boundary is confirmed. Related: #398.

shixi-li avatar Jul 28 '26 09:07 shixi-li

Looked at the current implementation in src/worktree.ts to work through the transaction-model questions before sending a PR.

Root cause, precisely

createWorktree, markWorktree, cleanupWorktrees, and gc all follow:

manifest = readManifest(root)   // read
... git worktree add/remove ... // side effect
manifest.worktrees = ...        // mutate in memory
writeManifest(root, manifest)   // full overwrite

writeManifest is a plain writeFile of the whole file — no cross-process coordination at all. Two callers can read the same snapshot; whichever writes last wins and silently drops the other's entry.

Proposed model: mutex, not reservation/commit/rollback

src/lock.ts already has withLocksMutex() — an exclusive-create (open(path, 'wx')) mutex file with backoff/retry and a deadline, used today to serialize the advisory path-lock feature. I'd reuse that same pattern for the manifest instead of introducing a reservation/commit/rollback transaction system:

  • Every manifest-touching operation here is short-lived (JSON read/write plus one git worktree add|remove call) and either fully succeeds or throws — there's no multi-step state that needs partial-failure recovery semantics.
  • A mutex keeps the change small and consistent with a pattern already proven in this package, instead of adding a second, more complex concurrency primitive.

Concretely: a new withManifestMutex(root, fn) in worktree.ts using its own mutex file (e.g. .loop-worktrees/.manifest.mutex), kept separate from lock.ts's .mutex file so manifest operations and advisory path-locks don't serialize against each other unnecessarily — they protect different resources.

Locking must cover the git operation, not just the manifest I/O

The mutex needs to wrap the entire critical section — duplicate check, git worktree add/remove, and the manifest read-modify-write — as one unit, for each of the four functions. Locking only the manifest read/write would leave the same race for identical-ID creates: two callers could both pass the "existing active worktree" check before either has committed a git branch or a manifest entry, and both call git worktree add -b loop/<runId>. Git will reject the second add (branch already exists), but leaves an inconsistent question of whether that failure path cleans up correctly — serializing the whole section removes the race instead of requiring careful failure-path bookkeeping.

For different run IDs this does mean create/remove calls are fully serialized rather than running git operations in parallel. Given these are short, low-frequency operations (loop orchestration, not a hot path), that tradeoff is worth the simplicity.

Stale-lock recovery

Match withLocksMutex's existing bounded retry (default ~5s deadline, clear error telling the operator to delete the mutex file manually if nothing else is running) — but add one improvement: since a crashed process could leave a mutex file behind indefinitely, on EEXIST also stat the mutex file's mtime. If it's older than a max age (proposing 30s — comfortably above the worst-case duration of a git worktree add), treat it as abandoned: attempt to unlink and re-acquire rather than waiting out the full deadline every time. If a live holder happens to exceed 30s, it simply loses the mutex and retries on its own next write, same as any other contender.

Atomic manifest writes

Independent of the mutex, writeManifest should write to a temp file in .loop-worktrees/ and rename() over manifest.json, rather than writing the target path directly. rename is atomic on the same volume on both POSIX and Windows, so a crash mid-write can never leave a truncated/corrupt manifest.json, and any reader that doesn't go through the mutex (a listWorktrees/readManifest call) never observes a half-written file.

Testing

Acceptance criteria call for cross-process regression tests. Node's event loop only interleaves at await points within one process, so an in-process "concurrent" test wouldn't actually exercise OS-level concurrency on the mutex file. Proposing the test harness spawn real sibling node processes (same pattern the existing test file already uses for git via execFile) each calling createWorktree/markWorktree and asserting via Promise.all that:

  • different run IDs: both processes succeed, both entries end up in the manifest
  • identical run IDs: exactly one succeeds, the other throws the "already has an active worktree" error, and no orphaned git worktree is left behind
  • manifest and git worktree state agree after every scenario

Re: ordering with #398

Checked #398 — it's the merged loop-swarm feature (sandboxed multi-agent consensus), unrelated to the manifest here. I don't see a real dependency; this can proceed independently.

Happy to send a PR along these lines if this matches what you had in mind — let me know if you'd rather see a different transaction model.

amarjaleelbanbhan avatar Jul 29 '26 17:07 amarjaleelbanbhan

Fixed by #430 — concurrent manifest mutations now serialized via file mutex + atomic write; concurrent create tests cover the repro.

cobusgreyling avatar Jul 29 '26 18:07 cobusgreyling