Skip to content

perf(sessions): coalesce transcript metadata reads (step 4a) - #166804

Merged
steipete merged 19 commits into
mainfrom
dbasync/tb4transcript
Oct 9, 2026
Merged

steipete merged 19 commits into
mainfrom
dbasync/tb4transcript

Conversation

@steipete

@steipete steipete commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Chat turns repeat transcript metadata preparation across replay, context, and reply delivery. Step 4a carries the admitted physical session target into those readers and combines compatible metadata reads.

The prerequisite #166703 is merged; the remaining transcript composition work is described below.

User Impact

Normal warmed chat turns perform less SQLite work. Fresh bounded history and replay metadata are prepared in the same history-worker snapshot, then consumed synchronously under the existing FIFO and native mutation witness. Delivery pairs anchors with watermarks and keeps payload decoding on the history reader.

Transcript bytes, branch/reset/rewrite generations, cursors, byte/event limits, permissions, and durability retain their existing contracts. There is no schema or configuration migration. Mutable SessionManager entries are only hints and cannot certify stored history; hydration still reads fresh persisted bytes.

Why This Change Was Made

The existing session-entry cohort remains the metadata contract. The selected owner accepts its original locator and physical SQLite aliases without rediscovery, while retaining the logical agent separately from the physical database owner. Bounded hydration adopts fresh bytes before deciding replay; a wrong or omitted hint takes the existing fallback. Full and incognito readers retain their existing ownership paths. Promise-returning callbacks are rejected at synchronous consumption boundaries.

Landing integration

Current head: 26cf2ffa30598898d384b4668b45371ac7ed366d, a merge of 4968106 with main 7d18cafe. GitHub reported a real conflict in the cohort worker. Resolution preserves main #167263's optional auth-profile source fact alongside the transcript facts, and migrates two new-main callers of the already-moved cohort guard to its existing leaf module. No new SQL, storage/API contract, or behavior is authored by that resolution.

The integrated tree passed fresh Codex P2 review, all 32 focused cohort/import/wrapper/process-build checks (397.76s wrapper), core types (6.12s), all 27 affected test type graphs (248.52s), and Madge with zero cycles (58.24s). The initial typecheck and worker build correctly caught the two stale imports; both are fixed. SQL proof and the completed ClawSweeper review are reused under the conflict-only landing policy. Prior CI and inherited-failure evidence below retain their old head/run pins and are not claimed as CI on this integration.

Against integrated main 7d18cafe: production +1115/−636, tests +362/−121, docs +12, tooling/config +32/−1 across 47 files. No new OPENCLAW environment names.

Prior CI completed on 49681061611a9575493de9b920cd9735db63dc06: run 37860107144, attempt 1 has 99 successful jobs and 23 skipped jobs. The sole failed root is subagent registry persistence > preserves restored interrupted-recovery owners for orphan replay, with the CI gate failing downstream. The prior transcript race failures are repaired. Security-fast and the current PR-context check passed.

This remaining failure is independently inherited: its unchanged fixture persists an already-terminal interrupted-recovery record without creating a child session. Recovery skips transcript result capture and fails a registry-owner/recovery-authority check after waiting for prior registry mutations. The test, fixture/mocks, and registry persistence/lifecycle/recovery owners are identical between tested main 6b2afbfe981afa47063a306291ec5c6a3608e66e and the candidate, and unchanged on inspected main 9284c76dea58496d0c02c925fa72f7aafad78ad0. The log does not distinguish which registry predicate changed; this is not attributed to transcript code or described as a reproduced main run. The inspected checkout is merge 549e3e069bdd5b3006b50ffcdf0f31947452e752, with exactly that main and PR head as parents. This qualifies for the explicitly authorized untouched-and-unrelated inherited-failure exception. Failed job.

ClawSweeper completed its review of 49681061611a9575493de9b920cd9735db63dc06 at 2026-10-08 23:40 UTC: ready for maintainer review, no actionable correctness or security findings, and no remaining before-merge items.

Prior reviewed test-repair head: 49681061611a9575493de9b920cd9735db63dc06. Its only change from 1620aa5b is the remaining three race-test observer repairs (+28/−33 test lines). Fresh Codex P2 review is clean, the selected test type graph passed, and all 22 tests in those three files passed locally (688.46s wrapper; runtime-config 455.83s, agents-support 172.41s). The tests still delegate to real worker validation and preserve every rewrite/close intervention, gate, rejection, and cleanup assertion. Production code is byte-identical to 1620aa5b; existing SQL proof is reused with its original pins.

The 1620aa5b CI run exposed these remaining old worker-pool/history-reader hooks in model-context snapshot, lifecycle-header, and context-projection tests. The observer cutover is now complete; the Gateway tail observer correctly stays on the history worker.

The same run also failed gateway-agent-skill-refresh.e2e.test.ts before its first agent turn: the fixture creates a Git repository without origin, then requests a managed worktree without a base ref. The worktree resolver rejects git ls-remote origin HEAD. The fixture and src/agents/worktrees/{base-ref,service}.ts are untouched by this PR and byte-identical to main a398553e; this is independently unrelated to transcript changes. This qualification uses source reachability under the authorized inherited-failure policy, not a claimed main-CI reproduction. Original failed job.

Reviewed runtime head: 1620aa5b57afb98bc4a5be92a5cf7d8785ed7c8d (parents 76e3c453 and main 469899e1). Fresh full-diff Codex P2 review is scoped clean. Core types passed (52.48s), all 27 affected test type graphs passed (768.76s), and Madge found zero cycles (75.58s). The assertion-safety ratchet passed, including the exact 4→3 allowance reduction in the original reader. All four formerly failing race cases passed locally (2 files, 4 selected tests; 932.74s wrapper / 559.80s Vitest under host load). Remaining cases were deliberately excluded from this focused replay, and are not claimed as newly executed. The current integrated cohort suite also passed both tests (242.75s wrapper / 112.82s Vitest), including retained runtime-target mapping and cancellation after cold preparation. A separate local lint attempt timed out while compiling prerequisite Plugin SDK declarations before lint started; exact-head CI supplies that check.

Source diff at 4968106 versus its integrated main: production +1113/−634, tests +362/−121, docs +12, tooling/config +32/−1. No new OPENCLAW environment names. No schema, stored-format, durability, or released SDK contract changes.

The prerequisite #166703 is merged. Main was integrated with merge commits only to resolve real conflicts and incorporate upstream fixes. The resolutions preserve main's retained runtime-target mapping and abort-aware index reader, alongside this PR's transcript metadata cohorts.

The landing repair keeps payload-tail reads (afterSeq) on the history worker and uses prepared execution only for bounded metadata. The replay race tests now pause the existing typed prepared reader after real worker validation; their rewrite, close, revoke, and no-consumption assertions are unchanged. Extracting the existing incremental transcript reader into a leaf module fixes the history-worker import boundary without changing its SQL, and the new file documents the stored-event type invariant required by the assertion-safety ratchet. The absent-database case retains initial replay validation.

Released SDK check: compared the public surface with stable v2026.9.9 and v2026.10.1-beta.1. setSessionTargetAsync(target, signal?) continues to return Promise<void>; the replay hook is explicitly internal in both releases. The generated SDK report for main 8879e5ef to integrated 7f0ee569 has digest 80bc652a: zero added/removed entrypoints and zero direct public signature changes. All 137 affected exports are reachable-closure changes (55 distinct declaration records). The later private routing correction and test observation change introduce no public contract change.

The earlier ClawSweeper review on 76e3c453 at 2026-10-08 21:47 UTC had no code or security findings and requested conflict resolution plus replay/delivery verification. Those items are complete; the latest exact-head review above is ready.

The previous 76e3c453 CI run 37848401658 failed the assertion-safety ratchet on the newly extracted file, then cancelled dependent jobs. This was PR-caused and is repaired; security-fast passed. Remote replay/delivery proof on that head found four failures (112 passed): one tail-routing regression and three obsolete test observation hooks, repaired as described above.

An earlier landing M,C sanity pair on main 395ad803 and candidate 76e3c453 completed all 13 turns, RPCs, cron, compaction, and shutdown: warmed ALL 1241.1→1212.9 statements/turn; first turn 2897→2818. The boot+connect+first window decreased 5472→5465. Connect's isolated +78 came entirely from untouched deferred-startup owners. The candidate recorded one excluded failed BEGIN IMMEDIATE during best-effort startup plugin-lease cleanup; baseline recorded none. These historical measurements retain their original pins and are not relabeled as execution of the repair. The Testbox lease was stopped and verified completed.

An earlier local baseline workload completed its chat turns but failed mentions.dismiss with Inbox UNAVAILABLE; no passing replay is claimed to fix that diagnostic. Original paired proof and published-driver update evidence remain below with their original source pins.

