Skip to content

perf(sessions): reuse transcript projection facts within reads - #169201

Merged
steipete merged 5 commits into
mainfrom
dbasync/projctx
Oct 11, 2026
Merged

steipete merged 5 commits into
mainfrom
dbasync/projctx

Conversation

@steipete

@steipete steipete commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Transcript context preparation reread projection readiness, watermark, and hot-state facts already selected by the same command, while activity recaps reopened the projection for each page.

User Impact

Reduces SQLite work during ordinary turns without changing transcript bytes, context limits, recap behavior, permissions, storage schemas, or update behavior.

Why This Change Was Made

Reuse the existing transaction-local transcript fact owner for projection-derived generation, sequence, mutation time, and cold state. Native writes and rollback invalidate those facts through the existing read revision. Current-turn replay consumes its selected projection's version and anchor; full hydration reads its cold state and version together. The activity owner now selects recap metadata, ancestry, and bounded pages in one snapshot. Size-limiting SQL projections stay in SQL.

Removed checks and accepted edges:

  • Removed the separate recap page-versus-snapshot generation/index/count comparison. All pages now share one synchronous SQLite snapshot; a later commit is observed by the next command.
  • Removed repeated watermark and hot-presence reads after projection admission. Facts are usable only in that snapshot; native writes and rollback retire them before reuse.
  • Removed the duplicate context-version read and readiness derivation while resolving the current turn's anchor. Replay admission still compares the requested version and retains the live read fence.
  • Removed the context-fact publication's second in-memory revision check. It has no asynchronous gap, and any intervening native mutation invalidates the captured revision when read.

T1 scope and residuals

No new main-thread SQL is added. The targeted read owners remain 8 → 8 T1 sites: active-context 6, projection-read 1, public watermark facade 1. Including the touched transcript-state owner gives 22 → 22 (its 14 T1 write/kernel sites are unchanged); including the adjacent transcript-anchor kernel gives 24 → 24 (2 unchanged sites). Current-turn, cold-state, and activity-summary-source have zero inventory-counted sites.

These residuals are not relabeled as worker-only: active-context serves the released deprecated synchronous SessionManager contract, preserved until the next Plugin SDK major; the projection payload reader also serves process-held incognito history; and the mixed watermark facade serves synchronous activity-summary ensure, title reads, and compatibility callbacks. Removing those synchronous paths requires their API/owner cutovers, so this PR stops at those calls under the task escape hatch. The changed worker command paths already execute off the Gateway main thread. This PR reduces executed SQL; it does not claim completion of the remaining T1 migration.

Evidence

Measured with the shared workload on one remote host in alternating order M1,C1,M2,C2,M3,C3. Base 8e17f906cde15285bbe94234fe75055f3890b64f; code candidate 69052f61c90792ae54fafb169048896f92c3e75a. The final head integrates main without conflicts, adds documentation, removes one unused type-only import found by the static gate, and adds the extracted module to the PR wrapper manifest; runtime code is unchanged from the measured candidate. Each warmed result averages ten turns; table cells are median [min–max] across three runs.

Metric Base Candidate
Warmed all-thread SQL / turn 338.3 [336.5–339.1] 328.3 [328.2–329.1]
Warmed requests / turn 88.9 [88.6–89.1] 88.8 [88.7–88.8]
Warmed MAIN SQL / turn 0 [0–0] 0 [0–0]
First-turn all-thread SQL 1093 [1073–1135] 1059 [1051–1093]
First-turn requests 194 [193–196] 196 [195–196]
Whole-workload SQL 9796 [9787–9798] 9653 [9652–9659]
Whole-workload requests 1709 [1705–1722] 1705 [1703–1705]

Warmed SQL falls 10 statements/turn (2.96%). Median candidate/base duration is 1.000 for warmed turns and 0.993 for the whole workload. All six runs passed statement conservation and request-census validation.

The primary first-turn request median rises 194 → 196, while first-turn SQL falls 1093 → 1059. The required extra alternating pair confirms redistribution: full-workload SQL 9828 → 9666 and requests 1725 → 1718, duration ratio 0.969. Its first turn rises 1132 → 1195 SQL / 194 → 199 requests; the additions are existing sessionRows.sharedFacts, session-exact-entries, and session-row-facts metadata work moving earlier, with no new domain-command request types. Primary three-pair medians above remain unchanged.

Connect SQL rises by 24: unchanged database.domain.publish memory-FTS setup 110 → 133 (+23) and userProfiles.authority.resolve 6 → 7 (+1). Combined boot+connect SQL is 3035 → 3059 (+0.79%) with requests unchanged at 114, within the combined-window tolerance. No added query comes from a changed owner.

Warmed native operation (SQL/turn) Base Candidate Delta
Projection snapshot 9.0 7.0 −2.0
Non-publication watermark 7.5 6.4 −1.1
Cold-presence marker 2.3 0.3 −2.0
Active leaf 1.0 1.0 0
Publication watermark 7.0 7.0 0

Direct owner attribution is deterministic across the three runs: activity-summary source 14 → 7 SQL (two projection SELECTs, one watermark SELECT, two BEGIN and two COMMIT removed); transcript hydration 27 → 26 and transcript anchors 12 → 11 (one cold-marker read removed each). That is 9 SQL/turn of direct owner savings. The observed raw median saving of 10 also contains unchanged session-row-facts/actor/exact-entry timing; component medians are not additive. Global BEGIN and COMMIT each fall 44.4 → 42.3 per warmed turn; the activity owner removes exactly two of each.

The code-change commit was reviewed with Codex autoreview: no actionable P0–P2 findings. The conflict-free integration retained that implementation. The later one-line type-import cleanup passed the second and final review (no P0/P1 findings).

Focused regressions cover fact reuse followed by an in-process rewrite/cold transition, and a recap read after a committed append. The new reuse regression fails on baseline for the intended reason: five SELECTs instead of one.

  • Owner tests on the integrated implementation (reused after the type-only import and manifest fixes): watermark 9/9, activity retry 27/27, and all four bounded-context, transcript-anchor, transcript-context, and transcript-preview sibling files passed.
  • Required changed-test commands: pnpm test src/config/sessions/session-accessor.sqlite-transcript-watermark.test.ts --maxWorkers=1 took 41.00s wall / 38.26s Vitest; pnpm test src/gateway/session-activity-summaries.retry.test.ts --maxWorkers=1 took 78.29s wall / 75.69s Vitest. Added regression execution: 0.895s + 1.334s = 2.229 CI seconds; the existing files account for the remaining execution/setup cost.
  • Madge, production/script Knip exports, export-name collisions, and both database ratchets passed. T1 raw 616 → 616, normalized 614 → 614; changed-file dialect counts: mechanical 2 → 2, design 0 → 0, engine-maintenance 0 → 0.
  • The source check:changed rerun passed all guards, production typechecking, and all 28 core-test typecheck graphs. Its full-tree Knip scan stopped on the untouched loadSubagentMaintenanceCandidatesInDatabase export; the same rule and file fail independently on main 23ad242958a4dd4601660e3933dc6e663c89c7a1. The remaining type-aware lint was run separately and passed all 11 changed TypeScript files, with zero warnings/errors; script lint also passed. The final manifest-only check:changed passed in 137.75s, including its planner-selected guards and script lint.

The first static run found one unused type-only import; the follow-up removes it without runtime changes. Initial CI then caught the new module missing from the PR wrapper extraction manifest; the one-line manifest fix passed both failed eager-import checks and all three wrapper-source closure cases (focused command walls 7.12s, 9.96s, and 3.64s).

Diff against the integrated base: production +149/−125 (net +24), tests +107/−1, docs +9/−0, wrapper manifest +1/−0. No SDK surface, storage schema, migration, update, plugin-loading, or service-lifecycle change; SDK diff and published-driver update cell do not apply.

Required CI run 38153442338 is red only on two unchanged test cases: subagent mixed-owner listing exhausts SQLite worker capacity, and ACP explicit-abort completion observes only the end lifecycle event. Both cases fail independently on main 23ad242958a4dd4601660e3933dc6e663c89c7a1: the Bun subagent case reports overloaded at worker admission (35.31s), and the ACP case reproduces the same [end] versus [start, end] assertion (86.18s). The inspected CI merge is f23e48bbf8528dcfd3b3e152caf3e43b7de17b31, combining main a44f088e7b9882e39f640870bd28b5fd7e71fee1 with the exact PR head. Its capacity policy and failing test sources are unchanged by this PR. Landing uses the authorized inherited-failure exception; no CI rerun or assertion weakening is used.

@clawsweeper

clawsweeper Bot commented Oct 11, 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 gateway Gateway runtime size: M labels Oct 11, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. 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 11, 2026
@clawsweeper

clawsweeper Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR reuses transcript facts within SQLite snapshots and reads Activity recap pages through one shared projection.

