Repository navigation
fix(state): move Gateway state consumers through existing workers - #169580
Conversation
Prepare machine state, profile identity, auth ownership, and lifecycle facts through existing workers. Keep committed facts with their owning Gateway and use write receipts at effect boundaries. Remove redundant state rereads and migrate bundled callers to asynchronous SDK replacements while retaining documented deprecated adapters.
|
🦞👀 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: needs real behavior proof before merge. What this changesThis PR moves Gateway state preparation into existing database workers and maintains prepared facts through committed write receipts. Example: A cold plugin call resolves TTS preferences with OPENCLAW_STATE_DIR=/tmp/tts-state and stored tts.prefsPath=/tmp/tts-state/custom.json.
Review scores
ProductKind: Refactor · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 5 items remain Keep this maintainer-owned PR open: the worker cutover is useful, but the cold synchronous TTS compatibility regression remains. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherGateway requests and plugin SDK calls consume machine settings, profile policy, credentials, and agent lifecycle facts from shared SQLite state; workers return prepared facts and publish committed invalidations. flowchart LR
A[Gateway and plugin callers] --> B[Asynchronous preparation]
B --> C[Existing database workers]
C --> D[Shared SQLite state]
C --> E[Prepared facts and receipts]
E --> F[Current authority guards]
F --> G[Credential and filesystem effects]
Technical reviewBest possible solution: Keep ordinary Gateway preparation asynchronous while preserving cold synchronous SDK behavior and proving revocation at the final credential, publication, and deletion effects. Do we have a high-confidence way to reproduce the issue? Source and the changed TTS test establish the cold-path regression: a persisted custom path is ignored before asynchronous admission; no runtime reproduction was executed during this read-only review. Is this the best way to solve the issue? Existing workers and writer receipts are the appropriate owners, but eliminating synchronous discovery from a released compatibility API must not change its returned path. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against db5cdcaf8e31. Merge-risk optionsMaintainer options:
Provenance checked
TestingProof path: in-process harness. SecurityNeeds attention: The changed receipt-backed authority boundaries need final-effect revocation evidence before security clearance. EvidenceSecurity concerns:
What I checked:
Likely related people:
PR surfacePR surface statistics unavailable: the file list is incomplete. LabelsLabel changes: No label 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 (27 earlier review cycles; latest 8 shown)
Reviewed October 12, 2026, 11:16 PM ET / October 13, 2026, 03:16 UTC (Revision 28). |
# Conflicts: # src/state/agent-deletion-journal.ts
…t1cut-state # Conflicts: # src/gateway/server-methods/push-authority-router.test.ts # src/gateway/server-methods/push.ts
# Conflicts: # src/gateway/server.node-version-mismatch.test.ts
…t1cut-state # Conflicts: # src/gateway/server-methods/sessions-goal.test.ts
…enclaw#169580) Route Gateway config and machine-state reads, lifecycle facts, and GitHub publication through existing worker owners. Reuse committed receipts for internal deletion bookkeeping while retaining credential and filesystem-effect authority checks. Share the credential-aware machine-state writer and remove superseded internal readers. Remove seven live main-thread SQLite call sites in the fixed state cohort (historical audit 33 to 26; current classification 30 to 23 including compatibility). Preserve released synchronous SDK signatures and add asynchronous replacements. Keep whole-store auth saves and cold discovery deferred to openclaw#169763. Align direct fixtures with worker-owned preparation and preserve main integration changes.
Prepare the shared auth owner before constructing the synthetic auth snapshot in the source-only credential refresh case. Commit 4466c0d (#169580) made synchronous auth paths consume prepared ownership; this fixture still relied on the removed cold preparation and failed before starting its reloader. Keep every credential-coherence assertion unchanged. The exact selected case, fixture format check, and type-aware lint pass in run 38544268431.
Prepare the shared auth owner before constructing the synthetic auth snapshot in the source-only credential refresh case. Commit 07dcf9c (openclaw#169580) made synchronous auth paths consume prepared ownership; this fixture still relied on the removed cold preparation and failed before starting its reloader. Keep every credential-coherence assertion unchanged. The exact selected case, fixture format check, and type-aware lint pass in run 38544268431.
What Problem This Solves
Gateway state consumers reached synchronous SQLite through shared-state and SDK owners although worker operations already existed. Config and machine-state operations now use the shared-state worker; profile policy uses its admitted catalog; personal GitHub connections use facts invalidated by write receipts. Authentication prepares its owner asynchronously. Deletion bookkeeping consumes the live lease and journal/provenance receipts. Canonical validation runs at admission; metadata writes use a conditional upsert without a preliminary SELECT. Bundled callers migrate together and private superseded readers are removed. Whole-store auth saves and cold discovery remain deferred to #169763.
User Impact
Gateway state access moves off the main thread while preserving its authorization, persistence and deletion behavior.
Credential, publication and filesystem-effect checks remain with their effect owners. Failed GitHub writes invalidate requested and commit-reported owners so a lost receipt cannot preserve old credentials. Explicit local-store and environment-only reads avoid ambient shared-owner preparation. Released synchronous SDK APIs remain deprecated compatibility paths. No lane schema, retention, stored-format, dependency or permission change is introduced.
Why This Change Was Made
Existing workers own the database operations and publish committed facts. Callers can reuse those facts without opening synchronous handles or rereading internal bookkeeping.
T1 and scope
63a034fSeven actual cuts cover four final-guard primitives, lifecycle facts, canonical-receipt runtime admission and publication lifecycle reads. The remaining 26 expressions are 25 original-file calls and one relocated reader. Worker use, deprecated released SDK/native compatibility, boot admission, migrations, Doctor/CLI one-shots, lock primitives and real credential/user-data/effect guards remain. Classification is not query savings; zero literal T1 or whole-Gateway MAIN SQL is not claimed. The original audited reduction remains seven calls. On integrated main
2d9b602a, the regenerated inventory classifies this same 17-file cohort as 24 T1 + 6 T1-compat calls; the candidate has 18 T1 + 5 T1-compat calls (30 → 23). Main's classification changes explain the different absolute totals.Evidence
The latest integration merges main
2d9b602a74ee482171c5f80ac8a775c3a2d26a2a; its only conflict resolves the reply-dispatch fixture to main’s version, dropping the process-global active-run assertion while preserving delivery/custody/deadline proof. The preceding integration resolved only the generated worker inventory. Earlier conflicts reconcile main’s async session preparation and deletion queue with the lane’s prepared-profile fixtures, extracted lifecycle binding and receipt-based guards. The inventory was regenerated from merged source. The latest integration changes no fixed-cohort source files. The preceding integration added main’ssingleStatementtransaction option and comment, with no new SQL call expression. The engine-storeinspectSqlitecontract, lexical boot admission, shared-state v22 and memory-incognito cutover are preserved. No new SQL measurement is claimed for this integration.6b9535cd4f9d(job 115087987866): zero entrypoint additions/removals, one additive export (agent-runtime.replaceRuntimeAuthProfileStoreSnapshotsAsync), 197 reachable changes, zero direct signature changes/removals. Released synchronous API signatures remain. This is reused evidence, not a current-head render.ae6132ab, completed with 142 successful and 20 skipped jobs. Production/test types, lint/source contracts, Knip/Madge, T1/dialect/worker ratchets, build, PostgreSQL conformance and security passed. The three behavioral failures are addressed below; this is prior-head evidence, not the final gate.The Phase E hold is absent. #169763 remains deferred. Diff against integrated main: 477 files, +10,170 / −8,204 lines (net +1,966), including earlier integration drift. Frozen-lockfile install, changed-fixture formatting/lint and whitespace checks pass.
Removed checks and accepted edges
5b242) retired held pending-read freshness; the retained delayed-read scaffolding is removed. Status preparation racing completion may require a refresh. Confirmation checks the live receipt before effects, and direct terminal-confirmation/no-extra-commands regression coverage remains.OAuth identity, credential replacement and reconnect-safe pin-removal checks protect real credentials/user data and remain. No generations, fencing or new cross-thread handshake is added.
Measurement
Original three-pair base
656287c940a5287da9efe69aabde2348695e07e1versus byte-verified candidate later committed asd595c2a59827c(manifest737bc8ebdb5edb70a246be2d25d884bae33855ebd357b703ef7c8572829eecd9). Measurements retain their recorded snapshots; neither series measures the current head.Original three alternating pairs:
The whole-workload request increase is +1.19% under the cold T1-move allowance. The newer combined pair below preserves the shared-family attribution required by the updated campaign rule.
Live integration pair and attribution
The combined SDK follow-up was measured with the unchanged shared harness: baseline
63a034f64e3af869a5affb0968d0d3a199121358, candidate1d4c0e3d1ab5d9655d6a3c00c35beb0cb154e70e. It is an earlier measured pin, not the final Git head. Later fixture/type/conflict and cold-auth/lost-receipt repairs were not remeasured; the table reports only the pinned pair. All 13 turns, child flow, cron, compaction and shutdown completed. The copied harness readiness budget alone was raised from 300 to 900 seconds after one loaded-host startup attempt ended before any turn; the shared harness and workload deadlines were unchanged.Main commit
7aae49e8677b18ca992b72a49221e1b6de4b45e4(#169660) introduces a transcript-triggered usage-cost sidecar absent from this baseline. It adds 122 SQL/18 requests plus 3 SQL/3 plugin-state requests per warmed turn. These are real inherited operations, not a state-lane saving or unexplained noise. This lane's warmed state operations add no statements or requests.The hydration increase decomposes exactly: nine additional borrowed reads and nine delivery-settlement hydrations follow usage-cache writes on the same writer thread; one follows an unchanged memory write; transcript-append hydrations fall by seven. Net +12 over ten turns. The usage operations' unscoped transaction bumps the global write revision used by actor residency. This points to a separate usage-owner optimization, not extra state preparation calls. No inherited deletion-status-cache saving is credited here.
Cold state operation counts (SQL/requests): machineState.read 0/0→5/5; userModelAccounts.links 8/2→4/1; profile ensureOwner 34/1→37/1; config health/snapshot and profile authority/attribution operations retain their counts. A skipped registry maintenance sweep lowers deletion snapshot sampling, so that reduction is not credited.
Limitations: one candidate startup sweep logs an invalidated registry snapshot and skips safely; the later cron workload passes. This existing check guards real deletion/retention data and stays. Candidate background Workshop review reaches an existing synchronous transcript effect guard (130 MAIN SQL across cron/compaction); base schedules the same review but rejects a stale anchor before admission. Scheduler/review/guard code is unchanged, although metadata preparation can affect timing. This is reported as background-flow placement variation, not zero whole-Gateway MAIN. Warmed MAIN outliers are unchanged secret-store timer work outside this lane. SQL conservation is exact with no missing contexts or duplicate sends; send/receive tracing has two unmatched records on base and three on candidate.
Current CI disposition
Current head:
2faeb9b28f31ecf609d57d9e8896105a69d89961. Exact-head CI 38487193297 follows the conflict-only integration. Its failed shard is empirically inherited as detailed below. The preceding run 38486203555 was superseded by that integration. Prior-head CI 38482903334, on414755eb, passed all static and security gates: production/test types, lint, Knip, Madge, database/T1/dialect ratchets, source contracts, PostgreSQL conformance, Security Review, Security High, Critical Quality and Opengrep. These remain prior-head evidence, not the final gate. Earlier failures were:models-config.providers.implicit.outcomes.test.ts: draining all timers also drains the process-wide recurring directory observer until Vitest's 10,000-timer limit. The fixture now advances by the sum of its six catalog delays and awaits the catalog operation. Concurrency, merge order and outcome assertions remain.dispatch-from-config.reply-dispatch.test.ts: two pending-final cases expected no timers anywhere in the process. The helper now checks the reply-run owner has no active run. Pending-final records, newer-intent protection and deadline advancement remain. Deadline cancellation itself is independently covered byreply-flow.test.tsand retry-owner tests.ops.run-admission-cleanup.test.ts, “releases scheduled ownership after cleanup-terminal persistence fails”: the same undefined-versus-1770372303000 assertion reproduced in a full-file run on main9690a6d7fa9cdb(10 passed, one failed). The failing file is unchanged by this PR. This is an empirical inherited-failure exception; the isolated case passing on both branches is not claimed as a repair. The main failure is assigned through the campaign's main-failure inbox.Focused replay on this head passed all three previously failing timer cases: both pending-final delivery cases and bounded catalog discovery. The two selected files completed in 181.56 seconds including compilation (individual Vitest durations: 109.37 and 46.12 seconds). No broad local suite was rerun.
The latest prior-head run also exposed two cases:
session-accessor.sqlite-scope.test.ts, “slow writer failure separates waiting and execution”: the same 120,000 ms timeout reproduced on the pinned integrated main7039a3213373c092e769899a230588f70e279f21(175.53 seconds Vitest / 184.40 seconds wrapper) and candidate (190.55 seconds Vitest / 231.52 seconds wrapper). The test and its queue/admission owner are unchanged against that main. This is empirical inherited evidence; an early assertion can strand the fixture's deferred writer before its cleanup block. The main-failure owner has the evidence. Two earlier baseline attempts failed on workspace setup and are not counted as behavioral proof.session-state-notices.test.ts, “cancels a newer watcher buffer when an older queued batch starts during close”: the full file passed on main (10 tests, 5.69 seconds Vitest / 10.55 seconds wrapper), so it is not claimed inherited. The fixture now awaits the actual singleton lifecycle drain instead of running every timer in the process. Pending notice cancellation releases queued buffers; mock settlements are resolved before draining. All cancellation, coalescing and deadline assertions remain. Changed-file formatting/lint and whitespace checks passed. Candidate focused replay passed all 10 cases in 3.92 seconds Vitest / 9.63 seconds wrapper.Current-head CI remains the landing gate; any new failures require attribution.
Final-head failure attribution
Job 115604878369 reports three 120,000 ms timeouts: the known slow-writer case and
session-entry-read.retirement.worker.test.tscases “settles ordered exact-entry refusal without waiting on the following writer” and “settles ordered exact-entry eviction without waiting on the following writer”. Running those same three cases in the same two-file sequence on integrated main2d9b602a74ee482171c5f80ac8a775c3a2d26a2areproduces all three timeouts (430.07 seconds Vitest / 439.07 seconds wrapper). These files and the retirement/ordered-reader/admission owners are unchanged by the PR. The candidate’s retirement file passes alone (two cases; 74.75 seconds including compilation). The slow-writer fixture can strand the process-global writer queue, and later fixture cleanup waits on that queue. This is an empirical inherited-failure exception, not a claim that an isolated pass fixes the sequence. The main-failure owner has the exact reproduction. No retries, weaker assertions, or timeout increases were added.Merge readiness
On exact head
2faeb9b28f31ecf609d57d9e8896105a69d89961, all static gates pass: production/test types, core/extension lint, Knip/dependencies, source contracts, Madge/architecture, database/T1/dialect ratchets, build artifacts and PostgreSQL conformance. Applicable security/quality checks completed with 21 successes, five skips and one neutral result. CI reports 144 successful and 19 skipped jobs, one failed job containing only the three empirically inherited timeouts above, and one still-running behavioral shard (checks-node-changed-compact-small-6, job 115604878705). No passing result is claimed for that pending shard or the aggregate gate. Landing uses the maintainer-approved relaxed v4 slow-CI exception after the focused fixture proofs; any newly revealed regression requires follow-up. Two review rounds are complete. No additional production change followed them.