Skip to content

fix(agents): lease session worktrees during runs - #103263

Merged
steipete merged 3 commits into
openclaw:mainfrom
yetval:fix/worktree-gc-live-session-race
Jul 11, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
yetval:fix/worktree-gc-live-session-race

Conversation

@yetval

@yetval yetval commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

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.gc would 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 on git worktree lock as 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_leases table. Admission and removal each run inside one runOpenClawStateWriteTransaction, which uses BEGIN 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:

  • The lease is acquired in prepareAgentCommandExecution before ensureAgentWorkspace, 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.
  • The worktree id is resolved from the session's stored worktree.id binding, 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.
  • Run leases and the removal claim are both token-owned: a run releases only its own token, and the removal claim rejects a competing live remover and clears or finalizes only under its own token, so two removers can never enter destructive work on one worktree at once.
  • Dead or reused-pid owners, including a removal claim whose remover process died before finalizing, are pruned inside the same transaction via isLockOwnerDefinitelyStale, so a killed holder never strands the worktree.
  • Lease cleanup is process-lifecycle-owned: release retries the row deletion within the call and drops the git guard only after the row is gone; a persistent state-database or git-unlock failure retains the row and guard and is retried on the next lease acquisition and at process exit, so the worktree stays protected and a stuck cleanup recovers without waiting for the process to end.
  • The in-process git-lock refcount reserves its slot synchronously before awaiting the git lock, so two overlapping same-process acquisitions cannot both record one holder and let the first release drop the guard while the other run is still live.

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

  • Branched off origin/main; head c4717de4. Mergeable, behind current main.
  • Focused suites pass. src/commands/agent.worktree-race.test.ts drives the real prepareAgentCommandExecution to prove the workspace-preparation window is leased and an authoritative removed binding fails closed before workspace setup. src/agents/worktrees/run-lease.test.ts and src/agents/worktrees/service.remove-lease.test.ts cover 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-aware and oxfmt --check clean on all changed files; run-tsgo.mjs -p tsconfig.core.json clean.
  • Review findings addressed across iterations: a stranded removal marker after a mid-removal crash (self-healing pid/start-time owner); an overwritable removal claim with non-owner-scoped cleanup (opaque token, exclusive rejection, owner-scoped abort); a lease acquired after workspace preparation and a removed authoritative binding that failed open (lease moved before 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 prepareAgentCommandExecution preparation path plus the real ManagedWorktreeService and the real shared-state SQLite lease store, driven on pristine origin/main f73c5541 versus this patch c4717de4 with 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-force ManagedWorktreeService removals from the parent during and after the run, and issues a second overlapping removal.
Evidence after fix:

### production run preparation
# BEFORE (pristine origin/main f73c5541)
removal during production workspace preparation: removed=true
managed checkout survived preparation: false
admission for a removed authoritative binding: preparation proceeded without its checkout
workspace setup ran on the removed worktree: true
# AFTER (this patch c4717de4, identical inputs)
removal during production workspace preparation: rejected: worktree is busy: locked by live pid 3081575
managed checkout survived preparation: true
admission for a removed authoritative binding: preparation fails: managed worktree was removed: .../worktrees/0cdd07f48a6b9ed0/race-session
workspace setup ran on the removed worktree: false

### two-process race against the real service
# BEFORE (pristine origin/main f73c5541)
separate-process run holder: run holds no lease
separate non-force removal during the live run: removed=true
nested in-flight file survived the removal attempt: false
removal after the run ends: rejected: unknown active worktree: 3df12926-0ce3-4056-8e1f-7dd110679a02
second remover racing the first: rejected: git worktree remove failed: fatal: '.../proof-concurrent' is not a working tree
# AFTER (this patch c4717de4, identical inputs)
separate-process run holder: run holds a lease
separate non-force removal during the live run: rejected: worktree is busy: locked by live pid 3081778
nested in-flight file survived the removal attempt: true
removal after the run ends: removed=true
second remover racing the first: rejected: worktree removal is already in progress

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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: XS labels Jul 10, 2026
@yetval
yetval marked this pull request as ready for review July 10, 2026 02:16
@yetval
yetval marked this pull request as draft July 10, 2026 02:17
@yetval
yetval marked this pull request as ready for review July 10, 2026 02:20
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. labels Jul 10, 2026
@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed July 11, 2026, 7:21 PM ET / 23:21 UTC.

Summary
The PR adds SQLite-backed shared run leases and exclusive removal claims for managed session worktrees, with a secondary Git worktree guard and focused race regressions.

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.

  • Persistent schema surface: 0 tables added, 1 existing lease table reused. The patch adds durable lease semantics without a state-database schema migration, but upgrade-safe row lifecycle still matters.

Stored data model
Persistent data-model change detected: serialized state: src/agents/worktrees/run-lease.test.ts, serialized state: src/agents/worktrees/service.remove-lease.test.ts. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster
Relationship: canonical
Canonical: #103263
Summary: This PR is the canonical candidate for the run-versus-removal lease race; the related GC callback work is complementary and independently necessary.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🦐 gold shrimp
Proof: 🦞 diamond lobster
Patch quality: 🦐 gold shrimp
Result: needs maintainer review before merge.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P2] Fix cleanup for a lease whose worktree was force-removed and add the focused regression.
  • Rerun the worktree lease, removal, and composed agent race suites on the repaired exact head.

Risk before merge

  • [P1] Force removal intentionally bypasses a live run lease and can delete an active checkout; even after the cleanup defect is fixed, maintainers should explicitly retain that operator-override contract.
  • [P1] The lease and removal paths govern persistent session workspace availability, so regression proof should continue covering both normal release and force-removal cleanup.

Maintainer options:

  1. Clear cleanup after force removal (recommended)
    Treat a removed or no-longer-present worktree as an already-cleared Git guard and cover force-remove-then-release, lifecycle drain, and restore or reacquire behavior.
  2. Pause the force override
    If safe cleanup cannot be made local, reject force removal while a live run lease exists until the lease lifecycle is redesigned.
Copy recommended automerge instruction
@clawsweeper automerge

Special instructions:
Fix run-lease Git-guard cleanup after force-removing a live leased worktree: do not retry unlock against a registry record whose worktree is already removed or absent, clear the held and pending cleanup state safely, and add focused force-remove-then-release plus restore or reacquire regression coverage.

Next step before merge

  • [P2] The remaining blocker is a narrow, mechanical lifecycle repair in the current PR rather than a product or ownership decision.

Security
Cleared: The patch adds no dependency, workflow, permission, secret, download, publishing, or third-party code-execution surface, and the local Git and SQLite changes expose no concrete security regression.

Review findings

  • [P2] Clear the Git guard after force-removing a live lease — src/agents/worktrees/run-lease.ts:125-132
Review details

Best 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:

  • [P2] Clear the Git guard after force-removing a live lease — src/agents/worktrees/run-lease.ts:125-132
    A forced removal unlocks and deletes the worktree, marks the registry record removed, and clears its lease rows. When the still-running lease later releases, this branch retrieves that removed record and tries git worktree unlock on a path that no longer exists; the failure keeps both the cleanup and gitLocked state pending, so later acquisition can adopt a guard that is not actually held. Treat removed or absent worktrees as an already-completed unlock and add a force-remove-then-release regression.
    Confidence: 0.97

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 453c049ac89d.

Label changes

Label changes:

  • add merge-risk: 🚨 session-state: The patch changes ownership and release semantics for session-bound worktrees across concurrent processes.
  • add merge-risk: 🚨 availability: The current force-removal cleanup path can retain a permanently retrying guard state and interfere with later lifecycle operations.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The PR contains convincing after-fix live output from the real agent preparation path and a separate-process race with real Git worktrees, the real service, and shared SQLite; no additional contributor proof is required for the reviewed behavior.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR contains convincing after-fix live output from the real agent preparation path and a separate-process race with real Git worktrees, the real service, and shared SQLite; no additional contributor proof is required for the reviewed behavior.

Label justifications:

  • P0: The underlying bug can destroy an active session worktree and its uncommitted in-flight files.
  • merge-risk: 🚨 session-state: The patch changes ownership and release semantics for session-bound worktrees across concurrent processes.
  • merge-risk: 🚨 availability: The current force-removal cleanup path can retain a permanently retrying guard state and interfere with later lifecycle operations.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Sufficient (live_output): The PR contains convincing after-fix live output from the real agent preparation path and a separate-process race with real Git worktrees, the real service, and shared SQLite; no additional contributor proof is required for the reviewed behavior.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR contains convincing after-fix live output from the real agent preparation path and a separate-process race with real Git worktrees, the real service, and shared SQLite; no additional contributor proof is required for the reviewed behavior.
Evidence reviewed

PR surface:

Source +699, Tests +639. Total +1338 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 5 895 196 +699
Tests 3 639 0 +639
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 1534 196 +1338

Acceptance criteria:

  • [P1] pnpm test src/agents/worktrees/run-lease.test.ts.
  • [P1] pnpm test src/agents/worktrees/service.remove-lease.test.ts.
  • [P1] pnpm test src/commands/agent.worktree-race.test.ts.
  • [P1] pnpm check:changed -- src/agents/worktrees/run-lease.ts src/agents/worktrees/run-lease.test.ts src/agents/worktrees/service.remove-lease.test.ts.

What I checked:

  • Atomic admission and removal gate: Run admission verifies the live registry record, prunes stale owners, rejects an active removal claim, and inserts its token row within one shared-state immediate transaction; removal performs its live-lease check and exclusive claim under the same transaction model. (src/agents/worktrees/registry.ts:254, dfbadd37a6cc)
  • Transaction contract: The shared-state writer uses a synchronous SQLite BEGIN IMMEDIATE transaction and rejects asynchronous transaction callbacks, matching the required atomic check-and-act boundary. (src/state/openclaw-state-db.ts:1496, dfbadd37a6cc)
  • Prior finding resolved: The maintainer follow-up serializes per-worktree Git-lock retain and release transitions and transfers unlock responsibility to a newer same-process holder, directly addressing the previous active-generation cleanup finding. (src/agents/worktrees/run-lease.ts:59, 2b689186a31f)
  • Force-removal cleanup defect: Force removal unlocks and deletes the worktree, marks its registry row removed, and clears its lease rows; the live run's later cleanup still retrieves that removed registry record and calls git worktree unlock on the deleted path, retaining the pending cleanup and in-process gitLocked state after the command fails. (src/agents/worktrees/run-lease.ts:125, dfbadd37a6cc)
  • Real behavior proof: The PR body records before-and-after output from the real preparation path and a separate-process race using the real managed-worktree service, Git operations, and shared SQLite store; current-head CI also completed successfully. (src/commands/agent.worktree-race.test.ts:1, dfbadd37a6cc)
  • Canonical scope check: The related manual-GC liveness issue and its candidate PR address missing caller predicates, not this PR's run-versus-removal lease race, so neither supersedes this work. (src/agents/worktrees/service.ts:742, 453c049ac89d)

Likely related people:

  • steipete: Current main history attributes the managed-worktree service to this person, the live PR is assigned to them, and they authored the current-head follow-ups for Git cleanup serialization and SQLite race-test seeding. (role: recent area contributor and assignee; confidence: high; commits: 324e8fff81c6, 2b689186a31f, dfbadd37a6cc; files: src/agents/worktrees/service.ts, src/agents/worktrees/run-lease.ts, src/commands/agent.worktree-race.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (16 earlier review cycles; latest 8 shown)
  • reviewed 2026-07-11T12:20:16.717Z sha 07a34750e892d688eef032adf38a2d1566f7f93b :: needs changes before merge. :: [P1] Keep failed lease cleanup retryable
  • reviewed 2026-07-11T12:27:19.058Z sha 07a34750e892d688eef032adf38a2d1566f7f93b :: needs changes before merge. :: [P1] Keep failed lease cleanup retryable
  • reviewed 2026-07-11T12:43:12.539Z sha 20d188b0d7fd494f2e9a02c36b4a6aa0ea9f10b6 :: needs changes before merge. :: [P1] Retry release within the production cleanup call
  • reviewed 2026-07-11T12:52:36.897Z sha 20d188b0d7fd494f2e9a02c36b4a6aa0ea9f10b6 :: needs real behavior proof before merge. :: [P1] Acquire the lease before workspace preparation | [P1] Fail closed for an authoritative removed binding | [P1] Retry release within the production cleanup call
  • reviewed 2026-07-11T13:47:19.250Z sha 0d1f681f9f037c8187e57c93b90f3353f618a37b :: needs changes before merge. :: [P1] Keep exhausted lease cleanup retryable
  • reviewed 2026-07-11T13:55:55.205Z sha 0d1f681f9f037c8187e57c93b90f3353f618a37b :: needs changes before merge. :: [P1] Keep exhausted lease cleanup retryable | [P2] Serialize same-process Git-lock refcount acquisition | [P2] Retain failed Git unlock cleanup
  • reviewed 2026-07-11T14:21:30.076Z sha c4717de4df278b8d450327eab0c2c62f8f1060c8 :: needs changes before merge. :: [P1] Keep failed unlock cleanup attached to the active lock generation
  • reviewed 2026-07-11T14:30:50.624Z sha c4717de4df278b8d450327eab0c2c62f8f1060c8 :: needs changes before merge. :: [P1] Keep failed unlock cleanup on the active lock generation

@yetval

yetval commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@yetval yetval changed the title fix(agents): re-check owner activity before force-removing a session worktree in GC fix(agents): lease session worktrees during runs Jul 10, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 10, 2026
@yetval

yetval commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@yetval

yetval commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@yetval
yetval force-pushed the fix/worktree-gc-live-session-race branch from a3833de to 9201264 Compare July 10, 2026 13:40
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 10, 2026
@Solvely-Colin

Copy link
Copy Markdown
Contributor

Doing a review and found a few things before merge that will help this.
Can you check these out to help.

  1. Rebase onto current origin/main and resolve src/agents/worktrees/service.ts.
  2. Acquire the managed-worktree lease before all workspace-dependent preparation.
  3. Add a composed regression test that pauses preparation while GC/removal races, covering both “run wins” and “removal wins before admission.”
  4. Prove that a removed managed session path fails instead of silently becoming an ordinary/recreated workspace.
  5. Rerun focused worktree, agent-command, session lifecycle tests and exact-head CI.

@yetval
yetval force-pushed the fix/worktree-gc-live-session-race branch from 9201264 to f12f790 Compare July 11, 2026 02:31
@openclaw-barnacle openclaw-barnacle Bot added the commands Command implementations label Jul 11, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 11, 2026
@yetval
yetval force-pushed the fix/worktree-gc-live-session-race branch from 0d1f681 to c4717de Compare July 11, 2026 14:15
@yetval

yetval commented Jul 11, 2026

Copy link
Copy Markdown
Contributor Author

Addressed all three cleanup-lifecycle findings; new head c4717de4.

  1. Concurrent same-process refcount (P2). The in-process git-lock refcount now reserves its slot synchronously before awaiting the git lock, so two overlapping acquisitions record refcount 2 and the guard holds until the last release. Regression: two Promise.all acquisitions, guard still live after the first release, released only after the second.

  2. Lifecycle-owned cleanup after exhausted row-delete (P1). A cleanup that cannot finish is retained in a process-owned pending set and retried on the next lease acquisition and at process exit, instead of being dropped by the single production caller. Regression: sustained delete failures keep the row and git guard, then a lifecycle retry frees both and lets removal proceed.

  3. Retained git-unlock (P2). Git unlock is now part of the same retained cleanup; an unlock failure keeps the guard and is retried on the next lifecycle drain. Regression: an injected unlock failure keeps the lock live, then a drain releases it.

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).

@yetval

yetval commented Jul 11, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@yetval

yetval commented Jul 11, 2026 •

Copy link
Copy Markdown
Contributor Author

@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.

yetval and others added 2 commits July 11, 2026 16:06
…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.
@steipete
steipete force-pushed the fix/worktree-gc-live-session-race branch from c4717de to 2b68918 Compare July 11, 2026 23:07
@clawsweeper

clawsweeper Bot commented Jul 11, 2026

Copy link
Copy Markdown
Contributor

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.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 11, 2026
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XL status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants