Skip to content

perf(sessions): share resident actor entries across projections - #182934

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-session-worker-heaps-20261024
Oct 25, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-session-worker-heaps-20261024

Conversation

@steipete

@steipete steipete commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Durable session actors retained two decoded copies of their session entry: one in the stored-row map and another in hot state. Each copy includes nested skill and system-prompt snapshots. Hot-state projection cloned that entry again after mutations.

User Impact

Active durable sessions retain less worker memory, especially when skill and system-prompt snapshots are large. No migration or configuration change is required.

Why This Change Was Made

Keep one actor-owned entry across those internal views. Incoming postimages still detach once, writers replace entries, transaction forks preserve the previous entry for rollback, and public reads/commit receipts remain detached. The existing cache limits, persisted representation, transcript contents, and public APIs are unchanged. Runtime production code is net −2 lines; tests are +2, the reproducible benchmark is +208, and documentation is +35. The broad non-test/non-doc diff is +236 because it includes the benchmark and its README. This tooling growth supports the requested owner-level proof; it adds no production instrumentation hook.

Release-note context: lower retained worker memory for active sessions with large entry snapshots.

Evidence

Node 26.12.1; a synthetic Gateway fixture with 5,000 sessions and 6,000 retained runs. Four real synthetic-provider child sessions were warmed through agent/tool turns, producing 36,514-byte session entries. Five fresh-process pairs used alternating launch order, identical source-replacement instrumentation, and forced GC in the native worker. Snapshots were captured outside timing windows.

Metric (5 samples per side) Base mean Candidate mean Paired change
Four-actor resident graph 1,060,800 B 860,948.8 B −199,851.2 B (−18.84%)
Whole native worker post-GC heap (context; mixed signs) 166,720,547.2 B 166,542,936 B −177,611.2 B (−0.11%)

The comparison uses base 803ad1fdc36e3473b4a9c538fd3dfb4a15f4431a with only the three runtime owner files replaced for the candidate. Their measured bytes match the current PR head; rebasing did not change those runtime files. The resident-owner saving is consistent. In the initial source-loaded SQLite worker snapshot, 50,258,296 bytes belonged to tsx’s in-process transform cache; this does not establish that deployed builds retain that cache. Loaded code and source-runtime machinery dominate the whole worker, so this is not a claim of a large whole-worker reduction. Transcript history windows, actor residency, statement caches, and reply-transfer lifetimes were audited; this patch changes only the demonstrated duplicate actor entry.

Latency and correctness

The candidate completed a full synthetic Gateway memory-soak run: 4 clients, 2 measured rounds, 8 completed measured turns and 8 session resets, plus warmup. The driver verified its edit-visibility control. Two simultaneous, CPU-swapped native-owner pairs completed with identical command identities and separate synthetic fixtures. Each side performed 1,200 native reads and 1,200 real patch commits. Shared quiet-slot and production guards remained healthy. The following are untraced results; percent changes are the mean of the two paired percentages.

Metric Base mean Candidate mean Signed paired delta
Worker CPU, ms/operation 1.5354 1.4334 −0.1020 (−6.66%)
Total GC, ms/operation 0.1205 0.1084 −0.0121 (−9.83%)
Read mean, ms 0.9920 0.9762 −0.0157 (−1.46%)
Read p95, ms 1.6221 1.5274 −0.0948 (−5.85%)
Read p99, ms 5.0419 5.0535 +0.0116 (+0.36%)
Commit mean, ms 3.7628 3.5888 −0.1740 (−4.69%)
Commit p95, ms 6.0186 5.5173 −0.5013 (−8.42%)
Commit p99, ms 10.2503 10.1863 −0.0641 (−0.39%)
Worker event-loop p95, ms 4.4114 4.1953 −0.2161 (−4.92%)
Worker event-loop p99, ms 6.6191 6.1440 −0.4751 (−7.21%)

Every read/commit tail has 1,200 samples per side per pair. Event-loop sample counts were 2,660→2,697 and 2,387→2,461. Read p99 deltas were −0.0731/+0.0964 ms; commit p99 deltas were +0.9084/−1.0365 ms. These mixed-sign tails are context, with no adverse paired-mean gate; CPU fell in both pairs (−6.27%/−7.05%).

Untraced GC kind Pair 1 base→candidate count; total ms; max ms Pair 2 base→candidate count; total ms; max ms
Scavenge 166→153; 265.892→231.736; 4.603→3.167 168→152; 246.896→224.010; 2.870→3.684
Incremental marking 6→5; 3.813→3.502; 0.781→0.819 5→5; 2.857→3.156; 0.689→0.711
Major 6→5; 35.250→27.486; 7.342→6.094 5→5; 23.882→30.545; 5.207→8.346
All GC 178→163; 304.955→262.723; 7.342→6.094 178→162; 273.634→257.712; 5.207→8.346

GC pause percentiles are context: fewer than 200 collections per kind/side and fewer than 50 majors. Neither maximum GC pause reaches the max-pause safeguard. Loop maxima were 59.507→58.032 and 38.896→66.224 ms. Separate traced pairs, with identical instrumentation on both sides, measured allocation and promotion. Allocation sampling used a 32 KiB interval and included objects collected by both minor and major GC. Promotion came from complete, isolate-matched V8 trace windows; 75 collections from other isolates were excluded on each side in each pair. Both pairs completed all 1,200 reads and 1,200 committed writes per side.

Traced owner metric (2 swapped pairs) Base mean Candidate mean Signed paired delta
Estimated allocation, bytes/operation 760,658.1 683,869.7 −76,788.4 (−10.09%)
Promotion, bytes/operation 108,350.5 84,950.0 −23,400.5 (−21.59%)

Allocation sample counts were 54,389→48,866 and 54,552→49,027; allocation fell 9.93% and 10.26%. Target-isolate trace GC counts were 171→157 and 172→158; promotion fell 22.34% and 20.84%. Traced timings are not used as gates. One temporary traced-preload launch failed syntax parsing before the workload and is preserved as setup failure; the corrected probe passed independent review, and both complete measured pairs are included.

Decision: the owner retains 18.84% less memory, CPU falls consistently by 6.66%, estimated allocation falls 10.09%, and promotion falls 21.59%, with no adverse untraced latency or total-GC gate. No adverse GC/promotion/max-pause result required A/A rejection controls. Whole-worker retained-heap variation remains inconclusive. This is a small production simplification, ready for the lead's landing decision; it is intentionally unmerged.

The exact PR head d89f3ecd709c30c526d88cfe7e13f7d2fafbdb4e has an inherited PostgreSQL conformance (2/3) failure: seven interactive-setup.integration.test.ts cases fail before Gateway readiness because the isolated runtime omits standalone-runtime-profile.mjs. All seven test signatures and the missing-module cause match the newest scheduled main run at attribution time: main job 121006161355, main head 87f00b1b5254861d944e524cdd8bb3a65f53b59f; compare PR job 121006359977. Both report 7 failed / 271 passed in that batch. The failing test, its fixture builder, the importing module, and the root helper have identical blobs on both heads. The root helper/import arrived in upstream #182856; the fixture's explicit copy list omits it. This lane does not change those files. Logs were fetched once per completed job; no CI reruns were requested. All other code checks completed successfully (62 successful check runs; skipped/neutral checks recorded separately). The aggregate CI gate remains red because of that shard. Its automatic classification used the older successful main run 40134490303, which predates the upstream import; the newer matching main job above is the current attribution evidence.

Focused proof: actor kernel and native worker tests (24 tests), export-name collision guard, and both eager-import/PR-wrapper closure files (22 tests) passed. Participant-repair and entry-residency consumer tests also passed (18 tests). Changed-file formatting/lint and the targeted scripts typecheck (pnpm tsgo:scripts, native checker) passed.

Independent subagent review (autoreview route unavailable): production/test/docs and the benchmark were reviewed in separate scopes, with no actionable P0/P1/P2 findings. The configured autoreview provider did not match the operator configuration; no configuration was changed.

Reproduction is documented in scripts/perf/README.md; the new owner probe measures native reads after host-replica invalidation, real patch commits, operation counts, worker CPU/GC/event-loop samples, and post-GC heap. Promotion requires a separate traced pass and is not inferred from retained bytes.

Worker attribution and cache bounds
Owner Bound/lifetime and observed attribution
Transcript worker source loader 12,644,352 B in tsx's transform cache; Node ModuleLoader retains 15,784,328 B, including its LoadCache and ResolveCache. These are source-loaded fixture costs, not a production-memory estimate.
Transcript database scopes/history 64 database scopes; reader idle expiry is 30 minutes. Recent history retains 16 windows, each admitted at ≤1 MiB serialized. Visible history projections retain 16 sessions per connection; boundary collections have no independent byte cap. Connection disposal clears them.
Model-context navigation One snapshot per connection, with maxEvents decoded requests and boundary/model/thinking facts; prefix membership scales with history pages. Identity changes and disposal invalidate it.
SQLite worker source loader 50,258,296 B in the tsx transform-result Map; a sampled cached value contains transformed code and source-map data.
Native actors 128 sessions and an 8 MiB serialized budget, with one oversized-session allowance; transcript navigation is bounded at 512 rows. This fixture exercised four resident actors. The patch removes one duplicate decoded entry per actor.
Session listing metadata One complete metadata snapshot per connection, without a separate row/byte cap; full prompt snapshots are excluded. Tracked writes invalidate it and its lifetime follows the connection.
SQL statements and transport 64 statements plus 64 candidate strings per connection, with a 64 KiB SQL/bindings admission bound. One staged input/result transfer is cleared at completion/error; there is no persistent completed-reply cache.

Source owners: session-transcript-worker-scopes.ts, session-accessor.sqlite-history-query.ts, session-accessor.sqlite-history-projection.worker.ts, session-model-context-pages.ts, session-actor-residency.worker.ts, session-accessor.sqlite-entry-cache-state.ts, src/infra/kysely-sync-cache-state.ts, and src/infra/sqlite-store.worker.ts.

@clawsweeper

clawsweeper Bot commented Oct 24, 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 24, 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-25T00:07:47.259343Z e6b7e73 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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts size: M labels Oct 24, 2026
@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 24, 2026
@clawsweeper

clawsweeper Bot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR shares one actor-owned session entry across internal projections while preserving detached public reads and commit receipts.

Example: Four warmed durable actors with 36,514-byte session entries.

  • Before: The reported resident actor graph averaged 1,060,800 bytes.
  • After: The reported graph averaged 860,948.8 bytes, an 18.84% reduction.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is focused and source-supported, with useful reported runtime measurements; performance validation remains incomplete.
Proof confidence 🦐 gold shrimp (3/6) Ordinary contributor proof gating is exempt for this maintainer-authored PR; the body reports native-worker memory pairs and successful synthetic Gateway turns, while its timing comparison remains an explicit landing hold.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Active durable sessions retain redundant decoded copies of potentially large skill and system-prompt snapshots.
Reason: The maintainer-authored direction has a measured resident-memory benefit, minimal runtime changes, and no new runtime configuration; the new flags belong to the standalone benchmark.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR removes demonstrated duplicate session-entry retention without introducing an actionable correctness or security defect.

Priority: P2
Reviewed head: af23e09e62bd5e2b5a0b96050ad042bde624bb69

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The explicitly queued baseline/candidate timing comparison remains outstanding; the added isolation assertions preserve behavior rather than demonstrate a base-failing correctness regression.
Agent review details

How this fits together

The durable session worker receives actor commands, maintains resident database facts, and returns snapshots or committed receipts through the existing worker transport.

flowchart LR
  A[Gateway session actor] --> B[Worker transport]
  B --> C[Durable actor owner]
  C --> D[Shared owned entry]
  D --> E[Stored row and hot projection]
  C --> F[Detached reads and receipts]
  C --> G[Existing database writer]
Loading

Technical review

Best possible solution:

Keep one immutable actor-owned entry internally and preserve copying at incoming postimages, public reads, and receipt publication.

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

Current-main source independently shows the duplicate entry clones, and the PR reports paired native-worker measurements; this read-only review executed no target code.

Is this the best way to solve the issue?

The production diff is the smallest complete fix using the existing mutation and transaction owners, with distinct caller-isolation coverage retained at the worker boundary.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced ownership change: The pinned introduced diff clones incoming entries once, shares that object between stored rows and hot state, and removes the projection's additional entry clone. (src/config/sessions/session-actor-transaction.ts:99, af23e09e62bd)
  • Public isolation remains: Actor reads return structuredClone(before.hot); exact transaction entry reads clone selected.entry; committed outcomes pass through the existing receipt capture owner before publication. (src/config/sessions/session-actor.worker.ts:458, af23e09e62bd)
  • Rollback and nested caller mutation: The existing worker scenario now mutates nested fields in both a returned read and a commit receipt, verifies resident values remain unchanged, and retains its revoked-commit rollback checks. (src/config/sessions/session-actor-worker.test.ts:216, af23e09e62bd)
  • Current main still retains duplicate entries: Pinned main separately clones the entry into entryRows and hot state, clones it during projection, and clones participant-updated entries again. (src/config/sessions/session-actor-transaction.ts:100, 2c8189c63d3f)
  • Reported runtime measurements and explicit hold: The full PR body reports five alternating fresh-process memory pairs and a successful synthetic Gateway soak with eight measured turns and eight resets; it explicitly requires the queued timing comparison before landing. (af23e09e62bd)
  • Complete check pagination reveals an additional failure: The second check page contains a failed PR context and evidence job whose annotation alleges missing sections that are present in the current body; PostgreSQL conformance and the CI gate remain pending, and no source defect is established by these statuses. (af23e09e62bd)

Likely related people:

  • Peter Steinberger: Raw commit d5173cc adds src/config/sessions/session-actor-transaction.ts:16 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d5173ccc77b9; files: src/config/sessions/session-actor-transaction.ts)

PR surface

Source -2, Tests +2, Docs +35, Other +208. Total +243 across 8 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 6 8 -2
Tests 2 4 2 +2
Docs 2 35 0 +35
Config 0 0 0 0
Generated 0 0 0 0
Other 1 208 0 +208
Total 8 253 10 +243

Review metrics

Metric Value Why it matters
Production versus test growth Runtime production net −2 lines; tests net +2 lines The runtime fix removes duplicate copies, while the existing worker test gains nested isolation coverage; the separate 208-line benchmark supplies reproducible owner-level measurement.

Labels

Label changes:

  • add P2: This is a bounded memory improvement for resident durable sessions, with no demonstrated outage or urgent regression.
  • 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 bounded memory improvement for resident durable sessions, with no demonstrated outage or urgent regression.
  • 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 24, 2026, 6:04 PM ET / 22:04 UTC.

@steipete
steipete force-pushed the steipete/perf-session-worker-heaps-20261024 branch from af23e09 to d89f3ec Compare October 24, 2026 22:29
@steipete
steipete force-pushed the steipete/perf-session-worker-heaps-20261024 branch from d89f3ec to f7a266d Compare October 24, 2026 23:37
Retain one actor-owned decoded entry across hot state and stored rows while preserving detached public reads, commit receipts, and rollback preimages. Five paired worker snapshots reduce the four-actor resident graph by 18.84%; add a reproducible native-owner probe and strengthen caller isolation coverage.
@steipete
steipete force-pushed the steipete/perf-session-worker-heaps-20261024 branch from f7a266d to e6b7e73 Compare October 25, 2026 00:05
@steipete
steipete merged commit 8f5390d into main Oct 25, 2026
117 checks passed
@steipete
steipete deleted the steipete/perf-session-worker-heaps-20261024 branch October 25, 2026 00:27
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 25, 2026
…claw#182934)

* perf(sessions): share resident actor entries across projections

Retain one actor-owned decoded entry across hot state and stored rows while preserving detached public reads, commit receipts, and rollback preimages. Five paired worker snapshots reduce the four-actor resident graph by 18.84%; add a reproducible native-owner probe and strengthen caller isolation coverage.

* test(perf): synchronize paired actor command identities
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 P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts size: M 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