Skip to content

perf(state): reduce shared SQLite worker heap retention - #174420

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-sqlite-store-worker-heap-20260919
Oct 16, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-sqlite-store-worker-heap-20260919

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

A shared-state SQLite command such as sessionUpstream.listWatched loaded the fallback dispatcher's unrelated store domains and retained their module graphs for the worker's lifetime.

User Impact

Shared-state workers retain less JavaScript code after ordinary session operations. No schema, persistence, retention, configuration, or permission contract changes.

Why This Change Was Made

Complete the existing lazy operation-registry cutover and delete the central fallback dispatcher. Each domain retains its transaction, admission, and receipt behavior. The backend continues to own database handles, cron preparation, and the updater's retained writer. Credential-writer guards now name the exact moved handlers.

Heap attribution found module/code residency, rather than an accumulating result queue or unbounded statement cache, to be the reproducible cause. Existing statement limits, idle-handle retirement, and result-transfer cleanup remain in place. Production source delta: 102 lines removed net.

Evidence

Synthetic Linux rig, Node 26.8.1, bundled worker, repository fixture generator with 5,000 sessions and 6,000 retained runs (--transcript-mib 64; agent DB 236 MB, shared DB 11.8 MB). All state and operations were synthetic. Heap samples follow a worker heap snapshot/collection.

Measurement Before After
Heap after registered machine-state write 27.4 MB 27.4 MB
Heap after upstream-session read 43.3 MB 34.8 MB
Heap after another 1,000 writes 44.5 MB 35.8 MB
Retained ModuleWrap objects after upstream read 1,634 1,255
Native DatabaseSync objects 2 2

About 20% less collected worker heap, confirmed after rebuilding the final submitted source (a9f8ff42ebe7). External memory remained approximately 4.7 MB. Snapshot self sizes attributed most retained memory to strings, compiled code, and module properties; the loaded module count fell 23%.

Write-latency comparison used alternating baseline/candidate processes, 500 warmup writes, then five batches of 500 writes with an upstream read every ten writes. Across two runs per version, batch means were 0.96–1.21 ms before and 0.82–1.11 ms after. This shows no write regression; the latency difference is small enough that this PR claims the heap reduction, not a throughput speedup.

Full Gateway startup cross-check used the same fixture shape and pinned Bun 1.4.3 runtime. The shared-state SQLite worker retained 47.1 MB before and 44.4 MB after collection (about 6% lower); the two SQLite workers together retained 66.0 MB before and 59.6 MB after (about 10% lower). Baseline worker attribution was verified in the heap snapshots; the candidate also recorded worker script names. This is a single startup comparison, so the focused alternating write benchmark remains the throughput evidence. A 30-call sessions.list smoke returned the expected 5,000-session catalog: baseline mean/p99 11.6/17.5 ms; candidate samples varied during startup recovery, then settled from 17.0/26.9 ms to 10.0/13.2 ms. These unmatched startup samples are not used to claim a latency speedup.

Focused proof:

  • TUI persistence/cleanup and updater delayed-admission/revocation tests passed (14 tests).
  • Worker registry routing and cold domain preparation passed, including a regression that refuses eager secrets/cron/updater loading.
  • Eager-import and PR-wrapper closure files passed (22 tests); export-name collision guard passed.
  • Changed-file source-backed lint, formatting, and diff checks passed. Database worker inventory regenerated with its ownership/credential guards intact.
  • Independent P0–P2 autoreview: scoped-clean, no actionable findings.
  • Rebased after a conflict confined to the generated database inventory; git range-diff confirms the production/script patch is unchanged from the reviewed and measured commit.
  • Initial PR CI caught a type-only import cycle and missing isolation annotations on the cold-import regression mocks. Moved the unchanged updater operation type into its existing leaf contract and documented the intentional throw-on-import mocks; both repairs passed fresh independent review. The following run then required pruning the obsolete fallback mock allowance; the owning generator removed exactly that entry (9,409 → 9,408), and independent review was clean. No runtime behavior changed in these CI repairs.
  • Runtime build on the rig was measurement preparation. No Testbox/Crabbox lease; PR CI supplies broad validation.

Limits: this isolates shared-state code residency on a production-shaped synthetic database, not the complete heap of a long-running deployment or its aggregate across multiple workers. The fixture intentionally uses a smaller transcript payload. Existing handle/cache limits were audited, not changed. No live Gateway rollout was performed.

@clawsweeper

clawsweeper Bot commented Oct 16, 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 agents Agent runtime and tooling size: XL labels Oct 16, 2026
Load shared-state command handlers through their domain registry and remove the eager fallback dispatcher. Preserve existing admission, transactions, receipts, cron preparation, and retained updater-writer lifecycle. Synthetic bundled-worker retained heap after 1,000 writes fell from 44.5 MB to 35.7 MB without a write latency regression.
@steipete
steipete force-pushed the steipete/perf-micro-sqlite-store-worker-heap-20260919 branch from a9f8ff4 to 496b623 Compare October 16, 2026 16:27
@steipete
steipete marked this pull request as ready for review October 16, 2026 16:27
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T16:44:39.619952Z 97d76fc New commits
ℹ️ 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.

@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 7599693dddcb0bafd8eb35b403ca8f90d2c11686
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/registry-write.worker.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.
  • src/secrets/store/secret-store.worker.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR replaces the shared SQLite worker’s fallback dispatcher with lazily loaded domain handlers.

Example: A shared-state worker executes sessionUpstream.listWatched after a machine-state write.

  • Before: The reported synthetic benchmark retained 43.3 MB of collected heap after loading unrelated fallback handlers.
  • After: The reported candidate retained 34.8 MB while returning the same session data.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch cleanly completes the existing design with no identified defects; reported runtime measurements support the benefit, though raw heap artifacts were not supplied for independent inspection.
Proof confidence 🐚 platinum hermit (4/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its body reports bundled-worker heap measurements and a synthetic-state Gateway startup and sessions.list run, while source inspection confirms preserved effect guards.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary session operations leave shared-state workers retaining unrelated JavaScript module graphs.
Reason: The maintainer-authored direction follows the existing lazy-loading design and reports a meaningful heap reduction without adding configuration, storage formats, or public APIs.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR completes a useful lazy-loading cutover that current main still lacks; source review found no actionable defects.

Priority: P2
Reviewed head: 7599693dddcb0bafd8eb35b403ca8f90d2c11686

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway and CLI owners submit typed operations to the shared-state worker, which loads domain handlers and returns results and committed receipts through the existing SQLite broker.

flowchart TD
  A[Gateway and CLI owners] --> B[SQLite worker broker]
  B --> C[Shared-state backend]
  C --> D[Lazy domain registry]
  C --> E[Cron and updater adapters]
  D --> F[Existing database kernels]
  E --> F
  F --> G[Results and commit receipts]
Loading

Technical review

Best possible solution:

Complete the existing lazy registry cutover while preserving database ownership, synchronous transactions, admission, receipts, and updater settlement.

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

Current-main routing shows sessionUpstream.listWatched loading the fallback dispatcher’s static module graph; the PR also reports matched synthetic before/after measurements, which were not rerun during this read-only review.

Is this the best way to solve the issue?

The change uses the existing domain registry, removes the replaced dispatcher, and preserves the specialized cron and updater owners, making it a focused solution to retained module residency.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

PR surface

Source -102, Tests +14, Docs +1, Other +10. Total -77 across 33 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 23 848 950 -102
Tests 3 49 35 +14
Docs 3 26 25 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 4 52 42 +10
Total 33 975 1052 -77

Labels

Label changes:

  • add P2: The reported heap reduction is a useful bounded runtime improvement without evidence of an urgent availability incident.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: The reported heap reduction is a useful bounded runtime improvement without evidence of an urgent availability incident.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • 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.

Reviewed October 16, 2026, 1:07 PM ET / 17:07 UTC.

@steipete
steipete merged commit 6f281b1 into main Oct 16, 2026
156 of 158 checks passed
@steipete
steipete deleted the steipete/perf-micro-sqlite-store-worker-heap-20260919 branch October 16, 2026 17:17
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…158510

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…esafe-decision-native

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)

# Conflicts:
#	src/agents/decision-inference.integration.test.ts
vincentkoc added a commit that referenced this pull request Oct 16, 2026
…/decision-tool-v2-proof-20261016

