Skip to content

perf(worktrees): avoid full session parsing during GC - #166072

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-owner-classification-allocations-20260919
Oct 6, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-micro-worktree-owner-classification-allocations-20260919

Conversation

@steipete

@steipete steipete commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Worktree cleanup repeatedly parses complete owner session entries, including saved prompts, merely to classify each checkout. A 1,000-owner GC pass previously resolved every active owner twice.

User Impact

Cleanup uses substantially less allocation and CPU while retaining fresh checks before destructive mutations. Unknown owner state still preserves the checkout. No schema, configuration, migration, or upgrade action is required.

Why This Change Was Made

The session accessor batches narrow activity and custody facts through its existing reader owner. GC shares those facts for one pass; mutation guards still reread one owner. The scalar accessor delegates to the same selection owner, and redundant per-request store/ID maps are removed. Logical identities and default paths are captured before yielding.

The rebase onto cc7e664dfe34 preserves main's board-presence fact in the same row query, admitted-revision row cache, per-key native error isolation, participant projection, and bound incognito actor. An omitted environment continues to use the captured actor's state root. Existing worktree diagnostics, budgets, removal backoff, shutdown settlement, and runtime-preparation changes remain in the base.

Production scope is +293 lines (+462/−169), including a one-line generated mock-allowance shrink; production source alone is +294. The narrow worker/storage projection must coexist with the full-entry APIs used by other session/SDK consumers, preserve shared/recovered stores and incognito ownership, and retain live destructive-mutation checks. The old GC full-payload path and duplicate row-selection/bookkeeping are removed. No persistent owner cache is added.

Evidence

Original allocation proof on base 355655951c77: 575.213 → 15.404 MB/pass (−97.32%), with full-entry/saved-prompt parses 2,000/2,000 → 0/0 and identical classifications. This is historical main-isolate allocation evidence; worker heaps were excluded. The RSS/CPU measurements below were made before the latest rebase, on base 614d42bc76b1; they do not measure allocation bytes. The rebase to cc7e664dfe34 preserves this lane’s GC algorithm and narrow projection while retaining upstream reader changes. These are historical measurements, not a new rig run on the rebased head.

1,000-owner fixture Baseline Final candidate Change
Cold median RSS 942.662 MB 1012.879 MB +7.45%
Matched prewarmed median RSS 1111.245 MB 978.297 MB −11.96%
Cold CPU per pass 2575.924 ms 84.056 ms −96.74%
Prewarmed CPU per pass 2139.375 ms 88.268 ms −95.87%

Each fresh process has 1,000 managed rows, active owners, stale checkout timestamps, ordinary directories, matching worktree bindings/revisions, and a synthetic 53,217-byte saved prompt per session. Two warmups precede twenty measured passes. Baseline cells were reused at the identical base with unchanged fixture bytes when the candidate was simplified; every classification matched. Commands ran on an isolated Linux rig (8 cores, Node 26.8.1), with nice -n 10 ionice -c3 and task-owned TMPDIR. This is source/tsx proof, not an installed-dist or production Gateway measurement.

The prior +18.54% RSS number conflated reader readiness and process capacity. The candidate starts one existing history worker when cold; it does not create one per pass. Gateway startup, recovery, and non-ephemeral operator connect already prewarm this shared lane best effort. Matching readiness matters: the candidate has substantially less transient main heap from full-entry decoding. Bootstrap RSS also changed direction before any classification, so no static-import cause or exact attribution of every native byte is claimed.

A 100-pass final-candidate run held five tracked workers and one history worker. RSS at passes 20/50/100 was 1012.527/1045.062/1069.859 MB, while main used heap fell 135.141 → 130.849 MB. The same SQLite writer reclaimed heap capacity between passes 50 and 100 without restarting. After confirmed history-worker retirement, the next ordinary pass reduced RSS by 67.723 MB while recreating the reader. This demonstrates reclaimable capacity; it does not establish a total-RSS plateau or rule out all small retention. No worker-lifetime change is proposed merely to improve a synthetic metric.

Final validation on the rebased candidate passed on Blacksmith Testbox (blacksmith-testbox, profile openclaw-check), lease tbx_01m498z24mhz1xrdcq4jq7xp5j:

  • node scripts/run-vitest.mjs <12 focused files> --maxWorkers=1: 186 tests passed, covering owner classification and mutation guards, GC lifecycle/CLI/progress, Gateway maintenance, narrow facts, board-presence batching, canonical/readonly/revalidation reads, and incognito actor composition. The Vitest groups reported 138.81 seconds total, excluding cold wrapper preparation.
  • node scripts/check-changed.mjs --staged: passed completely, including all 27 test-typecheck shards, core types, dead-export scans, lint, and structural/architecture guards. No skipped deadcode scan or inherited-error exception was needed.

The combined install, early checks, focused tests, and staged-gate remote command completed in 31m52.658s with exit 0. It used an exact-base worktree with the complete candidate patch staged and SHA256-verified (91ca1a2077ad0309a2738f5f15f987107f53b17ed1a15e662db829e264f94546).

Fresh detached direct-route Codex review is clean through P2 against base cc7e664dfe34fd3b0bd53473dc10d033dc5c0e29. No suites, typechecks, or builds ran on the Mac.

Current-head CI at b72bb5f4dbab completed: run 37519222926, 52 successful jobs, 23 skipped, no pending jobs. The only failures are security-fast and its aggregate gate, caused by the inherited MCP dependency advisory GHSA-6qxp-vccf-f47h in @modelcontextprotocol/client and @modelcontextprotocol/sdk. This lane changes no dependencies; that inherited failure is explicitly excepted for this update. All other CI jobs passed. GitHub confirmed the pushed head is MERGEABLE.

@clawsweeper

clawsweeper Bot commented Oct 6, 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 agents Agent runtime and tooling size: L labels Oct 6, 2026
@steipete
steipete enabled auto-merge (squash) October 6, 2026 10:17
@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 Oct 6, 2026
@clawsweeper

clawsweeper Bot commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed October 6, 2026, 3:34 PM ET / 19:34 UTC (Revision 3).

ClawSweeper review

What this changes

Managed-worktree cleanup batches small session-owner records instead of decoding complete session entries, while retaining fresh checks before removal.

Merge readiness

⛔ Blocked before merge - 1 item remains

The optimization remains useful and absent from current main. The rebase resolves the previous conflict blocker, and this review found no introduced correctness defects.

Priority: P2
Reviewed head: b72bb5f4dbab0a2262d2aeb258baa16e72e1c435

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused optimization with substantial recorded performance evidence, explicit measurement limits, and preserved cleanup safeguards.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Recorded isolated Linux runs exercise the production GC and session-reader path with 1,000 stored owners and show identical classifications with lower parsing and CPU costs. Measurements predate the rebase and are labeled historical; fresh rebased tests supplement them. No stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Recorded isolated Linux runs exercise the production GC and session-reader path with 1,000 stored owners and show identical classifications with lower parsing and CPU costs. Measurements predate the rebase and are labeled historical; fresh rebased tests supplement them. No stored-data contract changes require migration proof.
Evidence reviewed 8 items Introduced implementation: Reviewed the pinned merge-base-to-head delta. The census batches unique session owners, and failed census acquisition defaults to preserving their checkouts.
Classification does not replace mutation authority: Prepared facts feed preliminary classification; removal and capacity cleanup retain the original live policy. The removal owner rechecks owner state through commit guards and lifecycle admission.
Narrow storage projection and regression coverage: The new reader queries existing session tables without changing stored formats. Coverage checks retained windows, invalid certification, stale activity columns, duplicate custody fields, and avoidance of full payload parsing.
Findings None None.
Security None None.

How this fits together

Managed worktrees provide isolated repository checkouts for agent sessions. Cleanup combines checkout records, session activity, and live custody checks to decide which checkouts to preserve or remove.

flowchart TD
  A[Checkout records] --> C[Cleanup classification]
  B[Session reader worker] --> C
  C --> D[Preserve protected checkout]
  C --> E[Fresh owner and custody checks]
  E --> D
  E --> F[Guarded checkout removal]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +294, Tests +260, Docs +2, Other -1. Total +555 across 17 files.

View PR surface stats
Area Files Added Removed Net
Source 10 462 168 +294
Tests 5 268 8 +260
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 17 732 177 +555

Review metrics

Metric Value Why it matters
Production versus regression coverage production source +294 lines; tests +260 lines The PR explains the production growth as a narrow worker projection that preserves full-entry consumers and live cleanup guards.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/config/sessions/session-accessor.sqlite-worktree-owner.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep classification within the existing session-reader owner and preserve fresh custody checks at every destructive mutation.

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

Not applicable as a bug reproduction: the source establishes repeated full-entry decoding, and the PR supplies before/after performance measurements; this reviewer executed no runtime checks.

Is this the best way to solve the issue?

Yes. The patch extends the existing reader and selection owners, limits cached facts to one cleanup pass, and retains live removal checks without changing configuration or persisted data.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 76beb5685887.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded cleanup performance improvement with measured CPU savings and no demonstrated urgent user-facing regression.
  • 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 (live_output): Recorded isolated Linux runs exercise the production GC and session-reader path with 1,000 stored owners and show identical classifications with lower parsing and CPU costs. Measurements predate the rebase and are labeled historical; fresh rebased tests supplement them. No stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. Recorded isolated Linux runs exercise the production GC and session-reader path with 1,000 stored owners and show identical classifications with lower parsing and CPU costs. Measurements predate the rebase and are labeled historical; fresh rebased tests supplement them. No stored-data contract changes require migration proof.

Evidence

What I checked:

  • Introduced implementation: Reviewed the pinned merge-base-to-head delta. The census batches unique session owners, and failed census acquisition defaults to preserving their checkouts. (src/agents/worktrees/owner-protection.ts:116, b72bb5f4dbab)
  • Classification does not replace mutation authority: Prepared facts feed preliminary classification; removal and capacity cleanup retain the original live policy. The removal owner rechecks owner state through commit guards and lifecycle admission. (src/agents/worktrees/service.ts:1076, b72bb5f4dbab)
  • Narrow storage projection and regression coverage: The new reader queries existing session tables without changing stored formats. Coverage checks retained windows, invalid certification, stale activity columns, duplicate custody fields, and avoidance of full payload parsing. (src/config/sessions/session-accessor.sqlite-worktree-owner.test.ts:16, b72bb5f4dbab)
  • Still necessary on current main: Current main still resolves complete owner entries synchronously and has only the scalar logical worker accessor; it does not contain this batched worktree projection. No merged replacement was established. (src/agents/worktrees/owner-protection.ts:38, 76beb5685887)
  • Previous review blocker resolved: The raw test-merge commit records the pinned main parent followed by the exact PR head. Comparing that result with its main parent shows no changes to the main-only update-maintenance files. GitHub REST also reports the current head as mergeable. (d319f59d65e2)
  • Recorded behavior and validation evidence: The supplied complete PR body records isolated Linux source-run GC comparisons over 1,000 real stored session rows: identical classifications, zero full-entry parses, and substantially reduced CPU. It explicitly identifies those measurements as historical, reports cold RSS increasing 7.45%, and avoids claiming a retention plateau. The rebased candidate separately passed 186 focused tests and the staged structural/type/lint gate on Testbox. These runs were not executed by this reviewer. (b72bb5f4dbab)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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 (2 earlier review cycles)
  • reviewed 2026-10-06T10:19:49.652Z sha 3607a763a30331c42775951b362c9831fca63202 :: blocked before merge. :: none
  • reviewed 2026-10-06T11:04:55.156Z sha 22e4aca :: blocked before merge. :: none

@steipete
steipete force-pushed the steipete/perf-micro-worktree-owner-classification-allocations-20260919 branch from 3607a76 to 22e4aca Compare October 6, 2026 10:38
Batch narrow session owner facts for each GC pass while preserving fresh reads at destructive mutation guards. Share canonical store selection with single-entry worker reads and defer cleanup for uncertain metadata.
Capture logical identities before yielding and share each agent's selected
stores. Preserve bound incognito roots through the logical reader and cover
that composition with the existing actor test.
@steipete
steipete force-pushed the steipete/perf-micro-worktree-owner-classification-allocations-20260919 branch from 22e4aca to b72bb5f Compare October 6, 2026 19:28
@steipete
steipete merged commit 4de57f2 into main Oct 6, 2026
132 of 135 checks passed
@steipete
steipete deleted the steipete/perf-micro-worktree-owner-classification-allocations-20260919 branch October 6, 2026 19:38
vincentkoc added a commit that referenced this pull request Oct 6, 2026
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546': (30 commits)
  fix(ci): clear MCP audit and service-worker test blockers (#166217)
  test(gateway): wait for steering admission in FIFO fixtures
  fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358)
  perf(worktrees): avoid full session parsing during GC (#166072)
  fix(update): recover stopped legacy managed services (#166232)
  perf(gateway): stream bounded link preview metadata (#166195)
  perf(diagnostics): release completed Git operation state (#166214)
  chore(deps): update fs-safe to 0.24.1 and clone plugin source captures (#166189)
  feat(clients): adopt worker-local inference placement (#163647)
  test: serialize PowerShell completion process suites (#166229)
  test: stabilize release timing boundaries (#166218)
  refactor(sessions): persist run outcomes only; liveness comes from the run registry (#165733)
  test(gateway): prove mention refresh after config retargeting
  fix(team-reports): keep the missed closed day when catch-up runs after midnight (#165780)
  test(gateway): join WebChat queue admission and drain completion
  fix(logging): reject blank diagnostic stability query fields (#145532)
  fix(agents): report unparseable serialized edit arguments (#163577)
  improve(anthropic): log Claude Code version probe failures (#157697)
  fix(agents): clarify prompt-size provider failures (#159712)
  fix(memory): re-throw non-ENOENT/ENOTDIR errors in root memory file lookup (#107921)
  ...
vincentkoc added a commit that referenced this pull request Oct 6, 2026
* commit 'c39d9b0692dbaafa5b1bfe02514c9f6411ab5546':
  fix(ci): clear MCP audit and service-worker test blockers (#166217)
  test(gateway): wait for steering admission in FIFO fixtures
  fix(llama-cpp): managed setup crashes and loops on macOS below 13.3 (#163358)
  perf(worktrees): avoid full session parsing during GC (#166072)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 7, 2026
* perf(worktrees): avoid full session parsing during GC

Batch narrow session owner facts for each GC pass while preserving fresh reads at destructive mutation guards. Share canonical store selection with single-entry worker reads and defer cleanup for uncertain metadata.

* test(worktrees): align CLI fixture with owner census

* perf(worktrees): simplify batched owner selection

Capture logical identities before yielding and share each agent's selected
stores. Preserve bound incognito roots through the logical reader and cover
that composition with the existing actor test.
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. size: L 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