Repository navigation
improve: reduce repeated transcript reads per chat turn - #167238
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 changes before merge. What this changesThis PR combines conversation-history reads across chat preparation, replay, completion, and delivery, reuses committed message receipts, and incorporates separately landed export, catalog, and Tlon fixes. Review scores
ProductKind: Performance · Worth it: Yes Merge readiness⛔ Needs changes before merge - 1 item remains Keep open: this owner-authored PR provides a measured optimization that current main does not yet contain. No discrete actionable patch defect was identified in the inspected paths. Priority: P2 Before merge
FindingsNone. Provenance
Tests
Agent review detailsHow this fits togetherThe Gateway loads saved conversation history before running an agent and checks committed messages before declaring reply delivery complete. These changes carry compatible history facts through the existing database workers while retaining session-owner checks. flowchart TD
A[Chat turn] --> B[Session preparation]
B --> C[History worker snapshot]
C --> D[Live owner and source checks]
D --> E[Agent context and replay]
E --> F[Committed message receipts]
F --> G[Reply delivery and completion]
Technical reviewBest possible solution: Keep compatible reads composed within the existing history owners, with fresh prompt admission and live assertions at consumption and commit boundaries. Do we have a high-confidence way to reproduce the issue? Not applicable as a bug reproduction: the PR optimizes existing behavior, and recorded paired Gateway workloads demonstrate the repeated-read cost and its reduction. Is this the best way to solve the issue? Yes: composing compatible reads and carrying immutable commit facts through existing owners avoids adding a competing cache or execution owner. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 608134ea54c3. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
PR surfacePR surface statistics unavailable: the file list is incomplete. 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 (4 earlier review cycles)
Reviewed October 8, 2026, 10:33 PM ET / October 9, 2026, 02:33 UTC (Revision 5). |
…#167532) * perf(transcripts): stream meeting exports through the read worker Keep one snapshot across bounded export chunks and join asynchronous consumers before releasing reader custody. Replace repeated artifact batch queries with a fixed-head cursor and retain live lease checks at guarded file publication. * refactor(state): share bounded stream read dispatch Keep subagent restore and meeting transcript streaming inside the existing native section while moving their reply adapters out of the main dispatcher. Correct Promise executor and synchronous-read test lint violations. * fix(transcripts): preserve shared export path permissions Reuse the output writer’s compatible temporary-file owner while retaining guarded publication. Keep exports working beneath group-writable ancestors and exercise that contract in the existing artifact test.
Keep the full destination for Tlon Markdown links and images whose URL contains balanced parentheses (for example Wikipedia `Function_(mathematics)`), instead of cutting the href at the first `)`. Ordinary links, bare URLs and parenthesized text are unchanged. Co-authored-by: Ayaan Zaidi <[email protected]>
Await startup catalog publication before measuring explicit refresh requests. Assert the exact startup count and subsequent provider order independently, without polling, retries, or relaxed assertions. Fixes the fixture's double count exposed by b05104a; reproduced on pristine latest-main and repaired remotely. (cherry picked from commit dae5077c64dae94e370098636755272f0b50d33b)
Carry the committed shared-store location with prepared catalog input and include it in generation identity, so reused workers read credentials from the authoritative store after first login. Preserve configured and unconfigured provider login coverage, including passive publication and worker reuse. (cherry picked from commit d7a7b238bac29d147a9fa328b46d26f95d5bfda0)
Merge main without rebasing the reviewed transcript-read work. Preserve landed target selection, retention publication, cold restoration contracts, and prepared-reader test fixtures. Keep the measured child optimization separate from its squashed parent history.
Keep anchor query execution at one existing owner site, retain incognito selection in a leaf module, and exercise current preparation and combined delivery snapshots in the source-loss regressions.
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
) Chat turns repeatedly hydrate transcripts and read anchors and metadata across preparation, replay, completion, and delivery. Compose compatible reads in the existing transcript owners, reuse historical append receipts, and select delivery payloads, anchors, identity, and watermark in one snapshot. Preserve exact transcript bytes, limits, cold restoration outside writer admission, fresh replay phases, synchronous live-authority checks, and released SDK fallbacks. Integrate main without rebasing, preserve its target mapping and retention publication, and align source-loss fixtures with the new snapshot boundaries. No schema, durability, retention, permission, or configuration migration changes. Validation includes focused replay, context, cold-storage, entry, delivery and activity-summary suites; all 27 core-test type graphs; wrapper/import closure checks; no-T1-growth and line-cap ratchets; released SDK comparison; and clean independent P2 review. Reuse the PR's original paired SQL proof with its original baseline pin. Land under the explicitly approved inherited-CI exception. Run 37871955941 at 8185e13 has 102 successful jobs, 23 skipped jobs, two inherited root failures and their aggregate failure. The model-catalog Madge cycle also fails on main run 37868734021. The cancellation test passes before an unhandled rejection in unchanged detached subagent shutdown recovery. Security, CI lint, types, and repaired suites passed; the exception does not claim green CI.
Repair eager reader backedges introduced by 34cb8f7 (#167520) and ab5fd51 (#167238). Move physical-source validation and transcript presence queries to existing narrow owners, migrate every caller, and remove the broad exports. Preserve identity checks, query semantics, and snapshot ownership. The unchanged import regression passes with the fix and fails with both original edges when only the production diff is reversed. Core types and the import-cycle gate pass.
Repair eager reader backedges introduced by e414045 (openclaw#167520) and 23c7173 (openclaw#167238). Move physical-source validation and transcript presence queries to existing narrow owners, migrate every caller, and remove the broad exports. Preserve identity checks, query semantics, and snapshot ownership. The unchanged import regression passes with the fix and fails with both original edges when only the production diff is reversed. Core types and the import-cycle gate pass.
What Problem This Solves
Chat turns repeat transcript hydration, anchor lookup, and scalar metadata reads across preparation, replay, completion, and delivery. This continues the transcript budget work stacked on #166804.
User Impact
The same chat flow uses fewer SQLite statements and worker requests while preserving transcript bytes, generations, cursors, required-byte accounting, limits, and live-authority checks. No schema, durability, retention, permissions, or configuration migration changes.
Why This Change Was Made
Initial bounded hydration, replay acceptance, and physical message presence share the existing transcript cohort. Replay refreshes at synchronous prompt admission after hooks or compaction. Actual agent construction now carries the selected execution owner's context into bounded model-context preparation, without holding the writer queue across setup. Unbounded SDK reads still prepare outside the writer queue and validate freshly before consumption.
Hydration and delivery pass their current projection into anchor selection. One readiness query serves that pinned snapshot; standalone reads retain their checks. Foreign commits overlapping a bounded operation are observed on the next unpinned read. Source replacement, local native mutation, and live authority remain checked at synchronous acceptance.
Terminal consumers use immutable append receipts and the live assertion captured from the producer's original target. Downstream owners still validate the historical anchors. Activity summaries use the patch transaction's acknowledged watermark. Cold metadata joins initialization and turn preparation; the existing restoration owner runs outside the writer queue and before message hooks. Delivery selects visible payloads, anchors, tail, session identity, and watermark in one history snapshot.
Display policy loads before the synchronous snapshot. Legacy native payload reads capture their original database handle before that load and reject replacement. The resident presentation view never becomes authority.
The 65-file change has 720 net production/tooling lines, 1,129 net test/support lines, and 18 documentation lines. The production growth carries typed cohort facts and commit receipts through the existing owners, including durable and incognito adapters; the tests cover the removed reads at their freshness, authority, and delivery boundaries. It does not add another cache or execution owner.
Evidence
Warmed all-thread work falls 1,394.9 → 1,279.1 statements/turn (−115.8 / −8.30%), with MAIN unchanged at 28. First-turn work falls 4,323 → 4,205. Effective transcript cost falls 197 SQL / 18 requests → 80 / 4; the request target is met, while the 42-SQL target remains 38 statements away. These are fresh measurements against the pinned, unmerged parent
f11440d855ba1b79b80223a80b38cc4c78592e2d, not current main.Three alternating base/candidate pairs ran on one AWS Linux host with Node 24.21.0 and the unchanged shared workload. Values are side medians [min–max]; warmed values summarize ten-turn run means. Every gated duration ratio is ≤1.011. The original settling windows, helper threads, background work, and unassigned SQL remain included.
Individual warmed turns retain their full range: base 1385–1417; candidate 1264–1305.
The separate diagnostic census reports 226 → 211.2 total worker requests per warmed turn. Its counts do not replace the three-pair statement medians. Every warmed request completed, zero SQL context rows are missing, and native counts reconcile exactly in every phase/thread. Both sides retain two unmatched boot-only protocol sends/receives.
Requests are phase totals, except warmed is per turn. Second-session includes two top-level turns plus an awaited child: 357 → 339.5 requests per top-level turn.
Direct combined transcript + actor reads fall 32 requests / 248.2 SQL → 18 / 129.2, removing 14 requests and 119 SQL. The removed 14-SQL actor validation had also cached canonical-key and participant facts. Those two required reads now occur in the next metadata append: the same two append requests cost 79 → 81 SQL/turn (first append 29 → 31, second 50 → 50). This induced write-side cost is charged to the change. The net attributed saving is 117 SQL and 14 requests per warmed turn.
The original exact actor allocation is 14 requests / 51.2 SQL (rounded to 51 in the parent PR). Full effective cost is 197 → 80 SQL and 18 → 4 requests: 77 transcript SQL + (52.2 − 51.2) actor SQL + (81 − 79) metadata-append SQL. The 4-request target is met; the 42-SQL target remains 38 statements away. The whole census falls 118 SQL and 14.8 requests/turn; the additional net 1 SQL / 0.8 request reduction is outside the directly attributed lane saving.
The same census conserves the affected read families and their induced metadata-append costs in every phase. This diagnostic table is separate from the ordinary-run median gate; other changes are reported but not claimed as this lane's savings. Boot, connect, control, and shutdown have zero change in the affected union.
Shutdown has an additional unclaimed −3 SQL in the census; boot/connect/control are unchanged. Warmed values are per turn, other values are phase totals.
The relative statement gate passes. The three positive non-turn medians are each ≤10 statements and all their recorded owner source files are byte-identical to the base. Boot/connect have unchanged census request totals and no transcript-group requests. Per-group medians are not added together; the complete per-pair SQL/stack vectors reconcile to each phase delta.
Remaining Transcript Budget
Remaining transcript cost is explicit:
The 30 envelope/control statements are 12 existing schema/role/version checks, eight data-version probes, eight BEGIN/COMMIT statements, and two quarantine-decision reads. They remain in the existing admission owners; step 5 owns the connection/schema envelope work. The two hydration calls are distinct fresh phases separated by preparation/hooks; model context retains different payload filters and byte limits, and delivery reads after the assistant commit. The resident presentation view supplies no authority.
The 42-statement allocation is not achieved. Even removing every envelope/control statement hypothetically would leave 47 history facts plus one incremental actor read and two induced write-side reads. Further work needs to compose the remaining history kernels as well as admission envelopes, preserving exact payload/size/branch semantics; these measurements do not establish that every remaining fact query is irreducible. The overall warmed turn also remains above the campaign's 500-statement goal.
Validation
Final commit:
c7c5692d19a5c828a98ce89e972de528e5c81964.SDK API comparison was inspected (digest
20408311): zero added/removed entrypoints, 137 changed export records (136 reachable-type changes and one direct signature change). The direct change adds the optional internal[completedTurnMessageAnchor]property tofinalizeHarnessContextEngineTurn's turn candidate; existing arguments and return values remain compatible, and callers without receipts keep their fresh-read fallback. Reachable changes cover internal cohort/receipt types, moved patch types, SessionManager symbols, and declaration ordering. Neither new receipt symbol is promoted through an SDK barrel. The final render also compares against the measured candidate: all 130 affected direct declarations are identical; the only reachable declaration delta removes the unused internalSessionEntryPatchContextforwarder. The canonical type declaration and existingsession-accessorexport are unchanged.Three baseline negative controls fail at the intended budget assertions: delivery uses three transcript requests instead of one; admitted model context records two queued requests instead of one; initial replay hydrates twice instead of once. The original private classifier qualified delivery but returned exit 1 for the other two because their captured source coordinates were redacted. Independent inspection verified the pinned baseline, all six test/support overlay hashes, the sole failing test in each JSON report, and the unique matching assertions. The redacted reports and failed classifier result are preserved; no sanitizer was bypassed and no test was rerun to obtain different output. All corresponding positive candidate suites passed.
Runtime proof passed 658 tests in 37 files: 267 cases across all 13 changed test files and 391 cases in 24 sibling files. Coverage includes foreign rewrites at acceptance, next-unpinned-read freshness, revoked/replaced owners, FIFO settlement, physical message presence on empty active branches, exact cold-restored bytes, bounded context limits, branch/reset generations, delivery visibility, and transaction receipt invalidation. All 16 native calibration streams produced 8 calls / 2 prepares / 7 statements / 0 failures. Every ordinary/census workload had zero native SQL failures and zero remaining fixture children.
The canonical package build passed in 419.6 seconds. Published
[email protected]drove the candidate update cell successfully in 467.6 seconds (update operation 377.7 seconds): recorded completion, readiness 200, candidate build identity/version, durable history retained, incognito history cleared, and service cleanup all passed. The candidate retains package version 2026.9.8; the build identity and source manifest distinguish its bytes from the published driver.The package build logged a nonfatal Control UI startup-JS gzip violation: 373,567 bytes versus the 373,454-byte limit (+113 bytes). Startup CSS was 50,749 bytes, above its 46,080-byte advisory target and below the 51,200-byte hard ceiling. UI source is unchanged; no baseline UI package build was run to attribute these notices.
For each changed file, the command was
CI=1 pnpm test <file> --maxWorkers=1. These are measured AWS Linux CI-mode seconds, including preparation, not hosted GitHub Actions timings. The 13 commands total 777.94 seconds; the 24-file sibling group adds 295.60 seconds.Changed test execution costs
attempt-session-replay-cohort.test.tsattempt-session-replay.test.tsattempt-session-runtime-prepare.test.tsagent-end-side-effects.test.tscontext-engine-turn-outbox.test.tssession-manager-async-message.test.tssession-manager-model-context-snapshot.test.tssession-accessor.sqlite-entry-revalidation.test.tssession-cold-storage.transcript-turn.test.tssession-entry-cohort.worker.test.tssession-transcript-anchor-read.worker.test.tschat-send-reply-dispatch.test.tssession-activity-summaries.retry.test.tsFinal source validation: fresh independent Codex P2 review is scoped clean with no actionable findings. The complete
pnpm check:changedpassed on final source in 2,823.1 seconds, including core/script types, all 27 core-test type graphs, dead exports, all five core lint stripes, script lint, and database/runtime/account guards. Madge reports zero cycles; Knip, the database-worker no-T1-growth ratchet, wrapper inventory, formatting, and diff checks pass. Three max-lines warnings remain in byte-identical base files:src/agents/worktrees/service-preparation.ts,src/agents/tools/message-tool-execution.ts, andui/src/components/session-organizer-operations.runtime.ts. No baseline or ignore exception was added.The first changed-check found a test-only access to
.idon anunknownpersisted entry; it now uses the existing record helper, and all 15 outbox cases passed again (44.6 seconds). The next scan found an obsolete internal type forwarding export after its sole caller moved; that export is removed, and the canonical type andsession-accessorexport remain. The final complete check passes after both corrections.Runtime, measurement, SDK, and packaged-update evidence binds the full source digest
0f5c2b1144cf4006cdba99615810318d3395d725edc1550ba37dbbc111b7c9bf. Final source digest5f0f576934b421b4725fa6debb90b244f3ba1f56dd665f224286e64f2d0d5b38differs only in that test narrowing and removal of the unused internal type-only forwarding export. Two verified single-file transitions reconstruct the exact original full digest; every other product file is byte-identical. Node TypeScript stripping confirms the changed type module has zero executable tokens before and after. The transitions and erasure are independently verified on the retained proof host; the final SDK comparison checks the declaration change. Measurements retain their original source pin.Remote proof: runtime, measurements, and published-driver cell; final complete check and SDK comparison. Earlier aggregate failures retain the corrected test/type diagnostics and the negative-control classifier issue described above; the final follow-up exits 0. Both evidence archives and source transitions were hash-verified. The sole AWS lease was released and independently reports
hasHost=false.Scheduling included an approximately 48-minute proof-slot wait, a 15-minute Testbox admission timeout, and two AWS capacity refusals with 10/15-minute backoffs. All heavy work ran through the campaign proof-slot wrapper; the final runtime proof and static follow-ups reused one AWS lease. Historical candidate iterations are excluded from the tables above.
The parent has merged. Landing integrated main with a merge commit. The existing alternating-pair SQL proof is reused under the authorized landing policy; no new main-relative SQL measurement is claimed.
Landing integration
Integrated main
811d442afa2c1103ed10f33f3b64fb1afa7675f8without rebasing in3015123aab37d2d3192c3b1a96eadc9968ec9fb9. The landed parent's source was used to distinguish tb4b's own delta from squashed parent history. Resolution preserves main's runtime target mapping, live source checks, retention publication, and fused append metadata reads.8185e1307d392a286e353ffc596d42a942f03eb8repairs integration fixtures and guards: one anchor query execution site retains both SQL shapes; the unchanged incognito projection selector moves to a leaf module to keep the worker within its line limit. Source-loss tests now interrupt target preparation, Talk owns the first cold hydration, and delivery races occur before the combined authoritative snapshot. No assertion was weakened to obtain a pass. A transient incomplete test-variable rename was caught by local types/review and corrected before this push.Fresh independent Codex P2 reviews are clean on the integrated source and final repairs. The released signatures were checked against
v2026.10.1-beta.1and stablev2026.9.9: existing calls remain compatible, the finalizer receipt remains optional, and the canonical session-accessor type export remains. The existing SDK diff report (digest20408311) was inspected and retained as historical evidence; no new SDK surface is introduced by conflict resolution. Worker test routing and wrapper/import inventories were checked.Landing validation: production types and all 27 core-test type graphs pass; the eight-file replay/cohort/entry/cold-storage/model-context batch passes 123 tests in 821.62 seconds. Original replay, delivery, activity-summary, runtime-process graph and eager-wrapper/import checks passed in the earlier integration batch. SQLite worker and line-cap ratchets pass. The final three-file preview/delivery/anchor batch passes 20 tests in 890.69 seconds on the loaded local host. The final local lint wrapper timed out while rebuilding SDK declarations on the loaded host, before lint ran; required CI lint remains the landing gate.
The earlier CI run
37868811397exposed the fixed fixture/lint/SQL-site issues. Its Madge failure is independently present on main run37868734021, job113621794431:prepared-model-catalog-fingerprints.ts↔prepared-model-catalog-worker.ts; both files are untouched by tb4b. The registry failure insubagent-registry.persistence.test.tsoccurs at completion-authority revalidation before terminal session effects and is unrelated to this delta; the entire registry tree is identical to the integrated baseline. Its exact race winner is not established. These remain inherited failures, not passing checks.The integrated delta is 67 files: production/tooling +1,481/-747 (net +734), test/support +1,491/-337 (net +1,154), and docs +18. No new
OPENCLAW_*variable names. Existing public SDK, storage, durability, and live-authority contracts are retained.Final CI attempt 37871955941 is complete on
8185e1307d392a286e353ffc596d42a942f03eb8: 102 successful jobs, 23 skipped jobs, two inherited root failures and their aggregate failure; no cancellations. CI lint, production/test types, security-fast and repaired suites passed. In addition to the confirmed main Madge cycle,native-cancellation-authz.e2e.test.tspasses its assertions and then reports an unhandledOpenClaw state database read admission is closedrejection in detached subagent completion recovery. Its test, registry waiter/queue, state admission, and shutdown inputs are unchanged from the tested main parent; the rejection happens before any transcript work. The native admin evidence retains both failures, the complete job census, matching baseline proof and exact tested merge211725224d42b58d50d62c7979c3058a00fda970. This is an explicitly authorized inherited-failure landing, not a claim of green CI.