Evidence

The following paired measurements retain their original source pins.

Warmed all-thread work falls 1,435.9 → 1,402.6 statements/turn, with MAIN unchanged at 28. Effective transcript work falls 228 → 197 SQL and 25 → 18 requests, including incremental actor work. First and second sessions also improve against the pinned parent containing the write-planning prerequisites.

Phase counts, request attribution, measurement provenance, and diagnostic

Measured baseline aa49dc56d0c5d4a10f72de5c7ec6c0c22a5bf984 against measured candidate 3d24b92f0820cc8eec1645865aafa4be7eb77924 with three alternating M,C pairs on the same host/runtime and the unchanged shared SQL workload. Warmed ALL 1435.9→1402.6 (−33.3 /−2.32%), MAIN 28→28; first-turn ALL 4481→4432 (−49), MAIN 156→152. All final phase duration median ratios are ≤1.5. Per-run warmed means are M=[1463.8,1434.4,1435.9], C=[1421.6,1402.3,1402.6]; individual warmed ranges/maxima 1421–1552→1381–1473.

Final PR head f11440d855ba1b79b80223a80b38cc4c78592e2d adds only 30 lines to scripts/pr-lib/wrapper-components.txt; Gateway production code, tests, and docs are identical to measured 3d24b92f0820cc8eec1645865aafa4be7eb77924. The measurements retain their original 3d24 source pin; they are not relabeled as a new execution.

Phase MAIN baseline → candidate All-thread baseline → candidate All-thread delta Median duration ratio
01.boot 1869 → 1871 2764 → 2776 +12 1.006
01.connect 39 → 39 267 → 276 +9 1.076
02.first-turn 156 → 152 4481 → 4432 -49 1.250
03.warmed-mean 28 → 28 1435.9 → 1402.6 -33.3 1.172
04.second-session 147 → 148 4979 → 4918 -61 0.849
05.control-plane 0 → 0 47 → 44 -3 1.230
06.cron 50 → 57 1454 → 1430 -24 1.005
07.compaction 45 → 45 845 → 845 +0 0.638
08.shutdown 404 → 404 1092 → 1085 -7 0.707
Adjacent window Pair 1 ALL Pair 2 ALL Pair 3 ALL Median ALL
Boot + connect 3230 → 3062 3030 → 3052 3027 → 3052 3030 → 3052
Control + cron 1658 → 1395 1501 → 1490 1466 → 1493 1501 → 1490
Compaction + shutdown 2035 → 1940 1942 → 1936 1937 → 1927 1942 → 1936

Boot+12(+0.43%) and connect+9 satisfy NON-TURN TOLERANCE. Their unchanged cron/subagent, configuration/freshness, and agent-deletion/registry readiness owners were verified byte-for-byte against the baseline; boot+connect is 3030→3052(+0.73%), with no transcript/cohort requests in those phases. Integrated second-session decreases 61.

Increasing phase Delta Unchanged-owner attribution
Boot +12 / +0.43% Existing cron mutable-load/receipt and subagent-run reads, with configuration, ownership/freshness, and transaction envelopes.
Connect +9 Existing agent-deletion/registry snapshots and migration/schema-readiness probes.

All 18 identified owner modules are byte-identical to the baseline. Both census sides have zero transcript-group or session.entry.read requests in boot/connect.

The fresh request census reports total 233.0→225.0 requests/turn. Transcript 25 requests/228 SQL→17/183; actor 14/51→15/65. Effective step4a cost remains 18 requests/197 SQL, including its +1-request/+14-SQL actor increment; the direct combined saving is 7 requests/31 SQL. This is the approved step4a scope, with broader transcript composition left for follow-up.

The separate census gives this request breakdown; its single-run counts are diagnostic, while the ordinary three-pair medians above decide the statement gate.

Phase Requests baseline → candidate
Boot 60 → 63
Connect 36 → 36
First turn 331 → 321
Warmed mean 233 → 225
Second session 761 → 746
Control plane 5 → 5
Cron 200 → 186
Compaction 93 → 96
Shutdown 107 → 107
Warmed work Requests baseline → candidate SQL baseline → candidate
Transcript reads 25 → 17 228 → 183
Entire existing session-entry actor group 14 → 15 51 → 65
Combined 39 → 32 279 → 248
Effective step 4a, charging the actor increment 25 → 18 228 → 197

One candidate pair 2 shutdown-only failed BEGIN IMMEDIATE was retained in unchanged audit.writer.prune (database is locked). All workload/shutdown receipts passed; first/warmed/census native failures are zero. Counting that attempt does not change any gated median. Native CSV conservation and all 16 calibration streams passed.

Removed SQL is current-entry −28, anchors −25, watermarks −7, and history-page −1. Fresh hydration metadata adds 16 SQL and the actor adds 14 SQL/1 request, leaving the attributed reduction of 31 SQL/7 requests. Other total-request changes are not all claimed as lane savings.

The unchanged shared synthetic workload includes all 13 top-level turns, native child, control RPCs, cron, committed compaction, background/helpers, unassigned statements, and the original settling windows. Node 24.21.0, SQLite 3.53.4, macOS 27.0.1. Counts are side medians across three alternating pairs; the warmed row is the median of ten-turn run means. This is statement-count evidence, not unloaded-host latency evidence. Both census sides retain two unmatched boot protocol sends/receives; every warmed request completed and every native phase/thread total reconciled.

The earlier 513890… study was 1,496.35 → 1,463.70 statements/turn. Its second-session/control/cron window rose 0.78%, attributed to unchanged configuration/freshness, placement/notifier, and reconciliation owners while the affected request union fell 795 → 732 SQL. Those historical samples are excluded from the integrated comparison above.

Original-head validation

The original approved head was f11440d855ba1b79b80223a80b38cc4c78592e2d. Its sole change after the measured/reviewed runtime head is the PR-wrapper source inventory: 30 transitive dependencies required by the reused transcript kernel. Application code, tests, and documentation are byte-identical to the measured head. The final diff is 1,320 production lines, 30 tooling inventory lines, 369 test lines, and 12 documentation lines.

  • Independent Codex P2: full integrated candidate and final inventory repair both scoped clean; committed bytes match the reviewed files.
  • node scripts/check-changed.mjs --base aa49dc56d0c5 --head HEAD: complete runtime candidate passed, including production types, all 27 selected test type graphs, lint, and architecture guards. Final inventory-only tooling lane also passed, including the complete script-lint lane.
  • Knip production file/dependency scan: passed (107.9s). Madge: zero cycles. SQLite worker ratchet: no T1 call-count growth. Formatting and git diff --check: passed.
  • SDK API diff aa49dc56… → 3d24b92…: exit 0, digest e13db6e8. No added/removed entrypoints or direct export declaration changes. All 137 affected export closures are reachable changes (56 distinct records), covering internal cohort metadata, computed SessionManager symbols, declaration ordering, and normalized wildcard-module alignment. The replay symbol is explicitly @internal in stable v2026.9.8; neither internal symbol is exported by SDK barrels. These differences were inspected.
  • Remote proof uses AWS Crabbox after Testbox did not acquire a runner within 15 minutes. Source capsules verify the physical Git root, parent/tree, and every changed-file hash before running commands. Five product files passed 146 tests on 3d24b92…; their source is unchanged in the final head. The final head passes all 17 wrapper extraction tests and 248 tests in 13 sibling files, for 411 passed tests across 19 files overall. The published 2026.9.8 driver × final candidate update cell passed in 879.91s (updater 388.474s): recorded finished/succeeded, readiness 200, matching running build, durable history retained, and incognito history cleared. The built commit 865e5717… is the verified source-capsule carrier for final source f11440d….

AWS proof runs: product suites and final wrapper/sibling/update proof. The lease was released and independently verified; measurement worktrees and fixture children were also cleaned up.

For each changed test file, the command is CI=1 pnpm test <file> --maxWorkers=1. These are measured CI-mode AWS Linux seconds, not hosted GitHub Actions timing; wall time includes worker-artifact preparation.

Changed test file Passed tests pnpm wall seconds Vitest elapsed seconds
session-entry-cohort.worker.test.ts 1 28.695 8.77
chat-send-reply-dispatch.test.ts 45 74.169 54.37
attempt-session-replay.test.ts 71 213.455 193.76
session-transcript-anchor-read.worker.test.ts 8 34.465 31.57
session-manager-incognito.test.ts 21 26.957 7.19

The successful focused commands used 632.824 seconds of serial CI-mode wall time, including 27.557 seconds for the full wrapper suite and 227.526 seconds for the sibling group. Sibling coverage includes bounded/byte-size history, hydration acceptance/rejection/streaming, real selected-entry workers, FIFO ordering, worker errors, transcript write context, and attempt lifecycle preparation/settlement.

The full candidate package build completed. It logged a nonfatal Control UI startup JavaScript gzip budget violation: 373,577 bytes against a 373,454-byte enforcement limit (+123 bytes). UI files are unchanged, but no baseline UI build was used to attribute the warning.

The initial proof exposed three replay fixture issues: the selected execution owner's precise closed-admission error, logical versus physical shared-store setup, and revocation before a manager could open. Corrected fixtures pass, including the original post-open cleanup assertion. The inventory closure test then named the 30 dependencies now included in the extracted wrapper.

Remaining transcript budget

Step 4a is the accepted partial reduction to 197 statements / 18 requests. The original 42 / 4 allocation remains a follow-up target. The path/line anchors below are from the initial step-4a measurement; the fresh census confirms the same request/SQL breakdown:

Remaining path Requests / SQL per warmed turn
Initial manager hydration at src/agents/sessions/session-manager.ts:553, plus two fresh hydration cohorts at src/config/sessions/session-transcript-hydration.ts:224 3 / 64
Anchor reads at src/agents/harness/agent-end-side-effects.ts:90, src/gateway/server-methods/chat-send-reply-dispatch.ts:201, and src/config/sessions/session-transcript-anchor-read.ts:121 4 / 46
Cold-restoration scalar requests during initSessionStateAttempt and resolveAgentRunSessionTarget (one upstream async stack is unavailable) 4 / 8
End-of-turn current-entry and maintenance metadata at src/agents/harness/context-engine-lifecycle.ts:338 and :335 2 / 26
Initial model-context read at src/agents/sessions/session-manager.ts:130 1 / 13
Existing-transcript message presence at src/agents/embedded-agent-runner/run/attempt-transcript-helpers.ts:174 1 / 9
Delivery history at src/gateway/server-methods/chat-send-reply-dispatch.ts:240 1 / 12
Activity-summary watermark at src/gateway/session-activity-summaries.ts:458 1 / 5
Incremental selected-actor metadata 1 / 14

Concrete step-4b work:

  1. Compose the initial bounded persistence view and model-context preparation at their history owner, sharing source, header, navigation, and sizing facts within each genuinely fresh phase. Preserve the distinct payload filters, limits, and required-byte behavior. Never use mutable SDK-visible entries as persisted-history evidence.
  2. Join end-of-turn maintenance/current-entry facts and compatible agent-end anchor consumers into one bounded cohort per phase. Carry exact generations and anchors through synchronous consumers; open another fresh phase after an intervening await or mutation.
  3. Carry the selected physical target into cold restoration and combine scalar cold/hot checks with the owning history operation. Keep restoration with its current owner and retain foreign-commit, reset, and replacement checks.
  4. Prepare delivery payload selection with its initial anchors/watermark in the history lane, and have terminal/activity consumers use certified commit facts or one fresh metadata cohort. Preserve visible-answer selection, cursors, byte limits, and final live-authority checks.
  5. Remeasure the complete transcript group plus incremental actor work against the step-4a head, using alternating pairs and all-thread accounting. Record any extra phase required for correctness instead of omitting probes or holding a transaction across awaits.

Merge main at cbfbdc8 while retaining the selected session execution owner. Preserve transcriptOwner alongside the consolidated sessionPreparation input.

Seed the queued-reader freshness fixture through the existing synchronous writer so unrelated automatic maintenance cannot occupy its controlled race window. Preserve the original snapshot, queued-write, and event-order assertions.

The original head reproduced the fixture failure in all five runs; the merge base passed all five. A diagnostic proved that consumption preceded the queued write, and the corrected fixture passed all seven tests. Production and core test types, Madge, and independent P2 review passed on the integrated tree.
Merge main at e1dbb59 after #166698 landed. Keep the selected session execution and foreground fact implementation, and its freshness-fixture correction, unchanged while incorporating the canonical TEMP generation admission fix.

The integration required no conflict resolution or additional product changes. Fresh P2 review is clean; affected checks and alternating statement measurements remain required before landing.
Carry the admitted physical session owner into transcript preparation and
combine fresh bounded hydration with replay metadata under the existing
history reader. Combine delivery anchors and watermarks while preserving
source identity, synchronous consumption, and mutable SessionManager semantics.

Measured effective transcript work falls from 228 to 197 SQLite statements
and 25 to 18 logical requests per warmed turn, including incremental actor
work. Keep the remaining transcript composition budget for step 4b.
Merge main at 0abba2b while preserving both required-worker selection and the retained session reader.

Keep main's reply-input and classification helpers alongside the cohort fingerprint path. Reuse main's sessionTarget object while carrying the reader, lifecycle facts, abort check, and acknowledged initialization handoff through their existing owners.

Fresh independent P2 review found no actionable defects in the integrated tree. Exact-head runtime, SDK, CI, and statement proof remain landing gates.
Merge current main into the turn-budget step-one branch without rebasing.
Preserve main's native writer claim and empty-maintenance completion alongside
retained session-reader authority and the extracted preparation regressions.
Route the two model-selection consumers to the existing host-owned test
project after main moved placement reads to the shared-state worker.

The three missing-broker cases reproduce before the routing repair and pass
through the normal test router afterward. Post-integration production and
core test types pass; Madge reports no cycles. Fresh independent P2 review
found no actionable correctness findings.
@clawsweeper

clawsweeper Bot commented Oct 7, 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 scripts Repository scripts agents Agent runtime and tooling size: XL labels Oct 7, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 7, 2026
@clawsweeper

clawsweeper Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR combines compatible conversation-history metadata reads and reuses the physical session database already selected for a chat turn.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful measured performance work with real Gateway evidence, preserved ownership contracts, and no remaining actionable findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The fully inspected evidence exercises the changed transcript readers through real Gateway turns and records reduced SQL and requests after the change, plus a successful published-driver update preserving durable history. Measurement pins remain historical; subsequent routing repairs have focused worker proof, and the latest integration preserves the existing contracts. The diff changes no persistent data model.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes
User problem: Chat turns perform repeated conversation-history preparation that consumes avoidable database and worker work.
Reason: The area owner proposes a measured reduction through existing owners without adding configuration or changing stored history. The evidence supports this bounded step independently of the larger performance target.

Merge readiness

✅ Ready for maintainer review

This PR is ready for normal landing: the prior integration blocker is resolved, and no actionable correctness or security findings remain.

Priority: P2
Reviewed head: 26cf2ffa30598898d384b4668b45371ac7ed366d

Before merge

None.

Findings

None.

Agent review details

How this fits together

OpenClaw stores conversation history and session metadata in SQLite. Agent preparation, interrupted-turn replay, and reply delivery consume fresh worker-prepared facts before their existing owners make final decisions.

flowchart TD
  A[Chat turn] --> B[Selected session database]
  B --> C[Metadata reader]
  B --> D[History reader]
  C --> E[Current ownership and transcript checks]
  D --> E
  E --> F[Replay admission or reply delivery]
Loading

Technical review

Best possible solution:

Land the bounded composition through the existing session and history owners, then pursue the remaining transcript budget in the separately scoped follow-up.

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

Not applicable as a bug reproduction; the repeated-work baseline is supported by paired Gateway statement measurements and the existing separate read paths.

Is this the best way to solve the issue?

Yes: compatible facts share existing worker snapshots while payload decoding, fresh-phase checks, and final synchronous consumption retain their established owners.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced production change: The pinned merge-base-to-head diff combines replay metadata with fresh bounded hydration, adds watermark facts to anchor reads, and keeps payload-tail decoding on the history reader. (src/config/sessions/session-transcript-hydration.ts:201, 26cf2ffa3059)
  • Exact-target and live-authority checks: The selected reader must match the original session identity, logical agent, accepted physical paths, and state environment; borrowing also invokes the current commit assertion. Synchronous cohort consumption retains generation, caller, and native-mutation checks. (src/config/sessions/transcript-write-context.ts:156, 26cf2ffa3059)
  • Integration preserves both fact sets: The exact head records the previous reviewed head and pinned main as its raw parents. The cohort worker retains transcript facts alongside main's optional auth-profile source fact, and both newly added callers use the extracted scope guard. (src/config/sessions/session-entry-cohort.worker.ts:127, 26cf2ffa3059)
  • Real Gateway performance evidence: The fully read PR body reports three alternating baseline/candidate pairs through the shared Gateway workload, including 13 turns, control requests, cron, compaction, and shutdown. At the recorded measurement pins, warmed all-thread SQL falls from 1,435.9 to 1,402.6 statements per turn; effective transcript work falls from 228 SQL/25 requests to 197 SQL/18 requests. These remain historical measurements, not execution of the latest integration. The verified full-body SHA-256 is a5f8909adce8bc64e6a3326ca8a351d2f687685c4c325b36596e75cdbc6097f2. (3d24b92f0820)
  • Update and public-contract evidence: The PR records a published 2026.9.8 updater running against the original candidate: update finished successfully, readiness returned 200, the running build matched, durable history remained, and incognito history cleared. Later SDK comparisons retain Promise<void> for setSessionTargetAsync and report no direct public signature changes. The reviewed diff introduces no persistent schema or serialized-format change. (src/agents/sessions/session-manager-core.ts:135, f11440d855ba)
  • Current-head landing state: Fresh REST reads retain the exact reviewed head and report clean mergeability. The CI gate, dependency review, and sensitive-change review are successful; expanded check results contain no failed or pending checks, with CodeQL completed neutral. (26cf2ffa3059)

PR surface

Source +479, Tests +241, Docs +12, Other +31. Total +763 across 47 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 34 1115 636 +479
Tests 10 362 121 +241
Docs 1 12 0 +12
Config 0 0 0 0
Generated 0 0 0 0
Other 2 32 1 +31
Total 47 1521 758 +763

Review metrics

Metric Value Why it matters
Measured transcript work 228 → 197 SQL statements; 25 → 18 requests per warmed turn The original paired measurement includes incremental actor work and supports a bounded reduction without claiming the remaining budget is complete.

Labels

Label changes:

  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a measured internal performance improvement with preserved conversation and storage contracts, rather than an urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (8 earlier review cycles)
  • reviewed 2026-10-07T23:24:16.425Z sha f11440d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-08T20:14:09.542Z sha f11440d :: blocked before merge. :: none
  • reviewed 2026-10-08T21:35:38.799Z sha 7f0ee56 :: needs changes before merge. :: none
  • reviewed 2026-10-08T21:47:17.818Z sha 76e3c45 :: needs changes before merge. :: none
  • reviewed 2026-10-08T23:00:00.564Z sha 1620aa5 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-08T23:07:36.182Z sha 1620aa5 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-08T23:40:33.633Z sha 4968106 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-09T00:10:48.540Z sha 4968106 :: needs changes before merge. :: none

Reviewed October 8, 2026, 8:41 PM ET / October 9, 2026, 00:41 UTC (Revision 9).

Base automatically changed from dbasync/turnbudget-step1-current to main October 8, 2026 20:07
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 26cf2ffa30598898d384b4668b45371ac7ed366d
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/sandbox/runtime-status.ts: Controls sandbox containment or tool execution authority. Check filesystem and network isolation, approval scope, and command allowlists.

Carefully review these changes before merging.

Preserve current session ownership and retained history readers while merging main. Keep initial replay facts for absent databases, isolate incremental transcript rows from host reader imports, and group hydration worker types with their existing owner.
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
Resolve the type-only conflict by retaining the current search cancellation callback alongside the reviewed hydration reader contracts. Transcript runtime logic and SQL paths are unchanged by this resolution.
@clawsweeper clawsweeper Bot added status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 8, 2026
@clawsweeper clawsweeper Bot added status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@steipete
steipete merged commit 1b19614 into main Oct 9, 2026
179 checks passed
@steipete
steipete deleted the dbasync/tb4transcript branch October 9, 2026 00:42
@steipete

steipete commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…w#166804)

* perf(agent-db): retain selected session execution across turn phases

* perf(sessions): reuse empty pending-history counts

* refactor(agent-db): keep cohort scope within its reader module

* refactor(agent-db): make lazy cohort imports explicit

* refactor(agent-db): preserve session callback receivers

* perf(sessions): coalesce transcript metadata reads for step 4a

Carry the admitted physical session owner into transcript preparation and
combine fresh bounded hydration with replay metadata under the existing
history reader. Combine delivery anchors and watermarks while preserving
source identity, synchronous consumption, and mutable SessionManager semantics.

Measured effective transcript work falls from 228 to 197 SQLite statements
and 25 to 18 logical requests per warmed turn, including incremental actor
work. Keep the remaining transcript composition budget for step 4b.

* refactor(sessions): isolate transcript reload consumption

* test(sessions): document intentional async consumer rejection

* fix(tooling): include transcript cohort wrapper dependencies

* test(sessions): observe prepared metadata race boundaries
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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts security-sensitive-changed 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