Repository navigation
perf(sessions): route the remaining per-turn native session patches through the writer - #165193
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review in progressClawSweeper is reviewing this revision. This supersedes any previous blocked status. |
|
|
Codex review: blocked before merge. Reviewed October 4, 2026, 10:47 PM ET / October 5, 2026, 02:47 UTC (Revision 6). ClawSweeper reviewWhat this changesMoves same-store session lifecycle writes and their source checks into the existing database workers while preserving synchronous compatibility paths and shutdown settlement. Merge readiness⛔ Blocked before merge - 1 item remains This PR remains useful: current main still uses native lifecycle patches. No introduced correctness or security defect was found, and the documented bounded npm-timeout investigation resolves the previous review blocker under repository policy. Priority: P2 Review scores
Verification
How this fits togetherSession lifecycle persistence records agent starts, terminal outcomes, and recovery state in agent databases. Gateway requests and agent events feed this subsystem, which publishes committed session state to downstream consumers. flowchart TD
A[Agent events and session requests] --> B[Prepare source facts]
B --> C[Check live authority and store identity]
C --> D{Same physical store?}
D -->|Yes| E[Existing writer worker]
D -->|No| F[Native compatibility transaction]
E --> G[Publish committed session state]
F --> G
G --> H[Join accepted writes before shutdown]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +1097, Tests +968, Docs +12, Other +1. Total +2078 across 53 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep same-store lifecycle SQL with the existing writer, retain live final-commit authorization, and preserve the released synchronous compatibility boundaries. Do we have a high-confidence way to reproduce the issue? Not applicable as a bug reproduction: current-main source establishes the native lifecycle route, and the recorded production workload measures the changed SQL placement. Is this the best way to solve the issue? Yes. Reusing the existing writer and read workers preserves one ownership chain, while explicit native routing protects released synchronous and cross-store contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against d4ce3b2f33d4. 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)
|
Resolve the additive session transcript worker type import conflict by retaining both imports. Preserve the native cross-store SDK boundary and same-store worker cutover.
|
@clawsweeper re-review Integrated main with a merge commit, retaining both imports in the known additive conflict. The integrated candidate passed 89 focused tests including lifecycle source refusal, native cross-store routing, startup/restart recovery, and the four required import-closure checks; fresh P2 autoreview is clean. The published 2026.9.8 driver update cell and released SDK audit remain documented in the PR body. No schema or stored-data format changed. |
|
🦞👀 Re-review progress:
|
Assert forwarded authority and owned persistence settlement instead of callback or promise identity. Pin the restart fixture's shared-state root before creating its agent owner, and seed list metadata without scheduling competing maintenance. Preserve all behavioral assertions and existing deadlines.
|
@clawsweeper re-review Head 5d5593c repairs six CI fixtures without production changes. Callback and promise identity assumptions are replaced by live-authority and pending/settled behavior, recovery state is pinned before owner creation, and initial list metadata no longer schedules competing maintenance. Focused repaired behavior, check-changed, and fresh P2 autoreview passed. Full remote comparisons remain explicit pre-merge conditions in the body; no schema or stored-format change is introduced. |
|
🦞👀 Re-review progress:
|
Integrate the landed declaration-fixture dependency fix in #165221 without rebasing. Scoped integration proof passed 75 tests. The review's Talk-policy concern was rejected after source inspection and two real worker-authority probes confirmed current-policy revocation and fail-closed missing targets; no additional production change was needed.
|
@clawsweeper re-review Head 8ca43aa merges the now-landed declaration-fixture fix from main without conflicts. All required original/base comparisons and repaired full-file proofs are complete. New integration proof passed 75 tests, including the former declaration failure. The latest P2 Talk-policy concern was checked against its actual owner and disproved with two real-worker probes; disposition and full evidence are in the body. No additional authored production changes. Fresh CI is attached to this head. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…hrough the writer (openclaw#165193) * perf(sessions): route remaining native lifecycle patches through the writer * test(sessions): align lifecycle fixtures with worker ownership Assert forwarded authority and owned persistence settlement instead of callback or promise identity. Pin the restart fixture's shared-state root before creating its agent owner, and seed list metadata without scheduling competing maintenance. Preserve all behavioral assertions and existing deadlines.
What Problem This Solves
Warmed turns still performed two native session patches on the Gateway thread: lifecycle start publication and terminal lifecycle persistence. Temporary async-stack attribution identified
server-chat-lifecycle-publication.tsandsession-lifecycle-persistence-owner.ts→persistGatewaySessionLifecycleEventas their producers; the instrumentation has been removed.Why This Change Was Made
Send same-store lifecycle patches through the existing agent writer and patch worker. Recovery, companion, and Stop authority prepare source facts through the existing read worker, carry them through caller receipts and request/control adapters, and revalidate live authority before submission and after settlement. The write transaction rereads typed row, membership, and transcript predicates on its own connection. Conditional no-ops and target CAS checks keep their existing precedence; source refusal rolls back before the final commit grant.
Cross-store patches retain their native transaction: event-loop atomicity across stores is required while the released synchronous transcript SDK can mutate the source outside async queues. Routing is explicit from prepared physical identities, never an error fallback; revisit at the next SDK major. Process-held incognito sources and opaque released SDK guards retain their native contracts. Accepted lifecycle persistence joins before workers close and does not inherit scheduler cancellation.
User Impact
No schema, retention, durability, configuration, or released SDK behavior change. One existing writer owns the moved operations; unknown outcomes never replay. Production: +1,567 / −470 / net +1,097; 2,037 changed lines, plus one wrapper-inventory entry.
Pre-existing other-owner authority reads remain follow-up debt: the shared-profile role fallback in
src/gateway/operator-role-policy.ts:48and creator-alias fallback insrc/gateway/session-creator.ts:27. They remain live authority checks; moved source-storage predicates execute in the worker.Evidence
Candidate:
e023d086bd5d6ca95cee5d60a50a06060148ece9; implementation base:327dc38387b6afa8c8d62b4f6c8c9975143331d3. SQL baseline:82adb7a49d36e844e4ea1989bc5d865abac916f0, Node 24.21.0, the unchanged sqlmeasure workload. Aggregate counts include concurrent/background work and changes incorporated from main; they are not a latency claim or additive credit for this PR.Final sqlmeasure completed all 13 top-level turns, child run, cron, compaction, and graceful shutdown in 139.0s; Node 24.21.0. The two warmed native transactions are gone (20 → 0 across ten turns). Remaining native patch statements occur on first-turn initialization (48), second-session/child work (165), and cron (229). The measured native arm is
session-accessor.sqlite-entry.ts:559–627; all resolved disk paths stayed inside the synthetic fixture.Validation (all focused Vitest commands use
--maxWorkers=1):runtime-process-build-graph,get-reply.imports,openclaw-state.worker.imports, andeager-import-closure.Test-body cost for the changed tests: caller receipts 0.182s, patch worker 50.714s, opaque dispatch guards 15.128s, companion RPC 14.019s, lifecycle source/Stop 9.585s, sharing worker 50.690s, and the real close case 23.429s. The patch/sharing suites above 30s exercise worker admission, rollback/receipts, and current authorization across actual SQLite owners; mocks cannot prove those boundaries. The close case reuses its existing Gateway fixture. The commands above were batched; these are body totals, not standalone per-file wall times.
check-changed: passed, 2,372.83s wall. Earlier lint findings were corrected without weakening rules; the final test cleanup passed type-aware lint (52.08s) and its two regression cases (88.43s wall). No limit or baseline was weakened. Environment names remain 473/473, with zero new names.6790259c, 128 reachability impacts with unchanged direct export declarations; no entrypoint/export additions or removals and no released synchronous-to-asynchronous Gateway-context contract changes. Reachable declarations cover optional source metadata, an internal worker reader/command, an optional transcript-helper argument, and preserved reexports. The released reader facade does not expose the internal database reader as an SDK implementation requirement. Completed in 1,551.66s wall./readyzreturned 200, and the running build matchede023d086. Durable session identity/message survived; incognito history was empty after restart and artifact-leak checks passed. Canonical full package creation took 3,393s, including integrity checks; SHA-2567b3a1289965945f3007a41bae5f76c0251797202005b8ffcc13550eabb03e5c8. Owned container, volume, image, and remote lease were cleaned up.Build caveats: the first local package build reached its default 45-minute ceiling during cold declarations. The supported 90-minute package-build budget completed the full build; the runtime-cell deadline was never extended. The successful build retained a nonfatal UI startup-size warning: 365.1 KiB gzip versus 364.7 KiB. No budget or baseline file was changed.
Overlaps: #142236 in lifecycle persistence; #162433 is the inactive umbrella design draft. #164922 and #164989 are merged and incorporated; they own compound lifecycle/deletion commit snapshots and transcript context reads. This change leaves their ownership intact and keeps focused additive hunks. The incorporated prepared-sharing work in #164682 is preserved, together with main's placement-preservation, incognito-close, and shutdown-admission changes.
Landing validation
Merged main at
dc518bfca481d64aef69f9a4f8435fc6d46ed46dto resolve the additive import conflict with #165181. BothSessionEntrySnapshotFieldandHarnessCompletionSourceWorkerimports are retained; the resolution changes no runtime logic. The published-driver update cell, SDK API diff, and full check-changed above remain prior-head proof for unchanged PR implementation inputs, not current-head CI.Integrated candidate validation (each command uses
--maxWorkers=1):node scripts/run-vitest.mjs src/config/sessions/session-entry-patch.test.ts src/gateway/session-lifecycle-source-authority.test.ts src/gateway/session-lifecycle-persistence-owner.test.ts --maxWorkers=1: 34 tests / 3 files passed, 168.99s wall.node scripts/run-vitest.mjs src/agents/main-session-recovery/main-session-restart-recovery-marking.test.ts src/agents/subagents/registry/subagent-parent-recovery.restart-integration.test.ts test/scripts/runtime-process-build-graph.test.ts src/auto-reply/reply/get-reply.imports.test.ts src/state/openclaw-state.worker.imports.test.ts test/scripts/eager-import-closure.test.ts --maxWorkers=1: 55 tests / 6 files passed, 130.20s wall.agents-supportproject; Gateway and source-authority suites have host-worker ownership. No additional routing change was necessary.v2026.9.8: no changed direct SDK/runtime exports; synchronous callback callability remains intact. The extractedSessionTranscriptContextVersionretains its three fields and the existingcodex-session-transcript-runtimereexport. New source-preparation members and helper parameters are optional; internal worker methods do not become SDK implementation requirements. No compatibility removal or sync-to-async released signature change is introduced.e023d086. Its conflict item is resolved above; its data-model proof request is covered by the published2026.9.8driver × candidate update cell (984s). No stored schema or data format changed.The initial PR-context check failed because the problem heading did not match the required template. The body now uses
What Problem This Solves; no test assertion or gate was weakened. The integrated-head CI findings and subsequent fixture repair are recorded below; ClawSweeper completed with no actionable code or security findings.CI fixture repair
Integrated-head CI attempt 1 exposed six failing Node shards. The repairs are test-only and preserve production behavior:
in-process-gateway.test.tscompared a callback by identity even though the new source-authority adapter wraps it. The test now invokes the forwarded guard and proves its refusal propagates. The original file failed 5/5 on the PR and passed 5/5 on the merge base; the repaired file passes all 30 cases (14.347s wall).session-lifecycle-state.test.tsstill invoked the native guard option in its fake writer. It now exercisesworkerGuard.sourcewhile preserving rejection and unchanged-row assertions. Original PR: 5/5 same failure; baseline: 5/5 all 49 pass. Repaired file: 49 pass (88.205s wall).server.private-completion.test.tsandserver-runtime-subscriptions.test.tsassumed that tracked persistence was the underlying write promise. They now prove pending and settled behavior through the owned promise. Subscription cleanup also covers assertions that previously failed before the deferred work was released, causing CI's no-output timeout.main-session-restart-recovery.test.tscreated the agent owner before switching its shared-state root. The fixture now pins that root before its first write; the worker's cross-root refusal is unchanged.server.sessions.list-store-materialization.test.tsunnecessarily replaced its seeded row, scheduling maintenance before a raw malformed-row INSERT. Final metadata is now seeded through the fixture's existing maintenance-free initial writer, with all projection/read assertions retained.The first original-order four-file startup/shutdown baseline passed 46 tests. Original PR execution reached the stale promise-identity assertion and then blocked cleanup; later local 60-second-watchdog attempts on both revisions expired during cold worker compilation and are excluded as environment failures. The first complete private-completion comparison was PR 22 pass/1 fail versus baseline 23 pass; the first complete restart-recovery comparison was PR 149 pass/1 fail versus baseline 150 pass. These runtime comparisons and repaired full-file proofs are now complete, as recorded below. Local cold-compilation failures are excluded from the counts.
Fresh Codex P2 autoreview of the combined six-file repair: scoped-clean. No production code, test deadline, baseline, assertion exception, or new environment name was added by this repair.
Local repaired proof before publication: full in-process caller file 30 passed / 14.347s; full lifecycle-state file 49 passed / 88.205s; private timeout variants 3 passed / 126.329s; the full subscription file plus the changed list and drain-recovery cases 36 passed / 205.29s, with 151 unrelated cases intentionally skipped by the explicit name filter. All use
--maxWorkers=1. The six-filecheck-changedpassed, including all four affected typecheck groups, lint, formatting, and repository ratchets. The runtime repetition and full-file evidence is complete below.Completed comparison evidence
Restart recovery: five original PR full-file runs each reproduced only the cross-root fixture error (149 other cases passed); all five merge-base runs passed all 150 cases. The identical repair passed all 150 cases in 163.68s on Testbox run 37248068883; its lease is stopped. Subscription comparison: all five original PR runs reached the same post-transition stall under the existing CI 60-second watchdog after compilation and 16 prior passing cases; all five baseline full-file runs passed 34 cases. This excludes the earlier local cold-compilation failures.
Repaired-head CI attempt 1 resolved the six original Node fixture failures. Its remaining declaration-build failure is independently inherited: main commit
76922aba447(#165200) adds theruntime-postbuild-shared.mjsimport torun-node-input-state.mts, but the copied declaration fixture omits that module. Module linking fails before PR runtime code executes. The exact tested main parentc5012333049eef43cefe9c38ee4805a0dce971beand CI merge94afdf9b23b05e424983687de354605fd3b15837each reproduced the same missing-module failure 5/5, with 10 other tests passing every run. Their test, fixture, build entry point, import owner, and missing-helper source blobs are identical; this PR changes none of those files. The public CI Windows job is 111573781582. The ordinary main push run skipped the affected tests; it is not cited as passing proof.The npm-pack successor timeout in job 111573782272 was not reproduced in five complete tested-merge and five complete tested-main runs; its original cause remains unclassified. The list/private comparisons and repaired full-file checks are now complete. The original npm timeout remains unclassified; the final integrated head passed CI.
The full list-store baseline comparison reproduced the same raw-INSERT
SQLITE_BUSYrace in 2/5 runs, with the other cases passing; the other three full-file runs passed. Baseline command wall times were 123.723, 109.458, 106.588, 102.327, 102.170 seconds. This independently confirms the fixture race predates the PR. The repair removes its unnecessary maintenance-producing replacement instead of masking the lock with waits or retries.Runtime comparison and repair proof complete
All prescribed original/base comparisons for the six fixture repairs are complete. The private-completion file failed only the stale promise-identity assertion in all five original PR runs, with all 23 baseline cases passing in all five baseline runs. The list-store file reproduced the same existing SQLite lock in 2/5 baseline runs and 1/5 original PR runs; other cases passed.
Final Testbox proof passed the repaired complete files with
--maxWorkers=1: subscriptions 34/34, 30.166s; list-store materialization 3/3, 103.424s; private completion 23/23, 76.056s. The repaired source SHA-256 values match the published files. Current-head CI also passed all three list-store cases: 2.592s, 60.733s, and 0.933s test-body time in job 111573782294. No test deadline or baseline changed.Final main integration
Current head:
8ca43aa37bfbd7c81179362d61491fc56610d5bd. Main was merged again, without conflicts or rebase, to incorporate the landed declaration-fixture fix12785be2ff02from #165221. No new authored production change was needed. 75 tests across eight files passed in 414.31s with--maxWorkers=1: patch/lifecycle/source-authority, the four shared-registry/import checks, and the complete declaration-writer file. The previously missing-module case now passes. The inherited-failure admin exception is therefore no longer needed for that historical failure.Fresh P2 review raised a Talk-policy concern. Source inspection shows that the prepared existing-target path calls
authorizeSessionAgentRunagainst current committed policy, which callsauthorizeGatewaySessionCreation; missing Talk targets cannot obtain a prepared storage route. Two temporary real-worker diagnostic cases confirmed rejection after revoking the agent permission during source preparation and fail-closed absent targets (2 passed, 211.63s command wall). The concern was rejected as a false positive; the diagnostic was removed, with no production change and no accepted actionable findings remaining.The npm comparison completed in an isolated local Linux ARM64 container using Node 24.21.0, separate frozen installs, normal
qaRuntimebuilds, and verified exact source trees for CI merge94afdf9band tested-main parentc5012333. All 5 + 5 complete file runs passed all 23 cases (230 passes). The originally failing npm-pack case took 5.372–16.023s, while CI timed out at 120s on its x64/Node 24.19 environment. This does not establish an inherited failure or a fix; the original timeout remains unattributed. The necessary main integration passed fresh head-bound CI. All proof containers, volumes, and Testbox leases are stopped/removed.Landed
Merged as
48c022a42c131ec026291c4be79937722119b2f9after exact-head CI run 37256161247 passed for8ca43aa37bfbd7c81179362d61491fc56610d5bd. Nativescripts/prpreparation and merge completed through the ordinary green-check path. ClawSweeper completed on that exact head at 02:47 UTC with no introduced code or security findings and accepted the documented npm investigation and Talk-policy disposition. The recorded published-driver update covers the generic data-model checklist; stored contracts are unchanged.