Example: Activity prepares a recap batch of up to 64 messages with a 128 KiB payload limit.

  • Before: Metadata, ancestry, watermark, and bounded pages acquire their projection independently.
  • After: Those reads share one synchronous snapshot while preserving the message and byte limits.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The patch is coherent and the previous integration defect is repaired; reported measurements and focused coverage support it, while independently inspectable runtime evidence remains limited.
Proof confidence 🦐 gold shrimp (3/6) The supplied maintainer-authored designation exempts the ordinary contributor proof gate; the body reports remote transcript-read measurements and owner regressions, but supplies no inspectable shipped-entry-point trace.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Ordinary turns and Activity recaps repeat SQLite reads for facts already selected by the same command.
Reason: The established area owner proposes a focused optimization, documents the removed checks and accepted snapshot semantics, and preserves public and storage contracts.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it provides a focused performance improvement beyond current main, resolves the prior wrapper finding, and has no remaining actionable findings from this review.

Priority: P2
Reviewed head: 99ab43ad3f249a0e2ba063802a2d6ab58d4ce4d4

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: No inspectable shipped Gateway trace accompanies the reported workload measurements; ordinary contributor proof is exempt under the supplied maintainer-authored designation.
Agent review details

How this fits together

Transcript workers consume canonical SQLite session data and return bounded context, replay anchors, hydration results, and recap inputs to Gateway callers.

flowchart TD
  A[Gateway session request] --> B[Transcript worker]
  B --> C[SQLite read snapshot]
  C --> D[Projection and context facts]
  D --> E[Context and replay readers]
  D --> F[Activity recap pages]
  E --> G[Worker result]
  F --> G
Loading

Technical review

Best possible solution:

Retain the snapshot reuse and completed wrapper inventory while preserving existing transcript, replay, and storage contracts.

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

Source inspection confirms the repeated-read paths and the wrapper repair; no target code or tests were executed during this read-only review.

Is this the best way to solve the issue?

Extending the existing transaction-local fact owner and consolidating recap reads removes redundant work without introducing a competing cache or changing persisted data.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Transaction-local transcript facts keeps the original intent (da965e0: Reuse transcript version facts within the current transaction while invalidating them after native writes and rollback.)
  • Activity recap page consistency changes intended behavior with a stated reason (c2c48b4: Read bounded recap inputs in the history worker while preserving omission classification and detecting inconsistent pages.)
  • Replay version and anchor reads keeps the original intent (40cdfd0: Prepare replay against the exact hydrated transcript version and retain the read fence and final live admission.)
  • Full transcript hydration keeps the original intent (dbd3bf7: Hydrate through a worker-owned snapshot with bounded transfers, cold-state rejection, cancellation, and cleanup.)
  • Watermark semantics keeps the original intent (bcae52b: Preserve hot generation, cold sequence precedence, fresh bindings, and the caller's SQLite snapshot.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Prior wrapper finding resolved: The only change after the previously reviewed head adds session-transcript-context-facts.ts to the extraction inventory, completing the runtime dependency identified in the prior review. (scripts/pr-lib/wrapper-components.txt:1977, 99ab43ad3f24)
  • Snapshot-bound reuse: Reused facts require the same native handle, session, active transaction, and read-revision identity; the existing revision owner tracks native mutations and transaction settlement. (src/config/sessions/session-transcript-context-facts.ts:22, 99ab43ad3f24)
  • Replay checks preserved: Replay still compares generation, raw sequence, and mutation time against the requested version and applies the transcript read fence before returning an entry. (src/config/sessions/session-accessor.sqlite-current-turn.ts:26, 99ab43ad3f24)
  • One recap snapshot: Recap metadata, ancestry, watermark, and bounded pages now execute inside withCurrentProjectionSnapshot; the existing page reader retains SQL-based size selection and oversized-message classification. (src/gateway/session-activity-summary-source.ts:33, 99ab43ad3f24)
  • Reported performance and accepted scope: The full live body reports alternating remote workload measurements of 338.3 to 328.3 warmed SQL statements per turn, with no measured warmed-duration improvement, and explicitly preserves the released synchronous compatibility paths. (99ab43ad3f24)
  • Current main retains the repeated reads: The inspected current-main owners retain the separate recap reads and private transcript fact cache; this PR's additional reuse is not already implemented there. (src/gateway/session-activity-summary-source.ts, e6c4986438b3)

Likely related people:

  • Peter Steinberger: Raw commit da965e0 adds src/config/sessions/session-accessor.sqlite-transcript-state.ts:139 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: da965e09656e; files: src/config/sessions/session-accessor.sqlite-transcript-state.ts)
  • Vincent Koc: Raw commit 932846b adds src/config/sessions/session-accessor.sqlite-projection-read.ts:69 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 932846b521c0; files: src/config/sessions/session-accessor.sqlite-projection-read.ts)