* commit 'cff3c307ba6d0ce273abcdaf5cade848d9746d30':
  feat(decisions): preserve native catalog capabilities and accounting (#157492)
  fix(ui): avoid reactive read warnings in picker scrolling (#174436)
  refactor(test): remove unused Nextcloud fixture signing (#174470)
  refactor(browser): share managed tab eviction fixtures (#174474)
  fix(update): preserve Windows inspection path identities (#174471)
  perf: reduce large-session compaction and indexing allocations (#174433)
  perf(codex): reduce allocations while reading app-server output (#174468)
  fix(gateway): skip startup publication checks without a target (#174453)
  refactor: deslop agent harnesses, channel plugins and packages (wave-6 bundle A) (#173531)
  perf(state): reduce shared SQLite worker heap retention (#174420)
  refactor: remove routine channel callsite diagnostics (#174402)

# Conflicts:
#	docs/plugins/sdk-overview/capabilities.md
steipete added a commit that referenced this pull request Oct 16, 2026
The lazy registry cutover in 6f281b1 (#174420) retained all transcript
read handlers, but moved their namespace access behind Promise.all.
Dependency analysis then reported the live transcriptReadOperations table
as unused.

Select the named read and write tables inside their dynamic import
continuations before joining them. Preserve lazy concurrent loading,
all 18 read and six write handlers, and the read-then-write merge order.
Do not delete the live export or add a Knip ignore.

The real registry registers all 18 pre-cutover read operation names both
before and after. Core types, lint, formatting, and P2 review pass.
Production and script unused-export scans are clean; the full-tree scan
retains only the pre-existing Discord findings covered by #174482.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
)

* perf(state): reduce shared SQLite worker code retention

Load shared-state command handlers through their domain registry and remove the eager fallback dispatcher. Preserve existing admission, transactions, receipts, cron preparation, and retained updater-writer lifecycle. Synthetic bundled-worker retained heap after 1,000 writes fell from 44.5 MB to 35.7 MB without a write latency regression.

* fix(state): keep updater worker contracts acyclic

* test(state): explain cold worker import isolation

* test(state): prune retired worker mock allowance
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…aw#174498)

The lazy registry cutover in 250fe51 (openclaw#174420) retained all transcript
read handlers, but moved their namespace access behind Promise.all.
Dependency analysis then reported the live transcriptReadOperations table
as unused.

Select the named read and write tables inside their dynamic import
continuations before joining them. Preserve lazy concurrent loading,
all 18 read and six write handlers, and the read-then-write merge order.
Do not delete the live export or add a Knip ignore.

The real registry registers all 18 pre-cutover read operation names both
before and after. Core types, lint, formatting, and P2 review pass.
Production and script unused-export scans are clean; the full-tree scan
retains only the pre-existing Discord findings covered by openclaw#174482.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
…ump merge

One merge from the step-72 lane tip (8c4f725, upstream d0dbb62) to
upstream main f20c3c7 (BRIEF addendum
2026-10-20 17:25Z). 170 conflicted files (166 content, 3 modify/delete, 1
add/add), resolved in eight parallel slices (agents/subagents, agents other,
auto-reply x2, infra, gateway, config/sessions, rest) plus the lead's
src/state, schema, generated and baseline files. Rules per hunk: keep
continuation behaviour, adopt upstream everywhere else, port upstream changes
into the fork's split-out helpers, honour the Gate 2.7 reviewer ledgers.

Agent schema: upstream went 26 -> 31 (27 outbox sequence, 28 write layout,
29 index retirement, 30 trajectory storage, 31 memory revision; version
constant now in openclaw-schema-versions.ts). Continuation's recipient
authority, the lane's unreleased v27, is v32 on top of 31. The fleet's
schemas 25 and 26 (03de0ce runs agent 26 with the authority table) are
still recognised by shape: they run upstream's 26..31 steps, then the
idempotent authority step. The fleet-26 migration schema is anchored on
upstream's historical 26 plus the authority table, no longer on the authority
version. The lane's unreleased 27 is not recognised (upstream's 27 is the
outbox sequence): such dev databases are refused, not migrated (named in
agent-schema-history.md). Witness accepts 24..32. PostgreSQL: recipient
authority is SQLite-only; v32 is a version-only PG step and the port
descriptor accepts sources 27..31.

Structural ports onto upstream owners:
- shared state worker: upstream retired the eager dispatcher (openclaw#174420);
  continuation custody registers as the `continuationCustody` registry domain
  with typed per-command handlers; schema ensurer moved to
  createSqliteSchemaEnsurer + getOpenClawStateFeatureSchemaSql, run inside the
  write transaction; custody kernels take EngineConnection.
- session controller (openclaw#175837): continuation admission, election and idle
  waits use isSessionRunActiveForKey / resolveActiveSessionRunId /
  waitForSessionRunIdle; the folded provenance note uses
  steerSessionControllerOperation with waitForTranscriptCommit; session lanes
  are gone, so a subagent's continuation turn takes the subagent lane.
- incognito became memory-only (openclaw#170712): the fork's incognito branches in
  owner assignment and sharing follow upstream; recipient-authority capture is
  still refused for incognito sessions.
- openclaw#169714 (prepared runtime config): fork suites publish config per suite as
  upstream's do; announce's continuation owner loader carries the run's config.
- deleted, fully carried by upstream replacements: core-tool-factory-
  descriptors.ts (tool-catalog.ts), status.command-report-data.ts
  (status.command-report.ts), openclaw-state-worker-runtime.ts (registry);
  unused fork leftovers subagent-announce-reply.ts and the nested-matrix
  test-support.
- line-cap extractions of upstream code: openclaw-tools.pdf-tool.ts,
  subagent-registry-kill-confirmation.ts, agent-runner-recovery-read.ts,
  session-event-wake.merge.ts, user-turn-transcript.metadata.ts helpers.

Generated: worker inventory and config baseline regenerated; plugin SDK
surface measured on this tree: 3821 exports / 2212 callable (upstream 3810 /
2208, +11 / +4 continuation). Mock-factory baseline pruned to the exact tree
(9854 -> 8014; no entry outside either parent).

Proof on this tree: tsgo core 0, extensions 0, scripts 0, ui 0. Not yet run
(follow-up commits): test-shard typecheck, pnpm build, lint/line-cap and the
other static gates, Gate 2.7/2.5, tests. Known follow-ups: witness line cap,
system-events test shadowing, the restart-sentinel continuation-delivery
harness and the incognito-actor authority test ports, ledger MANUAL rows
marked ABSORB-8083-LEAD.

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

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts security-sensitive-changed size: XL 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