Repository navigation
fix(worktrees): recover leaked branches and accept delayed heartbeat acks - #164615
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 10:58 PM ET / October 4, 2026, 02:58 UTC (Revision 3). ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherManaged 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +123, Tests +148, Docs 0. Total +271 across 9 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
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.
|
Merged via squash.
|
What Problem This Solves
Fixes same-session worktree retries failing with
branch already existsafter 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
679753e464fdd67499b089e8ee6fb5ffb108a9feintegrates main at018fef1df0744cdde86c6d3061d60f9fb31f6970with 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 --checkis 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.
--maxWorkers=1)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 at2df2d8455db0bec1488ccfe8790b093f90362a4b, each withpnpm test src/agents/worktrees/service.test.ts --maxWorkers=1 -t 'keeps active submodules unpopulated when repository recursion is enabled'.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 was28a6f71449aa5542c9fb825dcb3423dfbb7abf82. These results are historical proof, not CI for the integrated head.The unchanged
service.exact-state-races.test.tsran standalone with--maxWorkers=1five times against the initial worker-renewal candidate and five times against the pinned baseline, with production files backed up and restored byte-for-byte: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 preceded09e30a19aa20515c8c5134d84a864c344c3041a6without extending a timeout or reviving expired authority.branch already exists: openclaw/retry-hydrationfailure — 83.75 sThe 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 showscancelledbecause 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-afterbefore 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.