Skip to content

fix(worktrees): stop idle cleanup from overwhelming shared storage - #192909

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-idle-worktree-cleanup-pacing-20260919
Nov 4, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-idle-worktree-cleanup-pacing-20260919

Conversation

@steipete

@steipete steipete commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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

  • 150 focused tests passed across scheduler, pressure probe, GC, CLI, paths, leases, removal budgets, registry reads, capacity, and worker custody. After simplifying error classification, the two affected files passed again (63 tests). The initial full focused run took 307.72 seconds; the final two-file run took 130.83 seconds, including worker compilation. Existing real-Git snapshot/recovery tests dominate this cost.
  • Pacing regression fails on the parent: three candidates start at time zero. Candidate starts are 0/60/120 seconds; the next sweep retains the same admission clock. Pressure, cancellation, and configuration changes are covered.
  • Oversized-workspace and archived-owner retry regressions fail before their fixes, then pass with restart, due-time, explicit-retry, preserved-content, and restore assertions.
  • Codex autoreview of the complete local candidate against 8cb658e39b6dbe1bbe03746bf2a468a898c15da2: scoped-clean through P2, no actionable findings.
  • pnpm check:changed ran. 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:149 TS2322, introduced by 3e361e28cdf9 / improve(ui): clarify browser and link reader feedback #192281. This is a main regression. The same exact-parent replay also fails for the sole unused postgresSchemaFingerprint export (re-exported without a consumer by cf50d4a36629 / feat(storage): support read-only PostgreSQL standby inspection #192645). Test-budget debt is already 191 lines on that parent; its sustained deficit begins at 53b1b400c46c / 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 54ed8024a777 ages both affected fixture records beyond the jitter window; the exact failing gc-partial: live case 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 is 7e77fba67ba21fed1143c477bb2de62fef1a2e27. Later test-only correction 54ed8024a777 changes 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

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/worktree-cleanup-pacing-measure.ts --source "$fixture" --prepare --files 62000 --file-bytes 18432
OPENCLAW_BENCH_BASELINE_DIR="$overlay" node --expose-gc --import ./scripts/tsx.mjs scripts/perf/worktree-cleanup-pacing-measure.ts --source "$fixture" --output "$newBaselineArm" --worktrees 2
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/worktree-cleanup-pacing-measure.ts --source "$fixture" --output "$newCandidateArm" --worktrees 2
# Separate diagnostic arm adds --profile to the candidate command.

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-parent package.json ESM marker. Accepted sequence was A/A, A/A, then A/B five times, followed by the separate profile arm.

Five-pair comparison

Metric per two-worktree cohort A median B median Median change A p95 B p95 P95 change
Owner wall, s 26.189 23.846 -8.95% 33.118 27.457 -17.09%
Process CPU, s 20.042 17.253 -13.91% 23.584 20.209 -14.31%
Main CPU, s 1.866 1.678 -10.07% 2.095 1.920 -8.35%
Main allocation, MiB 717.335 696.367 -2.92% 729.877 721.419 -1.16%

Intentional waiting, separate from owner service time

Timeline metric, s A median B median A p95 B p95
Virtualized scheduled wait 2.000 51.442 2.000 54.599
Logical complete cohort time 28.189 74.605 35.118 78.015

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

Arm Owner wall s Process CPU s Main CPU s Main allocation MiB Admission/removal gap s One-minute load before → after
control-1 25.084 16.709 1.440 711.794 13.078 (removal start) 10.34 → 9.66
control-2 19.061 17.100 1.478 719.961 7.608 (removal start) 10.93 → 12.03
control-3 23.292 16.503 1.473 730.466 10.228 (removal start) 10.10 → 10.20
control-4 17.807 15.366 1.377 718.469 7.124 (removal start) 8.88 → 11.05
pair-1-A 18.188 15.996 1.414 717.335 7.048 (removal start) 11.75 → 11.69
pair-1-B 23.846 16.595 1.509 699.250 60.001 (admission) 9.96 → 9.55
pair-2-A 28.562 20.042 1.866 702.655 13.885 (removal start) 19.64 → 16.69
pair-2-B 27.457 20.209 1.920 696.367 60.002 (admission) 13.45 → 13.67
pair-3-A 33.118 22.809 2.095 719.575 16.780 (removal start) 14.28 → 15.99
pair-3-B 19.397 17.253 1.678 721.419 60.001 (admission) 12.41 → 12.04
pair-4-A 22.065 18.762 1.757 729.877 8.738 (removal start) 12.32 → 15.62
pair-4-B 26.413 17.979 1.690 691.267 60.002 (admission) 12.31 → 12.83
pair-5-A 26.189 23.584 1.913 709.770 10.495 (removal start) 14.92 → 14.67
pair-5-B 20.608 14.249 1.284 596.889 60.001 (admission) 15.67 → 16.54
diagnostic-B 18.551 16.523 1.667 699.993 60.001 (admission) 16.36 → 15.38

Pairwise changes and A/A controls

A/B pair Owner wall Process CPU Main CPU Main allocation
1 +31.11% +3.75% +6.76% -2.52%
2 -3.87% +0.83% +2.91% -0.89%
3 -41.43% -24.36% -19.91% +0.26%
4 +19.71% -4.17% -3.79% -5.29%
5 -21.31% -39.58% -32.89% -15.90%
A/A control pair Owner wall Process CPU Main CPU Main allocation
control-1 / control-2 -24.01% +2.34% +2.66% +1.15%
control-3 / control-4 -23.55% -6.89% -6.50% -1.64%

Flags and attribution

Positive changes above 20% are listed explicitly; they are not erased by averaging or dismissed as spread:

  • pair-1: wallMs +31.11%.

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. Commits af33568d078e and ffcf101f7608 change 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 41881018650 tested merge cb526748c892ac8dc6d251cd01503b1bfe0d8662 of af33568d into exact main parent f1a317d4674280aba0865d381861ea0bb924032d. 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), reconciliation 3e114e23c33c / #192766 (leaves 8 debt), a4297e5af3c4 / #192903 (-1, leaves 7), then 8e1cc8c469d9 / #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 ffcf101f7608448a55a7c96078938894fdafa40e is tested by run 41882496440, merge 7597635649f675fb068e7d792ea1600155edd06f into exact main parent c9b26404f58f73b1292b15ef99814558c73b33fb. Ratchet job 126760067825 reports 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-base exits 1 with the same 7-over message and +256 main-only growth / +256 credit. No lane commit is present. The final 14→7 reduction is c4cef32628ec / #192905 (+7 scalar); the residual seven traces to 85905ea3b07d / #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 parent c9b26404f58f73b1292b15ef99814558c73b33fb reproduces the failed-recovery assertion on Node; exact pre-introducer parent 96dc3b77ddbabc4fb7b1e2a78d6039a0b9c4e13b passes 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 using expect.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 ffcf101f7608448a55a7c96078938894fdafa40e completed 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 294ec417a3f75c34491c7048392f4006dcc0871d is tested in run 41888808939, merge a7dc0ab1dff5033be18e285172e36e2b1001cf83 with ordered parents main dc13ca6d99ce258296cf74d501965ef4d9bf2ae1 and 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 in 85905ea3b07d / #192140, partial reconciliation 3e114e23c33c / #192766, subsequent neutral allocations and reconciliations described above, and f9a25d7c2cac / #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.poll deadline (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 publishes failed before filesystem cleanup, Gateway materialization, teardown, and the final local transaction.

Commit 5c08677792afedfa6d7fdf026cbc39155ec9c5aa replaces timed polling with the existing placement-store change event, registered after database reopen and before startup. The persisted case awaits the final local publication, 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 latest tag resolved to 2026.10.10; the installed CLI reports OpenClaw 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 --json completed with ok: 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 as aedae9dc410202f22504c6183823fd411699f723 at 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.

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.
@clawsweeper

clawsweeper Bot commented Nov 4, 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: L labels Nov 4, 2026
@steipete
steipete marked this pull request as ready for review November 4, 2026 17:15
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T19:13:16.118504Z 5c08677 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 4, 2026
@openclaw-barnacle openclaw-barnacle Bot added the cli CLI command changes label Nov 4, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 4, 2026
@clawsweeper

clawsweeper Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This 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.

  • Before: The sweep can attempt all three without a minute between starts.
  • After: Removal admissions occur at least 60 seconds apart, with longer pauses under IO pressure.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-level measurements support the design, but a confirmed consumer timeout and incomplete upgrade evidence prevent readiness.
Proof confidence 🦐 gold shrimp (3/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Large expired worktree cohorts can sustain filesystem cleanup pressure despite the scheduler's short yields.
Reason: The maintainer-authored direction addresses a concrete cleanup failure mode without adding configuration or a competing cleanup owner.

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
Reviewed head: ffcf101f7608448a55a7c96078938894fdafa40e

Before merge

  • Advance the archive fixture through paced retry continuations (P2) - The admission deadline survives completed sweeps, but createArchiveWorktreeFixture's cleanupWorktrees helper only awaits clock.advanceBy(0). In the snapshot-failed archive case, the first removal attempt sets nextRemovalAt; the second cleanup at the same synthetic time awaits a future resume job that nothing drives. Exact-head CI reports this case timing out. Update the shared fixture to start the sweep and drive its scheduled continuations to settlement, with controlled IO-pressure input, while preserving the production minute interval.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P2] Advance the archive fixture through paced retry continuations — src/gateway/worktree-maintenance.ts:245-246

Tests

  • Missing end-to-end proof: Provide a latest-stable upgrade run showing existing worktree records, snapshots, and retry behavior remain usable after the derived-revision change.
Agent review details

How this fits together

Gateway 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]
Loading

Technical review

Best 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:

  • [P2] Advance the archive fixture through paced retry continuations — src/gateway/worktree-maintenance.ts:245-246
    The admission deadline survives completed sweeps, but createArchiveWorktreeFixture's cleanupWorktrees helper only awaits clock.advanceBy(0). In the snapshot-failed archive case, the first removal attempt sets nextRemovalAt; the second cleanup at the same synthetic time awaits a future resume job that nothing drives. Exact-head CI reports this case timing out. Update the shared fixture to start the sweep and drive its scheduled continuations to settlement, with controlled IO-pressure input, while preserving the production minute interval.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/gateway/server.sessions.archive-worktree-lifecycle.test.ts --maxWorkers=1
  • pnpm test src/gateway/worktree-maintenance.test.ts --maxWorkers=1
  • git diff --check

What I checked:

  • Introduced change and current-main behavior: The pinned introduced diff adds beforeRemoval admission to the existing GC owner; fetched main retains the earlier short-yield scheduler and lacks these changes. (src/gateway/worktree-maintenance.ts:243, ffcf101f7608)
  • Exact-head failing archive consumer: CI reports a timeout in the snapshot-failed archive-retry case. Its shared fixture calls advanceBy(0) for each cleanup, while the new admission clock persists across sweeps; the retry schedules a future continuation that the fixture never drives. (src/gateway/test/server-sessions.worktree-fixture.ts:117, ffcf101f7608)
  • CI attribution limits: The same check also reports two placement-abandonment assertion failures whose cause is not established here. The PR separately records an exact-parent failing replay for inherited test-budget debt; its own net test growth is matched by allocation credit. Downloading job logs was blocked by the artifact host allowlist. (config/test-lines-allocations/worktree-cleanup-pacing.txt:2, ffcf101f7608)
  • Supplied production-owner measurements: The complete PR body reports real scheduler, owner-policy, SQLite, Git snapshot, and deletion runs on synthetic APFS checkouts, with scheduled waits virtualized and preserved snapshot contents. The committed script matches that boundary; it does not establish shipped Gateway or Linux btrfs performance. The captured body identity is SHA-256 a41163dafa1b7e225db9a8cb39ca901f2839fa821724dd4b8088dec6b6e2312b. (scripts/perf/worktree-cleanup-pacing-measure.ts:1, ffcf101f7608)
  • Persisted deferral compatibility: Removing runEndCleanup from the serialized revision deliberately invalidates existing derived deferral receipts once; user records and schema remain intact. Restart tests exercise newly written receipts, but the supplied evidence contains no latest-stable upgrade run. (src/agents/worktrees/registry-read.kernel.ts:115, ffcf101f7608)
  • Feature history and accepted direction: Peter Steinberger's merged history covers background GC, durable timeout backoff, corruption backoff, and subsequent scheduler refactors. This maintainer-authored PR explicitly accepts longer cohort completion for pacing and discloses measurement regressions and limits. (src/gateway/worktree-maintenance.ts:225, 0b9f3ab3aec3)

PR surface

Source +98, Tests +216, Docs +8, Other +364. Total +686 across 17 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 6 124 26 +98
Tests 8 281 65 +216
Docs 1 10 2 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 2 364 0 +364
Total 17 779 93 +686

Review metrics

Metric Value Why it matters
Runtime and regression growth Production +124/-26; tests +281/-65 Runtime growth supplies admission pacing and pressure sampling through existing owners; net regression growth of 216 lines has matching allocation credit.

Labels

Label changes:

  • add P2: This addresses sustained storage pressure from managed-worktree cleanup, with a focused consumer-fixture repair required before merge.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This addresses sustained storage pressure from managed-worktree cleanup, with a focused consumer-fixture repair required before merge.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 4, 2026, 1:21 PM ET / 18:21 UTC.

@steipete
steipete enabled auto-merge (squash) November 4, 2026 19:24
@steipete
steipete merged commit aedae9d into main Nov 4, 2026
155 of 156 checks passed
@steipete
steipete deleted the steipete/perf-micro-idle-worktree-cleanup-pacing-20260919 branch November 4, 2026 19:36
@steipete

steipete commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash auto-merge.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 5, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling cli CLI command changes docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant