Skip to content

perf(sessions): share immutable actor snapshot revisions - #169726

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-session-actor-snapshot-clone-20260919
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-session-actor-snapshot-clone-20260919

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Repeated actor reads and callback handoffs copy the same session snapshot, adding CPU and allocation pressure to agent steps and session reads. This completes the actor snapshot work beyond the prepared-append path in #169651. Related: #169701.

User Impact

Reduces snapshot overhead without changing stored data, schema, configuration, or update behavior. Internal actor facts and receipts are read-only; consumers that need to edit them make an explicit copy. Public mutable entry projections retain their detached-copy behavior.

Why This Change Was Made

The replica already owned a frozen revision but cloned it on each disclosure. SQLite admission facts and native commit receipts were already detached by MessagePort and were cloned again for callbacks. Share those immutable objects through the existing owner and compare installed revisions by identity. Generation, scoped write-token, live authority, stale-read, and unknown-outcome checks remain at their existing boundaries. Failure bookkeeping replaces the frozen result instead of mutating it.

Incognito branch reconciliation copies only its editable result value when reconciliation is required; the durable receipt stays frozen. Both existing branch-replacement regressions caught and now cover this mutable consumer.

Production delta: 26 insertions / 28 deletions, net −2 lines across five production files. No parallel cache or compatibility path is added.

Evidence

Measurement first: isolated Linux rig, Node 26.8.1, baseline 9a1b712a9b80. A task-only driver exercises the real SQLite actor executor and replica with synthetic transport/receipt facts: a 76,154-byte snapshot, one patch plus eight snapshot reads per step. Three interleaved baseline/candidate pairs run 1,000 steps each. This measures the actor boundary, not full Gateway throughput or real worker transport latency. Team was not accessed.

Measurement Before After
1,000-step wall time, median 4,233 ms 1,321 ms
Pair wall-time range 3,418–4,789 ms 1,209–1,531 ms
Actor-owned clone calls, separate 20-step capture including cold start 443 2
JSON UTF-8 payload bytes passed to those clones 33,552,971 76,259
Warm-step actor clone calls 22 0
SQLite-attributed native clone SELF, mean / sampled share 540.7 ms / 12.55% 0 / 0%
Replica-attributed native clone SELF, mean / sampled share 2,333.3 ms / 54.16% 0.08 ms / 0.005%
Immutable traversal SELF, mean / sampled share 127.4 ms / 2.96% 351.1 ms / 22.99%

Median speedup: 3.20×. Immutable traversal costs more, but replaces substantially more cloning. SELF is exclusive V8 sampled elapsed time, with native clone leaves assigned to their nearest source caller; synthetic transport clones are counted separately and excluded from actor clone counts. Byte counts are input payload estimates, not measured heap allocations. Shared-host timing and this focused workload do not establish a new full-Gateway SELF share; the earlier 900-second discovery profile is motivation only.

Proof:

  • pnpm test src/config/sessions/session-actor.test.ts src/config/sessions/session-actor-replica.test.ts src/config/sessions/session-actor-entry-residency.test.ts src/config/sessions/session-actor-worker.test.ts --maxWorkers=1: 47 passed, 52.16 s wrapper wall time (47.15 s Vitest, including source transforms).
  • Both new immutable-sharing assertions fail on the original production files and pass on the candidate. Existing tests cover superseding receipts during reads/disclosure, generation retirement, unknown outcomes, native failures, and mutable public entry projections.
  • Changed-file oxfmt --check, repository run-oxlint.mjs, and git diff --check: passed.
  • Hosted review caught the incognito readiness mutator; it is fixed with a value-only copy on the rare reconciliation path. Fresh independent Codex review of the complete patch is scoped clean, with no actionable P0–P2 findings.
  • pnpm test src/state/openclaw-agent-execution-incognito.session-actor.test.ts --maxWorkers=1: 6 passed, 100.45 s wrapper / 27.81 s Vitest (actual tests about 3.4 s; most wall time is preparation/imports). Both metadata/event reconciliation cases first failed with the read-only-property TypeError and pass after the fix.
  • No Testbox/Crabbox leases. Per lane instructions, broad typecheck, suites, and integration gates run in PR CI; Both exact-head runs ended under fail-fast after independently reproduced inherited failures. Unfinished typecheck, build, UI, and test lanes were cancelled and are not claimed as passing coverage.

Inherited CI failure: the existing attempt-transcript-lifecycle-prepare.test.ts case “uses a stale-version postimage once without replaying a durable append (incognito=false)” deliberately injects an invalid epoch and expects a retry removed by the prepared-append cutover. The same case fails with SessionActorStaleVersionError on an isolated, unchanged main snapshot at f0a14bf986e6085af1425c00f4d172f45a70ef8d (1 failed / 33 skipped, 147.79 s wrapper wall time). Relevant baseline source files were verified against Git blob IDs. The failing test and append caller are unchanged between the original CI baseline and that main snapshot. No CI rerun was requested.

Final-head CI qualification: run 38222685831 tested cb382da67fdf16242f8ae2fb02d6ac33938f44a5 merged with main ccb7b5f7e5de8e0e6c3bd20030c902d2134e9a15. Its sole originating failure is type-suppression-inventory.test.ts: an unchanged cleanup helper contains a nineteenth suppression while the unchanged inventory expects eighteen. Running that test on the exact unchanged main baseline reproduces the same mismatch (1 failed / 3 passed, 5.34 s wrapper / 3.95 s Vitest). Scanner, expectation, and helper blob IDs match the baseline. Security-fast passed; the successful fail-fast monitor cancelled unfinished siblings. Landing uses the authorized inherited-failure exception; no CI rerun or green-chasing push was requested.

Reuse frozen actor revisions for reads and callback handoffs while preserving generation, write-token, and live authority checks. Consumers that edit facts explicitly clone their working copy.
@clawsweeper

clawsweeper Bot commented Oct 12, 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.

@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 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR shares immutable session actor snapshots and callback evidence instead of repeatedly cloning them.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused performance evidence supports the optimization, but a missed mutable consumer introduces a concrete reconciliation failure.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization is outside the ordinary contributor proof gate; its supplied benchmark exercises the real executor and replica with synthetic transport and receipts.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Repeated snapshot copying adds CPU and allocation overhead during agent steps and session reads.
Reason: The maintainer-authored direction has a bounded benchmark, removes redundant copying through existing owners, and introduces no product knobs.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this useful performance PR open, but fix the incognito reconciliation callback before merging: it still mutates the newly frozen commit value.

Priority: P2
Reviewed head: 6d8aef7b4d88a9422887c1b176a7805854702814

Before merge

  • [P2] Copy the incognito reconciliation value before editing it (P2) - This now passes the frozen native outcome directly to the incognito transport’s afterCommitted. When an append replaces a transcript branch, that callback reconciles successfully and then assigns projectionNeedsReconcile = false on outcome.value or its nested append/header values. Those assignments now throw TypeError, so the executor returns a committed outcome with a failure and leaves the returned readiness flag true. The existing metadata/event branch-replacement test in src/state/openclaw-agent-execution-incognito.session-actor.test.ts covers this input. Update that production callback to copy its editable value while preserving the immutable receipt.

Findings

  • [P2] [P2] Copy the incognito reconciliation value before editing it — src/config/sessions/session-actor-sqlite.ts:406

Tests

  • Missing end-to-end proof: The reported validation excludes the existing incognito branch-replacement integration scenario, and no shipped Gateway run is supplied.
Agent review details

How this fits together

The Gateway’s session actor executor authorizes reads and writes, receives SQLite worker commit evidence, and installs snapshots in its existing bounded replica for callers.

flowchart LR
  A[Session callers] --> B[Actor executor]
  B --> C[Live authority checks]
  B --> D[SQLite worker]
  D --> E[Native commit evidence]
  E --> F[Immutable replica]
  F --> A
  E --> G[Postcommit reconciliation]
Loading

Technical review

Best possible solution:

Keep shared immutable revisions and copy only the value that incognito postcommit reconciliation needs to edit.

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

Source tracing shows the frozen commit value reaching an in-place mutation after incognito branch replacement, and an existing integration test supplies the exact scenario; no target code was executed during this read-only review.

Is this the best way to solve the issue?

Sharing revisions through the existing replica is a focused optimization, but the immutable contract must also reach the existing reconciliation consumer.

Full review comments:

  • [P2] [P2] Copy the incognito reconciliation value before editing it — src/config/sessions/session-actor-sqlite.ts:406
    This now passes the frozen native outcome directly to the incognito transport’s afterCommitted. When an append replaces a transcript branch, that callback reconciles successfully and then assigns projectionNeedsReconcile = false on outcome.value or its nested append/header values. Those assignments now throw TypeError, so the executor returns a committed outcome with a failure and leaves the returned readiness flag true. The existing metadata/event branch-replacement test in src/state/openclaw-agent-execution-incognito.session-actor.test.ts covers this input. Update that production callback to copy its editable value while preserving the immutable receipt.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Replica retention and disclosure changes intended behavior with a stated reason (d5173cc: The actor replica isolated retained state from borrowers; later entry-residency work retained complete frozen postimages.)
  • Admission callback isolation changes intended behavior with a stated reason (d728205: A detached callback copy prevented mutable policy callbacks from rewriting native commit evidence; this PR deliberately substitutes frozen shared facts.)
  • Superseding reads and disclosure checks keeps the original intent (fcf234a: Reads overtaken by committed receipts return newer authorized facts instead of failing a completed turn; the patch retains that recovery behavior.)
  • Postcommit callback working copies changes intended behavior with a stated reason (unknown: The existing incognito adapter edits a detached readiness value while preserving native receipt evidence. Local git log -S could not traverse unavailable historical blobs to establish its introduction.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/state/openclaw-agent-execution-incognito.session-actor.test.ts --maxWorkers=1
  • pnpm test src/config/sessions/session-actor.test.ts src/config/sessions/session-actor-replica.test.ts --maxWorkers=1
  • pnpm exec oxfmt --check src/state/openclaw-agent-execution-incognito-session-actors.ts
  • git diff --check

What I checked:

Likely related people:

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

PR surface

Source -3, Tests +20. Total +17 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 24 27 -3
Tests 2 28 8 +20
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 52 35 +17

Review metrics

Metric Value Why it matters
Production versus test LOC Production +24/-27; tests +28/-8 The optimization reduces production code while extending existing fixtures to check sharing and mutation isolation.

Labels

Label changes:

  • add P2: A useful internal performance improvement has a concrete, bounded incognito reconciliation regression that needs repair before merge.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦐 gold shrimp and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: A useful internal performance improvement has a concrete, bounded incognito reconciliation regression that needs repair before merge.
  • 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.

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 12, 2026, 3:54 AM ET / 07:54 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Fixed the incognito reconciliation finding in cb382da: the existing callback copies only outcome.value when reconciliation is required, then edits that working value while preserving the immutable native receipt. Both metadata/event branch-replacement cases reproduced the TypeError before this fix; the complete incognito actor file now passes all six tests. Fresh independent review of the full patch found no actionable P0–P2 findings.

The original CI failure is independently reproduced on unchanged main f0a14bf: attempt-transcript-lifecycle-prepare.test.ts still expects a stale-version retry in the prepared-append path. The PR body records that baseline proof and the unfinished coverage cancelled by fail-fast. The new head has its own CI run; no rerun was requested.

@steipete

Copy link
Copy Markdown
Contributor Author

Landing under the authorized inherited-failure exception on cb382da.

The sole originating failure in CI run 38222685831 is type-suppression-inventory.test.ts: the inventory expects 18 entries, but unchanged scripts/lib/managed-cleanup-handoff.mts contributes a nineteenth Bun-specific suppression. The same test fails on unchanged CI base ccb7b5f (1 failed / 3 passed; 5.34 s). The scanner, test, and helper blob IDs match. The successful fail-fast monitor cancelled unfinished siblings; those jobs are not passing evidence. No CI rerun was requested.

Local proof: 47 actor/replica/worker/residency tests and all 6 incognito actor tests pass, changed-file lint/format passes, and fresh independent review is clean. The hosted incognito reconciliation finding is fixed with a value-only copy. The earlier stale-version retry test also reproduces on unchanged main; it was not the originating failure of the final run.

The native merge wrapper stopped before submission because this lane has no separate wrapper review worktree. Using the explicitly authorized, exact-head REST fallback.

@steipete
steipete merged commit 230ea68 into main Oct 12, 2026
99 of 134 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-actor-snapshot-clone-20260919 branch October 12, 2026 08:32
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…9726)

* perf(sessions): share immutable actor snapshot revisions

Reuse frozen actor revisions for reads and callback handoffs while preserving generation, write-token, and live authority checks. Consumers that edit facts explicitly clone their working copy.

* fix(sessions): copy incognito readiness before editing shared facts
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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. 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