Skip to content

fix(models): model pickers wait for or lose models while the catalog rebuilds - #173585

Merged
obviyus merged 7 commits into
mainfrom
fix/models-list-keeps-previous
Oct 16, 2026
Merged

obviyus merged 7 commits into
mainfrom
fix/models-list-keeps-previous

Conversation

@obviyus

@obviyus obviyus commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: model pickers wait for, fail on, or briefly lose models while the Gateway rebuilds its model catalog after a settings change, sign-in, sign-out, key removal or plugin reload.

User Impact

models.list now answers from the last published list while the catalog owner rebuilds, instead of waiting for the replacement owner or failing with "Chat metadata access changed while preparing its metadata". A provider whose config, credentials, configured models or owning plugin changed is removed from that list at once and returns when the new catalog has it. Additions may appear late; removals are never shown.

Remaining limit (not fixed here): during a reload, synchronous plugin metadata rescans still block the Gateway main thread for 0.3–2 s, so any RPC (including a trivial last-heartbeat) is slow in that window. Tracked as a separate follow-up.

Why This Change Was Made

Two waits sat on the read path:

Both waits avoid errors; neither protects data the previous list cannot serve. Hot reloads also retire the previous owners immediately, so reads raced into retired owners and failed.

Changes:

  1. Read side (chat-metadata-runtime.ts, chat-metadata-model-list.ts): keep the last result per request shape. While a refresh, replacement, auth change or retired owner is pending, serve it minus providers whose identity changed (provider config slice, auth.profiles/order, runtime auth-store profiles, every configured model ref the visibility owner admits (primary, fallbacks, model maps, utility, image and PDF models), owning plugin entries). Any edit to the config env section hides every provider until the new catalog publishes, because it can hold any provider's key. A change to agents.*.modelPolicy does the same, since a policy can name any provider's models. A requester who now has personal-account links is never served the retained shared list; the read takes the existing personal-projection path. Superseded/unavailable read errors fall back to the same retained list; other errors still surface.
  2. Catalog owner (prepared-model-runtime.catalog-source.ts): a rebuild keeps a provider's discovered rows when only the installed-plugin fingerprint changed and the provider's own source and credentials are unchanged. Those rows are marked provisional and reacquired by the post-commit changed-provider refresh. The owning plugin's package version and install-record hash join the provider source, so an upgraded provider plugin does not carry its old rows. Native harness rows keep the existing rule (dropped when any agent/plugin setting changes), because a harness may list models from any of those settings.

State table used for the change:

Event During rebuild After commit
Model-neutral setting previous list same
Provider P config/credentials changed, deleted, or signed out previous − P P returns when rediscovered
Plugin config change (no provider change) previous list provisional rows until rediscovered
Sign-in to new provider Q previous list Q added when known
Remote catalog swap previous list (not adopted yet) atomic switch (#158000, #167178)

Evidence

Regression test server-chat-metadata-lifecycle.rebuild.test.ts: holds the replacement owner's catalog build forever (a provider that never answers), then reads models.list with a 1 s budget. On main it fails with models.list waited for the rebuild; with this change it passes, and it checks that signing out, removing the configured model and editing the config env section each hide openai/gpt-5.4 before the replacement publishes (the env, model-policy and primary-model steps each fail without their identity field). chat-metadata-runtime.personal-accounts.test.ts adds a case where a requester connects a personal account while the owner is retired; the read declines the retained shared list (fails without the link check). Two existing tests now assert the new contract: a retired owner without a published replacement serves its last list instead of rejecting (models.prepared.test.ts), and the readiness test holds the replacement's own list preparation after the refresh (chat-metadata-model-list-readiness.test.ts).

UI guard chat-loading-deadlines.e2e.test.ts: an existing chat sends a message while models.list never answers (passes on main and here; no UI change needed).

Isolated Gateway bench (real entry point, built dist, n = 12 per event): fake vLLM (healthy), Ollama that never answers, Codex app-server whose model/list never answers. Back-to-back models.list {view: "configured"} reads tagged during the triggering RPC. Times in ms.

Event (during) main p50 / p99 / max failed this PR p50 / p99 / max failed
settings change (model) 1.5 / 323 / 344 0 1.5 / 235 / 322 0
plugin settings change 1.6 / 366 / 1547 12 1.3 / 266 / 752 0
sign-in 2.2 / 613 / 763 1 2.4 / 624 / 1196 0
sign-out 1.6 / 781 / 907 12 1.9 / 378 / 537 0
provider deleted 2.3 / 1169 / 1799 0 2.4 / 825 / 2297 0
plugin reload 1.5 / 490 / 1080 12 2.0 / 470 / 818 0
catalog swap 1.7 / 84 / 654 0 1.7 / 94 / 463 0
restart (first reads) 1.5 / 131 / 335 0 1.6 / 105 / 281 0

No read after a sign-out or provider deletion returned that provider (0 violations in both runs).

Why p99 is still above 300 ms: a lag probe (last-heartbeat issued with each read) is as slow as models.list in every slow sample (for example 1453 vs 1445 ms), so the read path no longer waits. A Gateway --cpu-prof during sign-in / provider deletion / plugin reload attributes the busy main-thread segments to loadPluginMetadataSnapshot → installed plugin index rebuild with synchronous lstat/read/realpath (~26%), module compile/link of reloaded plugin code (~24%) and managed reload publishRuntime (~15%). Top callers: resolveManifestPluginsForModelIdNormalization and resolveConfigWidePluginMetadataSnapshot. That is the follow-up.

Local checks: tsgo:core, oxfmt and type-aware oxlint on changed files, focused tests (rebuild, lifecycle integration, catalog renewal, chat-metadata runtime and refresh, scoped refresh, catalog owner, native demand: 119 passed), UI E2E case above. prepared-model-runtime.catalog-retention.test.ts fails locally before any product code with gc is not defined (the local runner does not expose gc); left to CI.

Limits: other Pueue jobs shared the host during both bench runs. The remote catalog is adopted only at startup or every 6 h, so each catalog-swap rep restarts the Gateway with a new catalog URL.

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added app: web-ui App: web-ui gateway Gateway runtime scripts Repository scripts agents Agent runtime and tooling size: M labels Oct 16, 2026
@obviyus
obviyus force-pushed the fix/models-list-keeps-previous branch from 442a412 to 62029c9 Compare October 16, 2026 00:24
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Keeps unchanged published models visible during catalog rebuilds while promptly hiding providers whose relevant settings or credentials changed.

Example: A picker has listed openai/gpt-5.4 when replacement catalog discovery stops answering.

  • Before: Subsequent model-list reads can wait for discovery or fail after the previous owner retires.
  • After: Reads retain openai/gpt-5.4 until OpenAI credentials or relevant settings change, then hide it until republication.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful repair with real Gateway evidence, focused lifecycle coverage, and all previously identified defects addressed.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied built-Gateway benchmark exercises models.list during account, settings, and plugin reload events against held discovery services, records eliminated read failures and no removed-provider responses, and is supported by lifecycle regressions for policy, configured-model references, credentials, and personal-account eligibility.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Model pickers wait, fail, or temporarily lose unchanged models when catalog owners rebuild.
Reason: The maintainer-authored direction repairs observed availability failures while explicitly separating the remaining synchronous reload latency.

Merge readiness

✅ Ready for maintainer review

This PR addresses a current catalog-rebuild failure, resolves the prior findings, and has no remaining actionable review findings.

Priority: P2
Reviewed head: 9e2e839f39790b8d400cab2500dbd13164607f09

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway metadata lifecycle projects published catalog, configuration, and authentication facts into model-list responses consumed by pickers.

flowchart TD
  A[Configuration and auth changes] --> B[Catalog lifecycle owner]
  B --> C[Published catalog]
  C --> D[Metadata model-list projection]
  A --> E[Retained provider eligibility]
  D --> E
  E --> F[Models list RPC]
  F --> G[Model pickers]
Loading

Technical review

Best possible solution:

Retain eligible published responses within the existing metadata lifecycle while the catalog owner rebuilds and reacquires provisional providers.

Do we have a high-confidence way to reproduce the issue?

Current-main source exposes the replacement wait and retired-owner rejection, supported by the supplied held-discovery regression and Gateway comparison; no target code was executed during this review.

Is this the best way to solve the issue?

The change uses the existing metadata and catalog owners, bounds retained request variants, reuses configured-model visibility dependencies, and preserves credential and final-response authority checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against fe92b8e0bd20.

Provenance checked

  • Metadata replacement readiness changes intended behavior with a stated reason (c86d303: Waiting for publication prevented metadata construction from partial replacement-owner facts and preserved healthy-agent availability.)
  • Prepared model-list projections keeps the original intent (df57994: Prepared projections reduce repeated reconnect work while retaining account selection and authorization checks.)
  • Provider inventory retention changes intended behavior with a stated reason (ec7c8bb: Retention preserves catalog/auth identity across owner generations while fencing unverifiable native account inventory.)
  • Changed-provider reacquisition keeps the original intent (a14a5d1: Discovery-only providers must be reacquired after reload when their rows cannot be safely retained.)
  • Independent metadata readiness keeps the original intent (a80c975: Commands-only metadata must not wait for another agent's optional model-list preparation.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced change and prior-finding repair: The pinned introduction diff adds retained responses; the latest commit replaces incomplete configured-model identity checks with the visibility owner's existing primary, fallback, model-map, utility, image, and PDF references. (src/gateway/server-methods/chat-metadata-model-list.ts:66, 9e2e839f3979)
  • Current-main failure path: Current main awaits pending metadata refresh before reading models, while refresh awaits model-owner replacement; retired projections are rejected rather than served. (src/gateway/server-methods/chat-metadata-runtime.ts:351, fe92b8e0bd20)
  • Personal-account finding resolved: Retained shared responses are declined when the requester has personal-account links, with a regression covering connection of an account after the shared owner retires. (src/gateway/server-methods/chat-metadata-runtime.ts:396, 9e2e839f3979)
  • Provider retention and reacquisition: Retention still compares provider source and credentials, adds owning-plugin package identity, preserves native-row restrictions, and schedules provisional providers through the existing changed-provider acquisition path. (src/agents/prepared-model-runtime.catalog-source.ts:113, 9e2e839f3979)
  • Final publication authority remains enforced: The models.list handler rechecks current caller/session authority immediately before response publication and applies current operator presentation policy; retained catalog rows do not authorize model selection or execution. (src/gateway/server-methods/models.ts:159, 9e2e839f3979)
  • Supplied real Gateway evidence: The PR body reports built-Gateway reads during settings, account, provider, and plugin changes with nonresponding discovery services; plugin-change, sign-out, and reload read failures fall from 12 to zero, with zero removed-provider violations. (9e2e839f3979)

PR surface

Source +212, Tests +197, Other +1. Total +410 across 11 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 5 233 21 +212
Tests 5 200 3 +197
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 11 434 24 +410

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Repairs model-picker waits and transient read failures during account, configuration, and plugin changes without changing inference or persisted state.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/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.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-16T01:03:33.837Z sha 8a0f6c2 :: needs changes before merge. :: [P2] Invalidate retained selections when modelPolicy.allow changes | [P2] Recheck personal-account eligibility before returning a retained list
  • reviewed 2026-10-16T01:55:44.687Z sha e23b447 :: needs changes before merge. :: [P2] Invalidate retained rows when primary or fallback settings change

Reviewed October 15, 2026, 10:31 PM ET / October 16, 2026, 02:31 UTC (Revision 3).

@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 16, 2026
@obviyus
obviyus merged commit 204ff97 into main Oct 16, 2026
155 of 156 checks passed
@obviyus
obviyus deleted the fix/models-list-keeps-previous branch October 16, 2026 02:33
@obviyus

obviyus commented Oct 16, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in 204ff97.

  • Bug: models.list waited for, failed on, or briefly lost models while the Gateway rebuilt its catalog after a settings change, sign-in, sign-out, key removal or plugin reload.
  • Fix: reads during a rebuild serve the last published list, minus any provider whose config, credentials, configured models, model policy, env or plugin changed. Requesters with personal accounts keep their own projection. The catalog owner keeps unchanged providers' rows across plugin-fingerprint changes until they are rediscovered.
  • Proof: a regression test with a provider that never answers (fails on main), removal cases for each identity input, and an isolated-Gateway bench (n = 12 per event): failed reads went from up to 12 per event to 0, with no removed provider ever shown. The remaining reload latency is main-thread plugin metadata rescans, tracked separately.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 16, 2026
…rebuilds (openclaw#173585)

## What Problem This Solves

Fixes: model pickers wait for, fail on, or briefly lose models while the Gateway rebuilds its model catalog after a settings change, sign-in, sign-out, key removal or plugin reload.

## User Impact

`models.list` now answers from the last published list while the catalog owner rebuilds, instead of waiting for the replacement owner or failing with "Chat metadata access changed while preparing its metadata". A provider whose config, credentials, configured models or owning plugin changed is removed from that list at once and returns when the new catalog has it. Additions may appear late; removals are never shown.

Remaining limit (not fixed here): during a reload, synchronous plugin metadata rescans still block the Gateway main thread for 0.3–2 s, so any RPC (including a trivial `last-heartbeat`) is slow in that window. Tracked as a separate follow-up.

## Why This Change Was Made

Two waits sat on the read path:

- `chat-metadata-runtime.ts` `readCurrent` awaited the pending refresh, which awaits the model-runtime replacement gate. Added in openclaw#170805 to stop failures for healthy agents: "The existing model-runtime publication barrier owns replacement readiness; metadata follows it rather than constructing partial facts ahead of its commit." That PR states latency was not benchmarked.
- `server-model-catalog.ts` `readPreparedGatewayModelCatalogOwnerSnapshot` awaits the same gate (openclaw#160274: "model/auth replacements use the existing publication barrier, which catalog reads await before reacquiring the current owner").

Both waits avoid errors; neither protects data the previous list cannot serve. Hot reloads also retire the previous owners immediately, so reads raced into retired owners and failed.

Changes:

1. **Read side** (`chat-metadata-runtime.ts`, `chat-metadata-model-list.ts`): keep the last result per request shape. While a refresh, replacement, auth change or retired owner is pending, serve it minus providers whose identity changed (provider config slice, `auth.profiles`/order, runtime auth-store profiles, every configured model ref the visibility owner admits (primary, fallbacks, model maps, utility, image and PDF models), owning plugin entries). Any edit to the config `env` section hides every provider until the new catalog publishes, because it can hold any provider's key. A change to `agents.*.modelPolicy` does the same, since a policy can name any provider's models. A requester who now has personal-account links is never served the retained shared list; the read takes the existing personal-projection path. Superseded/unavailable read errors fall back to the same retained list; other errors still surface.
2. **Catalog owner** (`prepared-model-runtime.catalog-source.ts`): a rebuild keeps a provider's discovered rows when only the installed-plugin fingerprint changed and the provider's own source and credentials are unchanged. Those rows are marked provisional and reacquired by the post-commit changed-provider refresh. The owning plugin's package version and install-record hash join the provider source, so an upgraded provider plugin does not carry its old rows. Native harness rows keep the existing rule (dropped when any agent/plugin setting changes), because a harness may list models from any of those settings.

State table used for the change:

| Event | During rebuild | After commit |
|---|---|---|
| Model-neutral setting | previous list | same |
| Provider P config/credentials changed, deleted, or signed out | previous − P | P returns when rediscovered |
| Plugin config change (no provider change) | previous list | provisional rows until rediscovered |
| Sign-in to new provider Q | previous list | Q added when known |
| Remote catalog swap | previous list (not adopted yet) | atomic switch (openclaw#158000, openclaw#167178) |

## Evidence

Regression test `server-chat-metadata-lifecycle.rebuild.test.ts`: holds the replacement owner's catalog build forever (a provider that never answers), then reads `models.list` with a 1 s budget. On main it fails with `models.list waited for the rebuild`; with this change it passes, and it checks that signing out, removing the configured model and editing the config `env` section each hide `openai/gpt-5.4` before the replacement publishes (the `env`, model-policy and primary-model steps each fail without their identity field). `chat-metadata-runtime.personal-accounts.test.ts` adds a case where a requester connects a personal account while the owner is retired; the read declines the retained shared list (fails without the link check). Two existing tests now assert the new contract: a retired owner without a published replacement serves its last list instead of rejecting (`models.prepared.test.ts`), and the readiness test holds the replacement's own list preparation after the refresh (`chat-metadata-model-list-readiness.test.ts`).

UI guard `chat-loading-deadlines.e2e.test.ts`: an existing chat sends a message while `models.list` never answers (passes on main and here; no UI change needed).

Isolated Gateway bench (real entry point, built `dist`, n = 12 per event): fake vLLM (healthy), Ollama that never answers, Codex app-server whose `model/list` never answers. Back-to-back `models.list {view: "configured"}` reads tagged *during* the triggering RPC. Times in ms.

| Event (during) | main p50 / p99 / max | failed | this PR p50 / p99 / max | failed |
|---|---|---|---|---|
| settings change (model) | 1.5 / 323 / 344 | 0 | 1.5 / 235 / 322 | 0 |
| plugin settings change | 1.6 / 366 / 1547 | 12 | 1.3 / 266 / 752 | 0 |
| sign-in | 2.2 / 613 / 763 | 1 | 2.4 / 624 / 1196 | 0 |
| sign-out | 1.6 / 781 / 907 | 12 | 1.9 / 378 / 537 | 0 |
| provider deleted | 2.3 / 1169 / 1799 | 0 | 2.4 / 825 / 2297 | 0 |
| plugin reload | 1.5 / 490 / 1080 | 12 | 2.0 / 470 / 818 | 0 |
| catalog swap | 1.7 / 84 / 654 | 0 | 1.7 / 94 / 463 | 0 |
| restart (first reads) | 1.5 / 131 / 335 | 0 | 1.6 / 105 / 281 | 0 |

No read after a sign-out or provider deletion returned that provider (0 violations in both runs).

Why p99 is still above 300 ms: a lag probe (`last-heartbeat` issued with each read) is as slow as `models.list` in every slow sample (for example 1453 vs 1445 ms), so the read path no longer waits. A Gateway `--cpu-prof` during sign-in / provider deletion / plugin reload attributes the busy main-thread segments to `loadPluginMetadataSnapshot` → installed plugin index rebuild with synchronous `lstat`/`read`/`realpath` (~26%), module compile/link of reloaded plugin code (~24%) and managed reload `publishRuntime` (~15%). Top callers: `resolveManifestPluginsForModelIdNormalization` and `resolveConfigWidePluginMetadataSnapshot`. That is the follow-up.

Local checks: `tsgo:core`, oxfmt and type-aware oxlint on changed files, focused tests (rebuild, lifecycle integration, catalog renewal, chat-metadata runtime and refresh, scoped refresh, catalog owner, native demand: 119 passed), UI E2E case above. `prepared-model-runtime.catalog-retention.test.ts` fails locally before any product code with `gc is not defined` (the local runner does not expose `gc`); left to CI.

Limits: other Pueue jobs shared the host during both bench runs. The remote catalog is adopted only at startup or every 6 h, so each catalog-swap rep restarts the Gateway with a new catalog URL.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 17, 2026
…ttings changes (#173626)

Related: #173585, #169562

## What Problem This Solves

Fixes: the Gateway main thread blocks for hundreds of milliseconds after a sign-in, sign-out, key removal or plugin settings change, because runtime readers reload plugin metadata from disk although no plugin was installed.

## User Impact

User impact: less main-thread blocking after account and plugin settings changes, so model pickers and other Gateway requests stall less. No config, state or plugin contract changes.

## Why This Change Was Made

Config hot reload holds the plugin lifecycle lease (since #145484). The lease runs in a fresh operation plugin cache, so management sees what other processes committed while it waited. That isolation stays. But two kinds of work inside it reloaded plugin metadata on every event:

1. **A policy change rescanned the whole inventory.** Plugin activation (`enabled`) is the only config-owned fact in the installed plugin index. A changed policy hash (for example auto-enable after a sign-in) made the registry reader treat the persisted index as stale and run full discovery. Activation is now one projection over inventory records (`projectInstalledPluginIndexPolicy`), used by fresh builds and by the registry reader. When the persisted inventory passes its existing freshness checks and only the policy differs, the reader projects the new policy in memory. Install, uninstall, stale files, load paths and the other existing reasons still rediscover. Freshness checks tolerate missing files only for disabled records, so records the new policy enables are rechecked; if any is stale, the reader rediscovers. This matches the documented rule that enablement is evaluated from the current operation's policy, not stored with the facts.
2. **Post-commit Gateway readers could not see the published inventory.** The model-policy comparison (chat metadata lifecycle) and the prepared model runtime refresh inherit the lease's operation cache, so model-id normalization in `resolveDefaultModelForAgent` loaded a metadata snapshot from disk. As in #169562, the Gateway lifecycle owner now passes the snapshot it published. The chat metadata lifecycle hands `getPluginMetadataSnapshot()` to `modelSelectionPoliciesMatch`. The prepared runtime refresh forwards its existing `pluginMetadataSnapshot` option to the configured owner inputs. Readers without an explicit snapshot keep their current behavior.

## Evidence

- Regression tests, each fails on `main` and passes here:
  - `plugin-registry.test.ts`, "projects a config policy change over the persisted inventory without rescanning": on `main` the extensions dir is rescanned.
  - `plugin-registry.test.ts`, "rediscovers when a policy enables a persisted plugin whose files are gone": a projection-only reader would return an enabled plugin with no files.
  - `operator-model-presentation.test.ts`, two tests run inside an operation cache like the reload lease: the policy comparison and prepared runtime input collection load no plugin metadata. On `main` they load 2 and 1 snapshots.
- Focused suites pass: plugin registry, index and cache; capability generation; model selection; operator model policy; chat metadata lifecycle; prepared model runtime; agent database startup. Two kinds of local failure, neither CI-relevant:
  - 4 tests in `plugin-registry` and `installed-plugin-index` fail on macOS on both `main` and this branch (temp-dir environment).
  - One agent-database-startup test timed out at host load ~60 and passes alone.
- Isolated Gateway on a packaged layout (built dist, no `.git`, `src` or `extensions`), compared with the `main` it merges. CPU profile over 20 events (4 each of sign-in, sign-out, key removal, plugin reload and plugin settings change), two interleaved rounds:

| Main-thread CPU | main (round 1 / 2) | this PR (round 1 / 2) |
|---|---|---|
| model-id normalization metadata loads | 22555 / 20521 ms | 2 / 0 ms |
| plugin inventory rediscovery | 16873 / 16489 ms | 3638 / 1518 ms |
| all plugin metadata snapshot loads | 31650 / 29862 ms | 10194 / 8281 ms |
| busy segments ≥ 150 ms | 57 / 67 | 31 / 14 |

  What remains is `resolveConfigWidePluginMetadataSnapshot`: the explicit plugin reload, which is the owner's refresh path, plus startup config preflight.

- `last-heartbeat` lag probe during the event, n = 12 events each, runs interleaved base/PR. Host load was 30–101, so absolute values are inflated:

| Event (during) | main p50 / p99 | this PR p50 / p99 |
|---|---|---|
| sign-in | 1.8 / 698 ms | 2.6 / 329 ms |
| sign-out | 3.2 / 790 ms | 4.2 / 489 ms |
| key removal | 4.1 / 1009 ms | 2.0 / 359 ms |
| plugin reload | 1.4 / 710 ms | 1.0 / 489 ms |
| plugin settings change | 0.8 / 157 ms | 0.8 / 138 ms |

  No run showed a removed provider after its removal (0 violations).

Not covered: plugin reload still blocks, from the reload's own metadata refresh, plugin module re-import and runtime publication. That needs a separate change.

## Notes

A source checkout (`pnpm-workspace.yaml`, `src` and `extensions` at the package root) cannot measure this. There, `isBundledPluginInsideDevSourceRoot` and the private QA plugins make `requiresDerivedRegistryValidation` reject the persisted index on every read, so local dev Gateways still rescan. Packaged installs do not.

## Merge danger

Two-way door: a revert restores the reloads. Nothing is persisted or migrated, and lease isolation is unchanged. Blast radius if wrong:
- Plugin activation as seen by Gateway runtime reads after a config change. The projection uses the same rule and inputs as a fresh index build.
- Model-id normalization in the post-commit policy comparison and prepared runtime refresh. These use the inventory the Gateway published, which is what other runtime readers already use.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…ttings changes (openclaw#173626)

Related: openclaw#173585, openclaw#169562

## What Problem This Solves

Fixes: the Gateway main thread blocks for hundreds of milliseconds after a sign-in, sign-out, key removal or plugin settings change, because runtime readers reload plugin metadata from disk although no plugin was installed.

## User Impact

User impact: less main-thread blocking after account and plugin settings changes, so model pickers and other Gateway requests stall less. No config, state or plugin contract changes.

## Why This Change Was Made

Config hot reload holds the plugin lifecycle lease (since openclaw#145484). The lease runs in a fresh operation plugin cache, so management sees what other processes committed while it waited. That isolation stays. But two kinds of work inside it reloaded plugin metadata on every event:

1. **A policy change rescanned the whole inventory.** Plugin activation (`enabled`) is the only config-owned fact in the installed plugin index. A changed policy hash (for example auto-enable after a sign-in) made the registry reader treat the persisted index as stale and run full discovery. Activation is now one projection over inventory records (`projectInstalledPluginIndexPolicy`), used by fresh builds and by the registry reader. When the persisted inventory passes its existing freshness checks and only the policy differs, the reader projects the new policy in memory. Install, uninstall, stale files, load paths and the other existing reasons still rediscover. Freshness checks tolerate missing files only for disabled records, so records the new policy enables are rechecked; if any is stale, the reader rediscovers. This matches the documented rule that enablement is evaluated from the current operation's policy, not stored with the facts.
2. **Post-commit Gateway readers could not see the published inventory.** The model-policy comparison (chat metadata lifecycle) and the prepared model runtime refresh inherit the lease's operation cache, so model-id normalization in `resolveDefaultModelForAgent` loaded a metadata snapshot from disk. As in openclaw#169562, the Gateway lifecycle owner now passes the snapshot it published. The chat metadata lifecycle hands `getPluginMetadataSnapshot()` to `modelSelectionPoliciesMatch`. The prepared runtime refresh forwards its existing `pluginMetadataSnapshot` option to the configured owner inputs. Readers without an explicit snapshot keep their current behavior.

## Evidence

- Regression tests, each fails on `main` and passes here:
  - `plugin-registry.test.ts`, "projects a config policy change over the persisted inventory without rescanning": on `main` the extensions dir is rescanned.
  - `plugin-registry.test.ts`, "rediscovers when a policy enables a persisted plugin whose files are gone": a projection-only reader would return an enabled plugin with no files.
  - `operator-model-presentation.test.ts`, two tests run inside an operation cache like the reload lease: the policy comparison and prepared runtime input collection load no plugin metadata. On `main` they load 2 and 1 snapshots.
- Focused suites pass: plugin registry, index and cache; capability generation; model selection; operator model policy; chat metadata lifecycle; prepared model runtime; agent database startup. Two kinds of local failure, neither CI-relevant:
  - 4 tests in `plugin-registry` and `installed-plugin-index` fail on macOS on both `main` and this branch (temp-dir environment).
  - One agent-database-startup test timed out at host load ~60 and passes alone.
- Isolated Gateway on a packaged layout (built dist, no `.git`, `src` or `extensions`), compared with the `main` it merges. CPU profile over 20 events (4 each of sign-in, sign-out, key removal, plugin reload and plugin settings change), two interleaved rounds:

| Main-thread CPU | main (round 1 / 2) | this PR (round 1 / 2) |
|---|---|---|
| model-id normalization metadata loads | 22555 / 20521 ms | 2 / 0 ms |
| plugin inventory rediscovery | 16873 / 16489 ms | 3638 / 1518 ms |
| all plugin metadata snapshot loads | 31650 / 29862 ms | 10194 / 8281 ms |
| busy segments ≥ 150 ms | 57 / 67 | 31 / 14 |

  What remains is `resolveConfigWidePluginMetadataSnapshot`: the explicit plugin reload, which is the owner's refresh path, plus startup config preflight.

- `last-heartbeat` lag probe during the event, n = 12 events each, runs interleaved base/PR. Host load was 30–101, so absolute values are inflated:

| Event (during) | main p50 / p99 | this PR p50 / p99 |
|---|---|---|
| sign-in | 1.8 / 698 ms | 2.6 / 329 ms |
| sign-out | 3.2 / 790 ms | 4.2 / 489 ms |
| key removal | 4.1 / 1009 ms | 2.0 / 359 ms |
| plugin reload | 1.4 / 710 ms | 1.0 / 489 ms |
| plugin settings change | 0.8 / 157 ms | 0.8 / 138 ms |

  No run showed a removed provider after its removal (0 violations).

Not covered: plugin reload still blocks, from the reload's own metadata refresh, plugin module re-import and runtime publication. That needs a separate change.

## Notes

A source checkout (`pnpm-workspace.yaml`, `src` and `extensions` at the package root) cannot measure this. There, `isBundledPluginInsideDevSourceRoot` and the private QA plugins make `requiresDerivedRegistryValidation` reject the persisted index on every read, so local dev Gateways still rescan. Packaged installs do not.

## Merge danger

Two-way door: a revert restores the reloads. Nothing is persisted or migrated, and lease isolation is unchanged. Blast radius if wrong:
- Plugin activation as seen by Gateway runtime reads after a config change. The projection uses the same rule and inputs as a fresh index build.
- Model-id normalization in the post-commit policy comparison and prepared runtime refresh. These use the inventory the Gateway published, which is what other runtime readers already use.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant