Skip to content

fix(worktrees): preserve work during creation and cleanup races - #149914

Merged
steipete merged 1 commit into
mainfrom
codex/worktree-lifecycle-safety
Sep 16, 2026
Merged

steipete merged 1 commit into
mainfrom
codex/worktree-lifecycle-safety

Conversation

@steipete

@steipete steipete commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Related #101721.

What Problem This Solves

Fixes managed worktree creation using stale disk estimates after a source branch moves, and overlapping creation, restoration, cleanup, or failed session setup removing work owned by another operation.

User Impact

New worktrees retain native Git upstream tracking and submodule behavior while checking capacity for the commit actually selected. Cleanup preserves unfinished clones, active work, recovery snapshots, and checkouts reused by another session operation. Cancellation cleans up a fresh allocation; loss of allocation ownership preserves it for recovery.

Also fixes stale origin/HEAD fallback, nested working directories such as ..notes, and Git-lock recovery after registry-read failures. Existing configuration, public create results, schemas, and retention periods stay unchanged.

Why This Change Was Made

Git registers the branch without checking out files; the allocation owner then captures its commit and materializes that exact source. Rollback uses live allocation authority and the original Git registration, independently of caller cancellation. Snapshot expiry and orphan cleanup share that ownership, and session preparation consumes the service's actual allocation outcome.

Source-template keys exclude branch-tracking metadata so remote-based restores can reuse their templates. The unused caller-owned branch mode and dead lease bookkeeping are removed.

Evidence

  • Linux Testbox: 373 worktree tests and 276 Gateway creation, archive, delete, and worktree RPC tests passed. Run.
  • Reproduced moving-ref admission and submodule-recursion failures before fixing them; regressions cover cold/warm templates, upstream tracking, cancellation, actual lease loss, changed Git registration, and rollback/cleanup races.
  • Changed-file formatting, typechecks, lint, repository guards, and git diff --check passed.
  • Independent Codex review: no actionable P0–P2 findings.
  • Native macOS arm64 / APFS: all 28 tests in service.apfs.test.ts, filesystem-apfs.test.ts, filesystem-native.test.ts, and checkout-apfs.test.ts passed with no skips at landed commit 23fb1c04eaf6ccf995edc4c99008bc3229cf3272 (Node 26.8.2, 32.88 seconds). This verifies real clone identities, independent writes, modes/symlinks, ACL preservation and fallback, Git index edit detection, cancellation and authority fencing, plus creation, provisioning, removal, restore, invalidation, and cleanup. Temporary repositories, state, and worktrees used an APFS volume with sufficient free space; capacity checks remained enabled.
  • Required hosted CI passed for the reviewed head. Run.

Native ReFS block-clone integration remains unverified on a ReFS volume.

Pin checkout sizing and materialization to the commit Git actually registers,
while retaining native upstream tracking and submodule behavior. Keep rollback
under allocation ownership after caller cancellation and fence it after lease
loss or a changed Git registration.

Serialize orphan cleanup and snapshot expiry with creation and restore, recheck
activity before cleanup, and use the actual allocation outcome for session
rollback. Recover Git locks after registry errors, handle stale origin/HEAD and
nested working directories, and remove unused branch and lease machinery.
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL maintainer Maintainer-authored PR labels Sep 16, 2026
@steipete
steipete marked this pull request as ready for review September 16, 2026 09:03
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 16, 2026, 5:10 AM ET / 09:10 UTC.

ClawSweeper review

What this changes

The PR pins worktree creation to its selected commit, coordinates cleanup with allocation, and limits failed-session rollback to checkouts that operation created or restored.

Merge readiness

⛔ Blocked before merge - 1 item remains

This remains a useful lifecycle repair: current main retains the affected creation and cleanup paths, and no actionable introduced defect was found. The maintainer-protected PR is not a cleanup-close candidate.

Priority: P2
Reviewed head: 8da7971b6cd29064f91e2d5d8e84e9ce54e03b8c

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent lifecycle repair with focused regression coverage and no supported blocking finding.
Proof confidence 🌊 off-meta tidepool Not applicable: The supplied maintainer-author context exempts this internal repair from the external-contributor proof gate. Service regressions cover real Git creation, rollback, and lease reassignment; reported Linux results remain supplemental, with native backends skipped and linked job logs inaccessible to this reviewer.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied maintainer-author context exempts this internal repair from the external-contributor proof gate. Service regressions cover real Git creation, rollback, and lease reassignment; reported Linux results remain supplemental, with native backends skipped and linked job logs inaccessible to this reviewer.
Evidence reviewed 10 items Pinned change ownership: Reviewed the merge-base-to-head changes. The recorded test merge has the pinned base followed by the exact PR head as its parents; unrelated base-branch changes were excluded.
Creation and rollback owner: Creation registers without checkout, captures the registered commit, estimates that commit, and verifies the original registration before fallback or rollback. Allocation rollback checks live lease ownership independently of caller cancellation.
Cleanup and session integration: Orphan cleanup and snapshot expiry acquire the allocation lease and reread registry state. Session preparation consumes the service's materialized outcome instead of deciding rollback from an earlier directory observation.
Findings None None.
Security None None.

How this fits together

Managed worktrees give agent sessions isolated Git checkouts. The worktree service turns creation, restoration, and cleanup requests into filesystem operations and registry records consumed by the Gateway.

flowchart TD
  A[Session or CLI request] --> B[Worktree service]
  B --> C[Shared allocation lease]
  C --> D[Register and capture commit]
  D --> E[Check capacity and materialize files]
  E --> F[Publish registry and session outcome]
  C --> G[Cleanup with current ownership checks]
  G --> H[Preserve work or remove safely]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +74, Tests +537, Docs +2. Total +613 across 20 files.

View PR surface stats
Area Files Added Removed Net
Source 8 485 411 +74
Tests 11 1025 488 +537
Docs 1 6 4 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 20 1516 903 +613

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +74 net lines; tests +537 net lines Production growth implements shared lifecycle fencing and allocation outcomes, with most growth devoted to race regressions.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/worktrees/run-lease.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep allocation and destructive cleanup under one live lease, with commit-pinned materialization and owner-produced rollback outcomes.

Do we have a high-confidence way to reproduce the issue?

Yes, source establishes the moving-ref and cleanup interleavings, and focused regressions encode them through the production service. This read-only review did not execute a failing current-main reproduction.

Is this the best way to solve the issue?

Yes. Extending the existing allocation owner and returning its actual outcome repairs the race at its source while preserving public results, configuration, schemas, and retention periods.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6cfec0530a3b.

Labels

Label changes:

  • add P2: This addresses bounded managed-worktree creation and cleanup races without evidence of a widespread current outage.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer-author context exempts this internal repair from the external-contributor proof gate. Service regressions cover real Git creation, rollback, and lease reassignment; reported Linux results remain supplemental, with native backends skipped and linked job logs inaccessible to this reviewer.

Label justifications:

  • P2: This addresses bounded managed-worktree creation and cleanup races without evidence of a widespread current outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied maintainer-author context exempts this internal repair from the external-contributor proof gate. Service regressions cover real Git creation, rollback, and lease reassignment; reported Linux results remain supplemental, with native backends skipped and linked job logs inaccessible to this reviewer.

Evidence

What I checked:

  • Pinned change ownership: Reviewed the merge-base-to-head changes. The recorded test merge has the pinned base followed by the exact PR head as its parents; unrelated base-branch changes were excluded. (8da7971b6cd2)
  • Creation and rollback owner: Creation registers without checkout, captures the registered commit, estimates that commit, and verifies the original registration before fallback or rollback. Allocation rollback checks live lease ownership independently of caller cancellation. (src/agents/worktrees/checkout.ts:316, 8da7971b6cd2)
  • Cleanup and session integration: Orphan cleanup and snapshot expiry acquire the allocation lease and reread registry state. Session preparation consumes the service's materialized outcome instead of deciding rollback from an earlier directory observation. (src/gateway/session-worktree-preparation.ts:233, 8da7971b6cd2)
  • Regression coverage: Inspected introduced regressions for moving refs, cancellation, actual SQLite lease reassignment, changed Git registration, concurrent snapshot expiry, and session rollback. They exercise production service operations with real Git and temporary files; acceleration tests substitute directory copies for native backends. Tests were not executed during this read-only review. (src/agents/worktrees/service.capacity.test.ts:127, 8da7971b6cd2)
  • Current-main necessity: The inspected allocation, checkout, service, base-ref, run-lease, and session-preparation files have no changes between the pinned merge base and fetched main. Consequently, current main does not contain this repair. The local tag-containment check returned no tag containing the PR head; no fixed release is claimed. (src/agents/worktrees/service.ts, 6cfec0530a3b)
  • Related issue disposition: worktree GC TOCTOU race - concurrent create can be deleted by stale registry snapshot #101721 is closed. Its discussion credits earlier run-admission/removal serialization in fix(agents): lease session worktrees during runs #103263; that does not supersede this PR's unfinished-allocation and snapshot-expiry fixes.

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • fuller-stack-dev: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

@steipete

Copy link
Copy Markdown
Contributor Author

Checked the data-model compatibility flag against 8da7971b6cd29064f91e2d5d8e84e9ce54e03b8c: no persistent model or migration changes are present. In run-lease.ts, heldGitLocks and pendingLeaseCleanups are process-local Map/Set state; the removed gitUnlockPending field was unused bookkeeping in that Set. Moving registry reads inside the existing error handling repairs failed acquisition and deferred Git unlock without changing stored rows, lease scopes, serialization, retention, or the registry APIs. The registry and src/state/** have no diff from the PR base, so existing stored data requires no migration or backfill.

The passing 373-test worktree run includes registry persistence and existing-registry migration coverage, plus the regressions for reacquiring a Git guard after a registry-read failure and retrying a failed registry read during release. These exercise existing records through the unchanged SQLite owner and real Git locks. The tested source tree is exactly the pushed commit tree (cf302b3ce682fe5c0955c197e506e7f3a3ce5534). Testbox run. This resolves the compatibility concern; no migration test for a nonexistent data-format change is needed.

@steipete
steipete merged commit 23fb1c0 into main Sep 16, 2026
262 checks passed
@steipete
steipete deleted the codex/worktree-lifecycle-safety branch September 16, 2026 09:35
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 17, 2026
…claw#149914)

Pin checkout sizing and materialization to the commit Git actually registers,
while retaining native upstream tracking and submodule behavior. Keep rollback
under allocation ownership after caller cancellation and fence it after lease
loss or a changed Git registration.

Serialize orphan cleanup and snapshot expiry with creation and restore, recheck
activity before cleanup, and use the actual allocation outcome for session
rollback. Recover Git locks after registry errors, handle stale origin/HEAD and
nested working directories, and remove unused branch and lease machinery.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant