Skip to content

perf(sessions): reuse actor transcripts across scoped worker writes - #170199

Merged
steipete merged 11 commits into
mainfrom
dbasync/anchorreuse-rewrite
Oct 12, 2026
Merged

steipete merged 11 commits into
mainfrom
dbasync/anchorreuse-rewrite

Conversation

@steipete

@steipete steipete commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Ordinary turns discarded the session actor's retained transcript twice: trajectory-only writes invalidated unrelated session/transcript facts, then prompt capture rewrote the admitted user message without publishing a reusable committed result. That forced anchor reads even when the actor already held current context; activity-summary reads also lacked a replica path. Durable trajectory recording also retained a synchronous production fallback.

This PR combines the trajectory prerequisite from #170133 with committed rewrite reuse. Trajectory receipts name the affected session and sequence bounds; trajectory-only DML certifies that no session/transcript rows changed. Durable recording always uses the existing worker. For admission- and navigation-preserving rewrites, the existing transcript authority receipt carries canonical replacement rows and the resident actor postimage. The transaction owner publishes once after commit, and the bounded replica installs that result. A complete current actor can then serve anchors and hydration. When no admission fence is present, it can also serve activity-summary batches under the canonical byte/message/omission policy.

Content or topology changes, cold/incomplete state, and capacity overflow use the canonical reader. Rollback leaves stored messages unchanged and preserves the database owner's existing failed-write cache invalidation. This adds no cache owner, freshness query, generation, handshake, or synchronous fallback. Schema, retention policy, permissions, public SDK signatures, and update/service lifecycle behavior are unchanged.

SQL and main-thread impact

Trajectory T1 calls: 6 → 0, covering three append and three retention operations. The synchronous fixture implementation moved to test support; worker-only runtime code is classified accordingly.

Incremental committed-rewrite measurement

One unchanged shared-harness v2 pair on the same isolated Linux runner, ten warmed turns each: baseline ed573c1a3b8ad25e30d589b499202f6ec4b14d8a, candidate 9c6e73e6a17a9cc019bfc483d1159215088b806e. Native provisioning verified both source revisions/trees, and the harness hashes match. Counts below are turn-caused, all-thread counts, with background work attributed separately.

Per warmed turn Base Candidate
Statements, median [min–max] 204 [204–204] 193 [193–193]
Requests, median [min–max] 45 [45–45] 44 [44–44]
Statements, mean 204 193
Requests, mean 45 44
MAIN statements, median [min–max] 0 [0–0] 0 [0–0]
Standalone anchors, SQL / requests 10 / 1 0 / 0
Summary source, SQL / requests 7 / 1 7 / 1
Transcript hydration, SQL / requests 12 / 1 12 / 1

The incremental saving is 11 statements and one request per warmed turn (5.4% fewer statements). Anchor reads reach zero; the activity-summary read remains, so the combined anchor/summary target is only partly achieved. No hydration reduction is claimed for this step. Summary reuse deliberately requires both complete resident context and an unfenced read. The measured transcript contains ordinary model-snapshot and runtime-context custom entries, which the current simple-path eligibility rejects. Anchors can use snapshot/tail facts, but summaries require complete rows and retain their existing 7-statement/1-request read. Follow-up: support these ordinary linear metadata entries through canonical projection semantics, with a real-turn regression; keep the canonical reader for unsupported or incomplete paths.

Shared causal SELECT family, per turn Base Candidate
Exact-entry facts 4 4
Actor hydration 2 1
Entry-cache snapshot loads 0 0
Row facts 0 0
Watermark reads 1 1

None of the five shared causal families rises. Whole-workload statements: 7,063 → 6,913; requests: 1,251 → 1,239; MAIN: 1,067 → 1,059. Background SQL/minute: 909.09 → 963.31; legacy wall-window SQL/turn: 227.2 → 217.2. Those background/window values use different attribution bases and are not added to the causal saving. Both runs passed all 13 turns, child process, RPCs, cron, compaction, and shutdown, with no failed native calls or remaining fixture children. Workload times were 44.9 s and 49.3 s; no latency improvement is claimed.

This frozen pair isolates the incremental rewrite implementation. Final head 1e4edf6dca6dea81fc6a441d4ba1c4dc6992da32 also contains subsequent type/test/docs corrections and integration of main's projection receipts. Its exact-head CI is reported below; this pair is not a measurement of the complete final integrated tree. Earlier prerequisite savings use a different base and are not additive.

Earlier prerequisite measurement (different base; not additive)

Measured prerequisite step

One unchanged shared-harness v2 pair, ten warmed turns each: baseline 1c12d0c8e6cc8154feea661a3bb3fec8058699c6, candidate b2bf9f9c01683a3b7b33446fd96010e5af0e9824. These are turn-caused all-thread counts, excluding separately attributed background work. This pair measures the trajectory/scoped-summary prerequisite; it does not measure the subsequent rewrite-reuse change.

Per warmed turn Base Prerequisite candidate
Statements, median [min–max] 221.5 [215–232] 206 [206–211]
Requests, median [min–max] 52.5 [50–55] 46 [46–47]
Statements, mean 222.5 207.0
Requests, mean 52.5 46.2
MAIN statements 0 [0–0] 0 [0–0]
Standalone anchors, SQL / requests 10 / 1 10 / 1
Summary source, SQL / requests 7 / 1 7 / 1
Transcript hydration, SQL / requests 14 / 1.2 12 / 1

The observed mean reduction is 15.5 statements and 6.3 requests per warmed turn. Excluding unrelated auth-profile admission scheduling variation leaves a conservative attributable saving of 7.0 SQL statements and 4.6 requests per turn. Trajectory INSERT shapes and counts remain unchanged: two per warmed turn.

Shared causal SELECT family, per turn Base Prerequisite candidate
Exact-entry facts 6.0 4.0
Actor hydration 4.9 2.0
Entry-cache snapshot loads 0 0
Row facts 0 0
Watermark reads 1 1

Whole workload, including startup/shutdown: statements 8,212 → 7,337; requests 1,561 → 1,259; MAIN 1,103 → 1,096. No shared causal family rises. Both runs completed all 13 turns, native child, RPCs, cron, compaction, and shutdown with matching native calibration. Background and wall-window counts vary with host load; no latency improvement is claimed.

Main independently adopted the empty trajectory write scope in #170127 while this lane was in review. The historical prerequisite saving therefore is not all incremental against current main; the source SHAs above delimit that measurement.

Removed checks and accepted edges

  • Remove blanket session/transcript invalidation after trajectory-only DML. A trajectory append or trim no longer forces transcript rereads; writers changing session/transcript tables must publish those scopes.
  • Remove the synchronous durable-sink fallback. Worker failure surfaces through the existing settlement path.
  • Remove unconditional replica invalidation after admission- and navigation-preserving metadata rewrites. Reuse stays within the resident actor's existing committed write token; cold or incomplete facts use the reader.
  • Remove unconditional anchor/hydration reads when the committed receipt covers complete retained context, and summary reads when the unfenced replica path is eligible. Eviction, invalidation, or payload growth beyond existing limits discards that context and uses the reader.

The exact-row SQL compare-and-swap, transcript ownership fences, summary admission restriction, retention data checks, and execution-authority checks remain: they protect stored user messages, deletion correctness, and current source authority. Transcript append outside the actor, content rewrite, replacement, suffix trim, rewind, compaction, reset/deletion, and archive/restore retain invalidation coverage.

Evidence

The production-path regression exercises asynchronous prompt capture, assistant append, and public anchor/summary/hydration reads without history/discovery worker requests. Native transaction coverage proves one publication after commit, no publication and unchanged canonical messages after rollback, and invalidation after consecutive rewrites in one transaction. Other regressions cover trajectory append/trim/retention, every transcript writer class above, archive/restore, metadata byte growth, multibyte payloads, summary invalidation, role-aware omission, 64-message batches, and mutation isolation.

Basic changed-file formatting, oxlint, and git diff --check passed. Each reviewed implementation component completed at most two independent Codex review rounds. The prerequisite's final round had no actionable findings; the rewrite component's implementation and correction reviews were scoped-clean. The prerequisite byte-boundary concern was checked against the SQL/JSONL accounting and covered at cap/cap+1. Main integration preserves the existing preview/projection receipts and trajectory write scope. Replica type declarations moved to a leaf file to keep the combined implementation within the existing lint limit; this extraction changes no runtime behavior.

Final integrated-head CI 38308037252, source 1e4edf6dca6dea81fc6a441d4ba1c4dc6992da32, passes all production/test type stripes, lint stripes and aggregate lint, source contracts, Madge, T1/dialect/baseline ratchets, build artifacts, and the extension-package boundary. All 135 owner cases across ten files pass on this head: transcript replica (11), residency (4), public reuse (1), actor (17), transcript authority (9), summary retry (28), summary source (1), trajectory retention (21), trajectory store (29), and trajectory writer/mock caller (14). The public reuse regression took 7.855 s in CI. A CI bundle stopped on an unrelated earlier test before running the pure transcript replica file; its focused final-head run passes all 11 cases (12.10 s Vitest, 22.90 s runner).

Final-head Knip: inherited failure, not green. The production scan reports exactly the same three findings as scheduled main run 38305224828, job 114997826780: hasActiveDeliveryOwner in src/infra/outbound/delivery-queue-storage.ts, and listOpenClawStateFeatureSchemas plus OpenClawStateFeatureSchema in src/state/openclaw-state-feature-schema.ts. Both files are untouched by this PR; the red-main repair owner has the evidence. This qualifies for the authorized inherited-static-failure exception. The CI command stopped before its full export scan. A separate final-head full-tree-only scan hit its unchanged 600-second deadline (605.492 seconds including termination grace) without diagnostics; it is incomplete proof, not a pass. Earlier prerequisite full-tree scans were clean. No blanket final-head Knip success is claimed.

Aggregate CI is not claimed green. At the final evidence cutoff, 252 inspected failing cases matched the same cases on main, one matched an independent branch, and 46 cases across seven untouched files remained unclassified. Additional unhandled runtime-config errors are recorded separately. The unclassified files cover cron runs, media authority, concurrent OAuth agents, chat abort incarnation, embedded/yielded session abort, and run-orchestrator suspension. Runtime/config preparation errors and one OAuth timeout account for part of that unresolved evidence; these are not asserted to be inherited. No changed owner test fails, and no product regression caused by this PR has been established. The red-main repair owner received 50 records covering 49 matching test files plus Knip. These limits are disclosed under the authorized relaxed landing policy.

No published-driver update cell or SDK API diff is required: update, Doctor, schema migration, plugin loading, service lifecycle, and public SDK surfaces are unchanged.

Combined diff against integrated main 21f043cf86f5fd6bd2c5d279c8d205996661d237: 41 files, +1,582 / −688 lines, including regression tests and the regenerated inventory. The committed inventory changes global T1 from 481 to 465 and T1-compat from 2 to 9; this includes refreshed classifications already present on main. This lane claims only the verified trajectory 6 → 0 cutover. Final integrated source is 1e4edf6dca6dea81fc6a441d4ba1c4dc6992da32; same-revision CI 38308037252 provides the static and owner-test results above. The push-triggered PR run retained the old stacked-base event and stopped before tests on imported-main locale artifacts; that scope failure is not a source regression. An initial manual dispatch also stopped at preflight because the main validation tier requires identical workflow and source revisions. The corrected same-revision dispatch supplies final validation; neither preflight failure ran source checks.

Carry exact canonical replacement rows in the existing transcript authority receipt. Settle resident payloads with the owning transaction and preserve fallback for content changes, rollback, intervening writes, and bounded-context overflow. Cover the actual prompt-capture to anchor and activity-summary read flow.
@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: XL labels Oct 12, 2026
@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 preserves resident actor transcripts across compatible metadata rewrites and trajectory writes, allowing more reads to reuse committed context.

Example: A turn persists “Next question,” captures the identical model prompt, and appends “Next answer.”

  • Before: Prompt capture invalidates retained context, requiring subsequent anchor and recap reads.
  • After: The production-path regression retrieves anchors, recap messages, and hydrated context from the updated replica without history-worker requests.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The implementation and boundary regressions are coherent, with no established introduced defect; incremental production evidence remains limited.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; supplied Gateway output covers the trajectory prerequisite, while the incremental prompt-rewrite 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: Ordinary chat turns repeat transcript database work despite already retaining the current context.
Reason: The maintainer-authored direction extends an established optimization and retains the existing storage and authorization contracts.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep this PR open: it contains useful, maintainer-directed transcript reuse work, and no concrete introduced defect was established.

