Skip to content

improve: reduce Gateway pauses during worktree cleanup - #154545

Merged
steipete merged 2 commits into
mainfrom
codex/team-perf-worktree-cleanup-facts-20260921
Sep 22, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/team-perf-worktree-cleanup-facts-20260921

Conversation

@steipete

@steipete steipete commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Cleanup above the live-worktree limit repeatedly decoded and sorted retained registry history on the Gateway thread for every eviction candidate.

User Impact

Cleanup applies the same limits and protections with less work on the Gateway thread. Configuration, retention, snapshots, persisted state, and update behavior are unchanged.

Why This Change Was Made

The existing shared-state worker now selects only live IDs through the existing removed_at index. Cleanup rereads those IDs for every candidate, so a competing removal reduces pressure before the next eviction. The initial candidate inventory also uses the existing worker reader. Removal still owns fresh activity, owner, lease, Git-lock, and snapshot checks.

Evidence

Performance measurements below are from the reviewed initial head 962ffde2b97a. Main subsequently extracted the same limit loop into gc-limits.ts and added cleanup outcome reporting. The query cutover now uses that owner; the measurements were not rerun after this integration. Fresh review, focused tests, and the real Git lifecycle proof validate the integrated behavior.

A matched ABBA replay of the real cleanup entry point used 553 live synthetic rows (29 manual) plus 974 retained rows. Each row includes a valid synthetic cleanup outcome with a 360-character failure reason; this is a populated-history workload, not a measurement of production row payloads. Each process ran one cold pass and three warm passes. On macOS / Node 26.8.2 without allocation profiling, medians across the six warm passes were:

Metric Before After
Whole-process CPU 5,576.74 ms 604.06 ms
Main-thread CPU 4,773.27 ms 247.11 ms
Wall time 5,365.83 ms 732.52 ms

The local host was shared and loaded. The matching Linux / Node 26.8.2 ABBA run, with allocation sampling enabled, reduced median whole-process CPU from 4,040.07 to 224.56 ms, main-thread CPU from 3,145.20 to 82.64 ms, wall time from 3,179.66 to 187.14 ms, and sampled main-isolate allocations from 2.522 GB to 68.807 MB. The two cold candidate passes took 2.890 and 1.447 seconds. Linux proof completed with payload exit 0 and a stopped lease; the enclosing Testbox workflow may show cancellation after its owned cleanup. RSS was mixed across platforms/runs, so this does not establish a resident-memory or production-wide CPU saving.

Real Git lifecycle proof passed on macOS and Linux: an active run lease and a manual checkout remain protected, a deterministic competing remover stops cleanup at the correct count, and a recovery snapshot restores edited contents. Only task-owned synthetic repositories and state were used.

  • Initial focused registry, GC, removal-lease, and removal-safety suites: 55 tests passed, 153.31 s command wall time. After integration with current main: registry and GC suites, including cleanup outcome reporting, passed 39 tests in 126.02 s command wall time; the real Git lifecycle proof passed again.
  • Extended existing registry-worker tests cover captured state, zero host SQL, and removal/restoration visibility. Standalone pnpm test src/agents/worktrees/registry-read.test.ts --maxWorkers=1: 2 tests passed, 106.66 s command wall / 97.22 s Vitest duration on the loaded host (85% transform, about 10% tests). The existing fixture is reused; no production test seam was added. In exact-head CI run 35599970314, both cases passed and reported 0.871 s and 1.185 s (2.056 s summed case time; the verbose reporter does not provide a separate file wall time).
  • Changed checks passed locally: core and test typechecks, targeted formatting/lint, dead-export scan, import cycles, and selected ownership/schema guards. git diff --check passed.
  • Independent Codex review: no actionable P0–P2 findings.

The previous exact-head CI run failed in an unchanged library-read test fixture: temporary state was deleted before asynchronous worker lease drainage. The refreshed branch includes canonical main fix 103115f2f0b1, which drains agent workers before shared state and asserts settled custody. Its separate Linux / Node 24.19.0 proof passed three original-group runs (626 tests each), 20 standalone runs (9 tests each), and 72 sibling tests. The cleanup patch itself is unchanged by this refresh.

CI also caught the shared-state runtime exceeding its existing 700-line cap after nearby main changes. Grouping its two worktree read dispatches and using the existing kernel namespace brought it from 704 to 700 counted lines; the ratchet, behavior, and budget are unchanged. The exact failing ratchet now passes, as do targeted lint, independent review, and both registry-reader cases (one setup was initially refused by the disk reserve, then passed after space was restored).

Run 35590723180 also failed an unchanged Bun base64 memory assertion (71,474,209 bytes against a 67,108,864-byte budget). Its canonical repair is tracked separately in #154808; this PR does not relax the threshold or skip the test.

Run 35595268335 failed the unchanged UI rail fixture because its focus update had not settled before the assertion. This branch includes canonical main fix 0883394977d1: it moves the existing flush before the assertion, with production bytes unchanged. The owner verified the source against the failing CI merge and passed the 21-case rail suite plus 2,342 UI/component tests.

ClawSweeper review completed without findings for pre-refresh head 8acbd44d5d22. Its CI run 35599970314 failed the unchanged cron test holds adopted on-exit work until the previous scheduler drains (start) and a separate job that never acquired a runner or executed any steps. The branch now includes canonical main fix fd2c001cad2d, which synchronizes the cron fixture with owned callback entry and completion instead of elapsed time. The original 13-file group reproduced two failures on fresh main; the repaired group passed all 283 tests, followed by clean independent review and full selected checks. No runtime behavior, timeout, or assertion budget changed. The refreshed cleanup patch at 4aa9e9859bbf is aggregate patch-identical; its line-cap ratchet and diff sanity check pass. Fresh exact-head CI run 35610067697 passed all 159 jobs for 4aa9e9859bbf, and ClawSweeper completed its review of that head without findings. Native landing follows these completed gates.

@clawsweeper

clawsweeper Bot commented Sep 21, 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 agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Sep 21, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 21, 2026
@clawsweeper

clawsweeper Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 21, 2026, 11:16 AM ET / 15:16 UTC (Revision 9).

ClawSweeper review

What this changes

Moves worktree cleanup inventory reads into the existing database worker and fetches only live checkout IDs when recalculating cleanup pressure.

Merge readiness

✅ Ready for maintainer review

The optimization remains useful on current main, and no actionable correctness or security findings remain. Recorded lifecycle proof covers cleanup protections and recovery, and GitHub confirms successful CI for the reviewed head.

Priority: P2
Reviewed head: 4aa9e9859bbf603ee64dffc3d7b2ef5d72150158

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with credible lifecycle evidence, explicit benchmark limits, successful current-head CI, and no actionable findings.
Proof confidence 🦞 diamond lobster (5/6) ✨ media proof bonus Sufficient (linked_artifact): The captured evidence describes real cleanup and Git lifecycle runs on macOS/Linux, including competing removal, protected checkouts, and snapshot restoration after integration. Benchmark figures apply to the initial implementation and synthetic workload, not a measured production-wide saving.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (linked_artifact): The captured evidence describes real cleanup and Git lifecycle runs on macOS/Linux, including competing removal, protected checkouts, and snapshot restoration after integration. Benchmark figures apply to the initial implementation and synthetic workload, not a measured production-wide saving.
Evidence reviewed 9 items Verified introduced patch: The pinned merge-base-to-head diff changes registry reads and worker dispatch, with focused test extensions. It does not change removal authority, schemas, dependencies, configuration, or retention settings. Base-only approval changes were excluded from attribution.
Still necessary on main: Fetched main still materializes complete registry records synchronously for the initial inventory and each pressure refresh. The branch's narrower worker query is therefore a distinct remaining improvement.
Equivalent live-record selection: The new query selects IDs where removed_at is null, matching the existing row decoder's live-record semantics. It uses the existing removed_at index and performs a fresh query for every candidate rather than introducing a cache.
Findings None None.
Security None None.

How this fits together

Managed worktree cleanup applies count and size limits to agent-owned Git checkouts. Registry reads identify candidates, while the removal service checks activity, ownership, leases, locks, and recovery snapshots before deleting a checkout.

flowchart TD
  A[Cleanup limits] --> B[Cleanup planner]
  C[Worktree registry] --> D[Database worker]
  D -->|Fresh live IDs| B
  B --> E[Removal safety checks]
  E -->|Protected| F[Keep checkout]
  E -->|Eligible| G[Snapshot and remove]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +16, Tests +15. Total +31 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 5 30 14 +16
Tests 1 16 1 +15
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 46 15 +31

Review metrics

None.

Technical review

Best possible solution:

Keep fresh cleanup inventory reads in the existing worker while retaining removal safety decisions in the worktree service.

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

Yes: current main visibly decodes and sorts retained registry records for each candidate, and the PR documents a matched populated-history replay through the real cleanup entry point; this review did not execute it.

Is this the best way to solve the issue?

Yes: a narrow live-ID projection through the existing worker removes repeated decoding without duplicating storage ownership or changing cleanup policy.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded performance improvement for cleanup with large retained worktree histories.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (linked_artifact): The captured evidence describes real cleanup and Git lifecycle runs on macOS/Linux, including competing removal, protected checkouts, and snapshot restoration after integration. Benchmark figures apply to the initial implementation and synthetic workload, not a measured production-wide saving.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured evidence describes real cleanup and Git lifecycle runs on macOS/Linux, including competing removal, protected checkouts, and snapshot restoration after integration. Benchmark figures apply to the initial implementation and synthetic workload, not a measured production-wide saving.

Evidence

What I checked:

  • Verified introduced patch: The pinned merge-base-to-head diff changes registry reads and worker dispatch, with focused test extensions. It does not change removal authority, schemas, dependencies, configuration, or retention settings. Base-only approval changes were excluded from attribution. (src/agents/worktrees/gc-limits.ts:23, 4aa9e9859bbf)
  • Still necessary on main: Fetched main still materializes complete registry records synchronously for the initial inventory and each pressure refresh. The branch's narrower worker query is therefore a distinct remaining improvement. (src/agents/worktrees/gc-limits.ts:45, 28acdfc4504d)
  • Equivalent live-record selection: The new query selects IDs where removed_at is null, matching the existing row decoder's live-record semantics. It uses the existing removed_at index and performs a fresh query for every candidate rather than introducing a cache. (src/agents/worktrees/registry-read.kernel.ts:98, 4aa9e9859bbf)
  • Removal protections remain authoritative: Cleanup still passes the existing activity and owner commit guard into removal. Removal retains allocation custody, live-record rereads, exclusive removal claims, lock checks, and snapshot preparation before Git deletion; registry IDs do not grant deletion authority. (src/agents/worktrees/service.ts:1426, 4aa9e9859bbf)
  • Recorded production-path proof: The captured PR body at sourceRevision 1a0b701f0e14d1e86ce2cab238260fb9710afbe3380059959ebafe539ad68c42 reports matched macOS/Linux cleanup benchmarks and real Git lifecycle runs preserving active leases and manual checkouts, stopping after a competing removal, and restoring edited contents from snapshots. It explicitly identifies benchmark head 962ffde and states that lifecycle proof was repeated after integration; benchmark numbers were not rerun. The linked Linux run reports cancellation at workflow level, consistent with the disclosed cleanup caveat, so that conclusion alone is not treated as a behavioral pass.
  • Focused coverage and current CI: Extended registry tests cover captured state-directory identity, zero host SQL, and removal/restoration visibility. Existing cleanup tests cover competing removers, changed activity, manual protection, and size accounting. GitHub confirms CI run 35610067697 completed successfully for the exact reviewed head. Tests were not executed during this read-only review. (src/agents/worktrees/registry-read.test.ts:127, 4aa9e9859bbf)

Likely related people:

  • Peter Steinberger: Raw commit 88004e9 adds src/agents/worktrees/registry-read.ts:6 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 88004e9cc669; files: src/agents/worktrees/registry-read.ts)
  • Vincent Koc: Raw commit 585312d adds src/agents/worktrees/gc-limits.ts:82 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 585312d8ba73; files: src/agents/worktrees/gc-limits.ts)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (8 earlier review cycles)
  • reviewed 2026-09-21T07:11:48.325Z sha 962ffde :: needs changes before merge. :: none
  • reviewed 2026-09-21T08:48:03.157Z sha 122e8cd :: needs changes before merge. :: none
  • reviewed 2026-09-21T08:56:02.524Z sha 122e8cd :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T11:00:04.707Z sha f6cc9f2 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T11:54:46.976Z sha e2a3961138cc3ae3f711f22844f287627949e5aa :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T12:39:12.013Z sha 8acbd44 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T13:03:46.790Z sha 8acbd44 :: needs maintainer review before merge. :: none
  • reviewed 2026-09-21T14:17:09.786Z sha 4aa9e98 :: needs maintainer review before merge. :: none

@steipete
steipete force-pushed the codex/team-perf-worktree-cleanup-facts-20260921 branch from 962ffde to 122e8cd Compare September 21, 2026 08:40
@steipete
steipete marked this pull request as ready for review September 21, 2026 08:48
@steipete
steipete force-pushed the codex/team-perf-worktree-cleanup-facts-20260921 branch from 122e8cd to f6cc9f2 Compare September 21, 2026 10:48
@steipete
steipete force-pushed the codex/team-perf-worktree-cleanup-facts-20260921 branch from e2a3961 to 8acbd44 Compare September 21, 2026 12:30
Read fresh live IDs through the existing shared-state worker for every cleanup candidate instead of materializing retained records. Preserve live removal authority, active leases, owner protection, snapshots, and activity checks.
Share the worktree read dispatch guard and existing kernel namespace while preserving each operation and its database. This keeps the shared-state runtime within its existing line cap without changing the ratchet or adding a wrapper.
@steipete
steipete force-pushed the codex/team-perf-worktree-cleanup-facts-20260921 branch from 8acbd44 to 4aa9e98 Compare September 21, 2026 14:07
@steipete
steipete merged commit 24892b0 into main Sep 22, 2026
227 of 228 checks passed
@steipete
steipete deleted the codex/team-perf-worktree-cleanup-facts-20260921 branch September 22, 2026 02:42
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 22, 2026
* perf(worktrees): narrow cleanup registry reads

Read fresh live IDs through the existing shared-state worker for every cleanup candidate instead of materializing retained records. Preserve live removal authority, active leases, owner protection, snapshots, and activity checks.

* refactor(state): group worktree registry reads

Share the worktree read dispatch guard and existing kernel namespace while preserving each operation and its database. This keeps the shared-state runtime within its existing line cap without changing the ratchet or adding a wrapper.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant