Repository navigation
refactor(plugin-state): move runtime consumers to the worker - #166528
Conversation
|
🦞👀 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: needs maintainer review before merge. Reviewed October 7, 2026, 5:35 AM ET / 09:35 UTC (Revision 3). ClawSweeper reviewWhat this changesMove rescue-command approval storage and bundled OpenRouter capability loading into the existing database worker while preserving approval ordering, released SDK behavior, and shutdown settlement. Merge readiness✅ Ready for maintainer review This PR remains necessary: current main still performs these consumer operations synchronously. No actionable introduced defect was found, and the recorded integrated proof supports the cutover. The statement-budget interpretation is already accepted; no further maintainer decision is needed. Priority: P2 Review scores
Verification
How this fits togetherPlugin state stores rescue approvals and OpenRouter model capabilities in OpenClaw's shared SQLite database. These records feed approved administrative actions and model resolution; the worker moves their database work off the Gateway thread. flowchart TD
A[Rescue commands] --> B[Current caller authority]
B --> E[Plugin state worker]
C[OpenRouter catalog] --> D[Captured physical store]
D --> E
E --> F[Shared SQLite database]
F --> G[Approved administrative actions]
F --> H[Loaded model capabilities]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +209, Tests +199, Docs +17. Total +425 across 15 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Use the existing worker for runtime storage operations while preserving shipped SDK adapters, route-scoped approvals, physical-store affinity, and graceful shutdown settlement. Do we have a high-confidence way to reproduce the issue? Not applicable to a refactor bug reproduction; current-main source confirms the synchronous consumer paths, and the recorded before/after measurements exercise those paths. Is this the best way to solve the issue? Yes. Reusing the existing worker and lifecycle owners is a focused cutover, with explicit preservation of released synchronous SDK contracts. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 5077ad4f99aa. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
Integrate main at fa420c6 without conflict resolutions. Preserve the approved plugin-state worker cutover and existing SDK contracts.
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Merged via squash.
|
…rocess (#166705) ## What Problem This Solves Fixes: OpenRouter models offer only `off, ultra` on a fresh process, so `openclaw agent --local` (and a Gateway's first turn) rejects valid levels such as `--thinking low` and silently turns a configured `thinkingDefault: max` into `off`. ## User Impact User impact: configured OpenRouter models get their real thinking levels on the first turn of every process. `openai/gpt-5` offers minimal–high (no off, since reasoning is mandatory), `anthropic/claude-sonnet-4.5` offers off/on, `deepseek/deepseek-r1` is always on, and a configured `max` on gpt-5 sends `high` instead of `minimal`. ## Why This Change Was Made The OpenRouter thinking policy and dynamic model row read model capabilities from process memory only. That is deliberate (#160651, #166528): those reads run on synchronous session paths and must not touch SQLite or the network. On a cold process nothing has loaded yet when the prepared model runtime completes configured OpenRouter refs, so the row says `reasoning: false` and the level is chosen from that. Capabilities only load later, in `prepareDynamicModel`, after the level is fixed. The static catalog build already runs asynchronously before that completion, and only for providers whose configured refs need it. Core now passes that selected scope (`providerIds`, an existing catalog-context field) into static catalog hooks, and OpenRouter's static hook awaits its capability loader when OpenRouter is selected: a worker read of the persisted catalog, or one fetch when nothing is persisted yet. Unscoped static runs (doctor validation, the catalog worker, the bundled static fallback) pass no scope and stay network-free. The synchronous reads are unchanged. The provider SDK catalog docs describe the scoped static run. ## Evidence Live, real OpenRouter key, fresh isolated state per run, `openclaw agent --local`, request bodies captured at the HTTP client: | Model / input | main (630e969) | this PR | | --- | --- | --- | | gpt-5 `--thinking low` | rejected: `Use one of: off, ultra` | `reasoning: {effort: "low"}` | | gpt-5 `--thinking low` after a successful turn (SQLite populated) | rejected: `off, ultra` | `effort: "low"` | | gpt-5 default | `effort: "minimal"` (off clamped) | `effort: "medium"` | | gpt-5 `thinkingDefault: max` | `effort: "minimal"` | `effort: "high"` | | gpt-5 `--thinking off` | accepted | rejected: `Use one of: minimal, low, medium, high, ultra` | | claude-sonnet-4.5 `--thinking low` | rejected: `off, ultra` | `reasoning: {enabled: true}` | | claude-sonnet-4.5 default | `enabled: false` | `enabled: true` | | claude-sonnet-4.5 `--thinking off` | `enabled: false` | `enabled: false` | | deepseek-r1 `--thinking low` | rejected: `off, ultra` | `enabled: true` | | deepseek-r1 `--thinking off` | accepted (`enabled: true` sent) | rejected: `Use one of: always on, ultra` | The claude-sonnet-4.5 default change (`enabled: false` → `enabled: true`) is the cold path now matching warm behavior on main. OpenRouter reports this model as `{mandatory: false}` with no default, and OpenClaw applies its existing default for reasoning-capable models. A main Gateway (f186273, isolated, claude-sonnet-4.5 configured, no `--thinking`) sends `enabled: false` on turn 1, then `enabled: true` on turns 2 and 3. Gateway (isolated state and port, gpt-5 configured): first turn with `--thinking low` was rejected with `off, ultra` on main and sends `effort: "low"` with this PR; later turns were already correct on main. Tests: new `extensions/openrouter/static-catalog.test.ts` fails on main (row stays `reasoning: false`) and passes here; it also checks that unscoped static runs make no request. Existing OpenRouter, capability-cache, provider-discovery and implicit-catalog suites pass. Test cost (`pnpm test <file> --maxWorkers=1`, local): `extensions/openrouter/static-catalog.test.ts` 23s wall (Vitest 15.9s, test body 19ms); `src/agents/models-config.providers.implicit.discovery-scope.test.ts` 24s wall (Vitest 17.5s, 20 tests). Both are mostly transform time. Hosted CI run 37671257993 on 1f582fe passed all 79 jobs in 10m52s; the run does not report time per file. No overlap with Pash/Sarah changes. **Merge danger:** two-way door. No stored data, config or schema changes; reverting restores the previous cold behavior. Blast radius: OpenRouter users (first turn may now wait for one catalog read or fetch before selection, which the turn already did later), plus any static catalog hook that starts reading the new optional `providerIds` (none besides OpenRouter today). Co-authored-by: Ayaan Zaidi <[email protected]>
…rocess (openclaw#166705) ## What Problem This Solves Fixes: OpenRouter models offer only `off, ultra` on a fresh process, so `openclaw agent --local` (and a Gateway's first turn) rejects valid levels such as `--thinking low` and silently turns a configured `thinkingDefault: max` into `off`. ## User Impact User impact: configured OpenRouter models get their real thinking levels on the first turn of every process. `openai/gpt-5` offers minimal–high (no off, since reasoning is mandatory), `anthropic/claude-sonnet-4.5` offers off/on, `deepseek/deepseek-r1` is always on, and a configured `max` on gpt-5 sends `high` instead of `minimal`. ## Why This Change Was Made The OpenRouter thinking policy and dynamic model row read model capabilities from process memory only. That is deliberate (openclaw#160651, openclaw#166528): those reads run on synchronous session paths and must not touch SQLite or the network. On a cold process nothing has loaded yet when the prepared model runtime completes configured OpenRouter refs, so the row says `reasoning: false` and the level is chosen from that. Capabilities only load later, in `prepareDynamicModel`, after the level is fixed. The static catalog build already runs asynchronously before that completion, and only for providers whose configured refs need it. Core now passes that selected scope (`providerIds`, an existing catalog-context field) into static catalog hooks, and OpenRouter's static hook awaits its capability loader when OpenRouter is selected: a worker read of the persisted catalog, or one fetch when nothing is persisted yet. Unscoped static runs (doctor validation, the catalog worker, the bundled static fallback) pass no scope and stay network-free. The synchronous reads are unchanged. The provider SDK catalog docs describe the scoped static run. ## Evidence Live, real OpenRouter key, fresh isolated state per run, `openclaw agent --local`, request bodies captured at the HTTP client: | Model / input | main (c018fa5) | this PR | | --- | --- | --- | | gpt-5 `--thinking low` | rejected: `Use one of: off, ultra` | `reasoning: {effort: "low"}` | | gpt-5 `--thinking low` after a successful turn (SQLite populated) | rejected: `off, ultra` | `effort: "low"` | | gpt-5 default | `effort: "minimal"` (off clamped) | `effort: "medium"` | | gpt-5 `thinkingDefault: max` | `effort: "minimal"` | `effort: "high"` | | gpt-5 `--thinking off` | accepted | rejected: `Use one of: minimal, low, medium, high, ultra` | | claude-sonnet-4.5 `--thinking low` | rejected: `off, ultra` | `reasoning: {enabled: true}` | | claude-sonnet-4.5 default | `enabled: false` | `enabled: true` | | claude-sonnet-4.5 `--thinking off` | `enabled: false` | `enabled: false` | | deepseek-r1 `--thinking low` | rejected: `off, ultra` | `enabled: true` | | deepseek-r1 `--thinking off` | accepted (`enabled: true` sent) | rejected: `Use one of: always on, ultra` | The claude-sonnet-4.5 default change (`enabled: false` → `enabled: true`) is the cold path now matching warm behavior on main. OpenRouter reports this model as `{mandatory: false}` with no default, and OpenClaw applies its existing default for reasoning-capable models. A main Gateway (ac78700, isolated, claude-sonnet-4.5 configured, no `--thinking`) sends `enabled: false` on turn 1, then `enabled: true` on turns 2 and 3. Gateway (isolated state and port, gpt-5 configured): first turn with `--thinking low` was rejected with `off, ultra` on main and sends `effort: "low"` with this PR; later turns were already correct on main. Tests: new `extensions/openrouter/static-catalog.test.ts` fails on main (row stays `reasoning: false`) and passes here; it also checks that unscoped static runs make no request. Existing OpenRouter, capability-cache, provider-discovery and implicit-catalog suites pass. Test cost (`pnpm test <file> --maxWorkers=1`, local): `extensions/openrouter/static-catalog.test.ts` 23s wall (Vitest 15.9s, test body 19ms); `src/agents/models-config.providers.implicit.discovery-scope.test.ts` 24s wall (Vitest 17.5s, 20 tests). Both are mostly transform time. Hosted CI run 37671257993 on 1f582fe passed all 79 jobs in 10m52s; the run does not report time per file. No overlap with Pash/Sarah changes. **Merge danger:** two-way door. No stored data, config or schema changes; reverting restores the previous cold behavior. Blast radius: OpenRouter users (first turn may now wait for one catalog read or fetch before selection, which the turn already did later), plus any static catalog hook that starts reading the new optional `providerIds` (none besides OpenRouter today). Co-authored-by: Ayaan Zaidi <[email protected]>
What Problem This Solves
Rescue-command approvals and bundled OpenRouter capability loading still execute plugin-state SQLite work on the Gateway thread.
Why This Change Was Made
Move those consumers to the existing plugin-state worker. A rescue replacement keeps predecessor revocation and registration in one FIFO request with two committed transactions, preserving revocation if replacement fails. Each transaction and commit checks current caller authority; approved effects recheck that authority after waits. OpenRouter captures its physical store before loading/fetching, replaces the catalog in one worker transaction, and joins accepted refreshes through the existing model-runtime close owner. Retained plugin-state handles reuse transaction-owned schema and ownership checks after BEGIN.
User Impact
The measured moved operations issue zero MAIN-thread SQL. Schemas, stored formats, TTLs, quotas, and update behavior are unchanged. There are no new dependencies or OPENCLAW_* names.
Released synchronous keyed stores and opaque callback mutations remain under the v2026.9.8 SDK contract. The released OpenRouter synchronous getter retains its cold persisted read; bundled resolution uses the loaded-memory getter and consumes completed missing-model retry markers there. Normal context-engine activation already joins worker cleanup; synchronous cleanup remains for the provider-catalog SDK and CLI onboarding. Shared SDK kernels therefore remain in the static inventory: T1 836 → 836 (runtime caller cutover; zero raw-site retirement).
Production LOC: +280 / −71 / net +209 across nine production files. Fifteen files total including tests, routing, and documentation.
Statement budget
Five unchanged shared-harness workloads per revision on the same host. Cells are median [min–max]; warmed values are per turn. No background SQL was removed.
The old Cron MAIN 62-statement sample reproduced twice on unmodified base with the identical SQL multiset: ordinary work 12 + the existing late placement-orphan sweep 27 + publication reconciliation 23. The original 39→62 MAIN delta was the late orphan sweep +27 offset by four fewer publication freshness statements. Its minute sweep waits for idle work and can land in different phase windows. First-turn candidate medians fit the observed base ranges; warmed medians decrease.
Statement gate accepted using observed base variance. The first-turn increases (MAIN +1; all-thread +44), second-session increases (MAIN +33; all-thread +157, or +2.003062%), and control-plane all-thread increase (+10, or +17.5439%) are within base run-to-run variance: candidate medians are inside the base ranges, and min–max ranges overlap. The maintainer explicitly approved this assessment. Warmed MAIN and all-thread medians decrease; Cron medians also decrease. Boot all-thread +15 (+0.3812%) is within the 2% budget. Raw totals are preserved without rounding them down to pass or filtering background work.
Control's selected median-sample delta is the pre-existing device-pair notifier +12, scheduled busy-timeout maintenance +2, and schema freshness −4. The same notifier cohort occurs on unmodified base, including a control phase totaling 69 statements. Its unchanged 10-second timer reads subscribers, seen requests, and device pairings.
Second-session's selected all-thread median-sample delta is MAIN +46 and worker +111 (the MAIN median has a different representative run). MAIN includes scheduled publication +27, OAuth +7, registry +4, placement retirement +5, and net foreground freshness +3. The latter includes six additional reads through the unchanged 250ms verbose-level cache, offset by three fewer other freshness reads. Worker differences come from existing shared-state/session readers, maintenance, and transcript work; plugin-state work decreases by four. Traces lack cross-thread request IDs, so this attribution does not claim exact per-RPC equivalence. No new query defect was identified in the changed owner paths.
Focused real-entry measurements (three repetitions per revision, medians):
OpenRouter cold-load after range: 26–30 total statements. Counted setup/admission and close do not increase. Whole focused workload: MAIN 2,554 → 2,138; all-thread 3,161 → 3,045. No failed SQL in focused workloads. The full shared workloads retain inherited audit-pruning BEGIN lock failures during shutdown (base 0–2 per run; candidate 1–3); all ten workloads and graceful closes completed successfully. No non-shutdown SQL failed.
Evidence
Post-integration landing gate (2026-10-07)
Main
fa420c6eb2752a78430cef1f2e3bf15cc17d8e9ewas merged without conflicts into candidate2db4c052b7d4308d02de6ad978054e33b6ad83c3. The coordinator approved the phase-move interpretation below and authorized landing through normal exact-head CI and ClawSweeper gates.Three fixed full workloads per revision on the same loaded macOS host, with identical workload/observer bytes and fresh source-mapped builds. Successful native statements include all background work and all threads. Medians and ranges are unfiltered; warmed values are per turn.
Statement budget — phase move
Coordinator approved on 2026-10-07. Memory sync/FTS admission moves between compaction and shutdown depending on timing. Their combined all-thread statement window decreases in every corresponding run:
Control's +4 is scheduled WAL maintenance +4, pending-input history admission +3, and existing upstream-link/freshness/ownership reads −3; all occur in baseline traces. The coordinator accepted these phase moves, replacing the NEEDS DISCUSSION disposition. First and warmed turns decrease, whole-workload medians decrease 46,282→44,716 (−3.38%), and shutdown-only native database-is-locked failures disappear in the candidate samples. Raw counts remain unchanged; normal CI and ClawSweeper gates are not waived.
Representative median-sample attribution:
The positive SQL/stack groups also occur in the baseline traces, and the 61 source files represented by the compaction stacks are unchanged between the pinned revisions. The coordinator accepted the timing-dependent phase placement using these existing owners and the combined-window evidence above; the traces do not claim exact per-RPC causal equivalence. No extra runs were added to obtain a passing result, and no background work was removed from the counts.
All six Gateway workloads and their graceful closes passed. Main retained shutdown-only failed native database operations (database locked) of [2, 0, 2] per run; candidate had [0, 0, 0]. The unchanged counting contract excludes failed operations from successful-statement totals and reports them separately. On the integrated tree, 105 focused tests across eight files passed in 1,026.14s, covering rescue approvals, OpenRouter, real Gateway close, runtime-process build graph, and both import closures. Post-integration
pnpm tsgo:core,pnpm tsgo:core:test,pnpm tsgo:extensions, andpnpm tsgo:extensions:testpassed; madge found zero cycles. Fresh Codex P2 autoreview was scoped-clean. Released signatures were checked against stablev2026.9.8and latest local tagv2026.10.1-beta.1; the new replacement helpers remain internal.Original-head CI run 37595107001 passed, including
openclaw/ci-gate. The non-required PR-context failure was a template-heading mismatch; the body headings have been corrected. ClawSweeper completed its exact-original-head review with no findings. The coordinator resolved the statement-budget discussion. Native review and normal hosted gates are being refreshed for the integration head before landing.pnpm test <files> --maxWorkers=1: 758.77s wall on a heavily loaded host. Coverage includes approvals, concurrent replacement/consumption, invalid replacement revocation, post-wait authority, foreign TTL expiry, catalog persistence/store affinity, worker ownership, and SDK consumers.test/scripts/runtime-process-build-graph.test.ts,src/auto-reply/reply/get-reply.imports.test.ts, andsrc/state/openclaw-state.worker.imports.test.ts(18.74s + 76.24s shard wall).check-changedlanes passed across the local run and its exact-plan continuation. Core lint passed in 538.05s. Local extension declaration preparation timed out; after Testbox stayed queued for 15 minutes, the authorized AWS fallback completed all ten remaining lanes in 484.02s of gate time (542.04s remote command): extension lint 289.90s, script lint 37.69s, database-first guard 86.59s, import cycles 17.75s, and remaining guards green. Final source hashes were verified on the runner. Testbox and AWS leases are released, and owned runner processes have exited.Initial rescue verification exposed the single-transaction admission helper refusing the second transaction. The corrected domain operation requires exactly transaction/commit/transaction/commit, with current authority checked at all four grants. Statement measurement then identified and removed a duplicate pre-transaction ownership read while retaining the authoritative read after BEGIN.
Overlap
Focused overlap with #160918 in OpenRouter model resolution and #166094 in plugin-state/rescue cleanup. The umbrella draft #162433 is not used as an implementation base. Other wave-6 and turn-budget lanes retain their owners; no session-turn cache or service is introduced. Whoever lands second must merge current main and adapt overlapping hunks.