Repository navigation
perf(sessions): serve session observer authority reads from workers - #165205
Conversation
… workers Move current chat admission, reply authority, lifecycle preparation, verbosity, and maintenance reads through existing workers. Retain physical source identity and foreign-commit freshness, preserve accepted lifecycle settlement through close, and carry prepared transcript selection facts.
Join accepted event batches and listener settlement in fixtures. Keep restart metadata preparation with the work-admission owner and make callback this contracts explicit.
Merge main to resolve session admission and event-test conflicts. Preserve the qualified worker-backed admission owner from #164682 and main's consolidated tests, awaiting asynchronous event handling where required. Reuse internal-effects filtering across both Gateway read paths.\n\nThe complete candidate is clean through P2 autoreview. Focused conflict tests and remaining changed-check and published-driver update gates are tracked on #165028.
Use the existing async-aware event subscription helper in the consolidated verbosity test. The previous merge retained the plain unsubscribe callback while awaiting its drain method, causing a TypeError before the assertions. The corrected event-handler file passes all 82 tests. Together with the four unchanged passing files, the integrated focused group covers 163 cases. The one-line fixture correction is clean through P2 autoreview.
Merge main's transcript-context lane while retaining its prepared-start validation and released callback compatibility. Use the captured session initialization binding instead of a caller-thread session read, and combine context validation with lifecycle facts in the final anchor snapshot. Focused reply, anchor, context, runtime-build and import checks pass. P2 review raised a conditional global-alias concern, rejected after independent source tracing: the final read uses an admission receipt created from the selected stored key, and mismatched admission/session keys are refused beforehand. No actionable review finding remains.
Await asynchronous agent-event consumers and projection disposal. Move lifecycle fault injection to prepared callbacks, and track accepted writes through owner-controlled persistence before fixture cleanup. Initialize runtime config before observing row publications.
Use partial mocks for lifecycle preparation, session entry writes, and worker reads. Remove the three obsolete mock-factory baseline entries. The five affected tests, typed core lint, mock-export scanner, and P2 review pass.
|
🦞👀 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 5, 2026, 3:50 PM ET / 19:50 UTC (Revision 12). ClawSweeper reviewWhat this changesMoves session status, Side chat snapshots, and progress-visibility reads to database workers, updates bundled callers to await them, and preserves released synchronous plugin interfaces. Merge readiness⛔ Blocked before merge - 1 item remains Useful, qualified work remains absent from current main. The previous update/restart blocker is resolved for the reviewed head, and no actionable correctness or security finding remains. Priority: P2 Review scores
Verification
How this fits togetherThe session observer turns agent activity and stored session facts into status updates and Side chat context. Reply dispatch uses those session facts to decide which progress messages channels should display. flowchart TD
A[Agent activity and session facts] --> B[Observer work queue]
B --> C[Retained database worker read]
C --> D{Source and lifecycle current?}
D -->|Yes| E[Status and Side chat snapshots]
D -->|No| F[Reject stale observation]
E --> G[Guarded digest persistence]
C --> H[Channel progress visibility]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +752, Tests +1344, Docs +61. Total +2157 across 66 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Technical reviewBest possible solution: Keep observation and persistence with the existing worker owners, preserving fresh acceptance, shutdown settlement, and the released SDK deprecation window. Do we have a high-confidence way to reproduce the issue? Not applicable as a new bug report: this is a worker migration. Current-main source establishes the synchronous observer path, while the supplied SQL measurements and inspected regressions establish the performance and freshness boundaries. Is this the best way to solve the issue? Yes. The patch reuses existing retained readers and guarded writers, migrates bundled consumers together, and preserves shipped synchronous interfaces instead of introducing competing storage ownership. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 0ac81cf6ec1a. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (11 earlier review cycles; latest 8 shown)
|
Keep observer acceptance inside the existing retained Gateway reader, with writer FIFO custody and the native mutation witness. Database close revokes pending consumption instead of allowing detached rows to disclose stale companion snapshots. Follow-up visibility uses the same ordered owner while preserving logical store resolution, native reads, and maintenance fallback. Preserve released SDK signatures, schemas, retention, and shutdown settlement. Real-storage regressions reproduced both observer races and stale follow-up visibility before the fixes. Focused runtime and import checks pass; isolated Codex P2 review is clean. Final integration and CI remain landing gates.
Preserve mocked module exports, use the actual session-entry and close-result types, and retain fixture method receivers. Rename the accepted digest result to avoid shadowing its callback-local value. Runtime behavior and assertions are unchanged; focused runtime, type, lint, and architecture checks pass.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
Keep main related-row and qualified-address lookup support together with observer ordering and its admission-time freshness fence. Retain the broader main lifecycle ordering regression instead of its superseded duplicate.
|
@clawsweeper re-review A real conflict introduced by the newly landed related-row lookup has been resolved through merge commit a21f427. It preserves main's related rows and qualified addresses alongside observer ordering. Fresh P2 autoreview is clean; affected proof and final package qualification are recorded in the body. |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…penclaw#165205) * perf(sessions): serve remaining per-turn session authority reads from workers Move current chat admission, reply authority, lifecycle preparation, verbosity, and maintenance reads through existing workers. Retain physical source identity and foreign-commit freshness, preserve accepted lifecycle settlement through close, and carry prepared transcript selection facts. * refactor(sessions): finish async admission cutover Join accepted event batches and listener settlement in fixtures. Keep restart metadata preparation with the work-admission owner and make callback this contracts explicit. * test(sessions): drain the merged event subscription fixture Use the existing async-aware event subscription helper in the consolidated verbosity test. The previous merge retained the plain unsubscribe callback while awaiting its drain method, causing a TypeError before the assertions. The corrected event-handler file passes all 82 tests. Together with the four unchanged passing files, the integrated focused group covers 163 cases. The one-line fixture correction is clean through P2 autoreview. * test(gateway): finish async lifecycle fixture cutover Await asynchronous agent-event consumers and projection disposal. Move lifecycle fault injection to prepared callbacks, and track accepted writes through owner-controlled persistence before fixture cleanup. Initialize runtime config before observing row publications. * test(gateway): preserve lifecycle fixture module exports Use partial mocks for lifecycle preparation, session entry writes, and worker reads. Remove the three obsolete mock-factory baseline entries. The five affected tests, typed core lint, mock-export scanner, and P2 review pass. * perf(sessions): serve session observer authority reads from workers * test(sessions): cover observer failure authority revocation * fix(sessions): retain worker reads through observer consumption Keep observer acceptance inside the existing retained Gateway reader, with writer FIFO custody and the native mutation witness. Database close revokes pending consumption instead of allowing detached rows to disclose stale companion snapshots. Follow-up visibility uses the same ordered owner while preserving logical store resolution, native reads, and maintenance fallback. Preserve released SDK signatures, schemas, retention, and shutdown settlement. Real-storage regressions reproduced both observer races and stale follow-up visibility before the fixes. Focused runtime and import checks pass; isolated Codex P2 review is clean. Final integration and CI remain landing gates. * test(sessions): align retained read fixtures with owner contracts Preserve mocked module exports, use the actual session-entry and close-result types, and retain fixture method receivers. Rename the accepted digest result to avoid shadowing its callback-local value. Runtime behavior and assertions are unchanged; focused runtime, type, lint, and architecture checks pass.
Related: #165028
What Problem This Solves
Session status, Side chat, and progress visibility still read session authority on the Gateway thread. Moving these reads to workers must reject stale results after synchronous writes, resets, and database closure.
User Impact
Observer authority reads run off the Gateway thread, and status, Side chat snapshots, and progress visibility use current session facts at acceptance. Released synchronous plugin contracts keep working through their documented deprecation window. Schemas, stored bytes, retention, durability, and update behavior remain unchanged.
Why This Change Was Made
The existing Gateway/session reader retains discovery and physical database ownership through synchronous consumption. Its ordered reader keeps writer FIFO custody and checks the native mutation witness, so a synchronous SDK rewrite or revoked database generation cannot authorize stale results. Follow-up visibility keeps the existing logical store/key resolution, native incognito path, and maintenance fallback.
One observer queue preserves event order and reset fencing. Digest writes use the existing patch owner and transaction/commit guards. Shutdown rejects new observations and joins accepted persistence after scheduler cancellation, before closing database workers; unknown write outcomes are not replayed.
Bundled Gateway, Side chat, ACP, Discord, Slack, Telegram, and follow-up consumers use awaited methods/callbacks. The released synchronous observer methods, visibility callback, and reply-hook booleans remain deprecated compatibility surfaces, with registry records, migration documentation, and type tests. The compatibility catalog records SDK deprecations; it does not change stored data.
Part A #165028 landed as
4bd8ee5fedcb179527daeffffacbfa0920e61132. Main was first integrated atc5eba15df3829255c3dd926a47aeb72c46d6ad21. After #165454 introduced a real lookup conflict, merge commita21f4275773eefa8ea8af670e678f870f056d08cintegrated mainaf57555537a056dde973ddad2138e92c63a0f5f7. It preserves main's related-row selection, qualified addresses, and related-target callback together with observer ordering. The broader main lifecycle test replaces a superseded duplicate inherited from the stack. The observer uses the combined ordered/membership admission fence, follow-up visibility uses the current reader options contract, and the moved Discord fixtures await the async callbacks.Evidence
The retained-consumption fixes are
67489edb3d39andf8ee15f2f2ee; integration commits arec5eba15df3829anda21f4275773ee. The first integrated candidate passed 649 tests across 28 files and 12 routed projects in 360.18s, with--maxWorkers=1. Coverage includes real-storage observer rewrite/close races, queued-writer freshness, follow-up visibility, the real Gateway shutdown prelude, ACP ownership, released SDK contracts, Discord/Slack progress, import closures, and the compiled-wrapper inventory.The new unpublished-native-write regression demonstrably fails when observer ordering is removed: the previous lifecycle's Side chat snapshot resolves instead of being rejected. With ordering restored, all observer tests pass. The prior rewrite/close and follow-up controls also failed before their production repair. Shutdown proof verifies accepted digest persistence settles before database close. No test sleeps/retries or weaker assertions were introduced.
Production typechecks (
pnpm tsgo:prod, including core, UI, and all bundled extensions) passed in 56.08s. All 27 core-test graphs then passed in 477.14s and extension-test graphs in 36.63s. After the second integration, 96 affected tests across 9 files passed in 795.22s with--maxWorkers=1; time was dominated by cold transforms under host load. Production types passed in 38.16s, all 27 core-test graphs in 508.79s, and extension tests in 87.79s. The conflict files pass targeted lint and formatting. These runs cover the latest related-row lookup, qualified ownership, stale-read/close fences, accepted-write shutdown, and retained follow-up visibility. Fresh independent Codex P2 autoreview is scoped-clean for the complete introduced diff and integration. Worker-cutover routing was re-audited: real worker suites use the existing host-owned projects; remaining indirect channel/follow-up/companion fixtures mock those boundaries. No new route gaps were found.Released
v2026.9.8signatures were rechecked: synchronous observer methods, visibility callbacks, and reply-hook booleans remain beside additive async companions and compatibility records. The earlier scoped SDK report had no entrypoint additions/removals; the first integrated reportf7b75940completed with 0 entrypoint changes and 206 reachable-closure updates, with no new released-signature break. The final local reportaf57555537a0 → a21f4275773eealso completed: acknowledgementa981cb75, 0 entrypoint changes and 206 reachable exports. All 12 unique declaration changes match the earlier reviewed additions/removals; no new released-signature break exists. Final worker routing audit is clean, including related-row and incognito/sharing callers. The broad historical tag report's eight removed entrypoints already existed before this PR through #162333/#163366.The previous Slack readiness failure reproduced on the stacking base and candidate, but not in five pinned-main runs, so it never qualified for a main-inherited exception. Part A includes the owner-fixture repair; after integration, the full dispatch suite passes and the formerly failing cleanup case passed in 86ms.
Exact-head CI run 37357487685 succeeded for
a21f4275773ee: 561s workflow wall time and 11,295 summed job-wall seconds across the workflow's 87 jobs. The latest rollup has 99 successful checks and no failures; one cancelled non-required automation is retained as cancelled. CI supplies the complete changed-file gate result. Local changed checks on the preceding integrated source passed through core lint before the real main conflict required stopping them; affected final files were rechecked locally. ClawSweeper completed this exact head at 18:43 UTC with no actionable code/security findings. No inherited-failure exception is claimed.The published-driver update/restart cell passed on isolated AWS Crabbox, run
run_6a21ce605af6fc6a0b645de3f8a557bd/ leasecbx_b40954524c86. The released2026.9.8CLI updated to the package built froma21f4275773eefa8ea8af670e678f870f056d08c(the source version remains2026.9.8, distinguished by its build identity). The package build and tarball import/integrity checks passed. Installed build metadata matched the candidate, the managed service PID changed, readiness returned 200, the recorded update reachedfinished/succeeded, durable session identity/content survived, and incognito history was empty after restart with no incognito artifacts. The service was stopped by fixture cleanup and the cloud lease is released. Total proof command time was 1,195.857s, including frozen install, build, packaging, Docker preparation, and the updater cell.Testbox staging/queue exceeded the fallback threshold, so its owned lease was stopped and the authorized AWS fallback used. The first AWS fresh checkout lacked installed dependencies; that setup-only failure occurred before package testing and was corrected with a frozen install on a fresh lease. No product assertion was weakened or rerun for green. Final import-closure and runtime process-graph tests also passed in 43.86s, and the compiled-wrapper inventory passed in 21.65s on
a21f4275773ee. No newOPENCLAW_*names, dependencies, schema, retention, or protocol changes are introduced by this PR.Historical SQL measurement for the worker migration
This measured the original migration at
edcc5967bf97af0bf1329946c901f6b6ae3bb3f4, before the later retained-consumption repairs. Current boundary tests continue to assert zero caller-thread SQL for the moved observer reads; the historical totals below are not a new benchmark of the landing repair.SQL measurement
Same local sqlmeasure workload and instrumentation, Node 24.21.0 / SQLite 3.53.4, synthetic state and mock provider. Before is the accepted
d3576a5453b0e9750010fa4cd6d8ea24c5990489baseline; after is committed headedcc5967bf97af0bf1329946c901f6b6ae3bb3f4, stacked on A at219204ca5844. This cumulative comparison includes A and its updated main base; reductions are not additive per-lane credit or latency measurements.MAIN decreases 17.8% per warmed turn and 6.8% overall. Total SQL increases 10.9%, including worker work/admission. Static T1 stays unchanged because the shared native kernels and SDK adapters remain inventoried.
Observer-attributed MAIN executions across the ten warmed turns:
openclaw-agent-db-readonly.ts:116session-accessor.sqlite-entry-read.ts:320session-accessor.sqlite-participant-projection.ts:56session-canonical-key.ts:371After MAIN counts by warmed turn:
183, 183, 183, 183, 183, 183, 187, 183, 183, 180. These phase-window counts include concurrent/settling work. All 13 turns, the native child, 37 RPCs, scheduled cron, committed compaction, and graceful shutdown passed. Two baseline audit-worker shutdown failures and two candidate MAIN shutdownBEGIN IMMEDIATElock failures are excluded under the successful-statement counting method. The candidate failures originate inclearGatewayRestartIntentSync(src/infra/restart-intent.ts:431), outside the moved observer paths; Gateway shutdown still exited 0. Source-map builds: 220.0s before / 378.5s after; workload: 119.6s / 95.0s.Coordination: Part A owns the shared readers/verbosity helpers. Related session-authority, transcript, and lifecycle lanes retain their scopes, including cron #165129, placement #165166, and incognito #165151/#165134. #165110 and #165097 are incidental ACP/Discord cleanup overlaps; final integration preserves their mainline changes. #162433 is an inactive umbrella overlap. The observer commit grant adds no host SQL; its source checks use retained memory/configuration/physical-identity facts, while row predicates stay with the worker.