Repository navigation
fix(worktrees): stop idle cleanup from overwhelming shared storage - #192909
Conversation
Admit one idle removal per minute without rescanning the expired cohort, and defer admission during IO pressure or slow btrfs commits. Spread seven-day eligibility with stable per-checkout jitter while retaining live custody and lossless snapshots. Persist oversized workspace retry backoff and keep failure-outcome bookkeeping from invalidating it. Existing derived dispositions recheck once after upgrade; no schema or configuration change. Release-note context: background cleanup remains useful without draining expired cohorts in a burst; nested repositories, active owners, and snapshots remain protected. Explicit removal and capacity eviction retain existing policies.
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: blocked before merge. What this changesThis PR paces Gateway idle worktree removal, pauses under host IO pressure, spreads expiry, and preserves failed-snapshot retry backoff. Example: Three expired worktrees qualify for Gateway idle cleanup.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 2 items remain Keep this PR open: the cleanup fix has clear value, but the new pacing leaves an archive-retry fixture waiting indefinitely, matching an exact-head CI timeout. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherGateway maintenance supplies scheduling and current configuration authority to the managed-worktree service, which checks owners and leases before snapshotting, deleting checkouts, and recording SQLite registry outcomes. flowchart TD
A[Gateway maintenance] --> B[Admission pacing]
C[Linux IO counters] --> B
B --> D[Worktree GC]
D --> E[Live owner and lease checks]
E --> F[Git snapshot and checkout removal]
F --> G[SQLite registry]
Technical reviewBest possible solution: Retain the existing scheduler and registry owners, update the archive fixture to drive paced continuations with controlled pressure inputs, and establish upgrade compatibility. Do we have a high-confidence way to reproduce the issue? Current-main source confirms that short batch yields still drain the expired cohort; supplied synthetic measurements exercise that owner, while no live storage-pressure reproduction was run during this review. Is this the best way to solve the issue? The smallest complete fix belongs in the existing maintenance admission and registry backoff owners, which this PR uses; the new scheduling contract also requires updating its archive-test consumer. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0b9f3ab3aec3. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceAcceptance criteria:
What I checked:
PR surfaceSource +98, Tests +216, Docs +8, Other +364. Total +686 across 17 files. Added test files: 1. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed November 4, 2026, 1:21 PM ET / 18:21 UTC. |
|
Merged via squash auto-merge.
|
…penclaw#192909) * fix(worktrees): pace idle cleanup under host IO pressure Admit one idle removal per minute without rescanning the expired cohort, and defer admission during IO pressure or slow btrfs commits. Spread seven-day eligibility with stable per-checkout jitter while retaining live custody and lossless snapshots. Persist oversized workspace retry backoff and keep failure-outcome bookkeeping from invalidating it. Existing derived dispositions recheck once after upgrade; no schema or configuration change. Release-note context: background cleanup remains useful without draining expired cohorts in a burst; nested repositories, active owners, and snapshots remain protected. Explicit removal and capacity eviction retain existing policies. * test(worktrees): age CLI cleanup fixtures past expiry jitter * chore(perf): remove unused cleanup benchmark default * fix(perf): preserve optional cleanup benchmark arguments * test(worktrees): synchronize cleanup and placement consumers * test(worktrees): await placement publication without polling
What Problem This Solves
Fixes sustained removal bursts when many managed worktrees expire together. The existing sweep yielded for one second after eight records or five seconds of work, then continued draining its entire cohort; asynchronous filesystem cleanup could accumulate behind it.
User Impact
Gateway idle cleanup now admits at most one removal attempt per minute and waits five minutes before rechecking high Linux IO pressure or slow btrfs commits. It retains the existing sweep cursor, lossless snapshots, nested-repository protection, live-owner checks, cancellation, and shutdown drainage. Capacity eviction and explicit single-worktree removal keep their existing policies.
Why This Change Was Made
Stable per-checkout jitter extends seven-day age eligibility by up to one hour. A workspace snapshot exceeding its total byte limit now uses the existing durable two-to-24-hour retry backoff. Recording a failed cleanup outcome no longer invalidates that backoff for archived owners. Old derived deferral receipts are rechecked once after upgrade; no schema, configuration, or new inventory cache is introduced.
The existing scheduler owns pacing; its pause implementation is shared with scan checkpoints. No live pressure-admission API existed: the stall observer only records diagnostic samples. The small new probe reads Linux PSI and btrfs commit counters, ignores historical maxima and unchanged completed commits, and falls back to unconditional pacing when counters are unavailable. Runtime production delta is +98 lines; the existing service file does not grow. A rerunnable measurement script adds 362 lines separately. Regression coverage adds225 counted test lines with matching allocation; shared fixture changes add4 lines excluded by the ratchet.
Evidence
8cb658e39b6dbe1bbe03746bf2a468a898c15da2: scoped-clean through P2, no actionable findings.pnpm check:changedran. Patch-caused line-cap and floating-promise findings were corrected; focused line-cap and typed lint now pass. Remaining typecheck failure reproduces on the exact parent:browser-panel-render.tsx:149TS2322, introduced by3e361e28cdf9/ improve(ui): clarify browser and link reader feedback #192281. This is a main regression. The same exact-parent replay also fails for the sole unusedpostgresSchemaFingerprintexport (re-exported without a consumer bycf50d4a36629/ feat(storage): support read-only PostgreSQL standby inspection #192645). Test-budget debt is already 191 lines on that parent; its sustained deficit begins at53b1b400c46c/ fix(ui): toasts sit too low outside session pages #192769 (+68 unallocated lines, taking 8 slack to 60 debt), with later unallocated additions accounting for the remaining deficit. This patch adds exactly 216 lines and 216 credit, preserving that inherited debt. These are main regressions, not a wholly green local check.The initial CI run caught a CLI fixture aged only seven days plus one millisecond, now inside the added expiry jitter. Commit
54ed8024a777ages both affected fixture records beyond the jitter window; the exact failinggc-partial: livecase passes locally on the pinned Bun runtime (1 passed, 17 skipped, 12.71s driver). Typed lint and a fresh Codex autoreview of this test-only correction pass. Runtime and benchmark bytes are unchanged.Synthetic cleanup measurements
Protocol was published in PR #192909 before accepted samples. Baseline is exact parent
8cb658e39b6dbe1bbe03746bf2a468a898c15da2; candidate runtime is7e77fba67ba21fed1143c477bb2de62fef1a2e27. Later test-only correction54ed8024a777changes no measured production or benchmark bytes. The five changed baseline modules and the ESM package marker were verified byte-for-byte against the parent.Each fresh process creates two expired session-owned checkouts, each 62,000 tracked files / 1,142,784,000 bytes, with a tracked edit and an untracked note. It seeds 5,000 real session rows. The real scheduler, owner policy, SQLite registry, Git snapshot and removal run; only scheduled wait duration is virtualized. Source/checkout setup, final verification and drainage are outside the owner timing. The local filesystem is APFS with uncontrolled OS cache. Transcript bodies are omitted because this owner resolves selected session metadata rather than transcript payloads. No production data or Team access was used.
Four baseline controls form two A/A pairs, followed by five serial interleaved A/B pairs. One candidate CPU-profile arm is diagnostic and excluded from comparisons. The initial loader setup failure, pilot, and 100-file smoke are excluded. P95 uses nearest rank; with five values it is the maximum. Process CPU includes worker threads but excludes Git child-process CPU. Exact allocation covers the main V8 isolate only, excluding worker/native allocation.
Command and protocol
Directory variables name task-owned synthetic paths. The overlay contains exact-parent versions of
src/agents/worktrees/{gc-removal,service,registry-read.kernel,registry-retirement}.ts,src/gateway/worktree-maintenance.ts, and the exact-parentpackage.jsonESM marker. Accepted sequence was A/A, A/A, then A/B five times, followed by the separate profile arm.Five-pair comparison
Intentional waiting, separate from owner service time
The longer logical completion time is the requested pacing policy. Actual owner wall above excludes these virtualized scheduled waits; it still includes the real snapshot and filesystem work. Median columns describe separate distributions and need not add arithmetically.
Per-arm measurements
Pairwise changes and A/A controls
Flags and attribution
Positive changes above 20% are listed explicitly; they are not erased by averaging or dismissed as spread:
First-pair wall regression is concentrated in existing snapshot work. The before/after removal diagnostics are:
{ "A": [ { "durationMs": 5351, "admissionMs": 412, "preparationMs": 158, "snapshotMs": 4714, "checkoutRemovalMs": 24, "bodyFinalizeMs": 37, "tracked": 62000, "untracked": 1 }, { "durationMs": 3411, "admissionMs": 430, "preparationMs": 97, "snapshotMs": 2818, "checkoutRemovalMs": 24, "bodyFinalizeMs": 37, "tracked": 62000, "untracked": 1 } ], "B": [ { "durationMs": 8812, "admissionMs": 441, "preparationMs": 178, "snapshotMs": 8116, "checkoutRemovalMs": 28, "bodyFinalizeMs": 43, "tracked": 62000, "untracked": 1 }, { "durationMs": 5143, "admissionMs": 391, "preparationMs": 115, "snapshotMs": 4570, "checkoutRemovalMs": 25, "bodyFinalizeMs": 37, "tracked": 62000, "untracked": 1 } ] }The first pair used the same tracked/untracked counts and produced the identical complete snapshot tree. Its extra wall time occurs in the snapshot phase, while process CPU rose 3.75% and main allocation fell 2.52%. These observations locate the extra elapsed time; they do not causally prove an APFS cache/host explanation. No chat latency or btrfs improvement is claimed. Intentional logical wait is reported separately and must not be mistaken for owner service time.
Separate candidate main-thread CPU profile
This is a separate arm, excluded from all timing/CPU/allocation comparisons. It samples only the main thread and cannot reconstruct an earlier snapshot outlier or attribute Git child/worker CPU. The main thread was idle for 16.986 of 18.665 sampled seconds (91.0%). Its largest non-idle self sample was existing esbuild transformation (465 ms), followed by package metadata reads (197 ms); GC accounted for 157 ms. No busy pacing loop appeared. This locates main-thread cost in the diagnostic arm, but does not causally explain the first pair’s earlier snapshot slowdown.
{ "sampledWallMs": 18664.549, "specialSelfMs": { "(idle)": 16985.858, "(program)": 131.39, "(garbage collector)": 157.43 }, "topNonSpecialSelf": [ { "function": "runCallSync", "source": "node_modules/.pnpm/[email protected]/node_modules/esbuild/lib/main.js", "selfMs": 465.067 }, { "function": "get", "source": "node:internal/modules/package_json_reader", "selfMs": 196.812 }, { "function": "post", "source": "node:inspector", "selfMs": 113.745 }, { "function": "spawn", "source": "", "selfMs": 72.623 }, { "function": "compileSourceTextModule", "source": "node:internal/modules/esm/utils", "selfMs": 25.839 }, { "function": "(anonymous)", "source": "node_modules/.pnpm/[email protected]/node_modules/tsx/dist/index-DE3OBZuV.mjs", "selfMs": 23.331 }, { "function": "postMessage", "source": "node:internal/worker", "selfMs": 21.374 }, { "function": "FSReqCallback", "source": "", "selfMs": 18.904 }, { "function": "existsSync", "source": "", "selfMs": 15.652 }, { "function": "(anonymous)", "source": "node:internal/fs/utils", "selfMs": 14.823 }, { "function": "(anonymous)", "source": "node_modules/.pnpm/[email protected]/node_modules/tsx/dist/register-nyXW-TH3.mjs", "selfMs": 13.68 }, { "function": "unlink", "source": "", "selfMs": 11.803 } ] }Invariants and limitations
All 15 successful arms removed both checkouts, preserved the tracked edit and untracked note in the same complete snapshot tree
71d16e769470e887f16316e87b757e5286baa123, and retained 5,000 session rows. Final agent database size was 4,112,384 bytes in each arm. Candidate admissions were at least 60,000 ms apart. One-minute host load ranged 8.88–19.64.Actual btrfs cleaner/backref behavior, btrfs commit latency, Linux pressure performance, and chat latency remain unmeasured. Linux counter behavior and scheduler pressure backoff are covered by focused fixtures. The 35 GiB production transcript database is intentionally not copied or fabricated: transcript payload size is outside this owner boundary. Main allocation and process CPU are useful bounded measurements, not total native/worker/child allocation or all subprocess CPU.
The source setup failure was resolved by supplying the exact-parent ESM package marker to the sparse overlay before accepted samples. The controller paused between arms for a test-only CI repair; pair-1-B invocationSeconds therefore includes the post-drain pause and is not a performance metric. In-process owner measurements were captured before that pause. No arm was repeated to chase a passing number.
CI found two benchmark-harness diagnostics after the measured runs: an unused default under scripts lint, then optional-argument type errors when that default was removed. The final wrapper checks
params?.beforeRemoval, preserving the service's supported omitted argument and the measured path. Commitsaf33568d078eandffcf101f7608change only this wrapper; production runtime and measured scheduler calls remain unchanged. Exact scripts-tsconfig typed lint passes. Replaying the scripts typecheck removes both harness errors and reports only the already-attributed parent UI TS2322. Fresh Codex review with service/caller context is scoped-clean through P2. No measured arm was rerun or substituted. Earlier harness head:ffcf101f7608448a55a7c96078938894fdafa40e; exact-head CI 41882496440 failed and prompted the test-consumer repairs below.New CI main-budget regression
Run
41881018650tested mergecb526748c892ac8dc6d251cd01503b1bfe0d8662ofaf33568dinto exact main parentf1a317d4674280aba0865d381861ea0bb924032d. Its ratchet job reported 6,467,813 test lines against 6,467,799 ceiling: 14 over, with this lane's +216 test lines fully matched by +216 credit. The parent itself has 6,467,597 lines against 6,467,583 ceiling, the same 14 debt.A clean exact-parent replay selecting only later main commits fails with exit 1 and the same 14-over error:
node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base 3e114e23c33c55585bb6859bc695693749139f03 --no-merge-base. That interval contains +327 main test lines and +321 credit, with no lane-2188 changes. A zero-growth parent selection prints the debt but exits 0; it is not claimed as the failing reproduction.Exact LF accounting traces the residual debt through
85905ea3b07d/ #192140 (+34 unallocated), reconciliation3e114e23c33c/ #192766 (leaves 8 debt),a4297e5af3c4/ #192903 (-1, leaves 7), then8e1cc8c469d9/ #192478 (+7 unallocated, leaves 14). This is a newly observed main budget regression, not noise or debt introduced by this patch. Current-head CI must still complete and any other failure must be investigated before landing.Previous-head inherited CI and platform gap
The final head
ffcf101f7608448a55a7c96078938894fdafa40eis tested by run41882496440, merge7597635649f675fb068e7d792ea1600155edd06finto exact main parentc9b26404f58f73b1292b15ef99814558c73b33fb. Ratchet job126760067825reports 6,467,855 lines / 6,467,848 ceiling, 7 over; this lane adds exactly 216 test lines and 216 allocation. Exact main has 6,467,639 / 6,467,632, the same 7 debt.On that clean exact main parent,
node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base a4297e5af3c40d2222c911ba03b09e001e1c8ac3 --no-merge-baseexits 1 with the same 7-over message and +256 main-only growth / +256 credit. No lane commit is present. The final 14→7 reduction isc4cef32628ec/ #192905 (+7 scalar); the residual seven traces to85905ea3b07d/ #192140's unallocated growth, partial reconciliation #192766, and #192903's one-line shrink. This newly observed main regression is reported for follow-up. No cleanup owner source changed across the captured main drift.A Blacksmith Testbox qualification attempt (
tbx_01m6kw253eexjzghkb7p5fdmjk, run41884425288) returned a lease but was queued. It was stopped without waiting for capacity or switching providers; no filesystem payload or btrfs benchmark ran. The run settled and blocking cleanup reconciliation exited 0. APFS timings and Linux counter fixtures remain the available proof; actual btrfs commit/chat-tail effects remain unmeasured.CI consumer synchronization repairs
Run 41882496440 also exposed an archive retry fixture that advanced its scheduler by zero while the new cross-sweep cooldown awaited one minute. The same real-owner archive case reproduced locally before repair. The shared fixture now advances one minute when requesting completed cleanup and captures a quiet pressure probe; pressure admission is independently tested at its owner. Zero-time ticks remain available for concurrent custody tests.
Two placement-abandonment cases checked local placement immediately after startup. Main commit
d4f79d57d59e179c6c4ea7b4271dbf435cedae1a/ #192542 intentionally moved active worker recovery into tracked background work, so startup readiness no longer implies recovery completion. Exact main parentc9b26404f58f73b1292b15ef99814558c73b33fbreproduces the failed-recovery assertion on Node; exact pre-introducer parent96dc3b77ddbabc4fb7b1e2a78d6039a0b9c4e13bpasses both selected cases. The database-reopen CI failure did not independently reproduce, so it is not waived as inherited. Both cases now await the same authoritative{state: "local", turnClaim: null}publication usingexpect.poll, preserving all subsequent result, turn, and custody assertions. This fixes a newly observed main test regression rather than treating it as noise. No production code changes in these repairs.Consumer repair proof: all five affected files pass locally, 40 tests / 284.31s Vitest (289.43s driver). The previously timed-out snapshot-failed retry passes in 3.020s. Exact-c9 Node proof with the new background producer passes both selected placement cases (16.067s and 9.860s), then the isolated proof checkout was restored to clean c9. Targeted typed lint and formatting pass. Codex autoreview of the consumer repairs is scoped-clean through P2; its initial six-line grant was subsequently narrowed mechanically to the ratchet's exact +2 counted increase (218 total), because shared fixture helpers are excluded. Exact LF replay leaves the same 191 original-parent debt, with no over-allocation. Production runtime and accepted measurements are unchanged.
The consumer repairs are pushed in
294ec417a3f75c34491c7048392f4006dcc0871d; new exact-head CI is pending. No merge request has been submitted.Final repair-scope
pnpm check:changed --base ffcf101f7608448a55a7c96078938894fdafa40ecompleted at head294ec417 with exit2. It passes both lint shards, formatting, line-cap, database, mock-export, plugin, and other selected ratchets; the only two failing selected checks are the already-attributed original-parent UI TS2322 and unused postgresSchemaFingerprint export. The separate exact LF accounting preserves191 original-parent debt with +218/+218. This scoped command does not select the test-line ratchet.Prior exact-parent CI attribution
Head
294ec417a3f75c34491c7048392f4006dcc0871dis tested in run 41888808939, mergea7dc0ab1dff5033be18e285172e36e2b1001cf83with ordered parents maindc13ca6d99ce258296cf74d501965ef4d9bf2ae1and this head. Completed ratchet job126781354552 reports6,470,261 tests /6,470,260 ceiling, one over, lane growth+218 with+218 credit. Exact main parent has6,470,043 /6,470,042, the same one-line debt.A clean exact-parent replay selecting a positive-growth, main-only interval exits1:
node --import ./scripts/tsx.mjs scripts/check-test-lines-ratchet.mts --base f9a25d7c2caccd7fbcd14ab899543d453b54ebb5 --no-merge-base. It reports the same one-over error and main-only+56 growth/+56 credit. The residual chain is unallocated+34 LF in85905ea3b07d/ #192140, partial reconciliation3e114e23c33c/ #192766, subsequent neutral allocations and reconciliations described above, andf9a25d7c2cac/ #192777 deleting six LF to reduce seven debt to one.d80b444161de/ #192931 adds56 LF with56 credit, leaving one. This is a global budget counter, so the ledger establishes residual debt rather than assigning a particular physical line. It is a main regression and follow-up, not noise or lane-added debt. Cleanup-owner files did not drift across the captured main advance. That earlier run remained pending at this checkpoint. No exception was submitted; the final run passed all required gates.Placement publication correction
Run 41888808939 later failed one placement database-reopen case after the new one-second
expect.polldeadline (failed/ claim null); the other three placement cases and repaired archive fixture passed. Exact dc13 macOS Node and Bun replays were green, so the CI subset cannot distinguish an intermediate forced-abandonment publication from a terminal move failure. It is not waived as inherited. Production deliberately publishesfailedbefore filesystem cleanup, Gateway materialization, teardown, and the finallocaltransaction.Commit
5c08677792afedfa6d7fdf026cbc39155ec9c5aareplaces timed polling with the existing placement-store change event, registered after database reopen and before startup. The persisted case awaits the finallocalpublication, then makes the original exact local/turnClaim-null assertion and all downstream custody/chat/archive checks. The existing 90-second case deadline is unchanged; no timer, provider mock, production seam, or production-code change is added. All four cases pass locally(45.52s Vitest/50.05s driver) and with the exactdc13 background producer on pinned Bun(database9.444s,failed-recovery15.448s). Codex review is scoped-clean through P2; typed lint and format pass. Counted test growth is now 225 with 225 credit, preserving 191 original-parent debt. Final exact-head CI is green; see the landing result below.Latest-stable retained-data proof
The registry
latesttag resolved to 2026.10.10; the installed CLI reportsOpenClaw 2026.10.10 (7dc3350). In isolated synthetic state, its real CLI created two worktrees. The fixture marked one as an expired absent-session owner and inserted a nested repository; the stable GC wrote its real 12-field revision-bound deferral. The second worktree contained a tracked edit and untracked note, and the stable CLI snapshotted and removed it.At candidate head
5c08677792afedfa6d7fdf026cbc39155ec9c5aa, normal source-build publication qualified a dedicated offline fixture profile on a free loopback port.pnpm openclaw --profile lane2188-upgrade doctor --client-credentials --repair --non-interactive --jsoncompleted withok: true, using the existing backed-up migration owner. This was needed for a pre-existing client-credential migration between stable and main; this PR changes no schema. The candidate CLI then listed both records, rechecked the old deferral to the current 11-field derived revision while preserving the nested repository and both files, restored the stable-created snapshot exactly, retried cleanup after repairing only that synthetic nested repository, and restored that new snapshot exactly. All five candidate worktree commands exited 0; both tracked edits and untracked notes matched.The initial candidate CLI attempts were refused by normal artifact-publication safety because the fixture lacked a qualified offline profile; no guard was disabled and no Gateway was stopped or restarted. A direct owner probe could read the old records but correctly refused writes before backed-up migration custody; it is not the successful upgrade verdict. The dedicated-profile Doctor and full candidate CLI sequence above supply that verdict. No production data or Team access was involved. This untimed compatibility fixture is separate from the accepted performance arms.
Landing result
Exact-head CI run41894353325 completed successfully for
5c08677792afedfa6d7fdf026cbc39155ec9c5aa. Ordinary GitHub auto-merge squashed the PR asaedae9dc410202f22504c6183823fd411699f723at 2026-11-04T19:36:07Z. No admin exception or CI rerun was used. The earlier inherited local/base failures above remain historical attribution, not a claim of final CI failures. Codex autoreview is clean through P2. No production deployment or Team access occurred.