Repository navigation
perf(sessions): coalesce transcript metadata reads (step 4a) - #166804
Conversation
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.
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. What this changesThis PR combines compatible conversation-history metadata reads and reuses the physical session database already selected for a chat turn. Review scores
ProductKind: Performance · Worth it: Yes 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 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherOpenClaw 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]
Technical reviewBest 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
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfaceSource +479, Tests +241, Docs +12, Other +31. Total +763 across 47 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (8 earlier review cycles)
Reviewed October 8, 2026, 8:41 PM ET / October 9, 2026, 00:41 UTC (Revision 9). |
|
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.
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.
|
Merged via squash.
|
…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
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 of4968106with main7d18cafe. 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 issubagent 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
6b2afbfe981afa47063a306291ec5c6a3608e66eand the candidate, and unchanged on inspected main9284c76dea58496d0c02c925fa72f7aafad78ad0. 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 merge549e3e069bdd5b3006b50ffcdf0f31947452e752, 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
49681061611a9575493de9b920cd9735db63dc06at 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 from1620aa5bis 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 to1620aa5b; existing SQL proof is reused with its original pins.The
1620aa5bCI 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.tsbefore its first agent turn: the fixture creates a Git repository withoutorigin, then requests a managed worktree without a base ref. The worktree resolver rejectsgit ls-remote origin HEAD. The fixture andsrc/agents/worktrees/{base-ref,service}.tsare untouched by this PR and byte-identical to maina398553e; 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(parents76e3c453and main469899e1). 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
4968106versus 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.9andv2026.10.1-beta.1.setSessionTargetAsync(target, signal?)continues to returnPromise<void>; the replay hook is explicitly internal in both releases. The generated SDK report for main8879e5efto integrated7f0ee569has digest80bc652a: 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
76e3c453at 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
76e3c453CI 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
395ad803and candidate76e3c453completed 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 failedBEGIN IMMEDIATEduring 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.dismisswith 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
aa49dc56d0c5d4a10f72de5c7ec6c0c22a5bf984against measured candidate3d24b92f0820cc8eec1645865aafa4be7eb77924with 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
f11440d855ba1b79b80223a80b38cc4c78592e2dadds only 30 lines toscripts/pr-lib/wrapper-components.txt; Gateway production code, tests, and docs are identical to measured3d24b92f0820cc8eec1645865aafa4be7eb77924. The measurements retain their original 3d24 source pin; they are not relabeled as a new execution.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.
All 18 identified owner modules are byte-identical to the baseline. Both census sides have zero transcript-group or
session.entry.readrequests 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.
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.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.git diff --check: passed.aa49dc56…→3d24b92…: exit 0, digeste13db6e8. 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@internalin stablev2026.9.8; neither internal symbol is exported by SDK barrels. These differences were inspected.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 published2026.9.8driver × final candidate update cell passed in 879.91s (updater 388.474s): recordedfinished/succeeded, readiness 200, matching running build, durable history retained, and incognito history cleared. The built commit865e5717…is the verified source-capsule carrier for final sourcef11440d….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.session-entry-cohort.worker.test.tschat-send-reply-dispatch.test.tsattempt-session-replay.test.tssession-transcript-anchor-read.worker.test.tssession-manager-incognito.test.tsThe 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:
src/agents/sessions/session-manager.ts:553, plus two fresh hydration cohorts atsrc/config/sessions/session-transcript-hydration.ts:224src/agents/harness/agent-end-side-effects.ts:90,src/gateway/server-methods/chat-send-reply-dispatch.ts:201, andsrc/config/sessions/session-transcript-anchor-read.ts:121initSessionStateAttemptandresolveAgentRunSessionTarget(one upstream async stack is unavailable)src/agents/harness/context-engine-lifecycle.ts:338and:335src/agents/sessions/session-manager.ts:130src/agents/embedded-agent-runner/run/attempt-transcript-helpers.ts:174src/gateway/server-methods/chat-send-reply-dispatch.ts:240src/gateway/session-activity-summaries.ts:458Concrete step-4b work: