Repository navigation
perf(sessions): serve per-turn session projections and entry reads from workers - #164779
Conversation
Move model, sandbox, completion and Gateway metadata preparation off the calling thread while retaining live source authority and audited worker patch settlement. Preserve native incognito and opaque callback contracts; leave the entry-store write kernel unchanged.
Preserve exact-row validation and canonical-key error identity. Keep storage-backed source checks outside worker grants and retain acknowledged writer settlement.
|
🦞👀 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. |
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Codex review: blocked before merge. Reviewed October 4, 2026, 5:23 AM ET / 09:23 UTC (Revision 6). ClawSweeper reviewWhat this changesThe branch moves per-turn session metadata reads into existing database workers and updates callers, error transport, documentation, and test routing. Merge readiness⛔ Blocked before merge - 1 item remains The PR remains useful: current main retains the synchronous reads being migrated. No actionable introduced defect was found, and the recorded compatibility evidence resolves the previous upgrade checkbox. Priority: P2 Review scores
Verification
How this fits togetherSession storage supplies model choices, sandbox facts, dispatch metadata, and completion details to OpenClaw’s agent and Gateway workflows. Worker readers prepare those facts while existing execution and publication owners retain authorization. flowchart TD
A[Chat or agent turn] --> B[Session identity and store selection]
B --> C[Existing database workers]
C --> D[Prepared session metadata]
D --> E[Current authority checks]
E --> F[Agent execution and reply publication]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +241, Tests +640, Docs +15, Config 0, Other +1. Total +897 across 69 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Use the existing worker readers for descriptive preparation while preserving synchronous public contracts and live authorization at execution and publication. Do we have a high-confidence way to reproduce the issue? Not applicable to a functional bug report; the recorded paired Gateway workload establishes the synchronous SQL placement being improved. No repository code was executed during this review. Is this the best way to solve the issue? Yes. Reusing existing physical-reader and worker owners is a maintainable cutover, with public synchronous access and final-effect authority checks preserved. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d3af0db4027a. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (5 earlier review cycles)
|
Route worker-backed callers through the existing broker test lane, preserve contract command coverage, align synthetic entry readers, and await fixture shutdown. Synchronize provider cancellation on execution and terminal failure instead of a timer flush.
Integrate the mainline duration-formatter fix and preserve the session read cutover. Await database worker drainage before detached-compaction fixture snapshots, retaining row and byte-preservation assertions and surfacing run failures.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via explicitly authorized admin squash with attributed pre-existing CI failures.
|
Reply finalization moved to worker-backed session reads in #164779, while this fixture still mocked only the earlier reader. Route both readers through the existing synthetic session-selection owner, preserving current-activity checks and every transcript and media assertion. Found during #164755 validation and independently reproduced on main. Validation: all 132 full-file cases, Gateway-method types, lint, formatting, and P2 review pass.
The worker-backed session reader introduced in #164779 made the queue-only fixture enter durable writer admission from its threads lane. Declare its synthetic sessions detached, preserving session identities and all queue, placement, and lifecycle assertions. Found during #164744 validation and independently reproduced on main with three capacity-wait timeouts and host-owner admission errors. Validation: queue liveness 20/20, durable writer claims 6/6, formatting, and P2 review pass. Production guards and test deadlines are unchanged.
Route seven existing embedded-runner suites through the canonical infra project after worker-backed admission began requiring its host owner. Keep file isolation and every assertion; the registry also excludes these paths from their former agent projects. Reproduced the scheduled-main host-owner and warmup failures through the real wrapper. The same seven files then passed all 42 cases in 86.79s. Scoped lint, format, whitespace and independent review passed. Latest-main changes leave these test and routing inputs unchanged. Refs #164779 and main CI run 37200643847.
…om workers (openclaw#164779) * perf(sessions): read per-turn metadata through existing workers Move model, sandbox, completion and Gateway metadata preparation off the calling thread while retaining live source authority and audited worker patch settlement. Preserve native incognito and opaque callback contracts; leave the entry-store write kernel unchanged. * fix(sessions): clear run context when model preparation fails * perf(sessions): prepare dispatch and injection entries in workers Preserve exact-row validation and canonical-key error identity. Keep storage-backed source checks outside worker grants and retain acknowledged writer settlement. * refactor(sessions): keep prepared sandbox check within line budget * test(sessions): use current agent entry config in injection fixtures * refactor(sessions): make worker request and test await shapes explicit * test(sessions): repair worker read fixture integration Route worker-backed callers through the existing broker test lane, preserve contract command coverage, align synthetic entry readers, and await fixture shutdown. Synchronize provider cancellation on execution and terminal failure instead of a timer flush. * test(sessions): prune repaired mock export baseline * test(gateway): settle publication before durability probe
Reply finalization moved to worker-backed session reads in openclaw#164779, while this fixture still mocked only the earlier reader. Route both readers through the existing synthetic session-selection owner, preserving current-activity checks and every transcript and media assertion. Found during openclaw#164755 validation and independently reproduced on main. Validation: all 132 full-file cases, Gateway-method types, lint, formatting, and P2 review pass.
The worker-backed session reader introduced in openclaw#164779 made the queue-only fixture enter durable writer admission from its threads lane. Declare its synthetic sessions detached, preserving session identities and all queue, placement, and lifecycle assertions. Found during openclaw#164744 validation and independently reproduced on main with three capacity-wait timeouts and host-owner admission errors. Validation: queue liveness 20/20, durable writer claims 6/6, formatting, and P2 review pass. Production guards and test deadlines are unchanged.
Route seven existing embedded-runner suites through the canonical infra project after worker-backed admission began requiring its host owner. Keep file isolation and every assertion; the registry also excludes these paths from their former agent projects. Reproduced the scheduled-main host-owner and warmup failures through the real wrapper. The same seven files then passed all 42 cases in 86.79s. Scoped lint, format, whitespace and independent review passed. Latest-main changes leave these test and routing inputs unchanged. Refs openclaw#164779 and main CI run 37200643847.
What Problem This Solves
Warmed chat turns repeatedly read session participant, owner, provenance, and entry data on the Gateway thread. The same SQLite kernels also serve native authority checks, writer operations, and public synchronous contracts, so moving their async runtime callers needs to preserve those boundaries.
Why This Change Was Made
Use the existing session readers for model selection, harness admission, skill refresh, dispatch, empty injection probes, local-turn placement preparation, completion metadata, diff-baseline selection, and Gateway finalization/publication preparation. Carry prepared sandbox facts through workspace preparation. Exact candidate reads validate only selected rows; default stores remain single-store and explicit agent templates retain configured/discovered selection.
Each new await retains physical-store custody and the applicable caller checks. Local placement rechecks authority before claiming a turn. Source callbacks that can read their own agent store stay outside worker grants. Model-read failures share existing run-context cleanup. Canonical-key migration errors retain their class identity through a leaf module and the existing worker codec; the compiled-wrapper inventory includes that leaf.
#164514 owns the writer-claim and live-model writer cutover; this delta keeps it and awaits admission reads.
writeSessionEntryand its write sites remain excluded for #163592. TheensureSkillSnapshotrow refresh here is distinct from #164648's approval/defaults preparation. #158903 adds a separate admission helper in the placement file; these hunks only changeexecuteLocalTurn. #162433 remains the coordinated incidental overlap. No global worker-patch enablement or opaque callback contract change.User Impact
On measured head
04818d014e0f358f6a218bd6e3d77992aad9bf0dversus pinned main50b45abb1d479f98e2120423a328ee0390930f19, warmed turns average 505.7 → 458.0 main-thread statements (−9.4%). The six selected read sites fall 158 → 134 per turn (−15.2%); the full workload falls 12,660 → 11,940. This is an incremental read-side cutover: live guards, synchronous callbacks, and excluded writer work remain below. The owner-projection site is already zero on this main baseline, so this PR claims no additional reduction there.Production scope: 33 files, +425 / −184 / net +241 (609 changed lines), excluding tests, documentation, and tooling. Static T1: 915 → 915; shared native kernels are not relabeled worker-only. All-tier static calls are 2,540 → 2,541, with the additional call in the existing worker.
No new worker service, cache, schema, retention, durability, permission, or environment-variable name. Process-held incognito keeps its existing reader. Prepared metadata does not grant authority; live delivery, sharing, publication, and claim guards retain their owners.
Landing integration
Landing candidate:
7eb1f0d6233df42e9ad5d4512dc46ef89622eba6. Initial fixture repair:f58c076f400661ea483c5d49ee7306f89b20787a; exact mock-baseline shrink:920f2cfcb8b948; latest main merge:7cfd2c302ca521eab39e12adafbe5405a2753dcd; dashboard publication fixture repair:7eb1f0d6233df42e9ad5d4512dc46ef89622eba6.Integrated main through
5f5125bcb6a975351b6e2369e56397265582cece, including the admitted-schema work and the upstream ACPX fixture repair. All integrations use merge commits. The overlap with #164753 was the shared error registry: its model-lock error and this PR's canonical-session-key error both remain registered, with both leaf modules in the wrapper inventory. The full PR patch was identical across the latest main integration before the three-line dashboard fixture repair.Landing repairs give broker-dependent tests a single owner, keep plugin-contract discovery complete and disjoint, align synthetic session fixtures with the async readers, await database retirement before fixture reset/snapshots, and synchronize cancellation with actual provider entry and the terminal-failure callback. The dashboard durability probe now joins the saved row's publication before deliberately closing storage, preserving its observer and every existing assertion. These are test/tooling repairs, with no additional production behavior changes.
Released SDK audit: the five changed sync-to-async helpers are internal and absent from the released SDK barrels, runtime API, and documented subpaths at
v2026.9.8. PublicgetSessionEntryremains synchronous; the extracted error class preserves its original re-export and identity. The completed SDK reports below remain applicable to the test-only landing repairs. No stored-format or schema change is introduced, and the preserved published-driver update cell supplies upgrade evidence.Integrated proof: the 32 reader/authority cases passed again after the schema-admission integration (813.50 seconds command wall time), covering foreign commits on the next unpinned read, incognito exclusion, alias custody, cancellation, and Gateway authority. The earlier registry-conflict composition passed 78 runtime-process/wrapper/import/error tests (561.99 seconds). All 1,140 tests in the 15-file isolated repair campaign and focused script lint passed. The additional dashboard file passed all 34 cases (683.74 seconds). Fresh P2 reviews of the integrated delta and dashboard fixture change found no actionable findings. The original 130-run comparison is complete: all 65 original-head runs failed with the observed signatures, and all 65 baseline runs passed (five separate full-file runs per revision for each of 13 files). Valid prior runs were reused. Nine original-head results survive as validated streamed summaries/receipts rather than raw logs after a native staging disk incident; all 65 baseline raw logs are retained.
CI run
37186070579tested8fa787c0941b15bd21fa0ca8134963975d1e0f6c: 149 successful jobs, 14 skipped, three failed test jobs, and the downstream aggregate failure. The three roots are being handled explicitly:d2a9f9a114c2e2570ed861a5ab0273291d56a793repairs the fixture and is included in this integration. That commit records focused ACPX/ACP proof. The first Mac reproduction also had a cold timeout and a subsequent configuration-source failure, recorded separately; the eight Linux repetitions had only the canonical-key mismatch.5f5125bcb6a975351b6e2369e56397265582ceceunder two-CPU affinity. The failed state shows startup recovery finishing before deferred admission: the orphan remains running and the original inbound replay is skipped as duplicate. The independently inspected recovery/admission/test inputs are unchanged by this PR. This is inherited main behavior; passing older standalone revisions did not cover the newer main admission ordering used by CI. No CI rerun has been used.Current-head CI run 37189194601, attempt 1, completed at
7eb1f0d6233df42e9ad5d4512dc46ef89622eba6: 148 successful jobs, 14 skipped, three failed Node jobs and their downstream aggregate. No CI reruns were used. The actual checkout was501bd986ef98162cdb9b9adc0cdd1a2d814c51e7, with ordered parents main9c66d4c9a39b16d70e7c55186fe7e8550468a663and this head. It preserves newer main changes and contains only this PR's 69-path introduced delta.The explicitly authorized native inherited-failure exception is qualified for these roots; this is not a claim that CI passed:
5f5125bcb6a975351b6e2369e56397265582cecereproduce the same 11 failing cases: origins 1 failed/10 passed, forget recovery 8 failed, and settlement 2 failed/2 passed. The worker reuses admitted schema facts after another connection drops optional tables, so schema restoration is skipped before the intended recovery/lost-result checks. All 21 causal source blobs/trees are identical across reproduction main, CI baseline, PR head and tested merge. This failure follows main's schema-facts change inc828f7ed1d560295f78166a98fb54687dc162b28; it is not repaired here.The downstream CI gate reports those three roots; no job was cancelled.
security-fastsucceeded, and the exact-head Security Review publisher completed successfully. ClawSweeper completed its latest trusted review at2026-10-04T09:23:29.652Zwith no actionable code/security findings. Its generic compatibility checkbox is satisfied by the unchanged stored-data contract, released SDK report, and successful published-driver update cell already recorded below. Native admission still revalidates current security, review and head authority.The initial CI's independently inherited Windows import and two UI failures were fixed in incorporated main (
3c0f7e4c5cdade,65829ead96bb115b69782e6357e8b619b3add8bf, and42b9aee33a7b03442f4c5ce3f088fd5e7dcefaf0). All performance figures below remain tied to their original measured commits; they are not measurements of this newer integration.Landing repair proof and observed test cost
Isolated source: original head
04818d014e0f358f6a218bd6e3d77992aad9bf0dplus the reviewed 15-file repair patch45b1f0cd540f25086564e6c13d7779c8d9400b907e987d5d9c1c2ca9f2f7d3b1. Each file ran singly throughnode scripts/run-vitest.mjs <file> --maxWorkers=1, the repository test runner. These are observed isolated runner seconds, not projected GitHub CI seconds.src/agents/embedded-agent-runner/run-orchestrator.suspension.test.tssrc/gateway/server-methods/system-agent-nested-inference.integration.test.tssrc/agents/embedded-agent-runner/run.cli-dispatch-lane.test.tssrc/agents/embedded-agent-runner.run-embedded-agent.finalization-scope.test.tssrc/skills/runtime/session-snapshot.integration.test.tssrc/gateway/server-methods/sessions-diff.test.tssrc/auto-reply/reply/agent-runner-execution-provider-failures.test.tssrc/gateway/worker-environments/worker-github-binding.test.tssrc/gateway/github-publication-boundaries.test.tssrc/gateway/github-publication.test.tssrc/gateway/github-personal-publication.test.tssrc/gateway/github-publication-admission.test.tstest/scripts/test-projects.test.tstest/scripts/plugin-contract-test-plan.test.tstest/vitest-projects-config.test.tsThe local personal-publication run had six fixture Git setup failures before application entry (five
git init, one initial commit). The original helper discarded termination details, so the cause remains uncertain; a diagnostic replay passing is not evidence of a fix. The independent isolated full suite passed 50/50. Local script lint could not complete declaration preparation within its setup deadline; the independent isolated lint completed successfully.Landed composition
Native admin squash landed as
e95e11c679301368a2f30f09e13647597c65f730on2026-10-04T09:41:15Z, with direct parentbb9f63c75069bc2522f09b441d5ec93524ab6efe(#164648). Exec preparation landed during final admission; native reconciliation verified the exact prepared source and reconstructed landed tree against that main parent. Main'sexec-defaults.tsis unchanged by this squash.ensureSkillSnapshotretains main's async exec-preparation flow, with only this PR's intended worker-backed final row refresh and imports differing.Focused proof on that exact landed tree passed 16 cases: both complete session-update/exec-preparation files (9 passed, 185.667 seconds) and foreign-commit freshness plus the six incognito-owner cases (7 passed, 31 unrelated cases intentionally filtered, 68.207 seconds). Total wrapper wall time was 253.874 seconds. Source and dependency hashes stayed unchanged. This supplements the reviewed-head proof; it is not a new full-CI success claim.
Evidence
Main baseline pinned for the original integration/validation:
50b45abb1d479f98e2120423a328ee0390930f19. Measured candidate:04818d014e0f358f6a218bd6e3d77992aad9bf0d. Same supplied synthetic local-provider harness and native statement observer, fresh isolated state, real Gateway/storage/workers, source maps, and Node v26.10.0. Statement counts exclude prepare calls and include maintenance settling during each phase. These instrumented runs are not latency benchmarks.session-accessor.sqlite-participant-projection.ts:56session-accessor.sqlite-owner-projection.ts:83session-accessor.sqlite-provenance.ts:39session-accessor.sqlite-entry-read.ts:320session-accessor.sqlite-entry-read.ts:123session-accessor.sqlite-entry-read.ts:357Both runs passed all 13 top-level turns, child execution, cron, compaction, and clean shutdown (
[0, null]). Counts retain all maintenance/settling samples; they are not latency measurements. Before: one busy hostBEGINduring connection and three busy workerBEGINs at shutdown. After: two busy hostBEGINs during connection and no worker SQL errors. Neither run had warmed-turn SQL errors, and all workload outcome assertions passed.pnpm build2026.9.8× candidatec5a8b6a41322)node scripts/check-changed.mjsFocused commands use
pnpm test <files> --maxWorkers=1; times are observed command wall times, not projected GitHub CI duration. The new placement regressions failed on the native read (host SQL and missed read-boundary revocation), then passed after the repair. Coverage includes foreign commits on the next unpinned read, pinned-reader behavior, incognito exclusion, candidate-store selection, unrelated-row isolation, error-class identity, cancellation, and accepted settlement before worker close. Final Codex review through P2 completed with no accepted findings; the subsequent fixture and lint repairs each received scoped-clean P2 follow-ups. One reported error-handling finding was rejected: both migrated exact-read callers already return no candidates for missing database/schema, while corruption and query errors throw. The new exact projection preserves that native contract (session-accessor.sqlite-exact-read.ts:363–364); existing list/full inventory readers retain their stricter handling.Full build, the 626 focused/import tests, cycles, ratchet, package/update proof, and SDK comparisons used
5768b0871b86. Subsequent changes only rename an unexported binding, replace a two-field spread with explicit fields, and repair test fixtures. Public declarations, imports, and transport behavior are unchanged. The memory-flush suite covers the binding correction; final-head identity/dispatch tests, changed checks, and measurement cover the remaining edits. Earlier changed-check failures (one line of file growth, obsolete fixture fields, and two lint errors) were corrected and rerun. Final lint retains four existing max-lines warnings with zero errors.SDK diff digests: main
a097de53, released9e9163f6. The released2026.9.8comparison includes all intervening main changes: one added/eight removed entrypoints, 60 added/1,007 removed exports, 73 signature changes and 1,175 reachable changes. The main comparison isolates this lane and has only reachable changes. Both use the fixed SDK diff tool locally with a physicalTMPDIR; no renderer guard was bypassed.The update cell applies because the shared worker error-identity codec changes. Heavy proof used the authorized AWS Crabbox fallback after Testbox source packaging stalled; SDK comparisons run locally as requested. The full build emitted its non-gating startup gzip advisory and exited successfully.
The measured
04818every-phase trace reconciles 260 distinct selected-site stacks; 122 warmed caller chains total 134 selected statements per turn. Every phase matches the analyzer totals. The migratedexecuteLocalTurnread is absent from all selected-site stacks. Roots remaining in that measured revision are categorized below; these are explicit migration debts or excluded responsibilities, not a claim that all retained reads are authorization checks.Native caller contracts and migration debt in the measured 04818 workload
src/gateway/session-sharing-policy.ts:101;src/gateway/server-methods/session-mutation-guards.ts:358and line 366;src/gateway/server-methods/request-authorization.ts:161src/auto-reply/reply/session.ts:310, line 546 and line 957src/config/sessions/session-accessor.sqlite-projection-state.ts:123and line 143;src/config/sessions/session-accessor.sqlite-entry-mutation.ts:69;src/config/sessions/session-accessor.sqlite-provenance.ts:39writeSessionEntryprovenance. Entry-store writes remain excluded from this lane; preserve the writer's atomic operation.src/gateway/session-lifecycle-state.ts:361and line 397src/agents/embedded-agent-runner/run/pre-persisted-user-turn.ts:82src/agents/exec-defaults.ts:151;src/auto-reply/reply/session-updates.ts:147;src/agents/tools/openclaw-delegate-tool.ts:63src/plugin-sdk/agent-harness.ts:21; internal callers should carry prepared facts without changing that SDK contract.src/auto-reply/reply/reply-tool-authority.ts:186, line 305 and line 417src/gateway/server-chat.ts:348, called at line 1285src/gateway/AGENTS.md:80requires ingestion to capture content without awaiting row enrichment; the repair must supply prepared event facts or migrate the ordering owner.src/gateway/session-observer-model.ts:303and line 387;src/gateway/session-observer.ts:532and line 180src/gateway/server-methods/chat-send-session.ts:126qualifyChatSendSessionat line 253. Its synchronous API needs a coordinated asynchronous preparation cutover.src/gateway/server-methods/chat-send-session.ts:276src/gateway/github-publication-availability.ts:102and line 209src/trajectory/runtime-store-writer.ts:75src/gateway/worker-environments/live-event-projection.ts:47; migrate that ownership boundary together.src/agents/session-maintenance/run.ts:191assertAllowedchecks the generation and absence of pending final delivery inside session-work admission. This callback cannot simply become asynchronous.src/gateway/server-methods/chat-send-reply-dispatch.ts:169and line 233src/auto-reply/reply/dispatch-from-config.harness-defaults.ts:46dispatch-from-config.prepare-execution.ts:250additionally captures the run's commentary classification once. Reusing the initial session entry for every predicate call would change that behavior.Outside warmed turns, the trace also includes existing native parent-inheritance snapshots (
src/gateway/agent-turn/agent-session-persist.ts:181, line 329 andsrc/gateway/server-methods/agent-session-patch.ts:164). Cron orphan cleanup reaches separate placement-recovery preparation atsrc/gateway/server-worker-placement-session-target.ts:241and the live workspace/lifecycle binding closure at line 277. These remain with their existing writer/recovery owners; the initial qualified-target read is additional preparation debt.Pre-existing worker-grant debt
The following chain is retained existing work; the moved-operation boundary tests do not claim zero host
SQL for all grant callbacks:
src/gateway/server-methods/chat-send-handler.ts:320invokes admitted-inputauthority; line 334 forwards the same custody check during source staging.
src/gateway/server-methods/session-mutation-guards.ts:358and line 366 callcurrent session-sharing authorization, whose metadata reader is
src/gateway/session-sharing-policy.ts:101.src/config/sessions/session-pending-input-store.ts:194into the admissioncallback at
src/config/sessions/session-accessor.sqlite-replacement-worker.ts:138.src/config/sessions/session-pending-input-store.ts:256; commit dispatch is atline 301. Compound turn grants call custody currentness at
src/config/sessions/session-turn.ts:140and line 146, reached throughsrc/config/sessions/session-entry-patch.ts:272and line 253 respectively.These sharing reads can concern the same agent store as the pending-input/turn
operation. They are not covered by the allowance for short indexed reads of
another owner's state. Future migration must carry typed transaction-local
session facts through the existing custody/authorization owner while keeping
the host's live authority checks. It must not add host SQL, use
maintenance-refusable same-owner reads, or relax authorization to a stale snapshot.
Boundary tests in this PR cover the operations actually moved, not these retained
callbacks.