Skip to content

perf(memory): bound derived worker snapshot and pricing retention - #174067

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-worker-memory-budget-20260919
Oct 16, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-worker-memory-budget-20260919

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Memory indexing can retain up to 64 MiB of transcript snapshot payloads in one worker, and model pricing contexts retain full serialized pricing tables as their fingerprints. Both are reconstructible derived data.

User Impact

Reduces memory retained after indexing and pricing work without changing transcript output or pricing decisions. Existing persisted estimate fingerprints change once and are recomputed normally; no schema or configuration change is required. Revisiting an evicted transcript can require another database read.

Why This Change Was Made

The transcript export cache now uses the existing LRU owner with an 8 MiB aggregate source-byte budget, preserving its 16-entry and 4 MiB per-entry limits and generation-based append/rewrite checks. Pricing contexts retain a SHA-256 digest of the same deterministic serialization instead of the serialization itself.

Production delta is +1 line (8 added, 7 removed): the manual count-eviction loop is deleted, the existing cache supplies aggregate byte eviction, and the pricing digest requires its crypto import. No new cache framework, worker owner, configuration, or compatibility path is introduced.

Measurement

Compared base 08dd80a42558 with head 8925281ab99b6a240a060bd07f49c75a2f935fb9 in an isolated checkout on a Linux benchmark host using Node 26.10.0 and synthetic state only. The fixture contains 5,016 sessions, 6,000 retained runs, 200 startup approval records, 100 disabled cron jobs, and 12 synthetic Git projects. Its original agent database is 4,641,595,392 bytes, with 1,500 MiB of generated transcript text; sixteen approximately 3 MiB export sessions were then added. No production state was copied or exercised.

Three fresh-process rounds per revision, through the real buildSessionEntries() export worker and pricing owners:

Measurement (median) Before After
Transcript worker live heap after sixteen exports 168.7 MiB 126.4 MiB
Transcript worker heap capacity 190.6 MiB 134.1 MiB
Export process RSS after controlled GC 675.5 MiB 603.1 MiB
Export process RSS before controlled GC 675.4 MiB 614.4 MiB
Hot export read 15.3 ms 14.0 ms
Revisit first export after filling cache 15.3 ms 19.9 ms
Retained pricing fingerprint, 40,000 rows 8,953,548 bytes 64 bytes
Pricing process live heap 86.3 MiB 77.7 MiB
Repeated cost-fingerprint call 81.09 ms 0.040 ms

All sixteen export content hashes matched across all six runs, including rebuilding the evicted first session. The byte budget saves 42.3 MiB of live worker heap in this workload; the extra cold reread is the intended tradeoff. Timing is indicative because the benchmark host had concurrent workload. These are synthetic workload results, not a production-wide RSS prediction.

The matched built-Gateway list workload was neutral: RSS before explicit GC was 1,554.0 → 1,540.1 MiB; at the post-GC checkpoint it was 1,497.7 → 1,505.4 MiB (+0.5%). Both revisions used an offline-restored copy of the same fixture, 100 real sessions.list RPCs, and a 45-second settling interval. Mean RPC latency was 19.45 → 19.51 ms; p99 was 55.72 → 58.32 ms, with identical response sizes and session counts. These small differences are consistent with shared-host/allocator variation. This list-only workload does not exercise the export cache or large pricing tables, so no overall Gateway saving is claimed. Heap snapshots were taken after the measurement checkpoint.

Post-GC heap census, grouped by script. Both revisions had 14 live workers; used/capacity values are MiB, not per-worker RSS.

Worker script Count Before used / capacity After used / capacity
worker-native-lifecycle.worker.js 1 6.4 / 7.4 6.4 / 7.4
openclaw-state-read.worker.js 1 35.9 / 37.7 35.9 / 37.0
gateway-state-owner-heartbeat.worker.js 1 6.8 / 7.7 6.8 / 7.5
openclaw-state-lease-heartbeat.worker.js 1 16.1 / 17.0 16.0 / 17.0
sqlite-store.worker.js 2 124.1 / 128.6 123.7 / 128.4
session-transcript.worker.js 5 235.6 / 246.8 235.6 / 246.8
discovery.worker.js 1 33.7 / 34.8 33.7 / 36.1
prepared-model-catalog.worker.js 1 89.1 / 90.9 89.0 / 91.4
session-list.worker.js 1 105.4 / 107.1 105.4 / 107.4

Main-thread live heap was 330.8 → 329.4 MiB, with 341.4 MiB capacity on both revisions. The fixture deliberately disables live integrations; workers absent from this census are not covered by these measurements.

Worker Audit

Ten empty Node workers added about 8.1 MiB RSS each on this host. RSS is process-wide; per-worker process.memoryUsage().rss is not a valid isolate attribution. The census records each isolate's used heap and capacity separately.

The filesystem ownership heartbeat must remain isolated from SQLite lease heartbeats: SQL admission can block synchronously while filesystem renewal must stay live. Both heartbeat families already coalesce compatible work. The transcript label aggregates several worker pools rather than identifying one isolate. Recent-history pages and usage-rollup caches already have effective byte bounds; SQLite writer state is lifecycle-owned actor/context state, not an accumulated result cache.

Catalog workspace contexts remain resident because evicting them would recreate native module graphs that cannot unload. A synthetic catalog-worker heap snapshot contains 35.6 MiB of strings, 18.1 MiB of code, and 2,517 module jobs; it does not reproduce the larger production workload. Shared configured catalog facts are consumed by runtime-generation reuse and cannot simply be deleted. Existing 512 MiB old-generation limits for catalog, transcript, and SQLite writer workers remain unchanged; this PR does not claim that lower limits are safe.

Proof

  • 40 focused local tests passed across src/model-catalog/pricing.test.ts, packages/memory-host-sdk/src/host/session-files-reset-revision.test.ts, and src/infra/lru-cache.test.ts. The strengthened pricing retention regression fails on the original implementation.
  • Independent Codex autoreview: scoped-clean through P2; no actionable findings.
  • Changed-file formatting/lint and diff whitespace checks passed.
  • PR CI run 38881032686 passed on the exact head, including broad typechecks, changed lanes, builds, UI checks, and PostgreSQL conformance. No CI retries.
  • Linux builds were prepared solely for the benchmark. No Testbox/Crabbox lease was allocated; PR CI supplied broad validation.

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

@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-16T09:33:57.142501Z 8925281 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.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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. 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 limits retained transcript snapshots to an aggregate 8 MiB source-byte budget and replaces serialized pricing fingerprints with SHA-256 digests.

Example: One transcript worker indexes sixteen sessions whose snapshots each account for 4 MiB of source data.

  • Before: The cache can retain snapshots accounting for 64 MiB of source data.
  • After: The cache retains snapshots accounting for at most 8 MiB, rebuilding evicted snapshots when needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A focused, source-supported optimization with no identified defects; supplied validation is test-level and does not yet establish measured runtime savings.
Proof confidence 🦐 gold shrimp (3/6) Maintainer-authored PR outside the ordinary proof gate; supplied evidence reports focused tests, while runtime measurements remain in progress and are not claimed as observed proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Background indexing and usage pricing retain more reconstructible data in memory than necessary.
Reason: The maintainer-authored direction reduces retained data through existing owners with minimal production growth and no new user-facing controls.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR provides a focused memory reduction that current main does not contain, with no actionable correctness or security findings.

Priority: P2
Reviewed head: 8925281ab99b6a240a060bd07f49c75a2f935fb9

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Completed runtime retention measurements are not supplied; ordinary shipped-entry-point proof is exempt for this maintainer-authored PR.
Agent review details

How this fits together

The transcript worker derives memory-indexing entries from authoritative session data, while pricing contexts supply model rates and cache-invalidation fingerprints to usage accounting.

flowchart TD
  A[Session database] --> B[Transcript worker]
  B --> C[Bounded snapshot cache]
  B --> D[Memory indexing entries]
  E[Catalog and pricing policies] --> F[Pricing context]
  F --> G[Usage estimates and fingerprints]
Loading

Technical review

Best possible solution:

Use the existing LRU byte budget and compact pricing digest while preserving transcript reconstruction and normal estimate-cache invalidation.

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

Current-main source retains up to sixteen 4 MiB snapshots and the complete serialized pricing fingerprint; these retention paths are directly identifiable without executing target code.

Is this the best way to solve the issue?