PR surface

Source +24, Tests +106, Docs +9, Other +1. Total +140 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 9 149 125 +24
Tests 2 107 1 +106
Docs 1 9 0 +9
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 13 266 126 +140

Review metrics

Metric Value Why it matters
Production versus test LOC Production +149/-125; tests +107/-1 The net production growth supports a shared fact owner and one recap snapshot; the tests cover native-write invalidation and freshness after a committed append.

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded performance improvement to ordinary transcript reads, with no established urgent user-facing regression.
  • 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-11T15:49:06.605Z sha 9f11087 :: needs changes before merge. :: [P2] Include the new runtime module in the PR wrapper inventory

Reviewed October 11, 2026, 12:05 PM ET / 16:05 UTC (Revision 2).

@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 11, 2026
@clawsweeper clawsweeper Bot added 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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 11, 2026
@steipete
steipete merged commit 0bc7491 into main Oct 11, 2026
189 of 194 checks passed
@steipete
steipete deleted the dbasync/projctx branch October 11, 2026 16:34
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

steipete added a commit that referenced this pull request Oct 11, 2026
Retain connection-owned busy-timeout policy, skip empty audit expiry deletes
until due, and fold known transcript-root recency into watermark writes.
These remove seven deterministic SQLite statements per warmed turn.

The original four-item measurement reduced warmed all-thread statements from
336.7 to 321.5 and requests from 89.3 to 88.3. Its six-statement activity snapshot
saving also landed upstream in #169201; retain that path and its regression.
Gateway MAIN remains zero. Preserve the released synchronous SessionManager
contract under the documented T1 escape hatch. No schema or retention change.

Final-head activity/transcript proof: 69 tests. Type-aware lint, T1/dialect
ratchets, export collisions, SDK surface, and cycles pass; required CI is green.
Knip reports the same 41 UI findings on the final head and its main baseline,
with no changed finding files. SDK API diff reports no public API changes.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…law#169201)

* perf(sessions): reuse projection facts within transcript reads

* docs(sessions): describe snapshot-local transcript facts

* fix(sessions): remove unused transcript state type import

* fix(scripts): include transcript context facts in PR wrapper
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
Retain connection-owned busy-timeout policy, skip empty audit expiry deletes
until due, and fold known transcript-root recency into watermark writes.
These remove seven deterministic SQLite statements per warmed turn.

The original four-item measurement reduced warmed all-thread statements from
336.7 to 321.5 and requests from 89.3 to 88.3. Its six-statement activity snapshot
saving also landed upstream in openclaw#169201; retain that path and its regression.
Gateway MAIN remains zero. Preserve the released synchronous SessionManager
contract under the documented T1 escape hatch. No schema or retention change.

Final-head activity/transcript proof: 69 tests. Type-aware lint, T1/dialect
ratchets, export collisions, SDK surface, and cycles pass; required CI is green.
Knip reports the same 41 UI findings on the final head and its main baseline,
with no changed finding files. SDK API diff reports no public API changes.
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 20, 2026
First-parent upstream 19fe879..0bc7491 (100 commits, including
openclaw#169090 entry-writer postimages, openclaw#169201 transcript projection facts,
openclaw#169113/openclaw#169107/openclaw#169125 session-actor admission, openclaw#169110 bounded worker
heaps, openclaw#169130 inter-session provenance, openclaw#168931 Solid session UI).

Conflicts:
- session-accessor.sqlite-entry-mutation.ts: openclaw#169090 moved postimage
  publication into writeSessionEntry and replaced the revision-equality
  no-op check with postimages.changed. Took upstream's form; kept our
  recipient-authority advance on visibility narrowing (same transaction,
  after the write, before the no-op return).
- session-accessor.sqlite-entry-store.ts: import union (upstream dropped
  withProjectedParticipants/SessionEntryWindowFacts imports; ours adds the
  recipient-authority advance). Overlay vs upstream is now 2 lines.
- openclaw-tools.types.ts: import union (our RequestCompactionToolOpts,
  upstream's SessionsYieldRuntimeClaim).
- plugin-sdk-surface-report.mts: upstream raised the budgets to 3672/2133;
  ours stays +11/+4 on top (3683/2137).
- worker-access-inventory.md: regenerated on the merged tree.

Auto-merged files that carry continuation overlay (21) keep the overlay
byte-for-byte (interdiff of the +/- lines vs upstream before and after).

Refs #1475

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

docs Improvements or additions to documentation gateway Gateway runtime P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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