Skip to content

perf(sessions): reuse cold-state and participant read facts - #169989

Merged
steipete merged 2 commits into
mainfrom
dbasync/hotguard
Oct 12, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/hotguard

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Warm transcript pages repeatedly select the same cold-archive marker, and session metadata commits reread participant rows already obtained by the operation.

User Impact

Reduces repeated SQLite reads during chat and history/usage refresh. Schemas, retained transcript bytes, public APIs, permissions, and update behavior are unchanged.

A concurrent explicit archive can make one read-only page appear empty if it commits between receipt capture and the first row read. The next request observes invalidation and reports/restores cold storage. History or usage may briefly appear incomplete; transaction-local write guards remain intact.

Why This Change Was Made

The transcript owner retains at most 128 hot/cold facts per connection under existing session-ID write receipts. Consecutive read pages reuse them. Already-open snapshots retain only snapshot-local facts; their results never become current autocommit facts. Participant projections carry the existing autocommit result only into the metadata CAS owner’s already-admitted immediate write transaction, with existing local mutation and physical write receipts invalidating it. Ordinary deferred readers perform their first SELECT to establish a real SQLite snapshot; cached rows then stay within that snapshot.

Writer coverage: the cold-storage worker archives, restores, and externalizes archives under the session-ID scope; window/node deletion scopes every affected session before FK cascades. Native writes publish the existing receipts, including rollback invalidation. Incognito uses its process-owned native handle. Doctor orphan-window cleanup runs under exclusive offline maintenance; private backup writes do not mutate the live database. There is no supported foreign-process archiver while Gateway ownership is held.

Removed checks and accepted edges:

  • Per-page cold marker rereads: a concurrent explicit archive can yield one transient empty page as described above. No persistent stale fact survives its write receipt.
  • Participant CAS rereads: metadata CAS intentionally excludes participant fields. Concurrent participant updates survive and are returned; they do not reject an otherwise valid metadata change. Actual metadata conflicts retain the existing rejection contract.

T1 inventory in this area remains 1 → 1. The remaining readParticipantRows batch query serves native incognito projection and released synchronous entry APIs. Moving it requires the incognito/API owner cutover; relabeling this mixed kernel as worker-only would be incorrect. Cold-marker helpers add no new inventory call site. Repository T1 remains 482 → 482, compatibility calls 2 → 2. Measured warmed Gateway MAIN statements are reported below.

Related work: #169974 (usage refresh coalescing), #169960 (committed transcript context), and merged #169858 (exact-entry receipt preservation, included in the base). This change does not alter their scheduling, replica invalidation, or request routing.

Evidence

  • Basic changed-file oxfmt, direct oxlint, and git diff --check: passed.
  • Codex autoreview: two rounds passed with no actionable P0–P2 findings.
  • Regressions added for repeated pages, archive → cold, restore → hot, same-transaction writes, sibling writes, rollback, existing snapshot isolation, and deletion cascades. Existing metadata-CAS tests retain participant updates and reject real entry conflicts. PR CI owns test execution and static gates under the current campaign workflow.
  • One baseline/candidate live pair uses the shared synthetic SQL workload and request census, through the local CPU semaphore. No live Gateway, real credentials, or production data. Both runs passed chat, child, cron, compaction, RPC and shutdown checks; request SQL reconciles exactly in every phase/thread. Two unmatched startup requests exist in both runs; warmed accounting is complete. Base f6dd2d3d8b4c, candidate d6f09475c843; one pair with ten warmed turns per run, using the current reduced-proof workflow. Loaded host; no unloaded-host claim.
  • No update/Doctor/schema/plugin-loader/service-lifecycle code changed, so no published-driver update cell applies.
Warm metric Base f6dd2d3d8b4c Initial d6f09475c843 Final db6a8b200fc9
All-thread SQL/turn, median [min–max] 387.5 [368–419] 372 [350–488] 393 [352–465]
Worker requests/turn, median [min–max] 88.5 [80–98] 87 [79–108] 92.5 [79–107]
All-thread SQL/turn, mean 389.4 382.5 387.9
Worker requests/turn, mean 87.7 88.4 90.9
Gateway MAIN SQL/turn 0 0 0
Cold-marker SELECTs/turn 24.2 13.2 13.4
Participant projection SELECTs/turn 16.6 13.6 13.7
Participant CAS rereads/turn 3 0 0
Participant operation-snapshot reads/turn 3 3 3
Exact-entry primary reads/turn 5.7 6.1 6.5
Actor hydration primary reads/turn 4.5 4.7 4.5
Entry-cache snapshot loads/turn 0.5 0.6 0.7
Row-fact primary reads/turn 1 1 1
Watermark reads/turn 2 2 2

Initial-pair per-operation attribution: usage-cost drops 75 → 64.2 SQL/turn at 3 → 3 requests/turn; session.entry.patch.commit drops 37 → 34 SQL/turn at 6 → 6 requests/turn. The CAS reread class disappears, while the three real operation snapshots remain. These owners save 13.8 SQL/turn, with no added requests. Request routing is unchanged; this PR does not claim a structural request-count saving.

Disclosed shared-family variation: candidate ran six corpus inventory requests versus five (one primary snapshot each), 35 actor reads versus 33 (one hydration each), and 35 exact-entry requests versus 32 (three extra primary SELECTs; full-row queries remain 20 in each run). The remaining extra exact-entry read is a first-turn session.entry.read cohort projection (session-entry-cohort.worker.ts:155: 15 → 16 over the warm window). The three other extra reads are transcript-worker lifecycle projections (12 → 15); snapshot/full-row paths remain ten each. Candidate turn 1 also includes 26 write-preparation statements and two corpus scans; base has no warmed write-preparation statements and one first-turn corpus scan. These are additional invocations, not increased SQL per affected shared operation; writer invalidation publication, scheduling, and worker routing are unchanged. Raw means include this background work, including the +0.7 requests/turn. Whole-workload totals fall 10,502 → 10,257 SQL and 1,759 → 1,752 requests. The final-head run below verifies the snapshot correction; both candidate results remain visible rather than selecting the more favorable one.

Final-head confirmation: the same live workload passed on db6a8b200fc9 (146.6s runtime; 449.3s build), with exact SQL conservation, zero missing contexts, the same two unmatched startup requests, and no fixture children left running. usage-cost is 75 → 62.2 SQL/turn at 3 → 3 requests; session.entry.patch.commit is 37 → 34 SQL/turn at 6 → 6 requests. These owners save 15.8 SQL/turn, including removal of all three CAS rereads and usage-page cold guards 15 → 4 per turn. The three real operation snapshots remain.

Final shared-family attribution: the eight extra exact-entry primary reads over ten turns comprise five extra transcript lifecycle reads (requests 32 → 37, primary reads 12 → 17), two extra cohort projections (entry-read requests 45 → 47, cohort projections 15 → 17), and one extra read-only entry lookup (10 → 11). Both ten-query full-row paths remain at ten. The two extra snapshot loads comprise one extra corpus request (5 → 6) and one extra entry-list request (0 → 1), each with one snapshot. Actor hydration remains 45 → 45, row facts 10 → 10, and watermarks 20 → 20. Thus these increases are additional invocations, not additional reads per shared operation.

The final raw SQL median rises 5.5 while its mean falls 1.5; request median rises 4 and mean 3.2. The largest additional background component is database.domain.publish: +69 SQL/+15 requests over ten turns, exactly accounted for by cache/index/source jobs (+58 SQL/+15 requests) and vector initialization (+11 SQL at unchanged request count). Those owners and scheduling are untouched. Whole-workload totals are 10,502 → 10,375 SQL and 1,759 → 1,777 requests. Under the campaign's attribution-over-raw rule, this is disclosed background variation; no end-to-end median or structural request reduction is claimed. Shared-family details are handed to the campaign owner.

CI found a participant snapshot regression in the initial implementation: an autocommit result could enter an ordinary deferred reader without pinning its native SQLite snapshot. The follow-up commit limits this optimization to the existing immediate CAS writer, adopts the transaction revision, and strengthens the snapshot regression with a direct native read after the peer update. The exact test passed on current main and failed on the initial candidate; the corrected exact regression now passes locally (1 passed, 50 skipped; 124.67s Vitest, 158.66s test wrapper under contention). The unchanged-CAS/write-invalidation regression also passes on db6a8b200fc9 (1 passed, 7 skipped; 101ms test body, 30.13s Vitest, 58.70s wrapper). Final-head CI passed all 51 schema-facts cases (corrected snapshot case 38ms) and all 8 entry-revision cases (carry case 28ms). Final-head types, lint, source contracts, Madge and T1/dialect/worker ratchets also passed; the separate Knip scan completed with only the pre-existing src/infra/database-engine/contract.ts: TransactionRecipes unused type in production/full-tree scans (script scan clean). The exact same export fails in main job 114886687947, and main already contains fix 4cdac89cf0b656ef90cb22bb4fd3dfa9e7205bf9; the merge retains that fix. No changed-file Knip finding remains. The mocked history-worker runtime sibling passed all 32 cases locally (530.04s wrapper, including 262.648s cold worker build). Final-head CI passed all 39 cold-owner cases as well: 3 state, 23 archive/restore, 13 cold-read. Across the five touched test files, all 98 cases passed. The table records both candidates; the final run verifies the snapshot correction retains the intended savings. Final CI run 38276056220 completed with 22 successful static jobs and 11 red test shards plus the aggregate; this is not an all-green CI claim.

Broad-test disposition under the authorized relaxed landing policy: the pending-input savepoint lock, restricted-operator rewind lock, named branch-switch/cold-fork storage locks, and sticky-model catalog expectation have exact matching main failures in runs 38271415987 or 38265016301. Startup registry and history-worker reuse failures were reproduced locally at main 32c839147a80. Those failures have campaign owner handoffs. The cleared-selection archive catalog fixture is source-attributed to an unchanged upstream contract; the remaining rewind lock cases share the untouched lock stack but are not exact-main reproductions. Reclamation cleanup, agent-delete timeouts/cascading assertions, two visible-spawn cases, active-context preflight, session-create admission, and historical Doctor normalization remain unresolved broad failures; they are not labeled inherited. No remaining failure in a touched test file or proven regression in the changed owners remains. The initial snapshot regression was fixed before landing.

Changed-file CI timing (case-body totals; enclosing shards include other files):

Test file Passed Case-body seconds Shard seconds
session-cold-storage-state.test.ts 3 0.122 556
session-cold-storage.test.ts 23 47.077 399
session-accessor.sqlite-cold-read.test.ts 13 3.941 399 (same shard)
session-accessor.sqlite-entry-revision.test.ts 8 0.115 436
sqlite-schema-facts.test.ts 51 0.896 768

LOC: 10 files, +322/−90; production +139/−44, with the remainder tests and ownership documentation. Live-run elapsed time: base 130.7s, candidate 140.8s; builds 308.7s and 404.8s. Local test suites were not a proof gate; focused CI-failure diagnosis is recorded separately.

Reuse session-scoped cold facts across read pages and autocommit participant rows inside unchanged metadata transactions. Keep snapshot-local write guards and invalidate through existing writer receipts. Concurrent explicit archives may yield one transient empty read page; subsequent requests observe invalidation. No schema, retention, API, or update changes.
@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 docs Improvements or additions to documentation size: M 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 reuses receipt-invalidated cold-storage facts and unchanged participant rows to reduce repeated session SQLite reads.

Example: Read two history pages for session cold-facts without an intervening write.

  • Before: Both pages select the cold-archive marker.
  • After: The second page reuses the retained hot fact; archive writes invalidate it.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation is coherent and preserves persisted formats, but the workload measurement predates the participant correction.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this owner-directed PR; its reported synthetic workload covers the initial candidate, while corrected-head regressions support snapshot correctness and the final performance comparison remains pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Chat, history, and usage refreshes incur avoidable repeated SQLite reads.
Reason: The established feature owner selected a bounded optimization within the existing storage design and explicitly accepted its recoverable archive-overlap behavior.

Merge readiness

✅ Ready for maintainer review

Keep open: this owner-directed optimization remains absent from fetched main, and review found no actionable introduced defect.

Priority: P2
Reviewed head: db6a8b200fc9f460b18ff8b9503d98833c8588d2

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The corrected participant implementation has focused regression results but no completed workload comparison through a shipped entry point.
Agent review details

How this fits together

Session accessors receive history and metadata requests, read SQLite through connection-owned snapshots and writer receipts, and return transcript rows and participant projections.

flowchart TD
 A[History and metadata requests] --> B[Session accessors]
 B --> C[Connection read facts]
 C --> D[SQLite snapshots]
 E[Archive and session writers] --> F[Write receipts]
 F --> C
 D --> G[Transcript and participant results]
Loading

Technical review

Best possible solution:

Keep reuse within the existing receipt and snapshot owners while preserving participant freshness, write guards, and transcript bytes.

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

Current-main source shows repeated cold-marker queries and participant rereads across transaction revisions; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch extends existing cache and invalidation owners, and the correction preserves deferred-reader snapshots without introducing competing storage or authorization.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Cold-marker snapshot checks changes intended behavior with a stated reason (aa0ad4c: Automatic archival required detection and restoration of extracted transcripts before reading their events; this PR documents the bounded overlap tradeoff.)
  • Participant exact-read revision cache keeps the original intent (fcf275b: Reuse admitted participant rows while invalidating on writes, rollback, schema changes, and snapshot transitions.)
  • Transaction-local transcript facts keeps the original intent (0bc7491: Reuse projection-derived cold state within a read snapshot while preserving mutation and rollback invalidation.)
  • Entry mutation CAS keeps the original intent (8fe6ac8: Preserve authoritative entry comparison and publish writer postimages without additional persisted-entry rereads.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 0bc7491 adds src/config/sessions/session-cold-storage-state.ts:86 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0bc7491825b2; files: src/config/sessions/session-cold-storage-state.ts)

PR surface

Source +95, Tests +128, Docs +9. Total +232 across 10 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 4 139 44 +95
Tests 5 174 46 +128
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 322 90 +232

Review metrics

Metric Value Why it matters
Production versus test changes Production +139/−44; tests +174/−46 Growth implements bounded receipt-aware reuse with regression coverage for freshness, rollback, snapshot isolation, and deletion.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Focused session-read performance improvement without an established urgent availability or data-integrity failure.
  • 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.

Rank-up moves

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

  • Complete the corrected-candidate workload comparison to verify retained participant CAS savings.

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 (3 earlier review cycles)
  • reviewed 2026-10-12T15:57:22.094Z sha d6f0947 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T16:21:45.520Z sha db6a8b2 :: needs changes before merge. :: none
  • reviewed 2026-10-12T16:58:41.754Z sha db6a8b2 :: needs maintainer review before merge. :: none

Reviewed October 12, 2026, 1:34 PM ET / 17:34 UTC (Revision 4).

@clawsweeper clawsweeper Bot added 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. and removed 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. labels Oct 12, 2026
@steipete
steipete merged commit d79f645 into main Oct 12, 2026
187 of 201 checks passed
@steipete
steipete deleted the dbasync/hotguard branch October 12, 2026 17:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…#169989)

Reuse bounded transcript hot/cold facts under existing session write receipts, and carry participant preparation into the metadata CAS owner’s immediate write transaction. Preserve native read snapshots, archive/restore invalidation, and independent participant updates.

Reduces repeated transcript and metadata-commit SELECTs without changing schemas, retained bytes, public APIs, or request routing.
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: 👀 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