Priority: P2
Reviewed head: 1e4edf6dca6dea81fc6a441d4ba1c4dc6992da32

Before merge

  • Complete next step - Classify the failing check-dependencies and test checks on the reviewed head against base evidence, repairing only demonstrated diff-caused failures.

Findings

None.

Tests

  • Missing end-to-end proof: The planned matched Gateway comparison has not yet demonstrated the incremental rewrite-reuse result, and a base-failing run of the new regression was not supplied.
Agent review details

How this fits together

The session actor sits between chat-turn operations and per-agent SQLite workers, publishing committed facts to bounded replicas used by transcript and Activity readers.

flowchart TD
  A[Chat turn] --> B[Session actor]
  B --> C[SQLite worker]
  C --> D[Committed receipts]
  D --> E[Bounded actor replica]
  E --> F[Anchors hydration and recaps]
  F --> C
Loading

Technical review

Best possible solution:

Complete the existing actor-owned reuse path while preserving canonical fallbacks, exact stored bytes, and current caller authorization.

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

Current-main source and the prior committed-context work explain why compatible prompt rewrites discard reusable transcript context; no reproduction was executed during this read-only review.

Is this the best way to solve the issue?

The implementation extends existing actor and receipt owners, shares recap selection policy, and preserves bounded canonical reads rather than introducing another cache or freshness mechanism.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Resident transcript reuse and invalidation changes intended behavior with a stated reason (8656a68: Reuse committed context while conservatively invalidating history-changing operations and retaining canonical cold reads.)
  • Admission-preserving prompt rewrites keeps the original intent (5a1cd1a: Preserve transcript anchors for identical prompt captures; this patch retains that admission distinction and adds committed replica updates.)
  • Trajectory worker routing changes intended behavior with a stated reason (5cf0047: Move trajectory persistence off the Gateway thread while preserving settlement and native ownership paths; the body explicitly records removal of the remaining durable synchronous fallback.)
  • Activity recap selection keeps the original intent (0bc7491: Read recap metadata, ancestry, and bounded messages consistently; the patch shares incremental policy and compares replica results against the canonical worker.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 80d82ca adds src/config/sessions/session-actor.worker.ts:153 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.worker.ts)
  • Vitor Cepeda Lopes: Raw commit ca0a172 adds src/config/sessions/session-actor.worker.ts:370 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 +256, Tests +605, Docs +26, Other +7. Total +894 across 41 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 26 637 381 +256
Tests 12 837 232 +605
Docs 2 100 74 +26
Config 0 0 0 0
Generated 0 0 0 0
Other 1 8 1 +7
Total 41 1582 688 +894

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded runtime performance improvement without an established urgent user-facing regression.
  • 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 planned matched Gateway comparison showing anchor, recap-source, and hydration reads after prompt capture.

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-12T20:14:01.959Z sha 9c6e73e :: needs changes before merge. :: [P2] Respect rollback invalidation in the new residency regression
  • reviewed 2026-10-12T20:37:28.608Z sha 441e287 :: needs changes before merge. :: none

Reviewed October 12, 2026, 5:11 PM ET / 21:11 UTC (Revision 3).

@openclaw-barnacle openclaw-barnacle Bot added the agents Agent runtime and tooling label Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 12, 2026
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: msteams Channel integration: msteams channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web labels Oct 12, 2026
@steipete steipete changed the title perf(sessions): retain actor context through metadata rewrites perf(sessions): reuse actor transcripts across scoped worker writes Oct 12, 2026
@steipete
steipete changed the base branch from dbasync/anchorreuse to main October 12, 2026 20:56
@openclaw-barnacle openclaw-barnacle Bot removed channel: discord Channel integration: discord channel: imessage Channel integration: imessage channel: line Channel integration: line channel: matrix Channel integration: matrix channel: msteams Channel integration: msteams channel: slack Channel integration: slack channel: telegram Channel integration: telegram channel: voice-call Channel integration: voice-call channel: whatsapp-web Channel integration: whatsapp-web channel: zalouser Channel integration: zalouser app: macos App: macos app: web-ui App: web-ui extensions: llm-task Extension: llm-task extensions: lobster Extension: lobster extensions: memory-core Extension: memory-core extensions: memory-lancedb Extension: memory-lancedb labels Oct 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling 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: XL 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