Repository navigation
fix(agents): lease session worktrees during runs - #103263
Conversation
|
Codex review: needs changes before merge. Reviewed July 11, 2026, 7:21 PM ET / 23:21 UTC. Summary PR surface: Source +699, Tests +639. Total +1338 across 8 files. Reproducibility: yes. The supplied before-and-after proof drives the real preparation path and a real two-process Git and SQLite removal race, showing current main deletes the active checkout while the patched path preserves it. Review metrics: 1 noteworthy metric.
Stored data model Root-cause cluster Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Risk before merge
Maintainer options:
Copy recommended automerge instructionNext step before merge
Security Review findings
Review detailsBest possible solution: Keep the SQLite immediate transaction as the single cross-process admission and removal authority, but make Git-guard cleanup treat an already removed worktree as complete and add a force-remove-live-lease regression proving no pending cleanup or false guard survives. Do we have a high-confidence way to reproduce the issue? Yes. The supplied before-and-after proof drives the real preparation path and a real two-process Git and SQLite removal race, showing current main deletes the active checkout while the patched path preserves it. Is this the best way to solve the issue? Mostly yes. SQLite BEGIN IMMEDIATE is the narrowest repository-aligned cross-process authority, but the secondary Git-guard cleanup must explicitly handle a live lease whose worktree was force-removed. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 453c049ac89d. Label changesLabel changes:
Label justifications:
Evidence reviewedPR surface: Source +699, Tests +639. Total +1338 across 8 files. View PR surface stats
Acceptance criteria:
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
Review history (16 earlier review cycles; latest 8 shown)
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
a3833de to
9201264
Compare
|
Doing a review and found a few things before merge that will help this.
|
9201264 to
f12f790
Compare
0d1f681 to
c4717de
Compare
|
Addressed all three cleanup-lifecycle findings; new head c4717de4.
On the two risks flagged: force bypassing a live run lease is the intended operator-override contract, and it still prunes stale rows and takes the exclusive removing claim so it cannot corrupt a concurrent remover; I can gate it further if you want a stricter force contract. I will rebase onto the exact merge head when you are ready to land. Real behavior proof refreshed on c4717de4 (production preparation path via the real prepareAgentCommandExecution, plus the two-process race against the real service). |
|
@clawsweeper re-review |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
@steipete The core is now what you prescribed: a shared run-lease plus an exclusive removal claim over state_leases, serialized through one BEGIN IMMEDIATE, with opaque tokens, pid/start identity, stale-owner recovery, and the git lock kept only as a secondary raw-Git guard. The two-process race, parent/child shared readers, workspace-only children, SIGKILL recovery, ABA, and force parity are all covered. Where it is not converging is the secondary git-guard cleanup lifecycle. Since your review each re-review has found and I have fixed a new edge in that same area (removal-claim exclusivity, then release-retry ordering, then held-during-preparation, then refcount/retained-unlock), and the current head still carries one P1 there. Six heads in a day on the same corner is the signal that I am chasing review edges rather than closing. So I would rather ask you than keep spinning: do you want me to hold this while the SQLite lease semantics settle, or would you prefer to supersede it by closing this PR(Or Keeping open and making edits), or take the implementation yourself now that the shape is agreed? The design is where you wanted it; I am happy either to land one more focused pass on the git-guard cleanup or to step back and let you own it. Your call on which is the better use of your time. |
…emoval claim A resumed session's managed worktree could be removed mid-run by idle GC, a separate remover, or a manual worktrees.gc, destroying in-flight work; a session whose worktree was already removed was admitted anyway and ran without its checkout. Runs now take a shared run-lease and removal takes an exclusive claim, both held as rows in the shared state_leases table so admission and removal serialize through one BEGIN IMMEDIATE transaction. Lease rows carry an opaque token plus pid and process start time; dead or reused-pid owners are pruned inside the same transaction. Removal claims before any cleanliness or snapshot work and rejects while a live run lease exists; a run releases only its own token. The worktree id is resolved from the session binding or by containment over both the run cwd and workspace dir, so a workspace-only child still leases. The git worktree lock is retained as a secondary raw-Git guard and refcounted per process so a parent and a same-process child do not unlock each other.
c4717de to
2b68918
Compare
|
ClawSweeper status: review started. I am starting a fresh review of this pull request: fix(agents): lease session worktrees during runs This is item 1/1 in the current shard. Shard 0/1. This placeholder means the worker is alive and reading the current context. I will edit this same comment with the actual review when the claws are done clicking. Crustacean status: shell secured, claws on keyboard, evidence pebbles being sorted. |
|
Merged via squash.
|
What Problem This Solves
A resumed session's managed git worktree could be deleted out from under an active agent run. Idle GC, a separate remover, or a manual
worktrees.gcwould remove the session's isolated checkout while the run was still using it, destroying in-flight workspace files. The silent counterpart also existed: a session whose managed worktree had already been removed was admitted anyway and ran as if its cwd were an ordinary directory, with no checkout.Why This Change Was Made
This is a rewrite of the earlier approach after maintainer review. The earlier head used a process-local FIFO lease, which was an exclusive full-run mutex (a parent and a child run sharing one worktree could deadlock), leased only
cwd, and leaned ongit worktree lockas the admission/removal mutex even though that lock is not an atomic cross-process check-and-act.Runs now take a shared run-lease and removal takes an exclusive claim, both stored as rows in the existing shared-state
state_leasestable. Admission and removal each run inside onerunOpenClawStateWriteTransaction, which usesBEGIN IMMEDIATE(src/infra/sqlite-transaction.ts), so the read-check-write is serialized across processes by SQLite itself. That single transaction is the atomic admission/removal gate, replacing the git-lock TOCTOU. The git worktree lock is kept only as a secondary raw-Git guard, refcounted per process so a parent and a same-process child do not unlock each other.Ownership and lifetime details:
prepareAgentCommandExecutionbeforeensureAgentWorkspace, so the checkout is protected during workspace-dependent preparation, not just the run body; it is released on any prepare failure and in the run's outer cleanup.worktree.idbinding, or by containment over the run cwd and workspace dir. A session whose authoritative binding is removed or missing fails closed rather than continuing unmanaged.isLockOwnerDefinitelyStale, so a killed holder never strands the worktree.Choosing the shared state DB over sidecar claim files follows the repository storage policy (SQLite only for runtime registries), and reuses the cross-process lease table and transaction primitive already used by startup-migration checkpoints.
User Impact
Users resuming sessions with isolated worktrees can no longer have their live checkout deleted underneath an active run by idle GC, a manual gc, or session cleanup, including during workspace preparation, when the session works in a subdirectory of the worktree, and when a second process races the removal. A session whose checkout was removed while it was away now fails fast with a clear error instead of silently continuing without its files. Concurrent parent and child runs share one worktree without deadlocking, and two removers cannot corrupt a worktree by deleting it concurrently.
Evidence
origin/main; headc4717de4. Mergeable, behind current main.src/commands/agent.worktree-race.test.tsdrives the realprepareAgentCommandExecutionto prove the workspace-preparation window is leased and an authoritative removed binding fails closed before workspace setup.src/agents/worktrees/run-lease.test.tsandsrc/agents/worktrees/service.remove-lease.test.tscover parent/child shared readers with git-lock refcounting, workspace-only id resolution, fail-closed removed binding, dead-owner (SIGKILL) pruning, reused-pid (ABA) pruning, force parity, admission-fails-once-removing, dead-remover recovery, exclusive rejection of a second live remover (with and without force), owner-scoped abort that cannot clear a newer claim, a concurrent second remover rejected at the service level, a transient release failure recovering within one call, a sustained release failure retaining the lease and git guard and recovering on a later lifecycle retry, overlapping same-process acquisitions keeping the guard until the last release, and a git-unlock failure retained and released on a lifecycle retry.agent.test.ts,agent.session.test.ts, and the gateway worktrees/session-create/session-delete-lifecycle/server-maintenance suites pass unchanged.oxlint --type-awareandoxfmt --checkclean on all changed files;run-tsgo.mjs -p tsconfig.core.jsonclean.ensureAgentWorkspace, fail-closed binding); a non-retryable cleanup that dropped the git guard on a failed delete (bounded retry within the single release, guard retained until success); and cleanup ownership plus a concurrent refcount race (process-lifecycle-owned retry of a stuck row-delete or git-unlock, and a synchronous refcount reservation before the git lock await).Real behavior proof
Behavior addressed: the managed worktree must stay protected while the production run preparation reads or creates files and a separate process races removal; a session whose bound worktree was removed must fail admission before workspace setup instead of running without its checkout; and two removers must not enter destructive removal of one worktree at once.
Real environment tested: the real
prepareAgentCommandExecutionpreparation path plus the realManagedWorktreeServiceand the real shared-state SQLite lease store, driven on pristineorigin/mainf73c5541versus this patchc4717de4with identical inputs. The production path is driven with only config and plugin-registry loaders mocked (the real worktree service, registry, session store, and workspace step stay real, with the workspace step paused to hold the preparation window open). A second capture drives a genuine two-process race: a separate node process holds the run lease while the parent issues the removal, and a second overlapping removal is issued against the real service.Exact steps or command run after this patch: run the composed preparation test with observations recorded (
OPENCLAW_PROOF_OUT=... run-vitest src/commands/agent.worktree-race.test.ts), and run the two-process harness (node --import tsx proof-lease.mts) that creates a real session-owned git worktree with a nested workspace file, spawns a separate node process that acquires the run lease, issues non-forceManagedWorktreeServiceremovals from the parent during and after the run, and issues a second overlapping removal.Evidence after fix:
Observed result after fix: during production run preparation a racing removal is rejected as busy and the checkout survives, and a session bound to a removed worktree fails preparation before workspace setup runs; in the two-process race a separate process holding the run lease has its checkout preserved while a non-force removal is rejected and only succeeds after the run ends, and a second remover racing the first is rejected as already in progress. On the base, the same removals delete the live checkout and its in-flight file, preparation proceeds without a checkout and runs workspace setup on the removed worktree, and two removers collide into a corrupt half-removed worktree.
What was not tested: no live provider request, gateway deployment, or multi-host run was exercised; the two racing processes ran on the development Linux host sharing one state directory and git worktree, so cross-process protection rests on the directly exercised SQLite BEGIN IMMEDIATE serialization plus the on-disk git worktree lock; the production preparation capture mocks only the config and plugin-registry loaders and drives the real preparation, worktree service, registry, and session store.