Skip to content

fix(worktrees): avoid redundant cleanup passes and manifest scans - #198362

Merged
steipete merged 1 commit into
mainfrom
fix/worktree-maintenance-demand-2437k
Nov 13, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/worktree-maintenance-demand-2437k

Conversation

@steipete

@steipete steipete commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Worktree cleanup can repeat a full pass after an archive already covered by its census, and each archive-triggered pass can reread gigabytes of unchanged workspace manifests.

User Impact

Newly archived checkouts still receive prompt cleanup. Repeated archives and sessions without a checkout no longer wake GC. Hourly expiry checks remain, while unchanged manifest content avoids the reachability scan, including after restart. No configuration or schema change is required.

Why This Change Was Made

An archive arriving during scratch cleanup previously set archivePending, although the worktree census had not started. That flag requested another pass after completion. Clear it immediately before GC starts; archives arriving after that point retain their follow-up. Only a newly archived bound checkout requests the wake.

The existing hourly job now owns global manifest sweeping. Its existing writer records pending sweep epochs in config_machine_state, atomically with content preparation or manifest-reference changes. Two epochs preserve preparation grace; successful completion settles demand only when no later write needs another epoch. Failed sweeps remain pending, old databases receive an initial cycle, and ordinary projection bookkeeping does not request a scan. This avoids incorrectly treating zero checkout removals as proof that no abandoned preparation or obsolete manifest exists.

Production growth is +103 LOC against af10e5594d380c6cae45d45085618334ec0c8b7a, for durable work admission/settlement and hourly ownership. There is no graph cache, new state file, table, index, or schema version. Cleanup custody and identity decisions are unchanged.

Evidence

Acceptance was recorded in the draft body before measurement: reuse the prior synthetic manifest fixture; two parent A/A controls plus five alternating parent/candidate samples; compare warm owner timing, CPU, allocation, work counts, and logical pager reads separately. Preserve candidate digests, live content, preparation grace, failure/restart recovery, and immediate cleanup for a new bound archive.

The reused fixture from #198295 is 6,008,033,280 bytes, with 10,000 projections and 234 distinct 62,000-file manifests. It exercises the shared-state reader; it does not copy production agent data or benchmark unrelated transcript storage. Six unchanged requests represent one simulated hour. Parent already includes #198157 and #198295.

Measurement Parent Candidate
GC passes/hour, real session handler + virtual scheduler, six repeated archives 6 1
Graph scans, six unchanged sweep requests 6 0
SELECT statements, six requests 7,092 6 indexed one-row lookups
Logical pager bytes/hour, warm 39,581,294,592 0
Owner wall time, median / p95 11,375.394 / 12,042.278 ms 0.453 / 0.666 ms
Owner CPU, median / p95 11,475.337 / 11,767.835 ms 0.473 / 0.884 ms
Sampled owner allocation, median / p95 1,606,191,264 / 1,615,512,752 bytes 65,584 / 166,688 bytes

At n=5, p95 is the maximum. The two A/A timing controls were 11,709.759 and 11,541.070 ms. Host load was recorded per sample; submillisecond candidate timings are approximate. Pager reads use the same SQLite CACHE_MISS probe as #198295 with a 2 MiB pager cache and mmap disabled. Zero denotes warm metadata-cache hits, not a guarantee of no physical disk IO on cold admission. This is CAS-owner CPU/allocation, not Gateway main-thread CPU, chat latency, or btrfs delete throughput. A changed-content hour still permits its normal hourly scan; after settling, unchanged hours do not traverse the graph.

The candidate's first process, opening a parent-produced database without a demand marker, performed two settling scans; its subsequent pager/allocation processes performed zero warmup scans. Both fixture schema hashes stayed identical. Candidate digests matched every arm.

Rerunnable workload (use a task-owned synthetic fixture copy because demand mode updates sweep metadata):

node --expose-gc --import ./scripts/tsx.mjs   scripts/perf/local-workspace-manifest-read.ts   62000 5 timing /path/to/synthetic-copy.sqlite   --reuse --sweep --sweep-demand --sweep-step

Use allocation for the separate 32 KiB sampled allocation pass, --pager-extension=/path/to/pager-probe for logical bytes, and OPENCLAW_BENCH_BASELINE_DIR for the exact-parent sparse overlay. Send one stdin line per sample when using --sweep-step.

Three regressions fail on the exact parent: unbound/repeated archives request GC; an archive during scratch requests two passes; six unchanged sweeps still read the graph after reopen. 106 focused cases pass across the owner suites and scoped replays, covering archive/restore, post-census follow-ups, live and concurrently reused content, grace, retirement, interrupted sweep, and reopen. The clock-rate assertion needed a second explicit scheduler wake; nullable-epoch test callers and lint issues were corrected and replayed. No skipped or expected-failure baseline was added.

pnpm check:changed ran. Core/script types, affected test types, format, and changed lint are green after scoped repairs. The remaining unrelated local failure is RELEASE_VALIDATION_WAIVERS, reproduced with pinned Knip 6.40.0 on the exact parent and introduced by 2a1285197991490df98f847f425f2c7fdb41d433 / #173437. This existing main regression remains reported; it is not treated as noise.

Independent Codex autoreview of the local diff against that parent: scoped-clean P0–P2, no actionable findings. The final mechanical changes wrap documentation and remove a redundant test sweep, strengthening its immediate recovery assertion. No production deployment or manual cleanup was performed.

Stable-state upgrade and restart proof

At unchanged head e3ada3d457dc838f7d453385fc64257245233f3f, a separate checkout of stable v2026.11.3 (847611dcaa3bf0e2783335f961dd1fd0580e4d9f) wrote the synthetic projection through its actual state transaction and workspace mutation owner. The fixture contains an accepted manifest for keep.txt, workspace binding/source-path settings, pending target/ref, paused-runtime settings, and a 31-byte synthetic pending-recovery payload. No real user data or credentials were used.

Candidate pnpm openclaw doctor --fix --non-interactive saved a pre-migration SQLite backup and completed the existing schema-22-to-40 migrations, exit 0. These migrations already exist on the parent; this PR changes no schema. Direct worker admission initially refused without backed-up migration custody, as intended. The first Doctor attempt on the external-volume fixture was refused by secure-temp ancestor admission; the isolated fixture copy was moved to a safe private temporary root, without changing shared filesystem permissions.

The candidate's real workspace store then loaded and converted the stable accepted manifest, preserving its exact bytes/reference, source paths, binding, pending ref/target, paused-runtime settings, and recovery bytes. Two actual sweepLocalWorkspaceManifests calls settled epoch 2 with pending demand 0. A fresh Node process reloaded the same database, materialized the same manifest, and made six more sweep requests: epoch remained 2, demand remained 0, all stored fields/recovery bytes matched, and decoding the retained CAS tree still returned the expected keep.txt digest. No mocks or patched owner methods were used. This is stored-state compatibility and sweep/restart proof; it does not claim to replay a real external recovery operation from the synthetic sentinel payload.

Redacted receipts:

stable-seed: v2026.11.3, schema=22, projections=1, recoveryBytes=31
doctor: exit=0, pre-migration backup saved, schema=40
initial: acceptedManifestPreserved=true, workspaceSettingsPreserved=true, pendingRecoveryPreserved=true, converted=true, sweepsRequested=2, endEpoch=2, pending=0
restarted: acceptedManifestPreserved=true, workspaceSettingsPreserved=true, pendingRecoveryPreserved=true, casTreeIntact=true, sweepsRequested=6, startEpoch=2, endEpoch=2, pending=0

Exact-head CI: run 43462498583, native watcher GREEN (superseded jobs excluded by its existing rules). Hosted Codex review also completed with no findings.

@clawsweeper

clawsweeper Bot commented Nov 13, 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 13, 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-13T16:27:52.363650Z e3ada3d PR opened
ℹ️ 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 gateway Gateway runtime scripts Repository scripts size: M labels Nov 13, 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. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR coalesces archive cleanup requests and skips unchanged manifest scans using durable sweep demand.

Example: Six repeated archive requests over one simulated hour with unchanged workspace manifests.

  • Before: Six cleanup passes repeat the manifest graph scan.
  • After: Only hourly cleanup remains, and settled manifest content requires no graph scan.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused owner-level optimization with measured work reduction, upgrade/restart receipts, and successful exact-head validation; performance evidence is scoped to the production owners rather than whole-Gateway latency.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): Recorded real-SQLite owner measurements exercise unchanged sweep admission, while stable-written state passes candidate CLI Doctor migration, actual workspace conversion and sweep settlement, and separate-process reopen with retained content.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated archive activity consumes shared-storage IO and CPU through redundant cleanup and unchanged manifest scans.
Reason: The maintainer-authored direction has measured value and retains existing cleanup authority, recovery data, and preparation grace.

Merge readiness

✅ Ready for maintainer review

This PR remains useful and has no actionable findings. The added stable-upgrade and restart evidence resolves the previous compatibility blocker, and exact-head CI is green.

Priority: P2
Reviewed head: e3ada3d457dc838f7d453385fc64257245233f3f

Before merge

None.

Findings

None.

Agent review details

How this fits together

Session archive effects notify the Gateway maintenance owner, which removes retired checkouts and asks shared-state workers to collect unreachable manifest content.

flowchart TD
  A[Session archive] --> B[Archive effects]
  B --> C[Maintenance owner]
  D[Hourly scheduler] --> C
  C --> E[Worktree cleanup]
  C --> F[Manifest sweep worker]
  G[Workspace writer] --> H[SQLite sweep demand]
  H --> F
Loading

Technical review

Best possible solution:

Keep archive admission in the session-effects owner and durable sweep demand in the existing workspace writer, as this PR does.

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

Parent source unconditionally requests maintenance for archives and scans manifests on every cleanup pass; the supplied evidence reports matching regressions failing on that exact parent.

Is this the best way to solve the issue?

The change removes unnecessary work at existing owners, preserves two-epoch preparation grace, and records demand atomically instead of inferring it from checkout-removal counts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 2ca47150600a.

Provenance checked

  • Asynchronous archive cleanup keeps the original intent (339c4da: Return archive responses before snapshot and checkout removal while retaining background follow-ups and restoration safety.)
  • CAS sweep admission and cadence changes intended behavior with a stated reason (a25b072: Collect unreachable shared manifest packs using epoch protection; this PR explains replacing unconditional scans with durable writer-recorded demand.)
  • Bounded manifest read workload keeps the original intent (3e01309: Release metadata reads between bounded pages so maintenance cannot pin WAL checkpoints.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 339c4da adds src/gateway/worktree-maintenance.ts:39 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 339c4da81f54; files: src/gateway/worktree-maintenance.ts)

PR surface

Source +103, Tests +117, Docs +8, Other +57. Total +285 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 5 107 4 +103
Tests 6 119 2 +117
Docs 1 9 1 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 64 7 +57
Total 13 299 14 +285

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 regression coverage Production +107/-4 LOC; tests/support +119/-2 LOC. Production growth implements durable demand and settlement without another storage owner; regression growth covers distinct scheduling, restart, and failure boundaries.
New benchmark flag One tooling-only flag: --sweep-demand. Extends the existing committed workload to measure repeated sweep admission; it adds no runtime configuration.

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: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P2: Avoids substantial redundant cleanup IO on managed-worktree fleets while preserving existing cleanup and preparation contracts.
  • 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 (1 earlier review cycle)
  • reviewed 2026-11-13T16:40:48.884Z sha e3ada3d :: blocked before merge. :: none

Reviewed November 13, 2026, 11:59 AM ET / 16:59 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

Addressing the sole open item in review 6859104499 against unchanged head e3ada3d457dc838f7d453385fc64257245233f3f:

  1. Add data-model compatibility proof: completed a stable v2026.11.3 (847611dcaa3bf0e2783335f961dd1fd0580e4d9f) owner-written synthetic database → candidate CLI Doctor migration → actual workspace conversion and two sweep settlements → separate-process reopen and six unchanged sweep requests. The PR body now records the setup, commands, redacted receipts, and limits. Doctor saved the pre-migration backup and exited 0; existing schema 22 migrated to 40. Workspace settings/binding/source paths, exact accepted manifest bytes/reference, and pending ref/target/recovery bytes survived. After reopen, epoch stayed 2 and pending stayed 0 across all six requests, and the retained CAS tree decoded to the expected file digest. No mocks, new schema, or production data. The pending payload is a synthetic sentinel, so the evidence proves preservation, not replay of a real external recovery operation.

The missing-marker upgrade admission is at local-workspace-cas.kernel.ts:223; grace and conditional completion are at line 185. The existing conversion preserves pending legacy receipt bytes at local-workspace-manifest-scan.ts:407 and line 458. The committed restart/failure/retirement regression remains at local-workspace-store.test.ts:74.

Exact-head CI is green: run 43462498583. There are no source changes since review.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 13, 2026
@steipete
steipete merged commit 932bab7 into main Nov 13, 2026
167 of 170 checks passed
@steipete
steipete deleted the fix/worktree-maintenance-demand-2437k branch November 13, 2026 17:03
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime 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