Skip to content

fix: reply turns fail when a hosted model catalog is adopted before the turn starts - #167583

Closed
jalehman wants to merge 1 commit into
mainfrom
fix/model-runtime-generation-turn-race
Closed

jalehman wants to merge 1 commit into
mainfrom
fix/model-runtime-generation-turn-race

Conversation

@jalehman

@jalehman jalehman commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Fixes #167573

What Problem This Solves

Fixes: a chat turn fails with prepared model runtime plugin generation was superseded before any model call when the Gateway adopts a newer hosted model catalog between accepting the message and starting the turn. Any Gateway whose build is older than the hosted catalog adopts it at startup and on each refresh, so the first turn after an adoption can fail.

User Impact

User impact: messages accepted before a hosted catalog adoption now complete on the model runtime they were admitted with; later messages use the adopted catalog. No configuration change or user action is needed.

Why This Change Was Made

A reply turn records the published model-runtime generation at dispatch but acquires its run lease later. If a publication commits in between, the old generation is no longer the configured owner's, and the lease fails closed by design (#128138): a stale generation must not republish over newer state.

The fix makes recording the generation and holding it one step. The published-record owner now offers acquire, which reads the dispatch record and, in the same synchronous step, takes custody of its generation and keeps the configured snapshot borrowable. Dispatch disposes that lease when the attempt settles. runPreparedReply acquires its run lease inside that generation's scope, so the existing borrow contract (the same one the Gateway agent path and nested turns use) lends the admitted snapshot when a newer generation was published.

Invariants kept:

  • Custody keeps registries open but does not retain plugin work, so plugin reload drains do not wait on dispatching turns. The run lease retains work as before.
  • Without a live dispatch hold (a detached or copied generation, or a hold whose dispatch has ended), a stale generation still fails closed. The existing owner-selection tests for that contract pass unchanged.
  • Borrowing still requires matching config, agent, directories, workspace, metadata, binding capability, and runtime-plugin coverage.

I chose this over rebinding the turn to the newest generation when the lease finds it superseded. A rebind would mix generations within one turn: dispatch hooks ran on the old inbound plugin registry. It would also contradict the tested fail-closed contract for unheld stale generations.

This change is independent of #165957.

Evidence

  • Regression at the real boundary. A new test in src/agents/prepared-model-runtime.remote-publication.test.ts runs the real dispatchLowLevelChannelReplyFromConfig, the real prepared runtime, and the real runPreparedReply (turn internals mocked after admission). Inside the reply resolver it adopts a hosted catalog through applyRemoteModelCatalogUpdate, then starts the turn.
    • On base 608134ea54c (production code reverted, test kept), it fails with the production error: prepared model runtime plugin generation was superseded for …/agents/default/agent.
    • With the fix, it passes. The turn runs on the dispatch-admitted generation (catalog 200), and the next dispatch record carries the adopted catalog (300).
    • node scripts/run-vitest.mjs src/agents/prepared-model-runtime.remote-publication.test.ts --maxWorkers=1: 11/11 pass, wall time 25.8s. The new test takes about 1.6s of CI time.
    • The shared fixture now publishes with allowGatewaySubagentBinding: true, which matches Gateway startup.
  • Built Gateway. I ran src/gateway/gateway-active-memory.test.ts against a fresh pnpm build, with dist/build-info.json builtAt backdated so the hosted catalog is newer. I also made a local, uncommitted edit that turns hosted catalog refresh back on in that test.
    • Base 608134ea54c: 0/3 pass. Each run fails with generation was superseded.
    • This branch: 5/5 pass, about 16s each. In every run, remote model catalog applied is logged after chat.send.
  • Owner suites. All pass:
    • prepared-model-runtime* and prepared-model-catalog*: 58 files, 421 tests.
    • dispatch-from-config*: 31 files, 758 tests.
    • get-reply-run*, get-reply config-override, update-startup*, model-catalog, cron plugin-generation, and Gateway prepared-borrow, close, chat-metadata, remote-catalog, and auth-refresh suites: 31 files, 375 tests.
  • Static checks. pnpm tsgo:core, pnpm tsgo:core:test, oxlint, oxfmt, and git diff --check are clean.
  • Diff size. Production is +127/−36; most of the removals are re-indentation in get-reply-run.ts. Tests are +139/−40, mostly the regression test and moving dispatch test mocks to the new lease shape.

Gaps

  • A turn whose run lease cannot borrow the admitted snapshot still fails closed after a newer publication. This happens when the turn runs in a different workspace from the configured owner (for example, a spawned-workspace session), or when it selects a runtime plugin the admitted generation never loaded. Republishing from a historic generation is the hazard fix(agents): prevent reloads from losing queued replies or restoring stale credentials #128138 forbids.
  • A plugin reload in the window still fails the turn, now with the existing "retry after the plugin reload completes" error. The admitted generation's plugin instances are being retired, so this is intentional.
  • If a configured owner has already moved off the generation that dispatch reads, nothing is held. For example, a plugin retirement can leave the owner without a generation until recovery republishes. The turn then fails closed as it does today.
  • The Gateway agent method and isolated cron keep load followed immediately by their own run lease. Those paths do not have the dispatch-to-lease window this issue covers.

A reply turn recorded the prepared model-runtime generation at dispatch but
only acquired its run lease later. A hosted model catalog adoption committed in
between published a new generation, and the lease rejected the recorded one as
superseded before any model call, failing the user's turn.

Dispatch now admits the published record and holds its generation in the same
synchronous step. The hold keeps the generation's registries open (custody, not
plugin work, so plugin reload drains are not blocked) and lends the configured
snapshot to the turn's run lease through the existing borrow contract. The turn
finishes on the generation it was admitted with; later turns use the new one.
A stale generation without a live hold still fails closed.
@clawsweeper

clawsweeper Bot commented Oct 9, 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 agents Agent runtime and tooling size: M labels Oct 9, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 9, 2026
@clawsweeper

clawsweeper Bot commented Oct 9, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

The branch retains a reply’s admitted model runtime through dispatch preparation so a hosted catalog replacement does not invalidate its later run lease.

Example: A user sends hello while catalog 300 replaces catalog 200

  • Before: The reply can fail before inference with “prepared model runtime plugin generation was superseded.”
  • After: The admitted reply uses catalog 200 and delivers “finished,” while the next dispatch uses catalog 300.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Reported real Gateway before/after proof supports a clean focused repair, but acknowledged remaining acceptance cases make this a partial fix.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The fully read body reports after-fix runs through a built Gateway and real chat.send/agent.wait transport with an older build timestamp and catalog refresh enabled: all five branch runs completed after adoption, versus three superseded-generation failures on base. The inspected harness checks final replies, provider traffic, and history. The deterministic regression additionally covers dispatch admission under catalog 200 and subsequent catalog 300 publication. Results were not independently rerun; the patch changes no persisted format.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: An accepted message can receive no model reply when a hosted catalog update lands before the turn starts.
Reason: Retaining admitted model facts restores an established conversation contract through the existing owner. The stated different-workspace and unloaded-plugin gaps leave part of the linked issue’s acceptance unresolved.

Merge readiness

✅ Ready for maintainer review

Current main still exposes the reported race, and this PR offers a useful focused repair. No actionable introduced defect was found.

Priority: P1
Reviewed head: b3d5b4800fe2266e8fb9fbd0393c76f0a1c9843e

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Gateway prepares model choices, credentials, and plugin registrations before running a reply. Dispatch captures those facts, and the run lease keeps the selected runtime available through execution.

flowchart TD
  A[Incoming message] --> B[Published model runtime]
  B --> C[Dispatch retains admitted generation]
  D[Hosted catalog replacement] --> B
  C --> E[Prepare reply]
  E --> F{Snapshot matches selected runtime}
  F -->|Yes| G[Run reply on admitted generation]
  F -->|No| H[Reject unsupported borrowing]
  G --> I[Release dispatch custody]
Loading

Technical review

Best possible solution:

Keep dispatch custody and guarded borrowing in the existing runtime owners, consolidate overlapping repair work, and retain tracking for catalog-adoption cases outside this patch’s supported snapshot.

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

Yes: capture dispatch on catalog 200, publish catalog 300, then acquire the run lease with the captured generation. Current-main source establishes the rejection, and the contributor reports matching built-Gateway failures; this review did not execute code.

Is this the best way to solve the issue?

Yes for the supported reply-dispatch case: atomic custody repairs the ownership gap without rebinding the turn or weakening stale-generation checks. It does not satisfy the linked issue’s broader acceptance for different workspaces or previously unloaded runtime plugins.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Current-main necessity: None of the introduced paths changed between the merge base and fetched main. Main therefore still returns an unretained dispatch record and acquires the run lease later; the proposed custody handoff is absent. (src/agents/prepared-reply-dispatch-runtime.ts:163, 98eb5759c934)
  • Atomic custody and cleanup: The publication owner reads the record and retains its matching generation synchronously. Disposal clears the borrowing capability before awaiting physical cleanup, and the dispatch attempt owns disposal across returns and exceptions. (src/agents/prepared-reply-dispatch-runtime.ts:140, b3d5b4800fe2)
  • Existing borrowing boundary remains enforced: Borrowing still requires matching configuration, agent, directories, workspace, metadata, binding capability, and selected plugin coverage. The borrowed branch returns a lease without publishing historic state over the current owner. (src/agents/prepared-model-runtime-lease.ts:236, b3d5b4800fe2)
  • Reported built-Gateway proof: The fully read PR body reports a fresh built Gateway with its build timestamp backdated and catalog refresh enabled: the base failed all three runs with the superseded-generation error, while the branch passed five runs with catalog adoption logged after chat.send. The inspected harness launches dist/index.js, uses the real Gateway client, requires a final chat event and agent.wait status ok, and checks provider requests and chat history. These are contributor-reported results, not reviewer execution. Captured body sourceRevision: d963530e413c066129272de591f48c9c7a48c7f47bc31cd4a713b0ce5cf78382. (src/gateway/gateway-active-memory.test.ts:368, b3d5b4800fe2)
  • Focused regression value: The added regression drives real low-level reply dispatch, catalog publication, and run-lease acquisition, with execution mocked after admission. It checks delivery of finished under catalog 200 and subsequent publication of catalog 300; the body reports failure with base production code restored. (src/agents/prepared-model-runtime.remote-publication.test.ts:219, b3d5b4800fe2)
  • Established catalog and stale-generation contracts: Merged fix(models): apply downloaded catalogs without a Gateway restart #158000 requires admitted turns to retain their catalog rows and prices while later turns use the replacement. Merged fix(agents): prevent reloads from losing queued replies or restoring stale credentials #128138 permits old-state execution only through an open matching lease and forbids restoring retired configuration. This repair preserves both intents. (79e675521f7c)

PR surface

Source +91, Tests +99. Total +190 across 14 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 127 36 +91
Tests 6 139 40 +99
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 266 76 +190

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #167573
Summary: This PR is a focused candidate for the reported dispatch-to-lease race; an earlier open PR covers the same cause across additional preparation paths.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P1: Normal hosted catalog adoption can reject accepted conversation turns before inference, supported by current source and reported Gateway failures.
  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P1: Normal hosted catalog adoption can reject accepted conversation turns before inference, supported by current source and reported Gateway failures.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🐚 platinum hermit 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 8, 2026, 11:23 PM ET / October 9, 2026, 03:23 UTC.

@jalehman

jalehman commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #167492, which landed on main first and fixes the same race (a turn keeps its admitted model-runtime generation across a hosted catalog adoption), with broader coverage of cron and Gateway preparation. Closing this one.

@jalehman jalehman closed this Oct 9, 2026
@RomneyDa
RomneyDa deleted the fix/model-runtime-generation-turn-race branch October 22, 2026 05:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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.

fix: a hosted model catalog adoption fails a turn that has not called the model yet

1 participant