The change addresses both retained representations at their existing owners, removes manual eviction code, and preserves pricing inputs and transcript validity checks.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Transcript snapshot retention keeps the original intent (a00f582: Retain bounded projected transcripts to avoid rereading unchanged payloads while rebuilding after generation changes or eviction.)
  • Pricing fingerprint keeps the original intent (5347285: Fingerprint hosted prices and lookup policies so usage estimates invalidate when their pricing inputs change.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

  • Reviewed introduction and current main: The pinned introduced diff changes only snapshot retention, the retained pricing fingerprint, and its existing regression test; fetched main retains the original behavior in all three files. (8925281ab99b)
  • Existing retention owner reused: LruCache already accounts for replacement and deletion and evicts oldest entries until both limits hold; peek preserves the previous non-promoting lookup before successful snapshot retention. (src/infra/lru-cache.ts:75, 8925281ab99b)
  • Transcript correctness boundary preserved: Snapshot reuse still checks generation and sequence, honors the read fence, and sends cold transcripts through restoration; eviction only removes reconstructible process-local state. (src/config/sessions/session-accessor.sqlite-read.ts:190, 8925281ab99b)
  • Verified no-migration case: Persisted pricing fingerprints remain opaque SHA-256 strings produced by usage-format. The internal digest changes their value once; the existing codec rejects mismatched cache entries and the usage worker rebuilds them from transcripts without changing configuration, transcript data, or the stored format. (src/utils/usage-format.ts:201, 8925281ab99b)
  • Original snapshot intent: perf(memory): batch incremental indexing and preserve session caches #170302 introduced bounded, reconstructible projected snapshots; this PR preserves its incremental-read and full-read fallback contracts while tightening aggregate retention. (src/config/sessions/session-memory-entry.worker.ts:23, a00f58286fae)
  • Discussion and validation: The complete current body and comments provide reported focused-test results but no completed runtime measurements; the maintainer-authored proof exemption applies. The reviewed head is mergeable, with PostgreSQL conformance still running and the CI gate pending. (8925281ab99b)

Likely related people:

  • Ayaan Zaidi: Raw commit 504d290 adds src/model-catalog/pricing.ts:64 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 504d2905d69c; files: src/model-catalog/pricing.ts)

PR surface

Source +1, Tests +6. Total +7 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 8 7 +1
Tests 1 7 1 +6
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 15 8 +7

Labels

Label changes:

  • add P2: A focused reduction in reconstructible memory retention with no demonstrated urgent runtime failure.
  • 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: A focused reduction in reconstructible memory retention with no demonstrated 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.

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, 5:45 AM ET / 09:45 UTC.

@steipete
steipete merged commit faca2b7 into main Oct 16, 2026
127 of 128 checks passed
@steipete
steipete deleted the steipete/perf-micro-worker-memory-budget-20260919 branch October 16, 2026 09:53
vincentkoc added a commit that referenced this pull request Oct 16, 2026
* commit 'ac03ca0b6d26a7dc55d0d262e40d2549631b1ea7': (25 commits)
  fix: apply shared plugin model policy to decisions (#156621)
  perf: shortlist transcript relevance scores before metadata reads (#174058)
  fix: strip standalone trailing NO_REPLY from replies (#171990)
  fix(ci): avoid repeated discovery during changed-test planning (#174069)
  fix(sqlite): preserve transaction outcomes when warnings throw (#157151)
  fix(ai): native video handoff to chat-completions providers + preflight video cost (#170920)
  fix(litellm): image generation fails when the backend returns image URLs (#173508)
  test(memory,gateway,infra,subagents): remove low-value tests (batch d152) (#174034)
  perf(memory): bound derived worker snapshot and pricing retention (#174067)
  fix(test): reduce eager imports during test startup (#174056)
  refactor(codex): share lifecycle preflight fixtures (#174062)
  test(gateway,matrix,agents,ui): remove low-value tests (batch d150) (#174025)
  perf(infra): batch usage refresh maintenance (#174050)
  fix(gateway): revert cold session list worker regression (#174052)
  refactor(config): consolidate browser meeting configuration (#173947)
  fix(cron): keep global-session deliveries on the selected agent (#173855)
  test(compaction): assert structured stale-writer failure (#174064)
  fix(cli): local terminal chat sends model requests without the configured proxy (#173530)
  test(ui): restore bootstrap preference locale after each case (#174065)
  fix: download session files through the development proxy (#173973)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: XS 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