Skip to content

fix: bound background worktree deletion bursts - #202197

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-removal-paced-unlink-20260919
Nov 20, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-removal-paced-unlink-20260919

Conversation

@steipete

@steipete steipete commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Retiring a managed checkout handed its whole renamed tree to one recursive delete. On shared storage, that metadata burst can delay unrelated database persistence despite a low-priority subprocess and once-per-minute admission. Orphan GC could also rename and recursively delete a tree while paced cleanup was pending.

User Impact

Cleanup now limits unlink bursts and backs off on slow filesystem commits. Normal retirement and orphan recovery share the serialized deletion owner, including permission-repair retries. Snapshot preservation, live-run checks, owner custody, and Git checks remain intact. Background cleanup takes longer and uses more total CPU/allocation; foreground removal can still release the original checkout name promptly.

Why This Change Was Made

The existing child deletes at most 128 entries or 8 MiB apparent bytes, then requests a 100 ms pause. One indivisible oversized file occupies its own batch. It reuses the existing host-pressure probe between batches, including current/recent btrfs commit times, with five-second waits under pressure. The child has a separate 30-minute budget; foreground checkout timeouts are unchanged. A new SQLite telemetry channel or host-probe subsystem was unnecessary.

The 62k-file fixture completes in about 55 seconds with 489 pauses and 2.34 MB at most per ordinary burst. This makes the entry budget a practical starting point for background work; the 8 MiB guard also bounds larger-file mixtures. It is not a calibrated btrfs transaction or latency limit.

Snapshot inventory already runs in the Git worker. snapshotMs is asynchronous elapsed wall time; isMainThread identifies the logging owner. No duplicate snapshot worker was added. Cumulative MAIN CPU spans many callbacks and is distinct from uninterrupted blocking.

Evidence

Five final-head A/B pairs ran serially, with A/A controls and host load recorded. Cleanup uses 62,000 generated files × 18,432 bytes plus directories; service removal uses 50,000 dependency files × 22,000 bytes plus 2,388 tracked files. Setup is outside timing. With five samples, nearest-rank p95 is the observed maximum; it is not a production tail estimate. MB is decimal, allocation is total V8 allocation including instrumentation, not retained memory.

Metric Before median (min–p95) After median (min–p95)
Cleanup wall, s 2.66 (2.43–13.18) 54.77 (54.33–56.06)
Cleanup CPU, s 2.33 (2.19–11.83) 4.80 (3.69–6.12)
V8 allocated, MB 3.48 (3.25–3.74) 188.62 (181.29–189.41)
Maximum entries/burst 62,621 (62,621–62,621) 128 (128–128)
Maximum apparent MB/burst 1,142.78 (1,142.78–1,142.78) 2.34 (2.34–2.34)
Pauses 0 (0–0) 489 (489–489)
Metric Before median (min–p95) After median (min–p95)
Removal wall, ms 1,168.5 (1,108.5–1,501.4) 1,111.3 (1,050.2–1,151.6)
Snapshot wall, ms 526.6 (511.1–836.0) 515.9 (480.3–539.0)
Total process CPU, ms 940.8 (905.8–985.4) 873.3 (854.2–918.1)
Cumulative MAIN CPU, ms 86.8 (80.3–94.8) 81.0 (79.0–86.1)
MAIN V8 allocated, MB 38.47 (33.90–46.81) 34.54 (29.20–38.44)
Maximum event-loop delay, ms 12.20 (12.06–12.43) 12.19 (12.04–12.75)

All candidate cleanup runs made 489 scheduled pauses, with observed durations 99.12–102.39 ms (median 102.08 ms). No retired cleanup directory remained after the service processes settled. The extra total CPU and allocation buy bounded work and byte accounting; this is not a throughput improvement. Final-code profiling placed active cleanup samples mostly in unlink and snapshot inventory in the Git worker; a native sample of the cleanup child observed a 35.2 MB physical footprint.

An earlier loaded-host sample is retained in the local report: cleanup took 99.93 s / 44.86 s CPU, with host load rising sharply. Its service removal had 2.42 s snapshot wall time but only 16.91 ms maximum event-loop delay. It is not included in this fresh final-head series and is not hidden as a passing performance claim.

Sanitized actual final worker report excerpt (the committed driver asserts complete deletion before writing this):

{
  "files": 62000,
  "fileBytes": 18432,
  "entryCount": 62621,
  "elapsedMs": 56061.000542,
  "cpuMs": 6119.198,
  "allocatedBytes": 187561880,
  "maxBatchEntries": 128,
  "maxBatchBytes": 2340864,
  "pauses": 489
}
node --import ./scripts/tsx.mjs scripts/perf/retired-worktree-unlink-measure.ts --output "$PERF_ROOT/unlink-b"
node --import ./scripts/tsx.mjs scripts/perf/worktree-removal-snapshot-measure.ts --files 50000 --file-bytes 22000 --tracked 2388 --output "$PERF_ROOT/main-b"

Repeat with fresh cleanup outputs and --reuse-fixture --report <new-name>.json for service measurements. Baselines use the original cleanup worker via --worker <pinned-worker.ts> and OPENCLAW_BENCH_BASELINE_DIR for the pinned removal/GC modules. All baseline files came from 1ade2b7a8899ea45934f93e7ede48443dff7d515.

119 focused owner tests passed; a separate expanded GC/custody run passed 96 tests (these run counts overlap). The pacing regression fails on the original worker, and the held-open retirement/GC regression fails on the preceding PR head. Both pass with the fix. Coverage includes filesystem entry/byte counters, synthetic slow-commit holds, oversized-file batches, symlink targets, real compiled subprocess deletion, permission repair, live-run refusal, owner custody, pending slots, and #202122 scratch-only re-arming. Existing host-pressure tests prove current/recent slow btrfs commits trigger pressure with zero PSI.

The final full pnpm check:changed passed. Independent Codex autoreview is scoped-clean through P2; the subsequent test-only commit removes two redundant string conversions without changing behavior. All five final-head measurement pairs are complete and published above. The hosted Codex orphan-GC finding has a code/proof response and is resolved. No changed runtime module is imported by Control UI, so its browser-test boundary is not crossed.

This is APFS/macOS proof, not a Linux/btrfs latency experiment. Apparent bytes and entry counts do not bound physical delayed references or the size of a shared filesystem transaction. Pacing and the existing slow-commit brake mitigate bursts; they do not prove that the reported seven-second SQLite stall is eliminated. No live-service access, copied production data, configuration option, or schema change was used.

The separate generated SQLite file contains 5,000 session-shaped rows and occupies 37,621,940,224 bytes (35.04 GiB). It supplies passive storage scale on the same volume, not the production agent schema or an active 35 GiB database workload. No database commit-latency result is claimed.

Production delta: +112/−29, net +83 lines across three modules. Growth provides the bounded walker and one shared deletion queue; it removes the orphan recursive-delete bypass. There is no new cache, manager, schema, or public option.

Inherited CI Failure

Final head f19e348802aad625f0b43419aca879a164970fe7, CI run 44666643767, attempt 1: 41 passed, 27 skipped, 2 failed. The only independent failure is check-docs; the other is its aggregate gate. security-fast passed.

All 18 release-note heading errors reproduce on exact CI main parent c3d658254b0835eb1663067163adcde6b4620401, with the same failing file/config as tested merge 756c046bbe58b208bafa8e2093d411e9d69590d8. They were introduced by #201913 (72702a3600f77f42f40b9387b3f353fa4a5fac1a). Later #202186/#202192 edits only add a count paragraph. This is a main regression requiring repair, not noise. The user explicitly authorized the pinned-head inherited-failure exception; the native evidence retains this failed CI verdict.

@clawsweeper

clawsweeper Bot commented Nov 20, 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.

@chatgpt-codex-connector

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

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T03:12:01.359345Z 1d31d20 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling size: M labels Nov 20, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f808753fa7

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@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 20, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the hosted review's P1 finding in 1d31d20:

  1. Orphan GC bypassing paced deletion: removal-git.ts:37–71 now owns queued/running paths and one serialized deletion queue. gc-artifacts.ts:368–372 leaves active deletion with that owner, and both deletion attempts at lines 421 and 435 use the paced worker, including interrupted-cleanup recovery. Permission repair and canonical/registry safety checks remain intact. The real service regression at service.removal-safety.test.ts:145–149 fails on the preceding head (GC deletes the held-open retired checkout) and passes with this correction. All 96 tests in the expanded GC/custody run pass; fresh independent Codex P0–P2 autoreview is scoped-clean.

@clawsweeper review
Please review the final head, including orphan recovery and the shared deletion owner. No completed ClawSweeper review has appeared yet; the earlier bot comment only acknowledged receipt.

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@steipete

Copy link
Copy Markdown
Contributor Author

The final head is f19e348. Its only change from 1d31d20 is removing two redundant string conversions in the GC test mock; runtime code is identical. The failed lint check now passes, and all other changed-check lanes passed.

@clawsweeper re-review
Please bind the final review to this head. The orphan-GC correction and its red/green proof are detailed in the preceding numbered response.

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. 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 20, 2026
@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR bounds retired-worktree deletion bursts and routes orphan recovery through the same serialized cleanup queue.

Example: Retire a synthetic checkout containing 62,000 files.

  • Before: One recursive deletion processes the entire tree without scheduled pauses.
  • After: Deletion pauses between bounded batches, with all five published candidate runs completing within the entry and byte budgets.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and supported by completed production-path filesystem measurements, with platform limitations stated accurately.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Published final-head macOS output exercises the actual cleanup owner against real files, reports bounded batches and complete deletion, and pairs this with real service-removal measurements; Linux/btrfs transaction-latency improvement is expressly unclaimed.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Background checkout reclamation can create large filesystem metadata bursts that interfere with unrelated persistence.
Reason: The maintainer explicitly accepts the background throughput and allocation costs, and the completed measurements demonstrate the intended burst reduction without a foreground-removal regression.

Merge readiness

✅ Ready for maintainer review

The published final-head comparisons resolve the previous author hold, and this review found no actionable defects; CI remains red for the documented inherited docs failure.

Priority: P2
Reviewed head: f19e348802aad625f0b43419aca879a164970fe7

Before merge

None.

Findings

None.

Agent review details

How this fits together

Managed-worktree removal preserves a recovery snapshot and unregisters the checkout; the cleanup child reclaims its retired files, while orphan GC recovers interrupted deletions.

flowchart TD
  A[Managed checkout removal] --> B[Snapshot and Git unregistration]
  B --> C[Serialized deletion queue]
  D[Orphan GC and permission repair] --> C
  C --> E[Paced cleanup child]
  F[Host IO pressure probe] --> E
  E --> G[Retired files reclaimed]
Loading

Technical review

Best possible solution:

Retain the shared paced deletion owner and proceed through normal landing under the recorded inherited-CI exception.

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

Current main exposes the whole-tree recursive deletion directly, and the supplied real-filesystem comparison demonstrates the burst; no target code was executed during this review.

Is this the best way to solve the issue?

The smallest complete fix is to pace the existing cleanup child and route orphan deletion through its existing queue, preserving snapshot, custody, and permission-repair behavior.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 626527a745ad.

Provenance checked

  • Asynchronous checkout retirement keeps the original intent (4858422: Release the checkout name promptly while preserving snapshots, Git checks, and rollback.)
  • Whole-tree cleanup worker changes intended behavior with a stated reason (57f6d20: Use a declared packaged helper entry for the existing recursive deletion operation.)
  • Orphan deletion and permission repair keeps the original intent (8b2d702: Recover read-only orphan dependencies with confined directory permission repair and one retry.)
  • Orphan retirement custody keeps the original intent (9f441ad: Detach orphan directories under brief allocation custody and delete them after releasing that lease.)
  • Benchmark baseline preservation assertions changes intended behavior with a stated reason (3475ab3: Measure historical dependency-snapshot behavior while checking preservation of user edits.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 4858422 adds src/agents/worktrees/removal-git.ts:28 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 4858422de239; files: src/agents/worktrees/removal-git.ts)
  • Jason (Json): Raw commit 530ce23 adds src/agents/worktrees/removal-git.ts:3 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 530ce231326b; files: src/agents/worktrees/removal-git.ts)

PR surface

Source +83, Tests +104, Docs +9, Other +153. Total +349 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 112 29 +83
Tests 3 125 21 +104
Docs 1 10 1 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 2 155 2 +153
Total 9 402 53 +349

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production versus test delta Production +112/−29; tests +125/−21 Growth implements bounded traversal and shared deletion ownership, with distinct pacing, byte-budget, symlink, and orphan-coordination regressions.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This limits background filesystem interference without establishing an urgent current outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (2 earlier review cycles)
  • reviewed 2026-11-20T03:22:38.852Z sha f19e348 :: needs maintainer review before merge. :: none
  • reviewed 2026-11-20T03:38:17.123Z sha f19e348 :: needs changes before merge. :: none

Reviewed November 19, 2026, 10:58 PM ET / November 20, 2026, 03:58 UTC (Revision 3).

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Nov 20, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

Addressed the latest review's only open item on unchanged final head f19e348802aad625f0b43419aca879a164970fe7:

  1. Complete the final-head five-pair comparison and publish it: Done. The PR body now contains both complete n=5 A/B tables (medians, minima and observed p95/maxima), A/A context, the retained earlier outlier, exact commands, and a sanitized actual final-worker JSON report. All five final candidate cleanup runs completed with maximum 128 entries / 2,340,864 apparent bytes per burst and 489 scheduled pauses. Cleanup median: 2.655 → 54.768 seconds; CPU: 2.334 → 4.801 seconds; V8 allocation: 3.483 → 188.619 MB, including instrumentation. Real 50k-file service removal median: 1,168.5 → 1,111.3 ms; worst event-loop delay across the five runs: 12.43 → 12.75 ms. The committed production-entry driver asserts complete deletion at scripts/perf/retired-worktree-unlink-measure.ts:114–115; the real service measurement starts at scripts/perf/worktree-removal-snapshot-measure.ts:727. No retired cleanup directory remained after all service processes settled. No measurement work or author hold remains.

The final full pnpm check:changed passed. Exact-head CI is complete; only the attributed release-note lint regression and its aggregate are red, with parent reproduction and introducing #201913 documented. The macOS/btrfs limitation and higher background CPU/allocation cost remain explicit.

@clawsweeper re-review
Please recheck item 1 against the now-published final measurements. No source or test bytes changed after your reviewed head.

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Nov 20, 2026
@steipete
steipete merged commit 58dbe40 into main Nov 20, 2026
175 of 179 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-removal-paced-unlink-20260919 branch November 20, 2026 04:06
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 20, 2026
* fix: pace retired worktree cleanup

* fix: share paced deletion with orphan recovery

* test: remove redundant cleanup target conversions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation 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. scripts Repository scripts size: M 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