Skip to content

refactor(sessions): avoid cloning unchanged rollback state - #170484

Merged
steipete merged 4 commits into
mainfrom
dbasync/actorcow
Oct 13, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/actorcow

Conversation

@steipete

@steipete steipete commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Every durable session actor mutation, resident entry-patch publication, and transcript-rewrite publication deep-cloned all retained state for rollback. The clone traversed unchanged transcript payloads and indexes even for a small metadata command.

User Impact

No command, persistence, or isolation behavior changes. Metadata-only commands avoid walking all retained transcript payloads merely to prepare rollback. No migration or operator action is needed.

Why This Change Was Made

Fork the small mutable object shells and share immutable rows/payloads. Each map or navigation array detaches on its first write. The existing mutation owners replace rows, a rollback discards the working state, and only confirmed commit installs it. Returned snapshots and receipt postimages retain their existing deep-copy boundary. This removes the whole-state clone without changing commands, FIFO scheduling, persistence, SQL, or authority checks; no dependency or new state owner.

Rollback isolation protects real user data, so it is preserved. No authority check was removed, and no new rollback edge case is accepted. The change replaces the expensive isolation mechanism rather than weakening the contract.

Evidence

Measurement

Shared harness v2.1.0, baseline 62f79e969ef02 versus candidate 8dd786e4ee25: three alternating pairs, ten warmed turns per capture, Node 26.11.1 / SQLite 3.53.4 throughout. Values are median [min–max] of the per-run means. The original first pair crossed a host Node upgrade; it is excluded, and the one permitted extra pair supplies the third matched pair.

Measurement Base Candidate
Warmed causal statements, all threads 171.7 [170.8–172.2] 170.1 [170.0–172.0]
Warmed causal requests 41.5 [41.4–41.6] 41.1 [41.0–41.4]
Warmed MAIN statements 0 [0–0] 0 [0–0]
Warmed raw-window statements, all threads 208.3 [207.1–215.7] 204.5 [194.0–206.9]
Warmed raw-window requests 56.1 [52.9–58.7] 51.5 [48.2–53.1]
Complete-workload statements 6764 [6760–6847] 6676 [6546–6815]
Complete-workload requests 1276 [1242–1297] 1226 [1185–1276]
Complete-workload MAIN statements 827 [826–832] 827 [827–827]
Rollback preparation sampled intervals/turn 4.3 [3.9–5.2] 0.1 [0–0.2]

The removed cloneSessionActorStoredState accounts for 134 sampled intervals across 30 warmed turns; its replacement (forkSessionActorStoredState, map and navigation detachment) accounts for 3. The consolidated entry-publication helper is separate: 1.3 [1.2–2.0] sampled intervals/turn, including entry-boundary clones that existed before this change. V8's 1 ms sampling covers warmed windows plus settling intervals and excludes collector ancestry; zero means below sampling resolution. Weighted rollback intervals are 11.254 [8.392–15.479] → 0.108 [0–0.391] ms/turn, but include possible descheduling and are not latency or scheduler CPU accounting.

Per-operation statement medians are unchanged: actor execute 14 → 14; write transaction 9 → 9; phase entry write 8 → 8; append 14 → 14; transaction state 2 → 2. Actor-originating request medians are 8.1 → 8.0. Shared exact-entry reads are 4.1 → 4.0, hydration 1.1 → 1.0, and entry-cache snapshots, row facts, and watermark reads remain zero. No warmed SQL shape, request owner, or shared read family increases. This is a CPU optimization; incidental overall count reductions are not claimed as SQL savings.

First-turn causal statements are 394 [372–403] → 405 [373–418], with requests 81 → 81 and MAIN 33 → 33. Increases are cold runtime/canonical-schema admission and the existing upstream deletion-journal lookup; actor first-turn SQL groups are equal or lower. Background statements/minute are 587.5 → 664.1; timing-dependent background redistribution does not change the SQL-neutral actor result. Shutdown-only audit-prune database-lock refusals occurred on both base and candidate; every primary workload completed.

The shared 32-core host had sampled load 68–93. Latency is unmeasured: the quiet-host attempt ended during source preparation, before any remote workload ran. No latency or total-actor-CPU percentage claim is made.

T1: the durable actor rollback path is worker-owned, 0 → 0. The pre-existing mixed-access inventory in shared storage files remains 27 → 27; this PR changes only their resident-state mutation hooks, not native/incognito or compatibility call routing. No SQL or worker operation is added or removed.

Validation

  • Regression: entry update, transcript append, and input completion followed by rejection preserve the entire resident preimage, while the existing rollback and rehydration checks remain.
  • Snapshot isolation: nested caller edits to projected entry, participants, membership, pending input, transcript indexes, and versions leave retained facts unchanged.
  • FIFO regression: concurrent commands observe FIFO preimages across a rejected middle command, and the rejected value never reaches its successor.
  • Kernel owner tests: 2 passed (440.63 s including transform/setup and worker build), before the final helper consolidation and nested-entry assertion. The first full actor run passed all 17 existing tests; the new FIFO test exposed an incorrect epoch-continuity expectation. That initial run also detected source edits made during compilation. The corrected test allows existing rollback rehydration and checks actual preimages/values; its subsequent focused run passed on the committed head (389.93 s, 94% transform). Final-head CI covers the full changed files.
  • Type-aware core oxlint and formatting pass on the changed files; git diff --check passes. Both independent Codex reviews are clean (no P0–P2 findings). The first CI run caught a type-import cycle and a test using a retired entry field; both were corrected. CI on 8dd786e4ee25 passed in 624 seconds, including types, lint, source/export contracts, Madge, T1/dialect ratchets, builds, and changed-file test shards. The separate Knip export scan found no changed-scope issues and one unrelated unused QA helper; main already removes that helper in 582b6dd0041c. The clean main integration includes that fix. Following the updated compute-conservation rule, final integrated-head proof will come from PR CI, without another local Knip or test run.
  • No SDK API, schema, migration, updater, plugin loading, or service lifecycle changes; the update cell does not apply.

Production delta: +100 net lines (excluding tests and docs), within the increased 500-line budget. The coordinator hold was lifted. Main was merged cleanly in 0852b9c46c7d; the PR-only diff and actor code are unchanged. Integrated-head CI passed in 814 seconds (71 jobs completed, including skipped jobs), including the changed-file tests and static gates. Changed-file formatting, type-aware lint, and git diff --check also pass locally.

Keep unchanged transcript payloads and rows shared across a private command fork. Detach mutated collections before publication, preserve deep-copy return boundaries, and cover rollback, nested snapshot isolation, and FIFO preimages.
@clawsweeper

clawsweeper Bot commented Oct 13, 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 docs Improvements or additions to documentation size: M labels Oct 13, 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: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 13, 2026
@clawsweeper

clawsweeper Bot commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR replaces whole-state session rollback clones with shared unchanged rows and copies of collections when first mutated.

Example: A session activity command changes updatedAt from 601 to 603.

  • Before: Preparing rollback deep-clones retained transcript payloads and indexes.
  • After: Preparing rollback copies mutable shells and detaches changed collections while preserving the rejected command's preimage.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The focused patch has no actionable finding and passing exact-head CI; the performance benefit remains supported primarily by source inspection and harness validation.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored internal optimization is outside the ordinary contributor proof gate; supplied validation exercises real SQLite and actor owners, while the promised real-command performance comparison remains unfinished.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Small session metadata commands spend CPU traversing unchanged retained transcript payloads when preparing rollback.
Reason: Maintainer direction and feature history support this focused optimization, and the earlier projection work identified rollback cloning as a remaining cost.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it provides a focused, maintainer-directed optimization absent from current main, with no actionable correctness or security defect found.

Priority: P2
Reviewed head: 8dd786e4ee2582fba5e99e264f16788ea9f28b27

Before merge

  • Complete next step - Resume landing only after the author lifts the recorded Phase E hold.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied evidence does not yet include the recorded baseline/candidate CPU comparison through real session commands.
Agent review details

How this fits together

The serialized database worker applies session actor commands through existing SQLite transaction kernels and returns committed snapshots and receipts.

flowchart TD
  A[Session command] --> B[Serialized database worker]
  B --> C[Private working state]
  C --> D[Existing mutation kernels]
  D --> E[SQLite transaction]
  E --> F[Install committed state]
  E --> G[Discard rejected state]
Loading

Technical review

Best possible solution:

Keep rollback isolation within the existing transaction owner while copying mutated collections and preserving detached snapshot and receipt boundaries.

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

Current-main source demonstrates complete retained-state cloning before mutations; this read-only review did not measure runtime performance.

Is this the best way to solve the issue?

The approach fits the existing owner: inspected mutations replace rows or detach collections, mutable scalar shells are copied, and commit and disclosure boundaries remain intact.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Whole-state rollback isolation and retained mutation hooks changes intended behavior with a stated reason (d5173cc: Private working state preserves resident preimages while synchronous transaction kernels execute.)
  • Resident entry-patch publication keeps the original intent (80d82ca: Complete same-lifecycle postimages preserve untouched resident facts and avoid rehydration.)
  • Resident transcript-rewrite publication keeps the original intent (bc97659: Admission- and navigation-preserving rewrites publish reusable actor state after commit.)
  • Transcript append cursor and options keeps the original intent (65beb1e: A synchronous batch cursor reuses append preparation; the extracted declarations retain their fields and execution semantics.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit bc97659 adds src/config/sessions/session-actor-transaction.ts:14 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-transaction.ts)
  • Vitor Cepeda Lopes: Raw commit ca0a172 adds src/config/sessions/session-actor.worker.ts:351 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ca0a172d2927; files: src/config/sessions/session-actor.worker.ts)

PR surface

Source +100, Tests +69, Docs +7. Total +176 across 11 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 153 53 +100
Tests 2 76 7 +69
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 236 60 +176

Review metrics

Metric Value Why it matters
Production versus test LOC Production +153/-53, net +100; tests +76/-7, net +69. Production growth supplies collection detachment and preserves the type boundary; test growth checks rollback isolation and FIFO behavior.

Labels

Label changes:

  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a bounded session-performance improvement without an established urgent user-facing failure.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Complete the recorded baseline/candidate CPU comparison through real session commands.

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 (2 earlier review cycles)
  • reviewed 2026-10-13T01:19:37.792Z sha 6f8891e :: needs changes before merge. :: none
  • reviewed 2026-10-13T01:34:56.511Z sha 8dd786e :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 10:06 PM ET / October 13, 2026, 02:06 UTC (Revision 3).

@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 13, 2026
@steipete
steipete merged commit 49b372d into main Oct 13, 2026
128 checks passed
@steipete
steipete deleted the dbasync/actorcow branch October 13, 2026 05:23
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…170484)

Replace whole-state session actor rollback clones with first-write collection detachment. Preserve detached returned snapshots, rollback isolation, and FIFO command ordering.

Rollback preparation falls from 4.3 to 0.1 sampled intervals per warmed turn across three matched-runtime pairs; actor SQL and request operations remain flat. Latency is unmeasured. Regression coverage preserves the resident preimage after mutation rejection, nested snapshot isolation, and FIFO across rollback. Integrated-head CI passes.
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. size: M 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