Repository navigation
refactor(worktrees): move row guards and retirement to worker owner - #166236
Conversation
Use the existing read-only worker when another Gateway owns the selected state. Report missing-checkout retirement candidates without changing rows or sending an unfenced reconciliation RPC. Offline reconciliation holds the existing state owner and checkout mutation lease, then rereads the row and path before retirement. Preserve a checkout that reappears while listing waits for custody.
Use worker-backed exact-row predicates and snapshot retirement while retaining SQL-free generation guards through synchronous filesystem and Git effects. Serialize rebinding under the existing mutation lease and invalidate authority on row, owner-selection, and lease changes, including uncertain settlement. Join accepted removals and run-lease cleanup before closing worker transports. Fence native Doctor migration writes with existing maintenance ownership and route plugin runtime mutations through the existing local-state owner. Remove native runtime row facades and migrate all bundled consumers. Preserve the five lock and process-exit primitives, FIFO writes, and public SDK signatures.
|
🦞👀 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. |
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: blocked before merge. Reviewed October 7, 2026, 9:35 AM ET / 13:35 UTC (Revision 16). ClawSweeper reviewWhat this changesMoves managed Git checkout guards and snapshot retirement into database workers, makes foreign-process listing read-only, and reuses admitted session targets for publication discovery and compaction. Merge readiness⛔ Blocked before merge - 2 items remain The work remains useful and is not superseded by the inspected main implementation. Both prior proof requests are satisfied for the unchanged head, and no actionable correctness or security finding remains. The recorded CI failures remain subject to native landing gates. Priority: P2 Review scores
Verification
How this fits togetherManaged worktrees give agent sessions isolated Git checkouts and recovery snapshots. Session, plugin, and CLI requests enter the worktree owner, which coordinates database custody with filesystem and Git effects. flowchart TD
A[Session and plugin requests] --> C[Worktree lifecycle owner]
B[CLI listing] --> D{State owned elsewhere?}
D -->|Yes| E[Read-only registry worker]
D -->|No| C
C --> F[Worker predicates and live guards]
F --> G[Git and filesystem effects]
E --> H[Listing and retirement candidates]
G --> H
Before merge
Agent review detailsSecurityNone. PR surfacePR surface statistics unavailable: the file list is incomplete. Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep worktree predicates, retirement, and accepted-write settlement under the existing worker owner, with live guards protecting Git effects and foreign inspection remaining read-only. Do we have a high-confidence way to reproduce the issue? Yes, current-main source exposes native registry guards and retirement, and the supplied matched workloads exercise the affected paths. This read-only review did not execute a reproduction. Is this the best way to solve the issue? Yes, the patch extends existing worker and lifecycle owners, preserves transaction predicates and final-effect authority, and removes the moved native runtime facades rather than adding a competing implementation. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d5b7f82c461e. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (15 earlier review cycles; latest 8 shown)
|
Merge main without rebasing to incorporate the source-map audit repair and previously inherited dead-export fixes. Preserve both sides of the worker cutover and newly landed session-creation durability coverage. Await the worker-backed owner lookup in the new durability test's cleanup. Post-integration typechecking exposed the stale synchronous call; all four real Gateway recovery cases pass after the correction.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Exercise allocation loss through the real heartbeat worker and publish expiry through owner-bound test admissions. Preserve unknown-outcome causes, restore synthetic source repositories before releasing leases, and wait for child publication before HTTP assertions. Fix the Gateway test inventory order.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Preserve both publication settlement assertions and integrate current session read and teardown ownership fixes. Post-integration core, core-test, root-test types and import-cycle checks pass; 81 focused tests pass. Matched SQL measurement and isolated publication E2E remain pre-merge gates.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
Worktree row guards now execute in SQLite workers. Forward the isolation fixture observer into the native workers and require a workload SQLite witness from the same provisioner and source root. Preserve the canonical path, alias, HOME, operator override, and lease assertions. No production behavior changes. Restores isolation proof after #166236. Validation: 12 state tests and 228 wrapper/helper sibling tests passed; whole tooling config covered all 949 files (937 passed, 7 existing skips, 14 environment failures in 5 files resolved by corrected Ruby/Git replays). Type-aware and boundary lint, all root type graphs, check-changed, and P2 autoreview passed.
…penclaw#166236) * fix(worktrees): fence CLI listing with state ownership Use the existing read-only worker when another Gateway owns the selected state. Report missing-checkout retirement candidates without changing rows or sending an unfenced reconciliation RPC. Offline reconciliation holds the existing state owner and checkout mutation lease, then rereads the row and path before retirement. Preserve a checkout that reappears while listing waits for custody. * refactor(worktrees): move row guards and retirement to worker owner Use worker-backed exact-row predicates and snapshot retirement while retaining SQL-free generation guards through synchronous filesystem and Git effects. Serialize rebinding under the existing mutation lease and invalidate authority on row, owner-selection, and lease changes, including uncertain settlement. Join accepted removals and run-lease cleanup before closing worker transports. Fence native Doctor migration writes with existing maintenance ownership and route plugin runtime mutations through the existing local-state owner. Remove native runtime row facades and migrate all bundled consumers. Preserve the five lock and process-exit primitives, FIFO writes, and public SDK signatures. * test(worktrees): exercise recovery races through the owner * test(worktrees): align lease fixtures with worker ownership Exercise allocation loss through the real heartbeat worker and publish expiry through owner-bound test admissions. Preserve unknown-outcome causes, restore synthetic source repositories before releasing leases, and wait for child publication before HTTP assertions. Fix the Gateway test inventory order. * perf(gateway): skip worktree lookup for unbound sessions * perf(gateway): reuse admitted store for publication discovery
Worktree row guards now execute in SQLite workers. Forward the isolation fixture observer into the native workers and require a workload SQLite witness from the same provisioner and source root. Preserve the canonical path, alias, HOME, operator override, and lease assertions. No production behavior changes. Restores isolation proof after openclaw#166236. Validation: 12 state tests and 228 wrapper/helper sibling tests passed; whole tooling config covered all 949 files (937 passed, 7 existing skips, 14 environment failures in 5 files resolved by corrected Ruby/Git replays). Type-aware and boundary lint, all root type graphs, check-changed, and P2 autoreview passed.
Keep local workspace resolution and retirement guarded by their already-known worktree ID while awaiting the registry reader. Unrelated concurrent publication must not revoke the selected row; identity and removal changes to that row still reject the operation. The native Btrfs morning replay exposed this existing main regression from #166236. Reuse the selection contract introduced in #179240 instead of retrying or serializing the callers. The deterministic regression fails on exact parent 3a6cc65 and passes with this repair, including selected-row revocation controls. Allocate 46 regression-test lines for the real registry/session owner interleave.
What Problem This Solves
Managed-worktree guards and snapshot retirement repeatedly queried SQLite on the Gateway thread.
worktrees listcould also retire a missing checkout from another process while a Gateway owned the state.User Impact
Worktree effects and retirement use the existing worker-owned database operations. Foreign-process listing reports retirement candidates without changing the running Gateway's state. Offline reconciliation retains exclusive state ownership and the checkout mutation lease.
There are no schema, stored-format, retention, durability, dependency, protocol, config/default, or released SDK signature changes. Plugin worktree mutations preserve their Promise results and synchronous
commitGuardcontract. They run in the owning Gateway or under exclusive offline ownership; foreign-owner refusal and recovery are documented indocs/plugins/sdk-runtime/agent.md.Why This Change Was Made
The existing reader and receipt-owning writer now own worktree rows, transaction-local predicates, and snapshot retirement. Lifecycle generations revoke prepared effect authority at mutation admission. Filesystem/Git callbacks check those live facts without worktree SQL; worker transactions preserve FIFO and settle accepted writes before close. Doctor/startup migration writes retain schema-maintenance custody through their native transaction.
Publication discovery rejects unbound sessions before querying the worktree registry. When an embedded or worker turn already carries an admitted physical session locator, availability uses a fresh exact-row worker read instead of repeating store inventory/discovery. Canonical stored aliases, session/lifecycle/writer/caller authority, native/incognito handling and publication execution checks remain intact. The compaction RPC similarly carries its already-validated physical target; the compactor retains cold restoration and current-entry/live-authority checks.
Evidence
Reviewed head:
6f822da3a7df2fe15f01ec472156d5645f9526fe, integrating main4ed39a25f674ceecbe7bb066503941085c911b6eby merge commit. The source-map and MCP SDK advisory fixes, session-authority/native-creation changes, incognito project deletion guard, pending-slot ownership, schema admission and archive/category teardown fixes are included. Security requirements remain mandatory.Matched all-thread SQLite measurement
Three repetitions per source on the same dedicated AWS machine, using the unchanged shared harness, Node 24 and SQLite 3.53.4. All six full workloads and 18 scoped probe invocations passed. Every raw native phase matches its CSV, caller/worker calibration passes, and there are zero failed executions or prepares. All threads, helper processes, background statements, samples and paired differences remain counted. The lease was released after evidence download.
First session creation plus first chat and warmed turns must not increase. Every other workload phase may increase by at most 2% of its matched-main median, with attribution. This candidate passes every limit:
First-turn samples: main 5,887 / 5,895 / 5,904, PR 5,843 / 5,881 / 5,872. Warmed ten-turn means: main 2,261.6 / 2,258.8 / 2,261.9, PR 2,241.9 / 2,235.7 / 2,234.8. Whole totals: 43,488 / 43,458 / 43,574 → 43,244 / 43,248 / 43,230.
Shutdown samples are 917 / 922 / 922 → 923 / 921 / 923, paired changes +6 / −1 / +1. The capability statement is
SELECT sqlite_version() AS version, sqlite_compileoption_used('OMIT_LOAD_EXTENSION') AS omitted, owned by quarantine/read admission. Remaining pair variation is counted schema/data-version admission checks; differing busy-timeout literals net to zero statements. This is phase attribution, not subtraction or a claim that every individual pair decreases.All five product worktree operations decrease identically in all three pairs:
Probe setup, assertions and cleanup remain counted. Retirement's post-operation assertion reads rise 5 → 557 because the native verification reader opens a cold caller database after the worker operation; the complete retirement specimen still decreases 3,385 → 2,812. Complete plain and foreign-listing specimens decrease 2,821 → 2,212 and 3,324 → 2,761. These accounting windows are not presented as additional product operations or excluded from totals.
The separate publication composition E2E passes:
node scripts/run-vitest.mjs src/gateway/x-publication-owner-composition.e2e.test.ts --maxWorkers=1, one file/one test, 384.54s command wall time, 55.32s Vitest and 11.93s test time. It runs after all 108 observed measurement processes settle, with SQL tracing disabled and normal build/artifact guards intact. Candidate SHA/tree are unchanged before and after. Local preparation had refused to rebuild managed-Gateway artifacts; isolated proof completed that gate without bypassing the fence.Review and focused proof
Fresh full-candidate P2 review against integrated main is clean. ClawSweeper completed this exact head at 2026-10-07T13:03:14.131Z with no actionable code or security findings. Its recorded SQL and publication-E2E qualification gaps are closed by the evidence above. Its generic config/data-model flags do not identify a changed schema, stored format or default.
Post-integration production types pass (27.17s), all core-test type shards pass (538.97s), four root-test type graphs pass (53.99s), and madge reports zero runtime cycles (44.67s). Eight focused source files pass 81 tests in 350.44s, covering archive placement, category creation, publication availability, compaction/read failures, embedded dispatch, runtime build graph and reply import closure. Prior unchanged worktree/import/provisioning proof has 399 passes across 21 files, one default skip, and 1,294.33 command seconds. The preceding complete changed-file gate passed types, all three Knip scans, formatting/lint, storage/auth/dependency guards and import-cycle checks.
Regression-before/fix-after evidence covers unbound publication discovery, replaced session/lifecycle authority, physical-store continuity and canonical stored aliases. The initial alias fixture attempted an unsupported owner mutation and failed for the wrong reason; it is not regression proof. Its corrected independent-row fixture fails the intended assertion before the fix and passes afterward.
Exact-head CI and inherited failures
CI run 37624496046, attempt 1, completed with 87 successful jobs, 23 skipped, three failed test jobs and the aggregate gate. Security-fast, type, lint and other selected checks passed. CI checked out merge
7841deaa0ad7d1c5f722a0fa345a671c1f849bf4, ordered parents main86b83b74b4c68e147277b022b517c0d8b5322c16and this head. Reconstructing that merge produces its exact tree104285c00151ea2be7113ab4e35a41dbcc9d2387. No CI rerun was issued.86b83b74and five on tested merge7841deaareproduce the exact assertion, with logout passing every timeconfiguredis absent. The PR does not touch the failing test or status owners.Current and matching hosted-main jobs used Node 24.19.0/Linux x64. Prior owner/reset local controls used Node 26.10/macOS; new channel controls used Node 24.21/macOS, median command times 38.98s/39.15s. These local controls are differential source evidence, not claims of the hosted runtime. Broader main consolidation and unrelated PR startup imports are explicitly recorded; whole-program identity is not claimed. Underlying owner/reset lifecycle defects remain unrepaired. The native operator-approved inherited-failure exception retains these failures; it does not label CI green or waive security/review requirements.
Compatibility, retained contracts and history
Released reachability was checked against
v2026.10.1-beta.1andv2026.9.8. The publicapi.runtime.worktreescontract is preserved; new publication/compaction helpers are internal. The retained SDK diff report (digest60a33d0b) has zero direct-export/entrypoint declaration changes and 130 conservative reachable notices across three unchanged private declarations. No new environment names are added (464 → 464). Published-driver update proof passes: driver 2026.9.8 updates to the candidate lineage, readiness returns 200, durable history survives, incognito history clears, and service cleanup succeeds (run 37456422223, 271.67s cell; package build 745.6s). Later changes preserve that owner/transport/admission contract.Pre-existing short reads of other owners' live authority inside guards remain follow-up debt:
src/sessions/session-worktree-lifecycle.ts:144,src/gateway/session-worktree-preparation.ts:217,src/gateway/worker-environments/local-workspace-projection.ts:298, andsrc/gateway/github-publication-availability.ts:115. Native lock/exit primitives also retain their existing contracts. The zero-caller-SQL boundary applies to the moved worktree operations.Historical failures are retained rather than erased: the earlier comparison of
a8ce5625againstcc055867had first-turn median 6,124 → 6,119, cron 1,949 → 1,950 (+1), and compaction 1,029 → 1,050 (+21, 2.0408%). Cron included another maintenance preparation after a session write; the exact host discard trigger was not logged. Most compaction work shifted canonical-validation/admission checks from shutdown (24 and 18 opposing statements in two pairs), with additional cache/ACP reads. The compaction increase exceeded the allowed 2%, prompting removal of duplicate transcript-target discovery. The subsequent432445d9comparison fixed compaction (993 → 990) but failed first turn (5,985 → 5,988), prompting the admitted-store publication correction. The final source-bound comparison above passes both gates; lower totals were never used to excuse the earlier failures.Earlier inherited updater/Doctor, archive-admission and UI-type failures and their controls remain historical; integrated main repairs are not attributed to this PR. An initial projects timeout and baseline QA cleanup failure remain unexplained. A historical audit-event lock error was not declared fixed by a later pass. Fixture scratch moved from undersized tmpfs to disk and from a custody-invalid symlink to a real directory without weakening production checks. A discarded schema-marker experiment caused SIGBUS and was fully reverted; it is absent from this branch.
Overlap is integrated or kept focused: #166060, #166331, #166375, #165993, #166253, #165885, #165890, #165901, #165894, #165904, #165921, #165185, #150479, #156876, the SQL-efficiency and wave-6 entry/auth/approval/binding lanes, and later main session/status cleanup. #162433 is the inactive umbrella design. Overlap is not treated as a stop condition; no other branch was modified.