Skip to content

fix(workspaces): avoid rereading live packs during cleanup - #198295

Merged
steipete merged 1 commit into
mainfrom
fix/workspace-sweep-live-pack-reads-2437
Nov 13, 2026
Merged

steipete merged 1 commit into
mainfrom
fix/workspace-sweep-live-pack-reads-2437

Conversation

@steipete

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes excess database read work during workspace manifest sweeps when many packs remain live.

User Impact

Background workspace cleanup avoids reading live pack payload pages solely to check their age. Existing retention, checkpoint progress and publication protections remain in place.

Why This Change Was Made

Workspace manifest sweeps already selected narrow columns, but candidate discovery still read sweep_epoch for every live pack. In SQLite that field follows the large record payload, so reading it traverses payload overflow pages even though records_json is absent from the SQL projection.

Use the graph walk's existing live digest set to exclude bounded primary-key ranges before reading candidate digests and epochs. Each query skips at most 256 known-live keys and returns at most 256 candidates; epoch filtering happens after the limit. The final range covers the tail, and an empty live set still scans candidates. The writer retains its epoch check. Pending and previous checkpoint roots keep their existing protection. There is no schema, index, configuration, durable-state or cache change.

The shared range reader replaces the duplicated pack/path paging loops (+31 production LOC). Tests extend the existing owner regression with live-row work counts, tail garbage, and empty path roots (+9 test LOC). Benchmark stepping (+18 LOC) permits serial interleaved measurements in retained processes, with startup and control IO outside each sample. Documentation is +2 LOC.

Evidence

All 45 focused CAS/store/manifest tests passed; after the final mechanical sorting lint correction, the owner regression and focused core lint pass again. Fresh independent Codex review found no actionable P0–P2 findings. The final regression fails on exact parent 3e0130930848d53adcdf0418ae2e736197ca45ac with 312 epoch rows versus the permitted six and passes with this fix. It preserves checkpoint progress, pending/previous roots, publication behind the cursor, writer reuse, final-tail garbage and empty path roots.

pnpm check:changed completed. Its new sorting lint error is fixed and the exact focused lint command passes. The remaining production-unused export acquireConfiguredGatewayPostgresOwner reproduces with no resolution errors on the exact main parent 3e0130930848d53adcdf0418ae2e736197ca45ac; c886f82c779386cc320195732b6d1b74ad5d05ae / #196237 introduced that export with only in-module production use and test importers. This is a newly encountered main regression, recorded for its owner to fix, not dismissed as noise. Other selected checks passed. No UI-imported module is changed.

The acceptance rule recorded before measurement requires identical garbage, bounded reads/checkpoint progress, lower logical bytes, and disclosure of all timing/CPU/allocation changes.

Comparison is against merged #198157, through the production sweep handler entry point with sparse kernel overlays. Each fixture/mode used two baseline A/A controls followed by five serial interleaved pairs on the final source. Values are median / p95; with five samples, p95 is the maximum. Time/CPU/read holds below come from the unprofiled timing pass; allocation and native pager reads use separate passes.

Metric Live roots: before Live roots: after Mostly retired roots: before Mostly retired roots: after
Logical bytes/pass (all samples identical) 13,121,527,808 6,596,874,240 (-49.72%) 6,561,792,000 6,533,763,072 (-0.43%)
Total time, s 3.422 / 3.638 1.915 / 2.180 1.549 / 1.571 1.558 / 1.586
Sweep-owner CPU, s 3.378 / 3.486 1.987 / 2.025 1.625 / 1.660 1.608 / 1.649
Allocated bytes, MB 321.710 / 339.182 292.462 / 297.587 143.704 / 144.586 99.412 / 103.895
Maximum read hold/pass, ms 24.045 / 82.736 11.522 / 20.285 7.656 / 17.533 6.423 / 11.273
Read statements/pass 1,179 1,179 615 614
Maximum rows/read 256 256 256 256
Garbage packs 0 0 144,926 144,926

Live-root median time falls 44.0%, CPU 41.2%, and allocation 9.1%. History-heavy time is essentially flat (+0.6% median; paired differences -11 to +21 ms), CPU falls 1.0%, and allocation falls 30.8%. Its two timing A/A controls differed by 86 ms; that small paired timing change is not a resolved slowdown. All candidate digests match. Required graph reads dominate the remaining live volume; expired-history epochs still need reading.

Synthetic fixture: 6,008,033,280-byte SQLite DB, 234 accepted 62,000-file trees, 145,548 packs and 10,000 projections. The history fixture retires 233 roots and retains 144,926 garbage packs. Stored epochs are 2, sweep epoch 4, avoiding SQLite's header-only encoding of epochs 0/1. Node 26.12.1, SQLite 3.54.1, APFS, 2 MiB pager cache, mmap disabled. No production data. This invokes the state-owner handler in one process, not worker scheduling or whole-Gateway latency. Logical pager bytes measure read work, not physical disk IO. The byte fixture has no large source-path or checkpoint payloads; those retention paths are covered functionally by the owner regression. A separate final-source CPU profile keeps the remaining cost in SQLite/graph reads (179 of 1,819 inclusive owner samples were in the new range reader, across warmup plus one measured invocation). Expected production effect is to remove live-pack epoch reads; the actual byte saving depends on live versus unreachable content.

A/A controls, instrumented diagnostics, prior revision and reproduction

Live timing: A/A wall 3.451/3.483 s, CPU 3.507/3.454 s; paired host load 23.9–26.8.

Live allocation: A/A wall 3.357/3.659 s, CPU 3.417/3.440 s; paired host load 20.9–27.0.

Instrumented live allocation median/p95: wall 3.878 / 4.097 -> 2.218 / 3.000 s; CPU 3.356 / 3.526 -> 2.036 / 2.209 s; read hold 93.427 / 229.389 -> 104.152 / 120.260 ms. These diagnostics include adverse cells and do not replace unprofiled timing.

Live pager: A/A wall 4.615/4.852 s, CPU 3.367/3.550 s; paired host load 34.4–36.7.

Instrumented live pager median/p95: wall 3.851 / 5.220 -> 2.377 / 2.518 s; CPU 3.486 / 3.539 -> 2.085 / 2.122 s; read hold 122.700 / 168.998 -> 84.644 / 246.882 ms. These diagnostics include adverse cells and do not replace unprofiled timing.

History timing: A/A wall 1.690/1.604 s, CPU 1.819/1.644 s; paired host load 19.6–21.2.

History allocation: A/A wall 1.517/1.493 s, CPU 1.618/1.530 s; paired host load 18.3–19.6.

Instrumented history allocation median/p95: wall 1.501 / 1.528 -> 1.572 / 1.588 s; CPU 1.607 / 1.631 -> 1.650 / 1.701 s; read hold 5.722 / 7.004 -> 6.344 / 6.684 ms. These diagnostics include adverse cells and do not replace unprofiled timing.

History pager: A/A wall 1.528/1.525 s, CPU 1.641/1.562 s; paired host load 18.4–24.0.

Instrumented history pager median/p95: wall 1.668 / 1.926 -> 1.754 / 1.904 s; CPU 1.677 / 1.779 -> 1.666 / 1.743 s; read hold 8.984 / 46.308 -> 8.565 / 83.136 ms. These diagnostics include adverse cells and do not replace unprofiled timing.

The preceding in-place-sort revision ran under much heavier contention. Its live time/CPU medians improved 46.1%/41.4%, but history time rose 25.145 -> 28.594 s (+13.7%), CPU 2.428 -> 2.445 s (+0.7%), and history read-hold p95 670.671 -> 783.179 ms. Its live allocation-instrumented read-hold maximum rose 863.899 -> 1782.482 ms. These results are retained. Required lint repair to toSorted() changes allocation, so all paired modes were refreshed on the final source. Host load was substantially lower during that refresh; do not attribute the cross-run wall-time difference to the one-line sorting correction.

The earlier two-stage inventory/epoch-lookup prototype was rejected: although it halved live reads, history allocation rose 143.77 -> 233.98 MB (+62.75%). The final range query fetches candidates once and removes that regression.

Seed once in a new task-owned path:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/local-workspace-manifest-read.ts 62000 1 timing <fixture.sqlite> --sweep --sweep-epoch=4 --target-bytes=6000000000

Preserve the baseline kernel under its repository-relative path in a sparse overlay. Run both overlays with the same frozen surrounding source, fixture and arguments:

OPENCLAW_BENCH_BASELINE_DIR=<overlay> node --expose-gc --import ./scripts/tsx.mjs scripts/perf/local-workspace-manifest-read.ts 62000 7 timing <fixture.sqlite> --reuse --sweep --sweep-epoch=4 --sweep-step

Use seven baseline samples (two A/A plus five pairs) and five candidate samples. After each process emits ready, send one stdin newline per sample, alternating arms. Repeat in allocation mode; use timing plus --pager-extension=<SQLite CACHE_MISS probe> separately for logical pager bytes. The second fixture is a synthetic copy with tree_root_digest and baseline_ref cleared on all projections except synthetic-manifest; all 10,000 rows remain. No production schema is changed.

Read audit and index proposal

Projection discovery needs the keyset ID, accepted tree root, source-path root, and checkpoint receipt containing pending/previous recovery roots. Graph traversal needs children_json. Candidate discovery needs only unmarked digests and epochs. Pack record JSON, compressed source paths, projection journals and fingerprint blobs are not selected. Required recovery receipts cannot simply be dropped from reachability.

The remaining graph queries still read children_json after records_json in SQLite's serialized row. Propose a separate schema-owner evaluation of a covering index on local_workspace_tree_packs(tree_digest, children_json). Omitting epoch from that proposed index avoids index-key churn during epoch refreshes. No index is implemented here.

Retained synthetic evidence from #191779 used 77,750 packs, 10,000 projections and a 3.21 GB DB. Combined child-link and epoch covering indexes reduced logical reads from 3,807,997,952 to 155,140,096 bytes (-95.93%); the child-link index occupied 9,195,520 bytes. That combined result does not isolate the proposed child-only index. Its initial timing was adverse/confounded, and the fixture had no recovery journals or source-path rows, so it is not shipping proof. Before schema approval, measure current query plans, identical retention results, read/CPU/allocation gains, write and epoch-refresh costs, index growth, migration/admission time, and supported-engine behavior.

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime scripts Repository scripts size: S labels Nov 13, 2026
@steipete
steipete marked this pull request as ready for review November 13, 2026 13:48
@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-13T13:50:25.784729Z 4d765c5 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.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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. 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

Workspace cleanup excludes known-live content from bounded candidate queries before reading its age.

Example: The supplied synthetic SQLite fixture retains 234 workspace trees and 145,548 packs.

  • Before: A sweep reads 13,121,527,808 logical pager bytes.
  • After: The same sweep reads 6,596,874,240 logical pager bytes and returns the same garbage candidates.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, apparently correct optimization with substantial real-SQLite evidence, limited to an in-process production-owner boundary.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied final-source measurements exercise the production sweep handler against a real synthetic SQLite database, compare live-heavy and retired-root workloads, and show matching candidates with reduced logical reads; the evidence establishes owner-level efficiency, not Gateway scheduling or chat latency.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Background workspace cleanup performs avoidable database reads even when most saved workspace content remains live.
Reason: Maintainer-authored direction and comparable real-SQLite measurements support the improvement, with existing checkpoint and publication protections retained.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR removes demonstrated cleanup read waste that remains on main, and review found no actionable correctness or security defect.

Priority: P2
Reviewed head: 4d765c5c8ca5c40da5444bec36e62b0975b45462

Before merge

None.

Findings

None.

Agent review details

How this fits together

Workspace maintenance invokes the existing state-reader worker to discover unreachable manifest packs and source-path sets, then passes candidates to epoch-checked writer transactions for deletion.

flowchart TD
  A[Workspace maintenance] --> B[State reader worker]
  B --> C[Projection and checkpoint roots]
  C --> D[Live digest graph]
  D --> E[Bounded candidate ranges]
  E --> F[Epoch checked writer deletion]
Loading

Technical review

Best possible solution:

Use the existing live digest sets to exclude bounded ranges before epoch reads while preserving graph traversal and writer protection.

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

Current-main source reads live-pack epochs before reachability filtering, and the supplied exact-parent regression reports 312 epoch rows against a six-row bound; no target code was executed during this read-only review.

Is this the best way to solve the issue?

The change removes unnecessary reads at their existing owner, shares the algorithm between packs and path sets, and preserves retention semantics without adding storage, indexes, caches, or configuration.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 03fa4047b0c0.

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 3e01309 adds src/gateway/worker-environments/local-workspace-cas.kernel.ts:252 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 3e0130930848; files: src/gateway/worker-environments/local-workspace-cas.kernel.ts)

PR surface

Source +31, Tests +9, Docs +2, Other +18. Total +60 across 4 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 82 51 +31
Tests 1 16 7 +9
Docs 1 4 2 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 18 0 +18
Total 4 120 60 +60

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 growth production +31 LOC; tests +9 LOC The shared range reader replaces duplicated scans, and the existing retention regression gains focused work-count and boundary assertions.

Labels

Label changes:

  • add P2: This is a demonstrated background-maintenance efficiency improvement with bounded scope and no observed urgent runtime failure.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: This is a demonstrated background-maintenance efficiency improvement with bounded scope and no observed urgent runtime failure.
  • 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.
  • 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.

Reviewed November 13, 2026, 9:04 AM ET / 14:04 UTC.

@steipete
steipete merged commit 5bdadab into main Nov 13, 2026
220 of 223 checks passed
@steipete
steipete deleted the fix/workspace-sweep-live-pack-reads-2437 branch November 13, 2026 14:14
@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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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