Skip to content

fix(worktrees): parallel New Session worktrees are created one at a time - #166060

Merged
steipete merged 8 commits into
mainfrom
codex/stab-worktree-reservation
Oct 7, 2026
Merged

steipete merged 8 commits into
mainfrom
codex/stab-worktree-reservation

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Maintainer decision (2026-10-05): approved design. A persisted pending-slot reservation replaces the global create lease held across the whole worktree create. Maintainer approved the merge on 2026-10-06.

What Problem This Solves

Fixes: managed worktree creation was fully serialized. Every New Session with a worktree held one global create/capacity lease, across all repositories, for its whole creation: template preparation, materialization, provisioning, publication, and cleanup. Five parallel worktree sessions became ready one after another, at 10 / 18 / 28 / 40 / 55 s with a warm template (31 to 99 s cold), although each native clone takes 1 to 2 s.

User Impact

User impact: several worktree sessions started together now prepare in parallel; the last one is ready in about 20 s instead of 55 s. Capacity limits, name and owner dedup, rollback on failure, and eviction protection still hold. After a Gateway crash during creation, abandoned reservations and template readers are reclaimed and later creates proceed. Partially created checkouts are kept for manual recovery.

Why This Change Was Made

allocation.ts held the global lease through the entire create, and capacity counted only completed live records. Creates now reserve a persisted pending slot under a short lease (capacity counts live and pending slots; name and owner dedup happen at reservation), materialize outside the lease, then publish atomically (pending to live) or roll the slot back. Template preparation has its own build and reader custody, so one cold build serves concurrent waiters. Allocation reclaims pending slots whose owner process is dead, and template acquisition reaps dead readers, through the existing process-liveness and lease owners. A create's contention budget counts only time spent waiting to acquire allocation, checkout and template custody, never admitted preparation, so a create that finished preparing can always publish. A create that cannot acquire custody within the budget fails with an actionable error instead of waiting forever. All template SQL lives in a worker-thread owner (template-registry.worker.ts); the main-thread SQLite ratchet drops from 846 on main to 838. Existing state needs no migration (schema version unchanged). Main's fs-safe index cloning, stale pack-index rebuild, and complete cleanup reporting are preserved.

Evidence

Live (dev Gateway, OpenAI-backed agent on the built-in runtime, a large git repository, warm template):

Scenario main this branch
5 concurrent sessions.create {worktree: true}, when each run starts 10 / 18 / 28 / 40 / 55 s 16 / 18 / 19 / 20 / 20 s (second run 17 / 17 / 20 / 20 / 20 s)
SIGKILL while 5 creates are materializing, restart, then 3 concurrent creates 3/3 complete 3/3 complete twice (10 to 13 s)

Interim live finding during development: the first version hung one of three post-crash creates indefinitely (leaked dead-owner custody). That was fixed with regressions, and the crash replay above is on the fixed code.

Owner probes (synthetic repository): five concurrent creates complete in 5.5 to 8.2 s. After a SIGKILL, three restart creates complete in 9.5 to 11.2 s, with zero active pending slots and zero template readers on readback.

Tests: 240 cases across 21 files: reservation, capacity, templates, restoration, snapshot indexes, Git maintenance, GC, sandbox templates, CLI, and Gateway/RPC siblings. The final committed owner replay is 17 files with 182 tests passing (461 s). Negative controls reproduce the original serialization, the restart and budget hangs, and both queued-death cases. Oxlint, oxfmt, docs sanity, the madge cycle check (0), and the whole-branch autoreview are clean. Scoped types failed only on an unrelated main test-support error that main has since fixed (7b9405e22d7b).

CI follow-up: the first exact-head run failed the main-thread SQLite ratchet (846 -> 850, template-registry.ts 8 -> 12). The follow-up commits move all template SQL into the worker owner, which brings the ratchet to 838 and removes 99 production lines. They also route pending-slot recovery through the provisioning worker, and fix a stale GC fixture and the PR wrapper's pending-recovery routing. Both of those failures were reproduced before the fix. Owner coverage: 241 cases passing (one ReFS platform skip). The five-concurrent and SIGKILL probes still pass.

Second review/CI round (ClawSweeper revision 2 and CI run 37452061759):

  • [P2] the contention deadline also elapsed during preparation, so a slow but successful preparation could lose its checkout at publication. Allocation now tracks cumulative acquisition wait only; fake-clock regressions cover 29- and 30-minute admission waits followed by 2 minutes of preparation.
  • Cleanup diagnostics name the failed branch/worktree operation again and keep its cause.
  • Sparse retries keep the branch-exists refusal and leave partial files intact.
  • The project-registry cancellation failures were a fixture deadlock; the outcome assertions are unchanged.
  • The CI planner expectation now accepts provisioning's required infra owner.

All 65 worktree/project/planner area files pass (63 passed, 2 platform skips). Whole-branch autoreview: "patch is correct", no findings.

Production +1498/-713, tests +1296/-169, docs +9/-5 (against base 9ad97b2).

Reserve names, owners, and live-plus-pending capacity under short allocation custody; materialize and set up checkouts under their own mutation leases. Publish atomically and retain custody until rollback settles. Give templates independent persisted build and reader custody, and preserve uncertain native artifacts through existing GC recovery.

Reuse state_leases without a schema migration. Existing state loads unchanged. Deterministic owner regressions fail on the original global-lease path; local Git, SQLite, acceleration, source, restore, and eviction checks pass. Five-create isolated sample improves from 24.272s to 9.652s with higher peak RSS. Recovery retains uncertain paths and template readers rather than deleting potentially active native work.
Reclaim dead pending admissions before allocation and reap dead template readers without waiting for another OS boot. Preserve incomplete checkout paths and reject retained explicit names with recovery guidance. Share the existing contention budget across create retries.

Keep parallel materialization outside the global lease. Cover restart, owner/name reuse, deadline exhaustion, and the checkout mutation lease used by W16 fault injection tests. No schema or configuration migration.
Preserve current-main index cloning, pack-index repair, and complete cleanup outcomes. Recover dead pending admissions after queued contenders release checkout custody, without changing live-owner refusal or lease ordering.

Remove the superseded template touch path, bind stale-GC proof to template custody, and include reservation dependencies in extracted PR wrappers. Existing owner and downstream suites pass; new waiter cases fail before the repair. Core types retain the pinned-main missing gatewayLog error outside this owner.
@clawsweeper

clawsweeper Bot commented Oct 6, 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 scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 6, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 6, 2026, 8:57 PM ET / October 7, 2026, 00:57 UTC (Revision 5).

ClawSweeper review

What this changes

The branch allows managed session worktrees to prepare concurrently using persisted capacity reservations, shared template custody, and crash recovery.

Merge readiness

✅ Ready for maintainer review

The PR remains useful and has no actionable findings. The maintainer’s explicit merge approval resolves the previous review’s final decision blocker.

Priority: P2
Reviewed head: fe6591f9ad88444ac052dde03902d5d794cd0cc1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, coherent implementation with production-path concurrency and crash evidence, resolved prior findings, and successful enforced status gates.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured dev-Gateway sessions.create timing comparison and repeated SIGKILL/restart recovery exercise the changed worktree allocation, template, and publication path. Existing-state source inspection and same-version reopen/table-absence regressions support compatibility without migration; downgrade requires settled pending operations.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured dev-Gateway sessions.create timing comparison and repeated SIGKILL/restart recovery exercise the changed worktree allocation, template, and publication path. Existing-state source inspection and same-version reopen/table-absence regressions support compatibility without migration; downgrade requires settled pending operations.
Evidence reviewed 10 items Pinned introduced changes: Reviewed the merge-base-to-head changes, preserving the original head identity. The stale test merge was not used to infer removals or regressions of current-main behavior.
Still necessary on fetched main: Fetched main still invokes the entire creation callback inside the global allocation lease. The branch instead retains checkout custody while using short allocation intervals for reservation and publication.
Previous contention finding resolved: Acquisition timing stops when a lease is obtained. The new owner-boundary regressions exercise 29- and 30-minute contention waits followed by two minutes of preparation and require successful publication, intact files, and no pending slots.
Findings None None.
Security None None.

How this fits together

Managed worktrees give agent sessions separate Git checkouts. Session creation feeds repository and owner selections into this service, which allocates capacity, prepares files, and publishes the checkout for the session.

flowchart TD
  A[New session requests] --> B[Reserve capacity and identity]
  B --> C[Shared source template]
  C --> D[Parallel checkout preparation]
  D --> E[Atomic publication]
  E --> F[Session ready]
  D --> G[Failure or crash recovery]
  G --> B
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +779, Tests +1143, Docs +4, Other +2. Total +1928 across 46 files.

View PR surface stats
Area Files Added Removed Net
Source 25 1491 712 +779
Tests 17 1312 169 +1143
Docs 2 9 5 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 2 3 1 +2
Total 46 2815 887 +1928

Review metrics

Metric Value Why it matters
Production versus test growth production net +785 lines; tests net +1127 lines Production growth implements durable reservation and reader recovery; the added tests cover concurrency, cancellation, publication, and crash settlement.

Technical review

Best possible solution:

Retain one capacity owner with short reservation and publication custody, independent checkout preparation, and conservative recovery of uncertain artifacts.

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

Yes: fetched main holds the global allocation lease around the full creation callback, and the supplied live Gateway comparison demonstrates sequential readiness. This reviewer did not execute a reproduction.

Is this the best way to solve the issue?

Yes: the patch keeps the existing capacity and worker settlement owners while moving preparation outside global custody; the prior contention defect is repaired.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7880834c1961.

Labels

Label changes:

  • add merge-risk: 🚨 compatibility: Older builds do not understand active pending reservations; the documented requirement to settle operations before downgrade is covered by the final approval.

Label justifications:

  • P2: This improves concurrent session startup latency while preserving existing capacity and recovery contracts.
  • merge-risk: 🚨 compatibility: Older builds do not understand active pending reservations; the documented requirement to settle operations before downgrade is covered by the final approval.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured dev-Gateway sessions.create timing comparison and repeated SIGKILL/restart recovery exercise the changed worktree allocation, template, and publication path. Existing-state source inspection and same-version reopen/table-absence regressions support compatibility without migration; downgrade requires settled pending operations.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured dev-Gateway sessions.create timing comparison and repeated SIGKILL/restart recovery exercise the changed worktree allocation, template, and publication path. Existing-state source inspection and same-version reopen/table-absence regressions support compatibility without migration; downgrade requires settled pending operations.

Evidence

What I checked:

  • Pinned introduced changes: Reviewed the merge-base-to-head changes, preserving the original head identity. The stale test merge was not used to infer removals or regressions of current-main behavior. (fe6591f9ad88)
  • Still necessary on fetched main: Fetched main still invokes the entire creation callback inside the global allocation lease. The branch instead retains checkout custody while using short allocation intervals for reservation and publication. (src/agents/worktrees/service-preparation.ts:98, 7880834c1961)
  • Previous contention finding resolved: Acquisition timing stops when a lease is obtained. The new owner-boundary regressions exercise 29- and 30-minute contention waits followed by two minutes of preparation and require successful publication, intact files, and no pending slots. (src/agents/worktrees/service.pending-slots.test.ts:155, fe6591f9ad88)
  • Current authority and atomic publication: Reservation requires allocation and checkout leases; publication checks the pending checkout identity. The worker transaction revalidates lease ownership at transaction admission and commit. Tests reject missing custody and changed publication identity without losing the reservation. (src/agents/worktrees/registry-run-end.worker.ts:329, fe6591f9ad88)
  • Real production-path evidence: The captured PR body reports five concurrent sessions.create requests through a dev Gateway with an OpenAI-backed built-in agent and a large repository: readiness changes from 10/18/28/40/55 seconds to 16/18/19/20/20 seconds, with a second successful run. Two post-SIGKILL restart replays complete all three creates in 10–13 seconds. These observations exercise the changed allocation, template, publication, and recovery owners; they were not rerun during this read-only review. (fe6591f9ad88)
  • Existing-state compatibility: The pending reservations and template readers use new scopes in the existing state_leases table; existing worktree/template record shapes remain intact. The template regression exercises an absent same-version table, database reopening, and stale-generation refusals. The documented downgrade condition is to let pending operations settle first. (src/agents/worktrees/template-registry.test.ts:50, fe6591f9ad88)

Likely related people:

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

History

Review history (4 earlier review cycles)
  • reviewed 2026-10-06T09:59:20.235Z sha ab1e22c :: blocked before merge. :: [P2] [P2] Exclude preparation time from the contention budget
  • reviewed 2026-10-06T10:53:23.999Z sha 2f13c0b :: blocked before merge. :: [P2] [P2] Exclude preparation time from the contention budget
  • reviewed 2026-10-06T11:37:39.476Z sha 9a9215d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-06T12:01:26.495Z sha fe6591f :: blocked before merge. :: none

Use the admitted worker database for template reads, writes, and reader custody. Remove the synchronous registry implementation and its nested transaction; migrate test callers to the async owner. Keep transaction and commit admission and native settlement intact.

The SQLite worker ratchet falls from 850 T1 operations to 838 (base: 846). A real broker regression fails on the previous implementation when an explicit database differs from the environment default, and passes through the selected worker database after the cutover. Existing schema and retention contracts are unchanged.
Keep allocation recovery available in the extracted PR wrapper without loading the application command runtime. Reuse the existing run-end transaction, lease validation, and recovery kernel; remove the superseded dispatcher registration and consume the central command contract.

Exercise allocation recovery in the extracted bootstrap regression and align the GC ranking fixture with its synthetic slot inventory. Both the native PR flow and the upgraded bootstrap test failed on the previous routing; the bootstrap passes after the cutover. No schema, retention, or public command changes.
Share cumulative acquisition time across admission, checkout, and template lease waits. Completed preparation can acquire a free publication lease even after exhausting its contention budget; further contention retains actionable timeout diagnostics.

Preserve create cleanup operation diagnostics and the branch-exists refusal for retained sparse checkouts. Correct provisioning test ownership and isolate recovery settlement in project cancellation fixtures without weakening outcome assertions. Add fake-clock regressions that fail before the repair.
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 6, 2026
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper approve

Maintainer approval: merge this. The design was approved on 2026-10-05; the exact head has a clean ClawSweeper review and green required CI.

@clawsweeper

clawsweeper Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Command router queued. I will update this comment with the next step.

@steipete
steipete merged commit c6168a9 into main Oct 7, 2026
161 checks passed
@steipete
steipete deleted the codex/stab-worktree-reservation branch October 7, 2026 01:03
@steipete

steipete commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
…ime (openclaw#166060)

* fix(worktrees): reserve pending slots for parallel creation

Reserve names, owners, and live-plus-pending capacity under short allocation custody; materialize and set up checkouts under their own mutation leases. Publish atomically and retain custody until rollback settles. Give templates independent persisted build and reader custody, and preserve uncertain native artifacts through existing GC recovery.

Reuse state_leases without a schema migration. Existing state loads unchanged. Deterministic owner regressions fail on the original global-lease path; local Git, SQLite, acceleration, source, restore, and eviction checks pass. Five-create isolated sample improves from 24.272s to 9.652s with higher peak RSS. Recovery retains uncertain paths and template readers rather than deleting potentially active native work.

* fix(worktrees): recover custody after creator crashes

Reclaim dead pending admissions before allocation and reap dead template readers without waiting for another OS boot. Preserve incomplete checkout paths and reject retained explicit names with recovery guidance. Share the existing contention budget across create retries.

Keep parallel materialization outside the global lease. Cover restart, owner/name reuse, deadline exhaustion, and the checkout mutation lease used by W16 fault injection tests. No schema or configuration migration.

* fix(worktrees): complete reservation recovery integration

Preserve current-main index cloning, pack-index repair, and complete cleanup outcomes. Recover dead pending admissions after queued contenders release checkout custody, without changing live-owner refusal or lease ordering.

Remove the superseded template touch path, bind stale-GC proof to template custody, and include reservation dependencies in extracted PR wrappers. Existing owner and downstream suites pass; new waiter cases fail before the repair. Core types retain the pinned-main missing gatewayLog error outside this owner.

* fix(worktrees): consolidate template SQL in worker owner

Use the admitted worker database for template reads, writes, and reader custody. Remove the synchronous registry implementation and its nested transaction; migrate test callers to the async owner. Keep transaction and commit admission and native settlement intact.

The SQLite worker ratchet falls from 850 T1 operations to 838 (base: 846). A real broker regression fails on the previous implementation when an explicit database differs from the environment default, and passes through the selected worker database after the cutover. Existing schema and retention contracts are unchanged.

* test(worktrees): route provisioning proof through database broker

* fix(worktrees): route pending recovery through provisioning worker

Keep allocation recovery available in the extracted PR wrapper without loading the application command runtime. Reuse the existing run-end transaction, lease validation, and recovery kernel; remove the superseded dispatcher registration and consume the central command contract.

Exercise allocation recovery in the extracted bootstrap regression and align the GC ranking fixture with its synthetic slot inventory. Both the native PR flow and the upgraded bootstrap test failed on the previous routing; the bootstrap passes after the cutover. No schema, retention, or public command changes.

* fix(worktrees): exclude preparation from contention waits

Share cumulative acquisition time across admission, checkout, and template lease waits. Completed preparation can acquire a free publication lease even after exhausting its contention budget; further contention retains actionable timeout diagnostics.

Preserve create cleanup operation diagnostics and the branch-exists refusal for retained sparse checkouts. Correct provisioning test ownership and isolate recovery settlement in project cancellation fixtures without weakening outcome assertions. Add fake-clock regressions that fail before the repair.

* fix(worktrees): keep template validation index read-only
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts 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