Skip to content

fix(models): adopting a downloaded catalog briefly hides discovered models - #167178

Merged
obviyus merged 2 commits into
mainfrom
fix/adoption-row-loss
Oct 8, 2026
Merged

obviyus merged 2 commits into
mainfrom
fix/adoption-row-loss

Conversation

@obviyus

@obviyus obviyus commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: the model picker and models.list drop every discovered model (for example all OpenRouter rows) while a running Gateway adopts a newly downloaded hosted catalog. If that provider's discovery then fails, the provider stays reduced to its built-in rows until someone runs an explicit refresh.

A production Gateway showed this during a fleet catalog refresh: the list fell from 599 to 54 models for about 2.5 to 4 minutes.

User Impact

While a Gateway adopts a new catalog, pickers and models.list keep showing the current models and prices. The new catalog's models and prices appear together, once its discovery has finished. Adoption itself now takes as long as that discovery (seconds in practice). The previous catalog keeps serving during that time.

Why This Change Was Made

Adoption (#158000) built each replacement owner with static rows only and published it. It then started that owner's discovery fire-and-forget. Readers therefore saw only configured and catalog rows until discovery finished. A failed discovery left them that way, because failed providers carry no renewal deadline.

Adoption now waits for each candidate's own discovery, inside the candidate's catalog scope, before the single commit. The wait can be cancelled through the adoption's existing abort signal. The post-commit fire-and-forget is removed. loadFullModelCatalog gets a wait option, so adoption awaits the acquisition instead of the 5 s foreground race that ordinary readers use. Rows and prices still switch in one commit, and admitted runs keep their captured pair (#140086).

Maintainer decision (Ayaan, delegated): adoption waits for candidate discovery. The previous catalog's rows and prices keep serving coherently in the meantime, which is strictly safer than publishing a partial list.

Maintainer decision (Ayaan, delegated): if a provider's discovery fails during adoption, that provider publishes with the new catalog's built-in rows. Rows are never carried across catalog versions (#140086). On main this is also the end state, but only after a window in which every discovered row was gone.

Evidence

Regression test keeps discovered rows published until the adopted catalog's discovery completes holds the candidate's discovery and drives the real models.list handler. While discovery is held, readers still see the old catalog's discovered row and the old pricing generation. After release, they see only the new catalog's row and generation. It fails on main (expected [ 'remote-200' ] to include 'discovered-200') and passes with this change. The existing "bounds refresh with two agents…" test now asserts that adoption publishes only after the held discovery completes. All 10 tests in prepared-model-runtime.remote-publication.test.ts pass, and pnpm check:changed is green.

Live, on an isolated Gateway (loopback, separate state):

  • A local catalog mirror serves a fresh bundle per step. Each version renames kimi/k3 to Kimi K3 vN and sets the input price of openai/gpt-5.4-mini to N $/M.
  • OpenRouter's DNS resolution is delayed through a Node preload.
  • models.list is polled every 50 ms.
  • Adoption is triggered with openclaw models refresh followed by a models.list refresh.
Adoption main (adoption code unchanged on current main) This PR
Warm (no delay) 514 → 1 row (configured only) for 0.74–0.79 s, then 514 with the new marker 514 rows throughout; marker switches 3.3 s after the trigger
Candidate discovery delayed 3–4 s (its own DNS lookup) 514 → 1 row for 5.36 s 514 rows throughout; marker switches 4.98 s and 5.42 s after the trigger, right after the candidate's lookup completes
Candidate discovery fails (60 s DNS, 5 s fetch timeout) 514 → 1 row for 5.38 s, then 51 (OpenRouter 466 → 3 built-in rows) 514 rows with the old marker for 7.2 s, then 51 with the new marker (decision above)

On the final diff (rebuilt), the result was the same: a warm adoption with 994 rows throughout switched 2.1 s after the trigger. A 3 s delayed candidate discovery kept 994 rows throughout and switched 5.4 s after the trigger.

Prices follow the same commit. Usage for real openai/gpt-5.4-mini turns was computed at the bundled $0.75/M input before the marked catalogs. After adopting v28, v29 and v32, it was computed at exactly $28/$56, $29/$58 and $32/$64 per M (input/output). Real cheap turns (openclaw agent … --model openai/gpt-5.4-mini) completed with reply ok after each adoption. One turn on the final build hit a retryable agent-database admission error from the session-state layer, about 30 s after adoption. It is unrelated to the catalog, and the immediate retry succeeded.

Local review: codex review --base origin/main (model gpt-6-astra), round 1: "No actionable defects were found."

Merge danger: a two-way door. No stored state, schema, config or protocol changes, so a revert fully restores the previous behavior. Blast radius: every Gateway that adopts a downloaded hosted catalog. If this is wrong, adoption could stall behind a hung provider discovery. That wait is still bounded by each provider's own discovery timeouts and is cancelled by supersession, config reload or shutdown. Meanwhile the previous catalog keeps serving.

@clawsweeper

clawsweeper Bot commented Oct 8, 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 docs Improvements or additions to documentation agents Agent runtime and tooling size: S labels Oct 8, 2026
@obviyus
obviyus marked this pull request as ready for review October 8, 2026 11:02
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 7:16 AM ET / 11:16 UTC (Revision 2).

ClawSweeper review

What this changes

The branch completes provider discovery before publishing a downloaded catalog, keeping the previous models and prices available during preparation.

Example: A Gateway adopts a catalog while OpenRouter discovery is delayed

  • Before: The reported live comparison drops from 514 models to 1 for 5.36 seconds.
  • After: All 514 models remain visible until discovery finishes and the new catalog publishes.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused owner-level repair with relevant live comparisons, meaningful regression coverage, and no open findings.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied live output exercises the changed catalog publication owner through an isolated Gateway and models.list under real warm, delayed, and failed provider discovery. Final rebuilt runs retain 994 rows until publication, and real agent turns demonstrate matching adopted prices; no persisted data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Model pickers temporarily lose discovered models when a running Gateway adopts a downloaded catalog.
Reason: The existing preparation contract keeps the current generation visible until its successor is ready. The area-owner-authored PR records acceptance of waiting for discovery and preserving the built-in fallback when discovery fails.

Merge readiness

✅ Ready for maintainer review

This PR remains necessary: fetched main still exposes incomplete model lists during catalog adoption. The focused repair has sufficient live proof and no actionable review findings.

Priority: P2
Reviewed head: 19a2a2decd3eaa5451411fd57dc14c5b8eca7d1a

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway combines downloaded model metadata with provider discovery to supply model lists and pickers. Its prepared runtime publishes model rows and pricing together so requests use a coherent catalog generation.

flowchart TD
  A[Downloaded catalog] --> B[Prepare candidate generation]
  B --> C[Discover provider models]
  C --> D[Publish models and prices together]
  E[Previous models and prices] --> F[Picker and model list reads]
  D --> F
  D --> G[New requests and pricing]
Loading

Technical review

Best possible solution:

Complete candidate discovery within the existing catalog publication owner before switching model rows and prices together.

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

Yes: current-main source publishes static candidates before discovery, and the supplied live Gateway comparison demonstrates the resulting list contraction. This reviewer did not execute a reproduction.

Is this the best way to solve the issue?

Yes: correcting preparation order at the existing owner preserves atomic publication and ordinary reader deadlines without introducing a competing implementation.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point. Added test files: 1.

Security

None.

Evidence

What I checked:

  • Pinned introduced diff: Candidate discovery now settles before the existing serialized commit; post-commit discovery is removed. Only adoption requests the new internal wait option. (src/agents/prepared-model-runtime.configured-refresh.ts:487, 19a2a2decd3e)
  • Still necessary on fetched main: The production files and model documentation have no differences between the merge base and fetched main; the changed test file was checked separately and also has no differences. Main therefore still commits static candidates before starting discovery. (src/agents/prepared-model-runtime.configured-refresh.ts:517, 814046efacad)
  • Live behavior proof: The fully supplied PR body records an isolated Gateway, a local catalog mirror, real OpenRouter discovery, and models.list polling every 50 ms. After-fix warm and delayed runs retain 514 rows; final rebuilt runs retain 994 rows throughout and switch markers after 2.1 and 5.4 seconds. Real openai/gpt-5.4-mini turns reply 'ok', with usage prices matching adopted catalog versions. Captured source identity: 7f0dbf16256e3eef65005ebad35740d660c15b379ec5bed382ff7d97c59f67e4. (19a2a2decd3e)
  • Recorded owner decision: The PR records the delegated decision to wait for candidate discovery while the previous generation serves, and to publish new built-in rows when discovery fails rather than carry rows across catalog versions. The author's prior merged adoption work establishes relevant area ownership; this acceptance covers the current behavior. (src/agents/prepared-model-runtime.configured-refresh.ts:487, 19a2a2decd3e)
  • Feature history: The post-commit discovery path appears in commit 504d290, associated with merged fix(models): apply downloaded catalogs without a Gateway restart #158000. Its stated purpose was restart-free adoption with coherent rows and prices; it explicitly documented the temporary short-list window. (src/agents/prepared-model-runtime.configured-refresh.ts:517, 504d2905d69c)
  • Meaningful regression coverage: The new regression drives the real models.list handler while candidate discovery is held, checking old discovered rows before release and new rows afterward. The body reports failure on main and passage on head; this read-only review did not execute tests. (src/agents/prepared-model-runtime.remote-publication.test.ts:308, 19a2a2decd3e)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; confidence: low)
  • Peter Steinberger: Raw commit ab4d26a adds src/agents/prepared-model-runtime.catalog-access.ts:696 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: ab4d26a77b18; files: src/agents/prepared-model-runtime.catalog-access.ts)

PR surface

Source +10, Tests +44, Docs +2. Total +56 across 5 files.

View PR surface stats
Area Files Added Removed Net
Source 3 14 4 +10
Tests 1 50 6 +44
Docs 1 6 4 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 5 70 14 +56

Labels

Label changes:

No label changes.

Label justifications:

  • P2: Catalog adoption temporarily hides discovered models, with a bounded repair and no demonstrated urgent runtime outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-08T11:07:32.849Z sha 3bcea9d :: needs maintainer review before merge. :: none

@obviyus
obviyus force-pushed the fix/adoption-row-loss branch from 3bcea9d to 19a2a2d Compare October 8, 2026 11:10
@obviyus
obviyus merged commit a7fa7b2 into main Oct 8, 2026
128 of 129 checks passed
@obviyus
obviyus deleted the fix/adoption-row-loss branch October 8, 2026 11:24
@obviyus

obviyus commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in a7fa7b2.

Bug: adopting a downloaded hosted catalog published replacement owners with static rows only, then discovered afterwards, so pickers and models.list briefly dropped every discovered model. A failed discovery left a provider stuck on its built-in rows.

Fix: adoption now finishes each candidate's discovery before its single rows-and-prices commit. The previous catalog serves until then.

Proof: on an isolated Gateway, main dipped from 514 to 1 row for 0.74–5.4 s on each adoption. With the fix, 514 rows stayed visible and the new rows and prices switched together. The regression test fails on main and passes here.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…odels (openclaw#167178)

## What Problem This Solves

Fixes: the model picker and `models.list` drop every discovered model (for example all OpenRouter rows) while a running Gateway adopts a newly downloaded hosted catalog. If that provider's discovery then fails, the provider stays reduced to its built-in rows until someone runs an explicit refresh.

A production Gateway showed this during a fleet catalog refresh: the list fell from 599 to 54 models for about 2.5 to 4 minutes.

## User Impact

While a Gateway adopts a new catalog, pickers and `models.list` keep showing the current models and prices. The new catalog's models and prices appear together, once its discovery has finished. Adoption itself now takes as long as that discovery (seconds in practice). The previous catalog keeps serving during that time.

## Why This Change Was Made

Adoption (openclaw#158000) built each replacement owner with static rows only and published it. It then started that owner's discovery fire-and-forget. Readers therefore saw only configured and catalog rows until discovery finished. A failed discovery left them that way, because failed providers carry no renewal deadline.

Adoption now waits for each candidate's own discovery, inside the candidate's catalog scope, before the single commit. The wait can be cancelled through the adoption's existing abort signal. The post-commit fire-and-forget is removed. `loadFullModelCatalog` gets a `wait` option, so adoption awaits the acquisition instead of the 5 s foreground race that ordinary readers use. Rows and prices still switch in one commit, and admitted runs keep their captured pair (openclaw#140086).

Maintainer decision (Ayaan, delegated): adoption waits for candidate discovery. The previous catalog's rows and prices keep serving coherently in the meantime, which is strictly safer than publishing a partial list.

Maintainer decision (Ayaan, delegated): if a provider's discovery fails during adoption, that provider publishes with the new catalog's built-in rows. Rows are never carried across catalog versions (openclaw#140086). On `main` this is also the end state, but only after a window in which every discovered row was gone.

No overlap with Pash/Sarah changes.

## Evidence

Regression test `keeps discovered rows published until the adopted catalog's discovery completes` holds the candidate's discovery and drives the real `models.list` handler. While discovery is held, readers still see the old catalog's discovered row and the old pricing generation. After release, they see only the new catalog's row and generation. It fails on `main` (`expected [ 'remote-200' ] to include 'discovered-200'`) and passes with this change. The existing "bounds refresh with two agents…" test now asserts that adoption publishes only after the held discovery completes. All 10 tests in `prepared-model-runtime.remote-publication.test.ts` pass, and `pnpm check:changed` is green.

Live, on an isolated Gateway (loopback, separate state):
- A local catalog mirror serves a fresh bundle per step. Each version renames `kimi/k3` to `Kimi K3 vN` and sets the input price of `openai/gpt-5.4-mini` to N $/M.
- OpenRouter's DNS resolution is delayed through a Node preload.
- `models.list` is polled every 50 ms.
- Adoption is triggered with `openclaw models refresh` followed by a `models.list` refresh.

| Adoption | `main` (adoption code unchanged on current `main`) | This PR |
| --- | --- | --- |
| Warm (no delay) | 514 → **1** row (configured only) for 0.74–0.79 s, then 514 with the new marker | 514 rows throughout; marker switches 3.3 s after the trigger |
| Candidate discovery delayed 3–4 s (its own DNS lookup) | 514 → **1** row for 5.36 s | 514 rows throughout; marker switches 4.98 s and 5.42 s after the trigger, right after the candidate's lookup completes |
| Candidate discovery fails (60 s DNS, 5 s fetch timeout) | 514 → **1** row for 5.38 s, then 51 (OpenRouter 466 → 3 built-in rows) | 514 rows with the old marker for 7.2 s, then 51 with the new marker (decision above) |

On the final diff (rebuilt), the result was the same: a warm adoption with 994 rows throughout switched 2.1 s after the trigger. A 3 s delayed candidate discovery kept 994 rows throughout and switched 5.4 s after the trigger.

Prices follow the same commit. Usage for real `openai/gpt-5.4-mini` turns was computed at the bundled $0.75/M input before the marked catalogs. After adopting v28, v29 and v32, it was computed at exactly $28/$56, $29/$58 and $32/$64 per M (input/output). Real cheap turns (`openclaw agent … --model openai/gpt-5.4-mini`) completed with reply `ok` after each adoption. One turn on the final build hit a retryable agent-database admission error from the session-state layer, about 30 s after adoption. It is unrelated to the catalog, and the immediate retry succeeded.

Local review: `codex review --base origin/main` (model gpt-6-astra), round 1: "No actionable defects were found."

Merge danger: a two-way door. No stored state, schema, config or protocol changes, so a revert fully restores the previous behavior. Blast radius: every Gateway that adopts a downloaded hosted catalog. If this is wrong, adoption could stall behind a hung provider discovery. That wait is still bounded by each provider's own discovery timeouts and is cancelled by supersession, config reload or shutdown. Meanwhile the previous catalog keeps serving.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 16, 2026
…rebuilds (#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 #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 (#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 (#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.

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

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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