Skip to content

fix(worktrees): recover leaked branches and accept delayed heartbeat acks - #164615

Merged
steipete merged 2 commits into
mainfrom
steipete/worktree-capacity-lease-custody
Oct 4, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/worktree-capacity-lease-custody

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes same-session worktree retries failing with branch already exists after allocation ownership is lost during hydration, and valid lease checks failing when the parent resumes after the heartbeat response wait budget.

Related: #164521, which already landed worker-based allocation renewal, suppression of Git auto-maintenance during hydration/default-base fetches, and Git maintenance in the cleanup pass. This PR keeps that implementation and carries the remaining recovery and acknowledgment repairs.

User Impact

A failed creation can remove its unchanged, unprepared registration under fresh cleanup custody, allowing the same session to retry. Changed, published, or materialized checkouts remain preserved. A current heartbeat acknowledgment remains valid after a delayed parent wake while the worker is ready and the lease grant has not expired.

No schema, retention, durability, configuration, protocol, or migration changes are required. Production deployment and Gateway restart remain separate.

Why This Change Was Made

The old rollback immediately reused the lost allocation guard, so it could not delete the unprepared checkout or branch. Creation now lets allocation and source scopes unwind, reacquires allocation followed by source cleanup custody, and verifies the captured directory, Git registration, HEAD, empty checkout, and unpublished state before removal. The publication check uses the existing SQLite worker reader and revalidates cleanup authority after the awaited result. It never adopts an arbitrary branch by name.

The synchronous heartbeat guard previously discarded an already observed current acknowledgment solely because the parent resumed after the response wait budget. It now checks that acknowledgment and the unexpired grant before treating an unanswered wait as timed out. Persisted ownership validation, worker readiness, expired/replaced-owner refusal, the one-second unanswered-response budget, and asynchronous reply deadlines remain unchanged.

One additional preparation fetch remained uncovered by #164521: fetching a missing pinned commit in ensureProjectCheckoutCommit. That path now uses --no-auto-maintenance; the already-landed fetch flags and renewal tests are retained without duplicates.

Evidence

Head 679753e464fdd67499b089e8ee6fb5ffb108a9fe integrates main at 018fef1df0744cdde86c6d3061d60f9fb31f6970 with a merge commit. The remaining candidate changes nine files. Main's allocation renewal, maintenance behavior, allocation test, capacity fetch test, and default-base fetch test are retained exactly.

The original-head ClawSweeper P2 finding (new synchronous registry read during recovery) is addressed through the existing worker-backed reader. Extending the same-session retry regression to observe parent-thread registry SQL failed on the original callback as intended: 1 failed / 25 filtered, 175.11 s wall. The assertion captured the actual synchronous worktree SELECT. The combined-candidate run passed 65 unit tests and all 10 Gateway session-creation tests, plus 29 service tests, before a submodule-case timeout. The independent main control below reproduced that timeout. Core production typechecking, formatting, repository line/storage guards, and 15 test type graphs passed locally. The remaining focused selection completed on a clean Linux Hetzner lease: 181 tests passed across 11 files, with one Windows-only MSYS case skipped, in 396.23 s wall time (395.44 s runner time), using --maxWorkers=1. This includes all 43 race cases, the three recovery variants with the host-SQL assertion, the real heartbeat worker, allocation/maintenance/capacity/Git suites, and project/registry coverage. Full changed-file checks passed on the same lease in 2,449.59 s, including all 27 selected test type graphs, core types, lint, format, and the storage/import/runtime checks. All nine changed-source hashes matched again afterward. Both pre-commit and committed branch-mode Codex autoreview against origin/main are scoped-clean through P2. git diff --check is clean. PR CI run 37168116515 passed on this exact head with no reruns. ClawSweeper revision 2 completed on the same head with no actionable findings and confirmed the previous worker-read finding resolved.

An initial focused validation was stopped during worker preparation to apply that reviewed fix; it is not passing proof.

Current-head validation Result
Local unit / Gateway session-creation shards 65 / 10 tests passed
Remaining serial Linux selection (--maxWorkers=1) 181 passed across 11 files, 1 Windows-only case skipped; 396.23 s wall
Full changed-file checks Passed; 2,449.59 s wall, including all selected test type graphs and lint/format
Independent branch-mode Codex review through P2 Scoped clean
Exact-head CI / ClawSweeper revision 2 Success / no actionable findings

