Skip to content

perf(sessions): charge shared actor entry fields once in the replica pool - #199748

Merged
steipete merged 3 commits into
mainfrom
steipete/perf-actor-entry-interning-20261115
Nov 15, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/perf-actor-entry-interning-20261115

Conversation

@steipete

@steipete steipete commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The session actor replica budget charges each session for large skills snapshots that are already shared on the main heap. Repeated immutable prompt-report sections are also retained separately. This causes avoidable eviction within the existing 8 MiB / 128-replica limits.

User Impact

More session replicas fit within the existing memory budget. Stored entries, model context, authority checks and all wire encoders remain unchanged. Existing resident-entry references may be used more often because fewer replicas are evicted.

Why This Change Was Made

Charge each interned field once per replica pool, counting resident references and releasing the shared charge when the last resident reference goes away. Extend the existing bounded weak interner to immutable report sections while keeping session-specific report provenance separate.

The full wire-reference proposal is held separately at steipete/perf-actor-entry-wire-refs-20261115, commit e60041e30a5da06f5f6c21afdadb75b26e2e31f5. This PR contains no advertised field keys, command pins, worker field references or admission restoration. The coordinating maintainer will decide whether to revive that proposal after production component counters are available.

Evidence

Measurement acceptance: run the existing native append fixture on current main and the residency-only candidate at 2, 100, 200 and 400 sessions; record resident replicas and pool bytes, then measure post-GC main heap at 100 sessions. Compare resident and evicted native request/admission/receipt byte counts with identical fixture paths. Five actual-append rounds of 100 sessions per side measure main-thread CPU and allocation separately, including replica updates and excluding wire-capture instrumentation. The expected win is residency and memory accounting; per-append CPU/allocation should remain neutral or improve. Preserve model-context hashes and the existing wire shapes.

Baseline: 987c04a0086963d301cb4e440c758acc7178c7b6 (current main when measurement began). The synthetic entry contains a ~110 KB skills snapshot and a ~20 KB prompt report. Across 100 sessions there is one skills snapshot, 100 reports with distinct session provenance, and one value for each of four immutable report sections.

Active sessions Resident replicas, before → after Accounted pool bytes, before → after
2 2 → 2 626,376 → 334,270
100 27 → 100 8,125,902 → 2,633,858
200 27 → 128 8,126,388 → 1,427,546
400 27 → 128 8,126,388 → 1,427,430

Pool bytes are the owner's heap estimate, not physical heap measurements. The separate 100-session post-GC pass measured main heap 146.880 → 143.306 MiB (−3.574 MiB), and whole-process RSS 1,520.474 → 1,444.718 MiB. RSS includes native workers and is contextual.

Actual native append workload Main CPU per append, before → after Sampled main allocation per append, before → after Samples per side per mode
100 active sessions 1.582 → 1.381 ms (round medians) 588,993 → 369,651 B (mean) 5 × 100 appends
200 active sessions, AB then BA 1.580 → 1.622 ms (paired means) 623,841 → 610,710 B (paired means) 2 × 5 × 200 appends

At 100 sessions, fewer replica misses also reduce append work through the existing resident-token protocol. With 200 sessions, both sides still miss during sequential churn. Allocation fell 2.25% and 1.96% in the two cold-path pairs. CPU changed +201 µs then −117 µs per append (+12.8%, −7.3%); the signed absolute mean is +42 µs (+2.7%), so CPU is inconclusive rather than an adverse result. One-minute host load varied roughly 15–24. Untraced GC at 100 sessions fell 0.0381 → 0.0120 ms/append (10 → 5 collections; max 2.885 → 1.849 ms). At 200 sessions, total GC was effectively flat at 0.06375 → 0.06348 ms/append, 70 collections per side across both pairs, with maximum pauses 4.950 → 4.079 ms. No percentile gates are claimed from these small collection counts.

Wire equality: with matching residency, every captured admission/receipt byte count and every model-context hash matches main. Main→worker totals also match. At 2 resident sessions, per-append mean request/admission/receipt sizes are 1,931 / 1,990 / 5,260 B on both sides. At 200 evicted sessions they are 1,922.66 / 133,195.6 / 5,564.45 B on both sides; the 400-session comparison also matches. At 100 sessions, retaining all entries uses the existing resident-token path more often: admission bytes fall 133,191.2 → 2,003.4 B, request bytes rise 1,918.02 → 2,169.82 B, and receipts remain 5,553.05 B. This is a change in existing path selection, not an encoding change. All admission, command, worker, receipt and authority implementations are unchanged from main. The current authority Prometheus byte counter omits ordinary native admissions; no production counter improvement is claimed.

Reproduction (same --output path for both arms, move each completed report aside before running the other):

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/session-append-receipt-measure.ts \
  --output .local/residency-run --mode census --sessions 100 --rows 4 --rounds 1 --text-repeats 20
# Census: repeat with 2, 200 and 400 sessions. Heap: --mode heap, 100 sessions.
# Actual append work: --mode append-timing / append-allocation --rounds 5,
# at 100 and 200 sessions; reverse launch order for the second 200-session pair.

The existing pool-budget regression fails on main because replicas with a shared large prompt are evicted before reaching 128 entries. It also exercises retiring distinct shared values before admitting the next cohort. The former 16 KiB admission-budget regression is removed from this PR and remains on the held branch.

Runtime production delta: +86 LOC. Growth implements explicit shared-value accounting and immutable report-section interning; the former skills-only sharing path is replaced. The interner retains at most 256 weak lookup entries, and resident pool references are released with their last cell. No persisted shape, schema, configuration, or public contract changes. Author simplification removed command pinning, advertised keys, worker projections, admission restoration, wire-only tests and replay tooling from this PR. The remaining benchmark measures actual native appends.

All 106 focused tests passed: 68 actor/replica/worker tests, 14 prefix-stability tests and 24 eager-import/wrapper-closure tests. The matching session test typecheck and pnpm tsgo:test:root passed, as did changed-file lint/format, the assertion-safety and export-collision guards, and git diff --check. The test delta is +7 lines with an exact allocation entry. Runtime source is +86 LOC; the prescribed non-test diff including benchmark tooling is +196 LOC. On final head bcc0e285c84422a45f0aa06a1d3033110ade3e5d, CI run 43763608489 completed with one infrastructure failure: check-test-types timed out during all five checkout attempts and never ran TypeScript. The other required build, lint, typecheck and test jobs passed, including PostgreSQL conformance and its PostgreSQL 16 smoke. pnpm tsgo:test:root was rerun locally on this exact head and all four scopes passed (4.6/4.8/4.8/5.5 seconds). The local retry command was refused; no CI rerun was executed. The aggregate CI gate therefore remains red and needs checkout-job recovery by the coordinating maintainer. No production load or full Gateway stress was run; this is the requested residency-only owner/native-transport comparison. Independent review and merging remain with the coordinating maintainer.

@clawsweeper

clawsweeper Bot commented Nov 15, 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 Nov 15, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T22:31:17.870533Z 79235ca 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 scripts Repository scripts size: L labels Nov 15, 2026
@clawsweeper clawsweeper Bot added the clawsweeper:intake:feature Preliminary submission classification; full source review pending. label Nov 15, 2026
@steipete
steipete force-pushed the steipete/perf-actor-entry-interning-20261115 branch from 7fba73c to e60041e Compare November 15, 2026 20:24

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e60041e30a

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +24 to +25
for (const field of reportFields) {
const value = internSessionEntryField(report[field]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip absent report sections when sharing entry fields

When a persisted entry contains a sparse report such as systemPromptReport: { source: "run" }—an existing storage shape exercised in session-accessor.sqlite-prepared-reads.test.ts:57—report[field] is undefined. Passing it to internSessionEntryField throws TypeError: Cannot use 'in' operator to search for 'prompt' in undefined. Snapshot decoding does not populate missing sections, so previously readable entries now fail replica retention; the identical unconditional hashing in projectSessionActorEntryFields also prevents cold commands from reaching admission. Only intern and project sections that are present, preserving omitted sections unchanged.

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR shares immutable session-entry fields across replicas and compresses worker admission messages using their content keys.

Example: 100 active sessions share the same skills inventory and prompt-report sections.

  • Before: The supplied benchmark retains 27 replicas and transfers 138,736 admission-and-receipt bytes per append.
  • After: The supplied benchmark retains 100 replicas and transfers 7,588 bytes per append.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful owner-boundary performance evidence supports the optimization, but the persisted sparse-report failure blocks merge.
Proof confidence 🦐 gold shrimp (3/6) Sufficient (live_output): The supplied measurements exercise SessionManager appends through native workers and capture complete admission requests and receipts under replica pressure; source inspection matches that scenario, while whole-Gateway performance remains outside the claims.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Busy multi-session workloads repeatedly copy large unchanged entry fields and evict replicas whose shared payloads are charged repeatedly.
Reason: The maintainer-authored direction has substantial measured transport and allocation savings without adding configuration or changing persistence.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this maintainer-authored PR provides a measured performance improvement, but a confirmed sparse-report regression needs repair before merge.

Priority: P2
Reviewed head: e60041e30a5da06f5f6c21afdadb75b26e2e31f5

Before merge

  • Skip absent report sections in both field-sharing paths (P2) - A persisted entry with systemPromptReport: { source: "run" }, already exercised by session-accessor.sqlite-prepared-reads.test.ts:57, has undefined report sections. This call passes undefined to sessionEntryFieldKey, where "prompt" in snapshot throws. Stored snapshot decoding preserves that shape, so actor reads fail during replica retention; the equivalent unconditional call at line 79 also rejects cold commands before admission. Skip omitted sections in both loops, preserve their absence, and add an actor-boundary regression for this existing stored shape. This independently confirms the earlier review comment: perf(sessions): charge shared actor entry fields once in the replica pool #199748 (comment).

Findings

  • [P2] Skip absent report sections in both field-sharing paths — src/config/sessions/session-actor-entry-fields.ts:24-25
Agent review details

How this fits together

The session actor connects session operations to the database worker; replicas retain immutable entry facts, and admission messages deliver those facts to host authority callbacks before writes settle.

flowchart LR
  A[Session operations] --> B[Actor executor]
  C[Replica pool] --> B
  B --> D[Database worker]
  D --> E[Admission restoration]
  C --> E
  E --> F[Authority callbacks]
  D --> G[Committed receipts]
Loading

Technical review

Best possible solution:

Preserve omitted report sections in both sharing loops while retaining the existing interner, replica accounting, and command-local reference restoration.

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

Source establishes the failure: the existing persisted {source:"run"} report reaches unconditional hashing of undefined sections; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Extending the existing immutable-field interner and replica owner is coherent; the necessary invariant is that compression preserves every accepted entry shape and restores complete authority facts.

Full review comments:

  • [P2] Skip absent report sections in both field-sharing paths — src/config/sessions/session-actor-entry-fields.ts:24-25
    A persisted entry with systemPromptReport: { source: "run" }, already exercised by session-accessor.sqlite-prepared-reads.test.ts:57, has undefined report sections. This call passes undefined to sessionEntryFieldKey, where "prompt" in snapshot throws. Stored snapshot decoding preserves that shape, so actor reads fail during replica retention; the equivalent unconditional call at line 79 also rejects cold commands before admission. Skip omitted sections in both loops, preserve their absence, and add an actor-boundary regression for this existing stored shape. This independently confirms the earlier review comment: perf(sessions): charge shared actor entry fields once in the replica pool #199748 (comment).
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Immutable entry-field sharing keeps the original intent (d18033a: Share identical retained skills snapshots while preserving serialized bytes and mutable native-accessor isolation.)
  • Command-local admission and receipt references keeps the original intent (059f958: Retain the authoritative admission preimage through settlement so receipt compression survives replica eviction.)
  • Replica residency accounting changes intended behavior with a stated reason (4821920: Reuse recorded transcript charges while preserving bounded residency; this PR explains counting shared immutable values once.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/config/sessions/session-actor.test.ts src/config/sessions/session-actor-replica.test.ts src/config/sessions/session-accessor.sqlite-prepared-reads.test.ts --maxWorkers=1
  • pnpm tsgo:test:root
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit bc97659 adds src/config/sessions/session-actor-replica.types.ts:27 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: bc9765989862; files: src/config/sessions/session-actor-replica.types.ts)
  • Josh Avant: Raw commit 4821920 adds src/config/sessions/session-actor-replica.types.ts:24 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4821920804c9; files: src/config/sessions/session-actor-replica.types.ts)

PR surface

Source +199, Tests +95, Other +75. Total +369 across 16 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 246 47 +199
Tests 3 155 60 +95
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 4 149 74 +75
Total 16 550 181 +369

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The optimization has measurable value, with a focused compatibility defect affecting entries containing incomplete prompt reports.
  • merge-risk: 🚨 compatibility: Previously readable persisted sparse reports can now throw during replica retention or cold command admission.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 November 15, 2026, 3:41 PM ET / 20:41 UTC.

@steipete steipete changed the title perf(sessions): share actor entry fields across replicas and admissions perf(sessions): charge shared actor entry fields once in the replica pool Nov 15, 2026
@steipete
steipete force-pushed the steipete/perf-actor-entry-interning-20261115 branch from e60041e to 967ab87 Compare November 15, 2026 21:16

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 967ab87c1f

ℹ️ 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".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

capture = round >= 0;
before = captured.length,
admissionsBefore = admissions.length;
capture = round >= 0 && !measureAppends;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Limit receipt replay to modes that retain captured receipts

Running --mode append-timing or --mode append-allocation leaves captured empty because capture is disabled here; --mode heap also empties it after each append. However, the replay block still runs for every mode other than census. Its worker consequently sends undefined from the empty receipts array, causing the committed-receipt assertion to throw before result.json is written. All three new measurement modes therefore fail to report their results. Restrict receipt replay to the existing timing and allocation modes.

Useful? React with 👍 / 👎.

…pool

Count interned skills and immutable report sections once per pool, releasing the shared charge with its last resident reference. Keep admission, receipt and command encoders unchanged. Synthetic 100-session residency rises from 27 to 100 while post-GC main heap falls 3.57 MiB.
…ntry-interning-20261115

# Conflicts:
#	scripts/perf/session-append-receipt-measure.ts
@steipete

Copy link
Copy Markdown
Contributor Author

Merged current main to resolve a conflict in scripts/perf/session-append-receipt-measure.ts with #199767. Both PRs extended that benchmark harness in different directions. I kept main's version (the #199767 authority-component harness), so this PR no longer changes the benchmark script.

The residency numbers in the description were measured at bcc0e285 with that head's harness modes (heap, append-timing, append-allocation). Those modes are not on main after this merge. Runtime and test changes are unchanged from bcc0e285. Target tests pass locally (77/77, including the 14 prefix-stability tests), and pnpm tsgo:test:root passes.

@steipete
steipete merged commit eee22b4 into main Nov 15, 2026
132 of 133 checks passed
@steipete
steipete deleted the steipete/perf-actor-entry-interning-20261115 branch November 15, 2026 22:54
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…pool (openclaw#199748)

* perf(sessions): charge shared actor entry fields once in the replica pool

Count interned skills and immutable report sections once per pool, releasing the shared charge with its last resident reference. Keep admission, receipt and command encoders unchanged. Synthetic 100-session residency rises from 27 to 100 while post-GC main heap falls 3.57 MiB.

* perf(sessions): match residency test allocation to net growth
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 17, 2026
…pt report

Upstream eee22b4 (openclaw#199748) interns every system-prompt report subtree
(systemPrompt, injectedWorkspaceFiles, skills, tools) when it shares an
actor entry. This fixture cast a report holding only `tools`, so each case
failed with "snapshot is not an Object". Supply the four required subtrees.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Nov 19, 2026
…rk fixtures

Compile and behavior follow-through for upstream APIs the merge brought in,
each red on ddd0ec7 and green here:
- sessions-spawn-cloud: upstream's new paired-device case (openclaw#197469) mocks
  registerRun as void; the fork's registration returns ownership, so the mock
  returns a committed-row ownership (tsgo agents-tools TS2322; 16/16).
- finishPendingInput now takes an end cause (openclaw#200533): the fork's recorder
  case and transcript-events case pass "failed" (tsgo other TS2554).
- postcompaction-autocompaction: upstream's SessionMaintenanceRequest needs
  sourceTarget/sourceIdentities (prepareSessionMaintenanceRequest), so the
  command case prepares the request before scheduling (TS2739); the
  pressure-handoff report supplies the four subtrees upstream interns
  (openclaw#199748; 10 cases "snapshot is not an Object" without it, from chain
  47edd05); and the required-compaction-failure case crosses the 200k
  window with a new fitting-request case for openclaw#200714's fit-only preflight
  failure (from staging ead2225; red at 150k without it). 13/13.

(cherry picked from commit 47edd05)
Refs openclaw#129388

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

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: S status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant