Skip to content

perf(sessions): skip snapshot reads for prepared appends - #169651

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-structuredclone-hot-paths-20260919
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-structuredclone-hot-paths-20260919

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every prepared SessionManager append clones the complete resident actor snapshot merely to send its version back to the worker. The copy grows with the session's transcript indexes.

User Impact

Reduces copying during active conversations without changing transcript contents, ordering, configuration, or update behavior.

Why This Change Was Made

Prepared appends do not derive their mutation from a host snapshot. The worker already selects its current preimage inside the writer transaction when expected is omitted, then checks transcript predicates and current authority. Submit that command directly, removing the eager snapshot and unnecessary version retry. Operations that derive input from a snapshot retain their version checks.

Mutable policy callbacks and commit observers keep their existing isolation. Native commit custody and uncertain-outcome handling are unchanged. Production delta: 6 insertions, 12 deletions; net -6 lines.

Evidence

Independent reviews were clean through P2, including the rebased worker implementation and the test-only lint correction. The initial CI run identified an unbound test callback; the callback now retains its receiver, and the file-scoped typed lint check passes.

The native-kernel regression covers ordinary and tool-result appends with current write authority but revoked snapshot disclosure. Both cases fail on the original eager read and pass with this change. The full actor file passed 17 tests in 37.65 s (node scripts/run-vitest.mjs src/config/sessions/session-actor.test.ts --maxWorkers=1); the new cases took 209 ms and 287 ms. This proof ran on AWS Crabbox cbx_2f08fabae387 before rebasing. The sibling run passed 397 tests and exposed one pre-existing headline expectation, already repaired by #169327 and incorporated through the rebase. Final-head CI passed on 2a7ec7b07df796eac76eee68a129f5f282ee2296. The changed-test CI job took 271 seconds including setup and other selected tests.

A controlled production-owner benchmark used 20 resident durable actors and 2,000 appends per run, real SQLite workers/admission, and verified persisted transcript counts. Three uninstrumented profiles per variant and a separate clone census ran on the same isolated Linux rig, comparing c8dea3b59901 with the append change:

Measurement Before After
Median clone share of busy host-thread CPU 13.46% 8.67%
Explicit clone calls 16,000 12,000
Serialized copied-data estimate 266.94 MB 167.09 MB

This removes exactly two replica-read clones per warm append, cutting clone calls by 25% and the copied-data estimate by 37.4%. Serialized bytes estimate data copied; they are not a V8 heap-allocation measurement. Overall timing was noisy, so this PR makes no wall-time or total-CPU speedup claim.

Scope: the benchmark measures the production append owner, not the whole Gateway. The separate 20-model-session Gateway stress attempt repeatedly lost its shared WebSocket while the Gateway remained alive, so whole-Gateway CPU share and live-load latency remain unverified. No live deployment was modified.

Let the serialized worker choose the current actor preimage for prepared SessionManager appends. Preserve transcript predicates, live authority checks, and commit receipts while avoiding two full replica copies per warm append.
@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.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Oct 12, 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 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR submits prepared transcript appends without first copying the session actor snapshot or supplying its version.

Example: Persist a tool result containing "prepared result" during an active conversation.

  • Before: The host copies resident actor state to obtain and validate a version before submitting the append.
  • After: The worker selects current state inside its serialized transaction and persists the same result.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, narrowly correct optimization supported by production-owner measurements and focused regressions; shipped-entry-point performance remains unverified.
Proof confidence 🦐 gold shrimp (3/6) The task identifies this as maintainer-authored and outside the ordinary contributor proof gate; the supplied benchmark exercises the append owner with real SQLite workers, and the regression uses real kernels through an in-process transport harness.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Active conversations repeatedly copy growing transcript indexes merely to submit already-prepared writes.
Reason: The established feature owner proposes a measured simplification using an existing contract, with no new option, storage model, or competing owner.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR makes a useful, focused performance improvement through the existing session owner, with no introduced correctness or security defect found.

Priority: P2
Reviewed head: 2a7ec7b07df796eac76eee68a129f5f282ee2296

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied measurements cover the production append owner; the reported whole-Gateway stress attempt did not establish end-to-end performance.
Agent review details

How this fits together

SessionManager supplies prepared transcript mutations to the session actor, which commits them through the SQLite worker and returns native persistence receipts.

flowchart LR
A[SessionManager] --> B[Prepared append]
B --> C[Session actor]
C --> D[Serialized SQLite worker]
D --> E[Transcript predicates and live authority]
E --> F[Native commit]
F --> G[Receipt and publication]
Loading

Technical review

Best possible solution:

Use the worker’s transactional preimage for prepared appends while retaining version checks for operations derived from snapshots.

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

Current-main source shows the redundant snapshot/version path, and the supplied controlled benchmark reports its copying cost; no target code was executed during this review.

Is this the best way to solve the issue?

The change uses the existing optional-version contract at the caller that creates unnecessary work, preserving transcript predicates, serialized execution, and native settlement.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Prepared append snapshot selection and version retry changes intended behavior with a stated reason (ef6747c: Keep snapshot selection and the bounded stale-version retry within one writer FIFO reservation after concurrent participant writes caused session creation failures.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 5843d60 adds src/agents/sessions/session-manager-actor-append.ts:26 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5843d60cb445; files: src/agents/sessions/session-manager-actor-append.ts)

PR surface

Source -6, Tests +61. Total +55 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 12 -6
Tests 1 62 1 +61
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 68 13 +55

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +6/-12; tests +62/-1 Production shrinks while two parameterized cases protect prepared persistence without snapshot disclosure.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: A bounded performance improvement reduces growing transcript-index copying without changing configuration or intended conversation behavior.
  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-12T05:57:33.898Z sha 7b7b6ef :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 2:39 AM ET / 06:39 UTC (Revision 2).

@steipete
steipete merged commit 6703060 into main Oct 12, 2026
115 checks passed
@steipete
steipete deleted the steipete/perf-micro-structuredclone-hot-paths-20260919 branch October 12, 2026 06:47
steipete added a commit that referenced this pull request Oct 12, 2026
)

## What Problem This Solves

Transcript context, search, and rebuild paths repeat reads of facts already owned by the Gateway. The bundled memory visibility loader also enters the synchronous session-store path.

## User Impact

No configuration or storage-format change. Bundled memory visibility loads the complete cross-session view through the existing worker. The public synchronous loader remains compatible, emits a bounded deprecation warning, and is scheduled for removal in the next SDK major; its replacement is `loadCombinedSessionStoreForGatewayAsync`.

## Design

Use committed admission receipts for transcript bounds, return the completed search snapshot with projection readiness, and stop recounting/rechecking acknowledged rebuild work. Final publication retains source validation and bounded append catch-up. SQL projections that avoid materializing large payloads remain in SQL.

Removed checks and accepted edges:

- Admission identity/role/generation reread: direct SQLite edits outside the Gateway owner are unsupported; the admission receipt supplies committed bounds. Store/session/user-role validation and effect-boundary authority remain.
- Search connection revision reread: an append racing a completed search appears on the next search.
- Rebuild claim source/clean-index rereads: stale prepared work can temporarily dirty a derived index before final publication rejects it.
- Rebuild chunk recount/classification reread: acknowledged chunks are authoritative; final source validation remains.

Native-incognito paths remain for the separate incognito-removal migration. Deprecated public synchronous contracts and explicit offline maintenance remain honestly classified. Follow-up target/caller cutovers are being shipped separately; this PR does not claim the entire lane is at zero.

## Evidence

- Two Codex autoreview rounds completed without actionable findings.
- Before the testing-policy change: 28 focused suites / 402 tests passed. These cover admitted context, append catch-up, complete async projection fields, incognito exclusion, and zero caller-thread SQL in the async SDK loader. The last changed/mock-consumer batch passed 75 tests in 646.8 seconds.
- Local changed-file oxfmt, oxlint, and `git diff --check` pass.
- Ordinary PR CI run 38213044338 passed at `d23ecfbd6fe8691909e8c25445df2258de353106`, including the repaired built lifecycle fixture. Static CI run 38214212751 passed production/full Knip export scans, all types/lint, source contracts and ratchets; SDK API diff passed (base `4de0aa670075`, head `d23ecfbd6fe8`, acknowledgement `99e4d8f2`). Its unused-file check found two unrelated script entrypoints; main removed both in `3a20164800a9`, now incorporated conflict-free in `91338fabd80f7`. Final static run 38217360424 passed types, lint, source contracts, database ratchets and SDK diff (digest `5ff6265e`); it tests byte-identical PR1 source files as part of child head `3254d6171c275`. Madge reports zero cycles. Knip fails identically on main run 38216343022 in untouched UI exports `ComposerRunStatusContent` and `ChatPaneVersionsMenu`; this is an inherited static failure. Final PR1 ordinary CI 38221257521 at `1dcc93a2641d5` fails only the untouched stale-version actor test, whose implementation came from main #169651. These failures use the authorized inherited-failure landing route.
- Owned lexical T1 sites: **27 → 23** (read fence 1 → 0, rebuild 12 → 10, search 4 → 3). These are source sites, not per-turn statements.
- Two live alternating baseline/candidate pairs completed (the v6 pair plus the RAW TURN INCREASE follow-up). Source base `403e966fa7814238ad9fb67bc93641a59b04af1e`, candidate `95d395c19a94e5781df0f3d2827f944aef462288`; later changes are CI test-fixture repairs and conflict-free main integration. Shared workload is unchanged; temporary state is isolated on external storage.

| Metric | Base median [min–max] | Candidate median [min–max] |
| --- | ---: | ---: |
| Warmed all-thread statements/turn | 350.45 [348.2–352.7] | 340.15 [323.1–357.2] |
| Warmed requests/turn | 107.4 [107.2–107.6] | 104.9 [98.9–110.9] |
| Warmed MAIN statements/turn | 0.3 [0.2–0.4] | 0.1 [0–0.2] |
| Whole-workload statements | 9,968.5 [9,941–9,996] | 9,920.5 [9,633–10,208] |
| Whole-workload requests | 2,070.5 [2,046–2,095] | 2,052 [1,950–2,154] |

The first pair increased whole-workload statements/requests by 267/108; the follow-up decreased them by 363/145, satisfying the RAW TURN INCREASE lower-total condition. Warmed transcript publication remains exactly 27 statements / 7 requests per turn in all four runs. Whole-workload transcript publication was 478/103 → 478/103, then 477/102 → 478/103; Memory publication was 451/113 → 492/128, then 605/153 → 297/77; model context was 27/5 → 49/8, then 29/5 → 34/6. The trace shows existing context fallback after Memory writes but does not identify the failed fallback predicate.

Host load and background work varied substantially, so these results do not establish a causal SQL saving or runtime speedup. Warmed candidate/base duration ratios were 1.328 and 0.212. All four runs completed 13 turns, child execution, cron, compaction and shutdown. The first candidate's optional `mentions.dismiss` returned UNAVAILABLE before mention SQL; every RPC passed in both follow-up runs. That first sample is not claimed as entirely green.

- Broad CI also exposed two stale fixtures, now corrected: the memory-flush test asserting the removed source reread is deleted, and the cursor fixture awaits the existing projection reconciliation before checking replacement identity.
- Update cell is not applicable: no update, Doctor, schema/migration, plugin-loading, or service-lifecycle change.
- Diff against integrated main: **32 files, +279 / −539 lines**.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…9651)

* perf(sessions): skip snapshot reads for prepared appends

Let the serialized worker choose the current actor preimage for prepared SessionManager appends. Preserve transcript predicates, live authority checks, and commit receipts while avoiding two full replica copies per warm append.

* test(sessions): preserve the authority callback binding
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…claw#169523)

## What Problem This Solves

Transcript context, search, and rebuild paths repeat reads of facts already owned by the Gateway. The bundled memory visibility loader also enters the synchronous session-store path.

## User Impact

No configuration or storage-format change. Bundled memory visibility loads the complete cross-session view through the existing worker. The public synchronous loader remains compatible, emits a bounded deprecation warning, and is scheduled for removal in the next SDK major; its replacement is `loadCombinedSessionStoreForGatewayAsync`.

## Design

Use committed admission receipts for transcript bounds, return the completed search snapshot with projection readiness, and stop recounting/rechecking acknowledged rebuild work. Final publication retains source validation and bounded append catch-up. SQL projections that avoid materializing large payloads remain in SQL.

Removed checks and accepted edges:

- Admission identity/role/generation reread: direct SQLite edits outside the Gateway owner are unsupported; the admission receipt supplies committed bounds. Store/session/user-role validation and effect-boundary authority remain.
- Search connection revision reread: an append racing a completed search appears on the next search.
- Rebuild claim source/clean-index rereads: stale prepared work can temporarily dirty a derived index before final publication rejects it.
- Rebuild chunk recount/classification reread: acknowledged chunks are authoritative; final source validation remains.

Native-incognito paths remain for the separate incognito-removal migration. Deprecated public synchronous contracts and explicit offline maintenance remain honestly classified. Follow-up target/caller cutovers are being shipped separately; this PR does not claim the entire lane is at zero.

## Evidence

- Two Codex autoreview rounds completed without actionable findings.
- Before the testing-policy change: 28 focused suites / 402 tests passed. These cover admitted context, append catch-up, complete async projection fields, incognito exclusion, and zero caller-thread SQL in the async SDK loader. The last changed/mock-consumer batch passed 75 tests in 646.8 seconds.
- Local changed-file oxfmt, oxlint, and `git diff --check` pass.
- Ordinary PR CI run 38213044338 passed at `d23ecfbd6fe8691909e8c25445df2258de353106`, including the repaired built lifecycle fixture. Static CI run 38214212751 passed production/full Knip export scans, all types/lint, source contracts and ratchets; SDK API diff passed (base `10f79e8d1c24`, head `d23ecfbd6fe8`, acknowledgement `99e4d8f2`). Its unused-file check found two unrelated script entrypoints; main removed both in `07389389f157`, now incorporated conflict-free in `91338fabd80f7`. Final static run 38217360424 passed types, lint, source contracts, database ratchets and SDK diff (digest `5ff6265e`); it tests byte-identical PR1 source files as part of child head `3254d6171c275`. Madge reports zero cycles. Knip fails identically on main run 38216343022 in untouched UI exports `ComposerRunStatusContent` and `ChatPaneVersionsMenu`; this is an inherited static failure. Final PR1 ordinary CI 38221257521 at `1dcc93a2641d5` fails only the untouched stale-version actor test, whose implementation came from main openclaw#169651. These failures use the authorized inherited-failure landing route.
- Owned lexical T1 sites: **27 → 23** (read fence 1 → 0, rebuild 12 → 10, search 4 → 3). These are source sites, not per-turn statements.
- Two live alternating baseline/candidate pairs completed (the v6 pair plus the RAW TURN INCREASE follow-up). Source base `07df9bd4b780ddacbd23bcf76cd5fd19814c5819`, candidate `95d395c19a94e5781df0f3d2827f944aef462288`; later changes are CI test-fixture repairs and conflict-free main integration. Shared workload is unchanged; temporary state is isolated on external storage.

| Metric | Base median [min–max] | Candidate median [min–max] |
| --- | ---: | ---: |
| Warmed all-thread statements/turn | 350.45 [348.2–352.7] | 340.15 [323.1–357.2] |
| Warmed requests/turn | 107.4 [107.2–107.6] | 104.9 [98.9–110.9] |
| Warmed MAIN statements/turn | 0.3 [0.2–0.4] | 0.1 [0–0.2] |
| Whole-workload statements | 9,968.5 [9,941–9,996] | 9,920.5 [9,633–10,208] |
| Whole-workload requests | 2,070.5 [2,046–2,095] | 2,052 [1,950–2,154] |

The first pair increased whole-workload statements/requests by 267/108; the follow-up decreased them by 363/145, satisfying the RAW TURN INCREASE lower-total condition. Warmed transcript publication remains exactly 27 statements / 7 requests per turn in all four runs. Whole-workload transcript publication was 478/103 → 478/103, then 477/102 → 478/103; Memory publication was 451/113 → 492/128, then 605/153 → 297/77; model context was 27/5 → 49/8, then 29/5 → 34/6. The trace shows existing context fallback after Memory writes but does not identify the failed fallback predicate.

Host load and background work varied substantially, so these results do not establish a causal SQL saving or runtime speedup. Warmed candidate/base duration ratios were 1.328 and 0.212. All four runs completed 13 turns, child execution, cron, compaction and shutdown. The first candidate's optional `mentions.dismiss` returned UNAVAILABLE before mention SQL; every RPC passed in both follow-up runs. That first sample is not claimed as entirely green.

- Broad CI also exposed two stale fixtures, now corrected: the memory-flush test asserting the removed source reread is deleted, and the cursor fixture awaits the existing projection reconciliation before checking replacement identity.
- Update cell is not applicable: no update, Doctor, schema/migration, plugin-loading, or service-lifecycle change.
- Diff against integrated main: **32 files, +279 / −539 lines**.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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