Repository navigation
perf(agents): run per-turn session-entry patches through the worker - #164514
Conversation
Route audited writer claims, live-model-switch bookkeeping, and pending-final preparation, settlement, and cleanup through the existing agent executor. Preserve native opaque SDK callbacks and the excluded lifecycle and cron paths. The paired isolated Gateway workload reduces native patch transactions from 8 to 2 per warmed turn and target-site SQL from 48 to 12. Overall main-thread SQL averages 648.5 to 493.4 statements per warmed turn. Lifecycle persistence remains follow-up work after #142236; cron preparation remains with #161105. Local caller, settlement, error identity, import-boundary, cycle, and database ratchet proof passes. Full build, changed checks, and released SDK diff remain explicit merge preconditions under the maintainer's validation instruction.
|
🦞👀 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: blocked before merge. Reviewed October 3, 2026, 7:21 PM ET / 23:21 UTC (Revision 6). ClawSweeper reviewWhat this changesThis PR moves writer claims, model-switch bookkeeping, and final-reply persistence onto the existing database worker and adds boundary regressions. Merge readiness⛔ Blocked before merge - 2 items remain The change remains useful, with sufficient runtime evidence and no actionable introduced defect found. Explicitly deferred final-candidate validation remains incomplete. Likely related people: steipete (medium-confidence routing from prior merged session-worker and model-switch work). Priority: P2 Review scores
Verification
How this fits togetherAgent turns and reply delivery update session records in per-agent SQLite databases. The existing worker performs those updates and publishes committed results back to the Gateway before subsequent work proceeds. flowchart TD
A[Agent turn] --> C[Session patch preparation]
B[Reply delivery outcome] --> C
C --> D[Existing database worker]
D --> E[Validate current rows]
E --> F[Commit session update]
F --> G[Publish acknowledged result]
G --> H[Continue turn or delivery]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +10, Tests +275, Docs +10. Total +295 across 16 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Land the bounded caller cutover while preserving the existing worker owner, native compatibility paths, and separately scoped lifecycle work. Do we have a high-confidence way to reproduce the issue? Not applicable as a correctness bug reproduction; the paired Gateway workload establishes the existing main-thread SQL cost and its reduction. Is this the best way to solve the issue? Yes: selecting the existing worker path at audited internal callers is a narrow solution that preserves public callbacks and storage semantics. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against af10ddf84e64. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
Create and read producer-recovery sessions under the same explicit shared-state root as their delivery queue. Worker-backed pending-final settlement correctly rejects the previous fixture ownership mismatch. Preserve durable payloads and all existing assertions.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Keep the accounting persistence suite within its line cap by moving fixture construction into a dedicated test-support module. Preserve suite-owned state, immediate operation registration, and every test case and assertion.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…penclaw#164514) * perf(agents): run per-turn session-entry patches through the worker Route audited writer claims, live-model-switch bookkeeping, and pending-final preparation, settlement, and cleanup through the existing agent executor. Preserve native opaque SDK callbacks and the excluded lifecycle and cron paths. The paired isolated Gateway workload reduces native patch transactions from 8 to 2 per warmed turn and target-site SQL from 48 to 12. Overall main-thread SQL averages 648.5 to 493.4 statements per warmed turn. Lifecycle persistence remains follow-up work after openclaw#142236; cron preparation remains with openclaw#161105. Local caller, settlement, error identity, import-boundary, cycle, and database ratchet proof passes. Full build, changed checks, and released SDK diff remain explicit merge preconditions under the maintainer's validation instruction. * test(outbound): align recovery fixtures with queue state Create and read producer-recovery sessions under the same explicit shared-state root as their delivery queue. Worker-backed pending-final settlement correctly rejects the previous fixture ownership mismatch. Preserve durable payloads and all existing assertions. * test(agents): extract accounting persistence fixture Keep the accounting persistence suite within its line cap by moving fixture construction into a dedicated test-support module. Preserve suite-owned state, immediate operation registration, and every test case and assertion.
What Problem This Solves
Warmed Gateway chat turns still execute native session-entry patch transactions on the main thread for writer claims, model-switch bookkeeping, and final-delivery custody.
Why This Change Was Made
Explicitly select the existing worker patch path at the audited callers. The host prepares each reduction once; the existing agent executor rereads and compares authoritative rows in its synchronous transaction, publishes acknowledged commit facts inside the physical writer FIFO, and preserves unknown outcomes without replay. Both live-model-switch clear paths use the same owner.
The general patch default is unchanged. Opaque SDK updaters retain their nested-callback contract, and incognito and maintenance scopes retain their native owner. The writer claim's initial admission read remains separate migration debt.
Scope exclusions: lifecycle start/end persistence remains native while #142236 changes timeout history; cron preparation remains with #161105 and its separate authority-design work. The related umbrella #162433 remains separate from this bounded caller change. After this cutover, the only observed warmed native session-entry patch caller is
persistGatewaySessionLifecycleEvent, twice per turn. Follow-up: migrate it after the timeout-history fix lands. Cold session creation and subagent paths remain separately scoped debt.User Impact
The paired workload reduces native patch transactions 8 → 2 per warmed turn, target-site statements 48 → 12, and overall main-thread statements 648.5 → 493.4 per turn. This preserves schemas, retention, durability, public SDK signatures, permissions, and update behavior. No database opener, admission, transport, or lifecycle owner changes; the published-driver update cell is not applicable to this caller-only cutover. No new OPENCLAW_* environment names.
Production changes: +19 / -9 / net +10 lines across five files. Documentation explains the remaining native paths. Host-broker tests use the repository's existing forked test group.
Evidence
Paired agent transaction measurement
Baseline: task-start
origin/mainatf7d9a968f278aab97f470c387fc22e81fad012b8. Candidate measurement used staged treed2480806a0c287595e44315ce38253ff6536bae8, now verified identical to commit87a2537b5772d7810248b6a46f28521f7d816d3c. The measurement preceded that commit; its exact source tree was checked.Same checkout, Node 26.10.0, SQLite 3.53.4, macOS arm64; gateway-only
qaRuntimebuilds with source maps. Both runs used identical harness/observer bytes, 100-frame stack depth, fresh isolated state, the loopback mock provider, and the original workload. Prepares and failed native executions are excluded.:62before → after:62before → afterWarmed mean: 648.5 → 493.4 main-thread statements/turn, 155.1 fewer (23.9%). Median: 637 → 493. Every warmed turn has 8 → 2 native patch transactions, 48 → 12 statements at
openclaw-agent-db-transaction.ts:62, 64 → 16 across all helper source lines, and 159 → 42 statements with the helper anywhere in their stack.The only remaining warmed native patch caller is the excluded
persistGatewaySessionLifecycleEvent, twice per turn. Writer claim, final preparation, queue custody, delivered settlement, and final clear have direct preparation stacks. The queued exact live-switch patch loses its upstream async stack here; the original artifact stack and focused negative control identify that caller. Queued work is not attributed from a stale preceding stack.Both runs completed 13 top-level turns, the child turn, a successful Cron run, committed compaction, and clean shutdown
[0, null]. The Inbox was empty, so dismissal was a no-op. All resolved on-disk database paths were inside each synthetic fixture; null/in-memory locations retain their original unknown labels.Phase counts include concurrent maintenance, so unrelated SQL can shift between phases. Timings are not a latency benchmark. The historical 546/turn artifact used a different baseline/runtime and is not this pair’s comparator.
Excluded failed BEGIN admission attempts were all
SQLITE_BUSY: baseline 2 main-thread connection attempts and 3 worker shutdown attempts; candidate 2 worker shutdown attempts. All workload receipts succeeded. Both builds emitted the existing worker-deploy sourcemap warning; target helper/lifecycle source frames match their source.Baseline negative control used the corrected existing fork inventory plus candidate
live-model-switch.worker.test.tson original production. Both cases failed on native session SQL / BEGIN / COMMIT as expected: 186.689s wall, 84.07s Vitest.Baseline gateway setup/build: 612.506s wall including isolated install. Candidate gateway rebuild: 303.362s. Workload: 156.718s before and 107.035s after. No full build, broad gate, or SDK run is claimed by this measurement.
Static inventory: T1 1,198 → 1,198 (316 files);
pnpm check:database-worker-ratchet --base f7d9a968f278aab97f470c387fc22e81fad012b8passed. The shared native kernel remains for excluded and compatibility callers, so static site counts do not express this caller cutover. Madge reports 0 cycles (158.74 s).All Vitest commands used
--maxWorkers=1.These are loaded-host macOS command times, including transformation, worker preparation, and verification. The long close test reuses the existing real Gateway fixture to prove server shutdown ordering; a helper-only test cannot establish that order. CI timings are pending when this PR opens.
Landing validation: the coordinator assigned full build, changed-file checks, and the released SDK comparison to the lander. Final receipts below satisfy those preconditions. The original source-mapped
qaRuntimemeasurement builds are separate evidence.The existing patch-owner regressions cover FIFO, publication ordering, authority revocation, opaque SDK nested admission, and unknown outcomes without replay. The conflict regression explicitly checks error-class identity. The real Gateway close regression queues accepted final-delivery persistence behind a preceding worker patch, begins the close prelude, rejects newly scheduled work, and verifies committed state before database teardown.
Validation corrections: the first new observer test ran in Vitest's thread pool, where the product intentionally retains native execution; its host-broker routing was corrected without weakening the observer. The custom-root delivery fixture had reused a live executor under a different shared-state namespace; the corrected fixture creates its custom store under the intended root from the outset. The writer observer also now warms unchanged cold admission before observing the moved claim transaction; SQL assertions remain intact. Initial setup's final build stamp refused concurrent source edits and is not counted as a successful build.
Fresh Codex autoreview against the pinned merge base completed scoped-clean through P2, exit 0. Formatting and
git diff --checkpassed.Landing review: compatibility
The lander checked the latest local release tags (v2026.9.8, v2026.9.7, v2026.9.6), the v2026.9.8 session accessor and plugin runtime contracts, current
src/plugin-sdk/session-store-runtime.ts, andsrc/plugins/runtime/runtime-agent.ts. This PR changes no exported signature, sync/async behavior, callback shape, or export inventory. Released opaque updater callbacks remain on their existing native path; no compatibility record or new type test is required for this caller-only selection. The released SDK diff completed locally on final candidate36667aaf51b0f897b4e94dafe02184fee6e77e3fagainst both published beta/latest predecessors,v2026.9.8. Its acknowledgement digest ise9f58e0a. The cumulative release-to-head report is not empty: 8 removed entrypoints, 1 added entrypoint, and 2,307 affected export pairs; this is a cumulative report, not an assertion of zero release-to-head changes. These are inherited main changes: the PR delta from integrated mainbf761b0fcafcb0e014dc8e481bdd10bf34b274f0leaves package/SDK manifests,src/plugin-sdk,src/plugins/runtime, SDK documentation, accessor types and patch owner byte-identical, and leaves all six touched internal function signatures unchanged. No PR-introduced released contract change was found.ClawSweeper completed its fresh review of b13daf4 at 21:20 UTC with no remaining actionable code findings and confirmed that the fixture correction resolves its prior finding. Its data-model heuristic names session-bootstrap.ts, but inspection shows only the existing patch API selection changes: the stored activeWriterRunId field, reducers, schema, serialization, migrations, and retention are unchanged. No migration or upgrade behavior changes. The documented full build, changed checks, and SDK report remain landing gates.
Landing CI repair
Pushed fixture correction
b13daf453d09cf42f09a5881fb33b99e1dbe4480: the producer-recovery tests created sessions with the ambient shared-state owner, then recovered queue deliveries with an explicit custom root. The worker path correctly rejected that mismatch. Session creation and readback now use the same queue state environment; production code, durable payloads, and all assertions are unchanged.Attribution used Node 24.21.0 and
node scripts/run-vitest.mjs src/infra/outbound/delivery-queue.producer-recovery.test.ts --maxWorkers=1: merge basef7d9a968f278aab97f470c387fc22e81fad012b8passed all ten tests in 5/5 runs, while original head87a2537b5772d7810248b6a46f28521f7d816d3creproduced the same five ownership failures in 5/5 runs. The correction passes all ten tests (147.61s wall, 115.73s Vitest). P2 autoreview of the correction completed scoped-clean; formatting and diff sanity passed. These loaded-host timings are not a latency benchmark.The original UI failure is independently present in scheduled main CI:
board-mcp-app.e2e.test.ts:527reports the same 602-pixel bottom/body gap. Its test and rendering inputs are identical between that main checkout and the original PR CI main parent, and this PR changes no UI files. The layout change entered through main after this branch forked. Five full-file UI runs passed on each pre-regression branch head and fork base (50 cases); the actual CI merge reproduced the same 602-pixel gap with four sibling cases passing. Relevant UI/runtime/style/test/helper source is identical in the fixed-head CI merge. The comparison used matched Node 24.21.0 and Chromium 153, taking 864 seconds overall. No UI source or assertion was changed.Previous-head b13daf CI completed with every selected job passing except the independently attributed UI job and its aggregate gate; no jobs were cancelled. The fixture suite passes all ten cases in its hosted shard: 17.34 seconds per-file shard, including 16.28 seconds Vitest.
The required CLOSE-PRELUDE case,
joins scheduled plugin work before closing stores while retaining a deleted agent store, passes in hosted job 111294423398, taking 1.978 seconds. The completeserver-close.agent-databases.test.tsfile passes 5/5 without a test-name filter (49.50 seconds shard / 48.14 seconds Vitest). CI tested merge0be01bdcb3d47c74ffbb08879637bace00745ea2, with ordered parents10955cf09b4e43133eb23d6d8a25e7f880846a2band the fixed PR head.Final candidate gates
Candidate
9e07b0e3e9ea69cb342434e5f526b6eec2716ec1includes fixture extraction7ea7c5161e11aee85c6fb6355feaf26936da99b7and a conflict-free merge of main711e57e41b37fd3667cace1fc82572687903da39, bringing in the released SDK comparison fix from #164466. The accounting test had grown from 1,000 to 1,016 counted lines; its existing builders and diagnostic helper now live in a test-support module. Suite ownership, mocks, cleanup timing, every case and every assertion are preserved. All 97 accounting cases pass (303.36s command wall, 129.84s Vitest, including 133.18s cold worker preparation). The integrated line-cap ratchet passes. P2 autoreview of the complete integrated PR delta is scoped-clean.Full build passed on b13daf in Testbox; its combined build/check command then exposed the accounting line-cap failure fixed above. On the final candidate, the released SDK comparison is complete, changed-file checks are still running, and a fresh full build is required. The first final-candidate Testbox lease failed during warmup with
WaitDelay expired before I/O completebefore executing the payload (commandMs 0); it is completed. The first AWS source freeze stopped before provisioning because a temporary lint-limit file changed while the changed checks were running. No candidate failure was observed. Changed checks subsequently completed successfully on 9e07.Final candidate
36667aaf51b0f897b4e94dafe02184fee6e77e3fmerges mainbf761b0fcafcb0e014dc8e481bdd10bf34b274f0to incorporate the exact inherited UI fixture repair, #164535 (3d66dd51b57d8e16acf481d6425c7b95ad3d264b). The previous inherited-failure exception is therefore not requested. Main's same-file overlap is the type-onlyLiveSessionModelSelectionextraction from #164286; it merged cleanly. The normalized PR patch is identical before/after integration, and fresh P2 autoreview is scoped-clean. Main integration is a merge commit, not a rebase.The final-head released SDK comparison is complete (digest above). Final CI run 37161276479 completed successfully with all 70 jobs terminal and no failures. It tested merge
b3fc95e37b3e2e15a4c59cd2a6ee06147990567c, parentsdf24e6de4b2976e2f5c043eb3db5d41d0b8a2f1fand36667aaf51b0f897b4e94dafe02184fee6e77e3f.Final producer recovery passes 10/10 in job 111315210643, 18.85s per-file shard / 17.69s Vitest. Final CLOSE-PRELUDE passes in job 111315210675, exact required case 2.123s; complete file 5/5, 51.33s shard / 49.92s Vitest. No test-name filter, rerun, or assertion change was used.
Trusted ClawSweeper workflow 37161303607 completed successfully and reviewed this exact head at 23:21:47.773 UTC, with no code or security findings. Its manual validation reminder is handled by these final receipts. Its serialized-state heuristic is not a data-model change: session-bootstrap only selects the existing patch API; the reducer, stored activeWriterRunId field, serialization, schemas and migrations are unchanged. No migration or upgrade compatibility change is introduced.
Changed-file verification is complete. The complete
node scripts/check-changed.mjs --base 711e57e41b37fd3667cace1fc82572687903da39pass succeeded on 9e07; final-head hosted CI passed the selected format, core/scripts lint, core and all 27 core-test type graphs, conflict/Doctor registries, ratchets, config docs, duplicate coverage, coercion, package-patch/temp-output/webhook/pairing/cycle guards, native schema, runtime topology, deprecated API, wrapper-shadowing, and dead-export checks. An owner/source audit identified seven remaining contracts outside hosted CI; all seven passed locally on 36667:check:changelog-attributions,lint:extensions:no-guarded-wildcard-reexports,lint:extensions:no-plugin-sdk-wildcard-reexports,deps:pins:check,plugins:boundary-report:ci,check:media-download-helpers, andcheck:runtime-sidecar-loaders. No new environment names are introduced.Final full build passed on exact head
36667aaf51b0f897b4e94dafe02184fee6e77e3f, using Hetzner standard leasecbx_82647f9c1508, runrun_237cd51c828a912dbd031d71bc8060f4, Node 24.21.0 and pinned pnpm 12.5.1. The clean PR checkout verified its exact SHA before install andpnpm build. Build phases took 11m 58.5s; bootstrap/install/build command 12m 21.693s, exit 0. This includes AI/package/core/plugin declarations, all six unified declaration groups, SDK entrypoint declarations and export checks, plugin assets, runtime metadata, Control UI and startup metadata. Testbox warmup failure, AWS provisioning failure, and the first raw Hetzner image missing pnpm were infrastructure/setup failures before build execution; the successful run bootstrapped the repository toolchain. The lease release was accepted and cleanup is being verified. All required validation is complete; no inherited-CI admin exception or CI rerun is needed.