The Linux proof used Node 24.21.0 and pnpm 12.5.1 on a task-owned Hetzner lease. The source SHA and nine changed-file hashes were checked inside the execution shell. Testbox source preparation stalled before allocation; AWS then failed to provision within the documented fallback window and was released. The raw Hetzner image needed the repository's Node bootstrap and rg; after installing those prerequisites, tests and checks completed. These are infrastructure retries, not CI reruns or product fixes. The CI run above passed on its first ready-for-review attempt.

Submodule timeout attribution

The full local selection hit the existing 120-second deadline in service.test.ts > submodule checkout > keeps active submodules unpopulated when repository recursion is enabled. The same case then ran standalone three times on the unchanged staged candidate and once on a clean detached main checkout at 2df2d8455db0bec1488ccfe8790b093f90362a4b, each with pnpm test src/agents/worktrees/service.test.ts --maxWorkers=1 -t 'keeps active submodules unpopulated when repository recursion is enabled'.

Source Result Test-body time Command wall time
Candidate 1 Pass 44.28 s 377.44 s
Candidate 2 Pass 39.40 s 235.43 s
Candidate 3 Pass 110.75 s 374.15 s
Clean main control Same 120-second timeout Deadline exceeded 582.86 s

There is shared-path overlap in service.ts, service-preparation.ts, checkout.ts, and the heartbeat guard. The submodule test, fixtures, recursion flags, and materialization commands are unchanged. On successful creation, the recovery callback is unused; the differences are equivalent allocation delegation, capturing directory identity, result/error handling, and the ACK acceptance ordering. No new retry, timer, or submodule behavior was added. The main control's package manifest and lockfile match the integrated baseline; intervening test configuration additions concern other paths.

The failure is independently reproduced on main and is therefore not unique to this PR. Three candidate passes retain the original timeout; the slow third run is explicitly not a normal-duration result. During this comparison, host load averages were approximately 60–64 on 32 logical CPUs. This supports host-sensitive scheduling/I/O pressure, while the original log cannot identify the exact stalled operation. No timeout, assertion, or production behavior was weakened. The original failure remains recorded; a passing replay alone is not claimed as a fix.

Original regression diagnosis and proof before main integration

The original candidate was 814c705392d7386efd34b39b54ac00e8ccc0462e; its baseline was 28a6f71449aa5542c9fb825dcb3423dfbb7abf82. These results are historical proof, not CI for the integrated head.

The unchanged service.exact-state-races.test.ts ran standalone with --maxWorkers=1 five times against the initial worker-renewal candidate and five times against the pinned baseline, with production files backed up and restored byte-for-byte:

Run Initial worker candidate Pinned baseline
1 Pass — 284.77 s Pass — 241.31 s
2 Fail — 218.87 s Pass — 557.87 s
3 Fail — 179.42 s Pass — 535.32 s
4 Pass — 176.38 s Pass — 381.88 s
5 Pass — 210.80 s Pass — 453.63 s

Each run contains 43 tests. Candidate failures were activity-change rejection and move-ack rejection receiving a lost-capacity-lease error instead of their expected errors. The baseline passed 215/215. The originally reported interrupted-ref-deletion case passed all ten comparisons; these candidate failures were not classified as pre-existing flakes.

Temporary diagnostics captured a current acknowledgment (observedAck=236, currentAck=236, request=236), ready status, and 54,059 ms of remaining lease, but a negative response budget after a 1,923 ms parent delay. The diagnostic edits were removed. The acknowledgment repair restores the ordering that preceded 09e30a19aa20515c8c5134d84a864c344c3041a6 without extending a timeout or reviving expired authority.

Historical check Result and wall time
Delayed-ACK regression on original ordering Intended failure; 2 refusal controls passed — 73.43 s
Complete heartbeat lifetime and real-worker suites after repair 37 tests across 2 files passed — 178.75 s
Same-session retry on pre-fix production code Intended branch already exists: openclaw/retry-hydration failure — 83.75 s
Targeted allocation/recovery/fetch checks before ACK repair 10 tests across 4 files passed — 147.33 s
Changed checks Passed, including core and test types, lint, format, storage/worker and import guards — 1,619.06 s
Race file after ACK repair, 5 standalone runs 215/215 passed — 460.70 / 507.54 / 592.72 / 1,060.96 / 964.77 s
Original fake-clock allocation suite 3/3 passed — 11.98 s wall, 321 ms test time; baseline control failed as intended — 7.63 s
Independent Codex review through P2 Scoped clean

The original fake-clock allocation suite has been dropped in favor of #164521's real-worker allocation coverage. Its historical result is retained here only to explain the earlier diagnosis.

Linux proof run ran the full worktree test directory, Gateway session-creation worktree tests, and project registry tests on Linux x86_64, Node 24.19.0, pnpm 12.5.1, with --maxWorkers=1. It passed 43 files and 509 tests; 6 platform-gated files and 33 reported cases were skipped, with 3 additional nested Windows/ReFS cases unexecuted (545 declared). Vitest took 465.76 s; command wall time was 466.02 s. Provider command time including installation/hydration was 636.735 s; runner time was 646.565 s.

The tested source tree was 8ad4d1a1ae5316b54ed029dc7cd8da843d874cab, matching the original candidate, and its in-shell manifest was verified before testing. The wrapper returned exit 0 with a settled completion receipt. The Actions run shows cancelled because the native one-shot owner stopped the Testbox after successful completion; that lifecycle status is separate from command proof. The initial launch rejected unsupported --stop-after before allocation; its corrected documented invocation completed. Nonfatal synchronization/staging warnings followed success, and native lease completion was verified.

The expensive existing race/capacity suites retain real Git and SQLite proof: mocked deletion cannot establish correct branches, registrations, recovery bytes, and competing-writer behavior. The new ACK regression uses a fake clock; no sleeps, polling, or per-test Gateway boots were added.

Follow-ups and Limits

Lease loss before initial registration evidence is captured, process interruption, or loss after materialization can still preserve artifacts for inspection. Recovery is limited to an unchanged, unprepared registration; it does not infer deletion authority over partial user work.

Production timing and the exact missed renewal were supplied incident evidence, not a live reproduction. Remaining synchronous registry and lease-finalization migration is separate work; this PR preserves the existing authority checks and settlement contracts.

@clawsweeper

clawsweeper Bot commented Oct 3, 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 agents Agent runtime and tooling size: M labels Oct 3, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 10:58 PM ET / October 4, 2026, 02:58 UTC (Revision 3).

ClawSweeper review

What this changes

The PR recovers unchanged worktree branches after failed preparation, accepts timely heartbeat acknowledgments after delayed parent wakeups, and prevents automatic Git maintenance during pinned-commit fetches.

Merge readiness

✅ Ready for maintainer review

The remaining fixes are still necessary on current main. The previous worker-read finding is resolved, and no actionable introduced defect was found.

Priority: P2
Reviewed head: 679753e464fdd67499b089e8ee6fb5ffb108a9fe

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused repair with meaningful failing controls, production-boundary evidence, and successful exact-head CI.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The captured Linux evidence exercises production worktree creation with real Git and SQLite under injected allocation loss, observing successful retry and preservation of changed artifacts. Real-worker refusal controls supplement the deterministic delayed-ack regression; no stored-data format or migration contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The captured Linux evidence exercises production worktree creation with real Git and SQLite under injected allocation loss, observing successful retry and preservation of changed artifacts. Real-worker refusal controls supplement the deterministic delayed-ack regression; no stored-data format or migration contract changes.
Evidence reviewed 10 items Pinned introduction: Reviewed the complete introduced diff from pinned base 018fef1 to original head 679753e. The stale test merge was not used to infer removal of main-branch behavior.
Fresh cleanup authority: Recovery unwinds the failed scopes, reacquires allocation followed by source cleanup custody, and checks directory identity, Git metadata, captured HEAD, and an empty checkout before guarded Git removal. Existing caller-owned branches and materialized checkouts remain protected.
Prior finding resolved: The publication check now awaits the existing worker-backed registry reader and revalidates cleanup authority afterward. The recovery regression observes host SQL and requires no synchronous worktree registry reads.
Findings None None.
Security None None.

How this fits together

Managed worktrees give agent sessions separate Git checkouts. Allocation and source custody protect checkout creation and cleanup, while a heartbeat worker keeps the allocation lease alive.

flowchart TD
  A[Session requests checkout] --> B[Acquire allocation and source custody]
  B --> C[Register and prepare Git checkout]
  C --> D[Publish successful checkout]
  C --> E[Preparation loses lease]
  E --> F[Reacquire cleanup custody]
  F --> G[Verify unchanged unpublished checkout]
  G --> H[Remove artifacts and permit retry]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +123, Tests +148, Docs 0. Total +271 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 153 30 +123
Tests 3 149 1 +148
Docs 1 1 1 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 303 32 +271

Review metrics

Metric Value Why it matters
Production versus regression growth production +123 lines; tests +148 lines Production growth implements fresh-custody recovery and artifact identity checks; regression growth exercises recovery and refusal outcomes.

Technical review

Best possible solution:

Preserve one allocation and source-custody owner, recover only unchanged unpublished artifacts, and keep persisted lease authorization independent of worker liveness.

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

Yes, source establishes both failure paths: lost allocation custody prevents immediate rollback, and delayed parent wakeup rejects a current acknowledgment. The body records failing controls; this read-only review did not execute them.

Is this the best way to solve the issue?

Yes, the patch reuses existing custody and worker-reader owners, limits recovery to unchanged unpublished artifacts, and retains durable ownership checks around heartbeat waits.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs bounded worktree retry and lease-liveness failures without adding configuration or changing public contracts.
  • 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 (terminal): The captured Linux evidence exercises production worktree creation with real Git and SQLite under injected allocation loss, observing successful retry and preservation of changed artifacts. Real-worker refusal controls supplement the deterministic delayed-ack regression; no stored-data format or migration contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured Linux evidence exercises production worktree creation with real Git and SQLite under injected allocation loss, observing successful retry and preservation of changed artifacts. Real-worker refusal controls supplement the deterministic delayed-ack regression; no stored-data format or migration contract changes.

Evidence

What I checked:

  • Pinned introduction: Reviewed the complete introduced diff from pinned base 018fef1 to original head 679753e. The stale test merge was not used to infer removal of main-branch behavior. (679753e464fd)
  • Fresh cleanup authority: Recovery unwinds the failed scopes, reacquires allocation followed by source cleanup custody, and checks directory identity, Git metadata, captured HEAD, and an empty checkout before guarded Git removal. Existing caller-owned branches and materialized checkouts remain protected. (src/agents/worktrees/checkout.ts:534, 679753e464fd)
  • Prior finding resolved: The publication check now awaits the existing worker-backed registry reader and revalidates cleanup authority afterward. The recovery regression observes host SQL and requires no synchronous worktree registry reads. (src/agents/worktrees/service.ts:640, 679753e464fd)
  • Acknowledgment is not authorization: The changed heartbeat guard accepts only the current request acknowledgment while ready and before the supplied grant expires. Its lease-owner caller independently verifies persisted ownership before and after the synchronous wait; an acknowledgment cannot restore replaced ownership. (src/state/openclaw-state-lease.ts:391, 679753e464fd)
  • Behavior and refusal coverage: Recovery cases invoke the production service with real Git and SQLite, inject allocation loss, verify same-name retry, and preserve changed files or registration. Heartbeat coverage includes delayed current/stale/expired acknowledgments, plus real-worker replacement, expiry, and deletion refusal controls. The captured body records intended pre-fix failures and successful Linux after-fix runs. (src/agents/worktrees/service.capacity.test.ts:343, 679753e464fd)
  • Complete proof snapshot inspected: Read the full GitHub body, including the omitted ending, and verified SHA-256 9d2e07b69b2dbdd04c8512202d76dbffafe9c48290ad7aedeb24522f8cfb184c matches the supplied snapshot. It records 181 focused Linux tests passing, real-worker and recovery coverage, source-hash checks, and an independently reproduced main-side submodule timeout without weakened assertions. (679753e464fd)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; 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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-03T23:27:17.464Z sha 814c705 :: needs changes before merge. :: [P2] [P2] Move the recovery registry lookup into the SQLite worker
  • reviewed 2026-10-04T01:33:59.391Z sha 679753e :: needs maintainer review before merge. :: none

Integrate main and retain the renewal and Git maintenance implementation landed in #164521. Remove overlapping changes while preserving fresh-custody cleanup, delayed synchronous acknowledgement handling, and maintenance suppression for missing pinned project commits.

Address the ClawSweeper recovery-read finding through the existing SQLite worker and revalidate authority after the awaited result. The existing recovery regression now detects synchronous host registry reads.
@steipete steipete changed the title fix(worktrees): prevent capacity lease loss during slow preparation fix(worktrees): recover leaked branches and accept delayed heartbeat acks Oct 4, 2026
@steipete
steipete marked this pull request as ready for review October 4, 2026 01:28
@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. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 4, 2026
@steipete
steipete merged commit 4720657 into main Oct 4, 2026
222 checks passed
@steipete
steipete deleted the steipete/worktree-capacity-lease-custody branch October 4, 2026 03:23
@steipete

steipete commented Oct 4, 2026

Copy link
Copy Markdown
Contributor Author

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 docs Improvements or additions to documentation 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. size: M 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