Skip to content

perf(workers): bound resident database and transcript heaps - #169110

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-worker-heap-at-rest-20260919
Oct 11, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-worker-heap-at-rest-20260919

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

High-core Gateways retain repeated copies of database and transcript runtimes after bursts, while aggregate worker-heap metrics hide how many isolates contribute to each script.

Related: #167295.

User Impact

Reduces resident and peak worker memory without changing stored data, schemas, configuration, permissions, or update behavior. Operators can compare per-script live-worker counts with sampled counts and heap bytes, including workers whose samples are unavailable.

Why This Change Was Made

Extend the existing two-worker reader policy to foreground transcript history and search. Cap the shared SQLite broker at two workers instead of scaling up to eight with CPU count. Keep the existing per-database ordering, independent reader lanes, admission, and native cleanup owners; no scheduling or cache layer is added. The SQLite minimum remains two even on small machines.

The exporter adds bounded script series to openclaw_worker_count and openclaw_worker_heap_sampled_count, retaining the existing unlabeled totals. Missing samples count as live workers, and retired script series are removed on the next sample.

Production LOC: +17 overall. The sizing policy removes 3 net lines; the explicitly requested live/sample census adds 20 lines to the existing metric owner to account for missing samples and retire stale series. No new module, export, dependency, or configuration option. Two storage lifecycle fixtures now fill the actual broker budget instead of assuming four distinct workers; their retirement, carrier, and blocked-open assertions are preserved.

Evidence

Blacksmith Testbox tbx_01m4n7pxwjh2a86rxv88z5jz0x, Node 24.19.0, four available CPUs. Both variants use the same synthetic fixture: 2,000 sessions across 20 agent databases, 20 transcripts with 1,000 4-KiB messages each, and 2,000 synthetic catalog models. A 64-CPU sizing override exercises the high-core policy; this is not a native 64-core throughput result. All 20 metadata writes settle before the concurrent 20-session full-transcript reads. Every read verifies its event count and final ID; all writes and the 2,000-entry listing are checked.

Five-second idle observations use the production collector without forced GC. The comparison differs only in worker sizing. Build/rig commands: pnpm build, node --import ./scripts/tsx.mjs .local/lane-760/build-worker-heap-rig.mts, and node dist/lane-760-worker-heap-rig.mjs --root <fresh-state> --cpus 64.

Measurement Before After
RSS before burst 1,336 MiB 1,054 MiB
RSS after burst and idle 2,046 MiB 1,375 MiB
Sampled peak RSS during reads 2,165 MiB 1,435 MiB
Sampled peak worker heap during reads 834 MiB 443 MiB
Twenty metadata writes 3,933 ms 645 ms
Twenty concurrent full-transcript reads 1,561 ms 1,489 ms
Combined writes and reads 5,494 ms 2,134 ms
Script Before: initial idle / post-burst idle After: initial idle / post-burst idle
sqlite-store.worker.js 185.55 / 171.31 MiB (4 / 4 isolates) 95.44 / 104.00 MiB (2 / 2 isolates)
session-transcript.worker.js 92.65 / 48.20 MiB (2 / 1 isolates) 91.90 / 47.57 MiB (2 / 1 isolates)
prepared-model-catalog.worker.js 84.37 / 84.38 MiB (1 isolate) 84.35 / 84.36 MiB (1 isolate)

Peak transcript-worker population falls from nine to three in this fixture, including the independent projection worker. Post-burst RSS falls by 670 MiB (33%), sampled peak worker heap by 391 MiB (47%), and combined wall time by 2.57x. Five-second idle CPU is 1.2 ms before and 4.1 ms after; there is no additional timer or GC policy.

Separate heap snapshots were analyzed through scripts/heap-snapshot-diff.mjs. They show substantial loaded-module/loader state in every isolate, not a large retained decoded-transcript cache. The catalog additionally retains its prepared plugin generation. Its source capture belongs to the inventory owner, so idle retirement could reload changed plugin code into an existing publication; that lifetime remains intact. The catalog's roughly 84 MiB does not shrink in this change. Snapshot runs are separate from the unforced comparison above.

Validation completed so far:

  • On Blacksmith Testbox tbx_01m4n7pxwjh2a86rxv88z5jz0x, both full production builds passed. The paired build/benchmark command exited 0 in 238.6 s; the separate retained-heap analysis exited 0 in 10.1 s.
  • On Blacksmith Testbox tbx_01m4nbjv55z6qp7p1rdtgqnpjr, the existing native broker test fails on old sizing because three opened stores use three workers instead of the expected two. The candidate's 11 broker tests and all 34 Prometheus service tests pass (39.63 s combined wrapper wall time). The 30 storage/generation lifecycle tests pass (45.54 s wrapper wall time).
  • Relevant worker, history, storage, and exporter sibling coverage passed after updating the old capacity expectations. The broad sibling run exposed the stale eight-worker broker assertion; its subsequent full-file rerun passed. One existing platform/capability case was skipped.
  • Independent Codex review through P2 is scoped-clean with broker, transcript lifecycle, and test context supplied. The rebased commit preserves all eight reviewed file hashes.

Rebased changed-file gate and baseline qualification on Blacksmith Testbox tbx_01m4ncmhevy5kbpk25041d71z7, commit 16493f280f5e5c58c1794d7f513956643a87be01: all guards, core types, 28 core-test type graphs, extension types, and extension-test types passed. The gate then failed only on unrelated UI dead exports. The unchanged current-main baseline 3a0db8a3a05283c21600bc39e2772bf1432f7d0e independently fails the same node --import ./scripts/tsx.mjs scripts/check-deadcode-exports.mts scan with the same chat exports, including ChatCiAutomation, ChatCiDetails, ChatClawHubCard, and the Solid tool-card/content/outcome hosts. The baseline has additional unrelated findings. No dead-export exception or suppression was added. The remaining native lint plan passed with zero warnings/errors, and all 47 assertions in the four changed test files passed again on that pinned commit. No guard was disabled; the failed global scan remains recorded as an inherited failure.

Per-file cost on that Testbox, via node scripts/run-vitest.mjs <file> --maxWorkers=1 (the pnpm test wrapper):

Changed test Wrapper wall Vitest duration
src/infra/sqlite-worker-broker.test.ts 27.54 s 25.47 s
src/infra/sqlite-worker-store.generation.test.ts 7.91 s 5.79 s
src/infra/sqlite-worker-store.test.ts 25.68 s 23.58 s
extensions/diagnostics-prometheus/src/service.event-loop.test.ts 2.88 s 1.59 s

Hosted CI: the first head's run 38141089913 found one further stale four-worker expectation in bun-sqlite-library.worker.test.ts; the fail-fast monitor cancelled the rest. Follow-up commit 0d58e6166de7dabdbcdf0493661fd039ac1636f1 changes its three admitted-worker expectations to two while retaining the five-worker conservative branch, alias sharing, reopen, and termination assertions. The entire Bun/SQLite family passes on the isolated Linux rig (Node 26.8.1): 33 tests across three files, 96.29 s wrapper wall / 91.48 s Vitest duration including cold worker compilation. The narrowed core-test type graph and final lint pass; the unrelated UI dead-export scan remains the sole local-gate failure. Independent P2 review of this follow-up is scoped-clean. Current-head CI run 38145733548 completed with 49 successful jobs, 8 fail-fast cancellations, and one originating failure: UI production types. The exact tested merge 9705fb2a2d4cdd445823a4b91b185ff65acd51ed has main parent 38f456226f626dd3868c2a4e754e75bf37b59e68; its entire UI tree, UI tsconfig, package manifest, lockfile, and typecheck wrapper match that parent byte-for-byte. The same six TS2322/TS2717 tab-panel errors reproduce on that untouched parent with node scripts/run-tsgo.mjs -p tsconfig.ui.json (exit 2). Core and extension production types pass in the hosted job. Security-fast and Security Review passed. The inherited UI failure is retained explicitly for the authorized admin landing; cancelled checks are not counted as successful.

The follow-up proof used nice -n 10 ionice -c3 node scripts/run-vitest.mjs src/infra/bun-sqlite-library.worker.test.ts src/infra/bun-sqlite-library.capabilities.test.ts src/infra/bun-sqlite-close-probe.test.ts --maxWorkers=1, followed by the changed-test gate and its remaining native lint plan. Testbox expiry, an AWS workspace-renewal failure, and a Hetzner dependency-download 504 prevented earlier follow-up attempts from producing a test verdict; those are not passing proof. All performance measurements above remain the original paired Testbox measurements.

Limits: synthetic production-owner paths with compiled workers, not a full deployed Gateway or production-memory projection. No live Gateway was accessed. Catalog generation retention is unchanged; the improvement comes from fewer duplicate database/transcript isolates.

The initial changed-file gate found an unrelated pre-existing max-lines suppression in src/web-search/runtime.test.ts. The branch was rebased onto current main, including existing fix cedb310b3ab1; no unrelated fix was copied into this diff.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 extensions: diagnostics-prometheus size: S labels Oct 11, 2026
@steipete
steipete marked this pull request as ready for review October 11, 2026 12:54
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR caps shared SQLite and foreground transcript worker pools and adds per-script live and sampled worker counts.

Example: A Node Gateway reports 64 available CPUs.

  • Before: The SQLite broker can create eight workers, and each foreground transcript pool can create eight.
  • After: The SQLite broker uses at most two workers, and each foreground transcript pool uses at most two.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is focused and correct on inspection, with meaningful owner-boundary coverage; performance evidence remains component-scoped rather than a shipped Gateway flow.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored item is outside the ordinary contributor proof gate; its evidence exercises compiled SQLite and transcript owners with synthetic data, while exporter coverage uses an in-process harness and no deployed Gateway claim is made.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: High-core Gateways retain duplicate database and transcript runtimes, while operators cannot distinguish worker population from sampling coverage by script.
Reason: The feature-history owner supplies a bounded change and a comparable production-owner measurement, with preserved ordering and cleanup and no operator setting or persisted-format change.

Merge readiness

✅ Ready for maintainer review

This PR provides a focused memory improvement that current main does not contain. The earlier Bun fixture finding is resolved; no actionable patch defect remains, and the reported CI failure is supported as inherited.

Priority: P2
Reviewed head: 0d58e6166de7dabdbcdf0493661fd039ac1636f1

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied component benchmark does not exercise a deployed Gateway or native high-core throughput; its limited scope is explicitly recorded.
Agent review details

How this fits together

Gateway database commands and transcript reads enter existing worker owners, which return settled writes and read results; the worker registry supplies memory samples to the Prometheus exporter.

flowchart TD
  A[Gateway requests] --> B[Worker sizing owner]
  B --> C[SQLite broker]
  B --> D[Transcript reader pools]
  C --> E[Worker resource registry]
  D --> E
  E --> F[Prometheus exporter]
Loading

Technical review

Best possible solution:

Land the focused sizing and census changes through the native maintainer workflow with the inherited UI failure recorded.

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

Current-main sizing permits eight SQLite and foreground transcript workers on a 64-CPU input; the supplied compiled-owner comparison reports the resulting memory difference, but no new execution was performed in this review.

Is this the best way to solve the issue?

Reducing duplicated isolates in the existing sizing owner addresses the measured cause without adding scheduling machinery, and the exporter reuses the registry's complete fresh-or-missing census.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • SQLite and foreground transcript sizing changes intended behavior with a stated reason (b3196df: The central sizing refactor preserved prior CPU-scaled broker and foreground budgets while retaining parallel lanes and serial ownership.)
  • General reader cap changes intended behavior with a stated reason (9932db4: The earlier change reduced duplicated reader isolates but explicitly excluded SQLite and foreground transcript pools; this PR supplies measurements for extending the policy.)
  • Worker memory metrics keeps the original intent (perf(diagnostics): attribute Worker heap usage by script #154295: Per-script heap attribution uses bounded labels and expires stale samples; the new counts preserve those boundaries and existing aggregate series.)
  • Storage lifecycle fixtures keeps the original intent (fix(update): preserve failures and running worker code during replacement #153764: The fixtures protect retained runtime generations and native settlement; filling the actual broker capacity preserves their intended failure scenarios.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b3196df adds src/infra/worker-pool-sizing.ts:23 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b3196dfda335; files: src/infra/worker-pool-sizing.ts)

PR surface

Source +17, Tests +24, Docs +9. Total +50 across 9 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 27 10 +17
Tests 5 47 23 +24
Docs 2 14 5 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 9 88 38 +50

Review metrics

Metric Value Why it matters
Production versus test growth Production +17 net lines; tests +24 net lines Production growth adds the live/sample census to the existing exporter while sizing shrinks; test growth extends metric-output coverage and preserves capacity lifecycle scenarios.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded runtime memory and observability improvement without evidence of an urgent outage.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-11T13:00:57.519Z sha 16493f2 :: needs changes before merge. :: [P2] Update the remaining admitted-broker lifecycle expectations
  • reviewed 2026-10-11T14:13:37.706Z sha 0d58e61 :: needs changes before merge. :: none

Reviewed October 11, 2026, 10:43 AM ET / 14:43 UTC (Revision 3).

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 11, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The remaining CI failure is inherited UI typechecking, not a worker-lane regression. Run 38145733548 tested merge 9705fb2a2d4cdd445823a4b91b185ff65acd51ed (main parent 38f456226f626dd3868c2a4e754e75bf37b59e68, PR head 0d58e6166de7dabdbcdf0493661fd039ac1636f1).

node scripts/run-tsgo.mjs -p tsconfig.ui.json reproduces all six TS2322/TS2717 errors on that unchanged main parent: browser-panel-render, panel-elements, panel-tab-strip-solid, and terminal-panel-view. The complete UI tree, UI tsconfig, package manifest, lockfile, and typecheck wrapper have identical Git object IDs in the parent and tested merge. Core and extension production typechecks passed in the hosted job. Security-fast and Security Review passed; the fail-fast monitor cancelled eight remaining jobs after the UI failure.

Scoped worker/storage/exporter tests, all 28 core-test type graphs, extension types/tests, and lint passed. The corrected Bun/SQLite family also passed all 33 tests on the isolated Linux rig. The earlier global UI dead-export failure was separately reproduced on unchanged main and remains documented in the PR body.

This qualifies for the requested inherited-failure landing exception. No CI rerun, update-branch push, deadcode suppression, or UI change is included.

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete
steipete merged commit 48f3aa1 into main Oct 11, 2026
146 of 157 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-heap-at-rest-20260919 branch October 11, 2026 14:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…#169110)

* perf(workers): bound resident database and transcript heaps

* test(workers): align native-close fixture with broker capacity
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream 19fe879..0bc7491 (100 commits, including
openclaw#169090 entry-writer postimages, openclaw#169201 transcript projection facts,
openclaw#169113/openclaw#169107/openclaw#169125 session-actor admission, openclaw#169110 bounded worker
heaps, openclaw#169130 inter-session provenance, openclaw#168931 Solid session UI).

Conflicts:
- session-accessor.sqlite-entry-mutation.ts: openclaw#169090 moved postimage
  publication into writeSessionEntry and replaced the revision-equality
  no-op check with postimages.changed. Took upstream's form; kept our
  recipient-authority advance on visibility narrowing (same transaction,
  after the write, before the no-op return).
- session-accessor.sqlite-entry-store.ts: import union (upstream dropped
  withProjectedParticipants/SessionEntryWindowFacts imports; ours adds the
  recipient-authority advance). Overlay vs upstream is now 2 lines.
- openclaw-tools.types.ts: import union (our RequestCompactionToolOpts,
  upstream's SessionsYieldRuntimeClaim).
- plugin-sdk-surface-report.mts: upstream raised the budgets to 3672/2133;
  ours stays +11/+4 on top (3683/2137).
- worker-access-inventory.md: regenerated on the merged tree.

Auto-merged files that carry continuation overlay (21) keep the overlay
byte-for-byte (interdiff of the +/- lines vs upstream before and after).

Refs #1475

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 extensions: diagnostics-prometheus gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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