Skip to content

fix(worktrees): give chat writes breathing room during large cleanup - #202607

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-2706-commit-aware-chunks
Nov 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-2706-commit-aware-chunks

Conversation

@steipete

@steipete steipete commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A large retired-worktree deletion can keep generating filesystem metadata work for several minutes and delay chat transcript writes even below the 40 GiB reservation watermark added in #202563. One reported deletion lasted 392 seconds with a 6.34-second btrfs commit and multi-second foreground writer delays.

Related: #202197, #202563, #202204.

User Impact

User impact: optional Linux cleanup yields sooner when filesystem commits slow down and splits large trees into shorter passes, giving foreground writers quiet intervals. Reclaiming a large tree takes longer by design. Retention, lossless removal and recovery snapshots are unchanged; no configuration or schema migration is required. This is a mitigation, not a guarantee of shared-filesystem transaction latency.

Why This Change Was Made

Reuse the existing pressure probe: removal reacts to an in-progress or newly observed btrfs commit taking at least 500 ms. Linux deletion yields at pressure or 30 seconds elapsed. The existing serialized deletion owner keeps the queue quiet for 30 seconds, then resumes unfinished files behind already queued siblings. Its pending-path protection spans cooldowns, so orphan GC cannot take over an active removal. Files left in the retired directory provide restart progress; there is no new cursor store or scan cache.

The 40/20 GiB reservation policy remains; resumed passes start below the low watermark. Historical completed commit samples do not repeatedly block a restarted pass. Non-Linux platforms retain ordinary batch pacing. A single filesystem call can overshoot the pass budget, and each child retains its separate 30-minute timeout. Sustained external pressure can postpone reclamation indefinitely; failed or interrupted cleanup retains the existing recovery path.

We use observed commit statistics and quiet intervals instead of forcing syncfs on the shared filesystem. A forced sync would itself join the shared transaction; apparent file bytes are not a reliable delayed-reference estimate.

Also remove the two unused spawn-test fixtures left by #202522, along with their unused imports. Existing active fixture behavior and tests remain.

Evidence

The 600 ms commit regression fails on the base (pressure remains false), as does the bounded-pass regression (the entire tree is deleted instead of yielding). Candidate worker/probe/service-removal-safety tests pass: 34 tests. The real service test proves pending-path protection through a yield/cooldown while the original checkout name can be restored. Existing GC tests pass (29), and all four consumers of the trimmed spawn fixture pass (26). The two unchanged Gateway pressure-probe consumers also pass (60).

pnpm check:changed was run. An authoring error removing the still-used logger import was corrected; its affected tests and core typecheck replay pass. Required core test type shards, scripts typecheck and targeted formatting passed. The full-tree unused-export check still reports the exact-parent main regression below; this is not relabeled green.

Codex autoreview of the complete local change against 9d151f83665822939144b00546bf52c1488e7223 is scoped-clean through P2. An earlier review was interrupted before any verdict when the fixture-import error was found. Pr-simplify retained one pressure owner and one serialized deletion owner; production growth is net +32 lines, while the unused fixture removal deletes 137 net test-support lines.

Measurement acceptance rule, declared before the campaign

The committed workload is scripts/perf/retired-worktree-unlink-measure.ts. Use a synthetic node_modules-shaped tree with 62,000 files / 1,142,784,000 apparent bytes and a reflink sibling on a disposable btrfs loopback mount. Run A/A controls then five serial A/B pairs, with frozen baseline/candidate bundles, real timers and host load recorded. Report wall time, CPU, V8 allocation, maximum pass duration and sampled metadata reservation. A 20% CPU/allocation regression requires investigation; longer total elapsed time from deliberate 30-second quiet intervals is the requested tradeoff.

Separately bind fake sysfs counters only inside a disposable mount namespace: reservations below 40 GiB and one fresh 600 ms commit per 8,192 removals. Verify pressure terminates a pass before further unlinks and that all passes eventually complete. Accelerated timer wall times are diagnostic only. Reuse the prior reservation proof; do not claim this fixture reproduces production SQLite stalls or the reported six-second commit. No production data or service access.

Completed measurements

Node 26.12.1 / Linux 7.2.12-orbstack / btrfs-progs 6.2, disposable 32 GiB sparse loop image. Each fresh tree has 62,000 files, 1,142,784,000 apparent bytes and 63,242 total entries, plus a reflink sibling. A/A controls followed by five serial A/B pairs; no owned compilation/tests/checks overlapped timed runs. n=5 p95 is the maximum, not a production-tail estimate.

Metric Baseline median (min–p95) Candidate median (min–p95)
Wall, s 53.989 (51.452–54.290) 83.576 (82.526–84.308)
Longest pass, s 53.989 (51.452–54.289) 30.049 (30.022–30.075)
CPU, s 2.797 (1.255–3.710) 3.162 (2.071–3.874)
V8 allocated, MB 217.034 (209.271–219.277) 235.390 (226.041–244.275)
Sampled may_use peak, GiB 0.266 (0.243–0.293) 0.263 (0.231–0.278)

All trees complete. Each baseline uses one pass; each candidate uses two, separated by one 30-second quiet interval. Median longest-pass reduction 44.3%; total elapsed +54.8% is the requested reclamation-throughput tradeoff. Instrumented CPU +13.1%, allocation +8.5%. A/A wall 54.433/54.326 s, CPU 3.559/3.531 s, allocation 219.890/217.208 MB. Every sample, including the low-CPU second baseline, is retained in the lane report.

The driver imports frozen worker entrypoints per pass; subprocess startup is excluded. CPU/allocation include instrumentation. Its 20 ms reservation sampler runs through the quiet interval too, adding roughly 1,500 reads for that interval; no estimated cost was subtracted. Actual reservation peaks stay below 0.3 GiB, so this is not a reproduction of the production stall or high reservation incident.

The separate fake-sysfs trace holds reservation at 39.6 GiB and publishes a fresh 600 ms commit per 8,192 removals. Baseline removes 63,242 entries in one pass. Candidate yields seven times at exactly 8,192 entries, then removes the final 5,898 in its eighth pass. Both complete; scheduled waits 49.4 → 259.4 s. Accelerated physical time 9.825 → 9.614 s is diagnostic only. Fake files were bind-mounted solely over task-owned loop filesystem counters inside a disposable private mount namespace; no production filesystem or data was used.

Exact reviewed head: 414db65688667024817f5fc9fba9124af4656151. Exact-head CI run 44781791763 succeeded: 40 jobs passed, 29 skipped, no reruns. ClawSweeper revision 2, reviewed 2026-11-20 17:26:29 UTC, has zero findings and zero open checklist items on this head. The earlier measurement request is addressed; production foreground writer latency remains unverified.

Main regression requiring follow-up

On exact base 9d151f83665822939144b00546bf52c1488e7223, the canonical dead-export checker reports settingsParentRoute in ui/src/lib/settings-navigation.ts. #202521 / b7b72dc5b0ef9418bd5ee81cec721b775b5fc524 removed its last external caller from settings-sidebar.tsx; an internal call remains. This lane does not edit UI modules. The two #202522 unused fixtures also reproduced on this base and are fixed here. No suppression or expected-failure exception is added.

Split Linux retired-tree removal into bounded passes with a serialized quiet interval and react to fresh or ongoing 500 ms btrfs commits. Preserve pending-path custody and the reservation low watermark across resumption. Remove unused spawn-test fixtures left by #202522.
@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.

@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
@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. 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 makes Linux retired-worktree deletion yield on slow filesystem commits or after 30 seconds, then resume after a queue-wide quiet interval.

Example: A large retired tree encounters a fresh 600 ms btrfs commit below 40 GiB of metadata reservations.

  • Before: The 1,000 ms threshold permits deletion to continue without a bounded pass.
  • After: The next pressure check yields deletion, the queue pauses for 30 seconds, and remaining files resume later.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The earlier measurement request is addressed with meaningful physical-filesystem evidence; confidence remains bounded by in-process orchestration and the absence of a measured foreground writer-latency result.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the contributor proof gate; its updated evidence nevertheless exercises the actual worker on disposable btrfs storage with real timers, injected commit counters, and complete deletion, supported by a service harness covering cooldown custody and restoration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Large background worktree deletions can delay foreground chat transcript writes on shared btrfs storage.
Reason: The maintainer-authored direction accepts lower reclamation throughput to provide quiet intervals and preserves existing recovery behavior.

Merge readiness

✅ Ready for maintainer review

Keep this useful maintainer-authored PR open: current main lacks bounded cleanup passes, and source review found no blocking correctness or security defect.

Priority: P2
Reviewed head: 414db65688667024817f5fc9fba9124af4656151

Before merge

None.

Findings

None.

Agent review details

How this fits together

Managed-worktree removal and orphan recovery submit retired directories to one serialized deletion owner, which launches the filesystem worker and protects pending paths until completion.

flowchart TD
  A[Managed removal] --> C[Serialized deletion owner]
  B[Orphan recovery] --> C
  C --> D[Cleanup worker]
  E[Host pressure probe] --> D
  D --> F[Remaining retired files]
  D --> G[Yield or completion]
  G --> C
Loading

Technical review

Best possible solution:

Keep bounded yielding in the existing worker and serialized queue, preserving recovery and pending-path custody without another scheduler or persisted cursor.

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

The pinned base ignores fresh 600 ms commits and has no elapsed pass bound; supplied physical-btrfs measurements exercise that unbounded duration, while the reported foreground writer stall remains independently unverified.

Is this the best way to solve the issue?

This is a focused mitigation using the existing owners and remaining files as progress, with distinct coverage for pressure yielding, bounded resumption, and custody during cooldown.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 89117ca211c5.

Provenance checked

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:7 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 +32, Tests -62, Docs +5, Other +42. Total +17 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 74 42 +32
Tests 4 99 161 -62
Docs 1 10 5 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 1 52 10 +42
Total 9 235 218 +17

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
Measurement flags 2 new benchmark-only flags --fake-commits and --commit-counter exercise the production pressure path; they add no Gateway configuration or user preference.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • remove rating: 🧂 unranked krab: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.

Label justifications:

  • P2: Mitigates foreground transcript-write delays during optional Linux cleanup, with a limited filesystem and workload scope.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

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 (1 earlier review cycle)
  • reviewed 2026-11-20T17:14:25.804Z sha 414db65 :: needs maintainer review before merge. :: none

Reviewed November 20, 2026, 12:26 PM ET / 17:26 UTC (Revision 2).

@steipete
steipete marked this pull request as ready for review November 20, 2026 17:17
@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-20T17:19:20.055593Z 414db65 Draft marked ready
ℹ️ 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.

@steipete

Copy link
Copy Markdown
Contributor Author
  1. The evidence request under Tests is addressed in the updated Completed measurements section. On the exact reviewed head 414db65688667024817f5fc9fba9124af4656151, A/A controls and five serial physical btrfs A/B pairs complete all 62,000-file trees. Baseline median longest pass is 53.989 s; candidate is 30.049 s, with total cleanup 53.989 → 83.576 s. Instrumented CPU +13.1%, allocation +8.5%. All candidate samples use two passes and one real 30-second quiet interval in the harness. The below-watermark fake-sysfs trace additionally yields on each fresh 600 ms commit at 39.6 GiB, completing in eight passes.

The production queue owner preserves pending custody through cooldown/requeue. The real service regression exercises that owner with a controlled cooldown, proves GC leaves the retired path alone, restores the original checkout name, and lets the resumed real subprocess finish. Physical timing imports the real worker entrypoint per pass and excludes subprocess startup; the service test covers that separate orchestration boundary. No production SQLite-stall elimination is claimed.

The body now includes the complete table, A/A variation, sampling overhead and remaining proof limits. Source head is unchanged. Your first review has no code findings or open checklist items.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels Nov 20, 2026
@steipete
steipete merged commit 09bef75 into main Nov 20, 2026
241 of 245 checks passed
@steipete
steipete deleted the steipete/perf-2706-commit-aware-chunks branch November 20, 2026 17:33
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 21, 2026
…penclaw#202607)

Split Linux retired-tree removal into bounded passes with a serialized quiet interval and react to fresh or ongoing 500 ms btrfs commits. Preserve pending-path custody and the reservation low watermark across resumption. Remove unused spawn-test fixtures left by openclaw#202522.
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. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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