Skip to content

opensecret: health-aware Auto model selection for Router V2 - #968

Merged
AnthonyRonning merged 2 commits into
masterfrom
codex-auto-model-maple
Sep 18, 2026
Merged

AnthonyRonning merged 2 commits into
masterfrom
codex-auto-model-maple

Conversation

@AnthonyRonning

@AnthonyRonning AnthonyRonning commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Router V2 resolved an Auto alias to one public model before any health check, so an Auto Quick request whose only route was unavailable had nowhere to go. This adds the missing Auto model-selection stage: a small compiled policy that may choose another approved model of the same tier when every route of the preferred model is unavailable, decided before any model-dependent work and pinned for the whole response. Explicit selections never change public model and Router V1 is untouched.

Policy (src/inference/auto_model.rs, auto-model-v1)

Selector Plan Preferred (alias target) Alternate
auto:quick paid deepseek-v4-1-flash glm-5-3-flash
auto:powerful paid glm-5-3 kimi-k3
auto:quick free gpt-oss-120b none
auto:powerful free glm-5-3 (denied by plan, unchanged) none

A model is unavailable only when all of its configured routes are open or probing under that model's own FailoverPolicy, evaluated from one health snapshot across every candidate (GLM Flash keeps its capacity-only gates). Same-model provider failover therefore still happens before any model change. Every candidate passes the real plan check; an alias never grants access. A preferred model with no configured route at all is a server error, never something an alternate quietly masks.

An alternate is skipped when the request needs more context than its window (Responses: user message + system prompt + inline instructions + max_output_tokens; Chat: text-only token estimate including tool schemas and the caller's max_tokens or max_completion_tokens, with a byte bound so tokenizing only happens near the limit), when it lacks vision the request needs, or, for Kimi on Chat, when assistant tool-call ids are not in Kimi form. Image parts are not counted because their provider token cost is model-specific. When no candidate is eligible the request gets the established typed capacity result with the earliest bounded recovery hint and zero upstream sends.

One bounded second decision before any send

The Responses context builder keeps the system prompt regardless of truncation and keeps the conversation's first user turn whenever it fits, so an alternate admitted by the up-front estimate can still fail the context build; and a chosen model can lose its routes between the decision and the pin. In each of those cases the request decides exactly once more with that model excluded, before any provider send. The exclusion carries its cause: a model that lost its routes is excluded as unavailable with the capacity result's own retry hint, so when nothing else is eligible (free Quick has a single candidate; a paid alternate can be incompatible) the request still returns the 503 capacity contract with Retry-After, not a server error. Surface behavior at the late boundaries differs: Responses rebuilds its context for the new model without repeating image descriptions and pins; at its first-send claim it can only replan same-model providers or fail safely, it does not reselect models there. Chat re-prepares the route and can take its one bounded cross-model decision at the first-send claim as well, since it has no model-dependent preparation to rebuild. Any capacity result after billed image helper work is not replay-safe. A message too large for the tier's own model keeps its existing context error, checked before the decision. After the first send the logical response stays pinned; nothing is ever replayed.

Sticky routes (src/inference/sticky_routes.rs)

Router V2 remembers the route a provider accepted per account, inference surface, and selector, and forgets it one idle hour after the account's last accepted request (bounded to 50k entries per enclave; lookups do not extend or reorder entries). The same-model planner prefers the remembered provider over the weighted bucket while it is eligible (RouteSelectionSource::Sticky, PlanDecision::RememberedRoute), and Auto retries the remembered alternate before the preferred model while it stays healthy. This keeps warmed provider prompt caches; a remembered route is a preference, never a permit. Consequences to be aware of: an account that stays active keeps a healthy alternate (or shifted provider) until it has been idle for an hour, and memory is enclave-local like the health state, so conversations that hop enclaves can see different decisions.

Where the decision sits

  • Chat Completions: after alias resolution, before route preparation. The body is only inspected when a V2 Auto decision is actually needed.
  • Responses: after input normalization, user key retrieval, conversation ownership, the usage gate, and the caller's message budget against the alias target, and before both context builds, image description, persistence, and pinning. body.model is written by alias resolution and then once more from the decision; every model-dependent step reads it after that second write.
  • The intent carries the decision (preferred_model_id(), auto_model_reason()), and the pinned-route log includes selector, preferred, chosen, reason, provider, and policy version. Persisted responses.model, response payloads, and usage attribution all use the executed model.

Unchanged: first-send probe claims and same-model replanning, tool-loop pinning, no replay after any upstream failure, Responses disconnect/cancellation/storage behavior, transport, usage publication.

Known limitations and follow-ups

Three independent read-only model reviews (security, control-flow correctness, and product/operations lenses) plus the earlier review found no P0 or P1 at dbe7c6e4. These are the items worth knowing; none changes the contract above.

  • After the one bounded reselection has been spent on a model that lost its routes at pin time, a context overflow on the rebuilt context for the new model returns the context-limit error (413) instead of the 503 capacity result the same request receives when the preferred model is already unavailable at the first decision. This needs a conversation larger than the alternate's window plus a route loss between decision and pin; there is no replay or data effect. Small fix; it can land in this PR or as a follow-up.
  • Responses error precedence for requests with more than one fault changed on all routing modes: the user key, conversation ownership, and usage gate now run before the message budget check. Single-fault requests and success paths return exactly the errors they did before.
  • The handler-level reselection loops are covered only through the functions they call; no test drives a loop end to end because the crate has no AppState fixture. A regression in the once-only guards would not be caught by the suite.
  • The only log line that joins selector, chosen model, reason, provider, and route source is at debug level. Promote it to info for non-primary decisions and sticky or fallback routes before relying on logs to watch a rollout.
  • Chat's admission estimate for a smaller-window alternate counts text only. A near-window request with images can be admitted to GLM 5.3 Flash and rejected by the provider after the send; no replay follows.
  • Sticky memory is a preference cache, not state: other accounts' activity can evict an entry under the 50k bound, helper and title executions occupy entries that no user decision reads, and memory is per enclave, so a conversation that moves between enclaves can see different decisions. A conversation-affine hint from the last persisted response model would be a separate change.
  • Long Responses histories that fit the preferred model are middle-truncated for a smaller-window alternate by the existing context contract, exactly as an explicit request for that model would be.

Validation

Static/unit, from services/opensecret/ in the pinned Nix shell with the dev-shell hooks disabled:

  • cargo fmt --all -- --check clean.
  • cargo clippy --locked --all-targets --all-features -- -D warnings clean.
  • cargo test --locked --all-features: 681 passed, 0 failed, 23 ignored (the ignored tests are the existing database and live-provider suites).

New focused tests cover: candidate tables anchored to the Router V2 alias targets; primary, retained, fallback, and excluded-candidate decisions; context, vision, and Kimi tool-history incompatibility; free-plan gates and the unconfigured-preferred error; recovery hints only for health rejections; the bounded token estimate; per-model availability under each failover policy from one snapshot; remembered-provider planning; sticky memory expiry, eviction order, and per-surface keys; cache reads that do not disturb eviction order; and a mock-provider flow where the request that discovers a DeepSeek 503 is not replayed, the next Auto Quick request moves to GLM Flash before any send, the response model is canonicalized, an explicit DeepSeek request stays capacity-unavailable with zero sends, and the account retains GLM Flash while DeepSeek stays open. The DeepSeek-to-GLM Flash smaller-window case is tested for both the alternate skip and the existing truncation contract, an overflowing remembered alternate is shown to yield to the healthy preferred model, and a reselection with no eligible alternate (free single-candidate Auto, paid Auto with an incompatible alternate, on both surfaces) keeps the capacity result and retry hint with zero sends, including the Responses replay-safety downgrade after helper work.

Local encrypted full stack (this component's pinned local stack with a loopback stub for the router flag, deterministic Free and Pro fixture users, live Tinfoil and Continuum routes, healthy path only), run on the first revision of this branch: the TypeScript SDK streaming Chat and Responses tests passed on Router V2 for the Pro user with auto:quick and for the Free user with auto:quick, and passed again with the flag off; the backend log showed routing_mode=V2 with reason=primary decisions on both surfaces and both plans, routing_mode=Legacy with no decision when the flag is off, and the Rust SDK streaming test drove an auto:powerful V2 decision on the Chat surface. Two live-suite assertions unrelated to routing fail with reasoning models (the Rust test's 10-token budget is consumed by GLM reasoning; the TypeScript workflow test expects the first output item to be a message while DeepSeek emits reasoning first).

Not exercised here: induced provider failures against the real binary (the plain-HTTP Tinfoil transport is test-only, so outages exist only in the mock-provider tests), the bounded second decision end to end, API-key attribution end to end, image-helper requests through the full stack, and multi-enclave behavior. No flags, prices, PCRs, or deployments were changed; production rollout is a separate decision.

🤖 Generated with Claude Code

Router V2 resolved an Auto alias to one public model before any health
check, so a single-route model with no eligible provider left Auto Quick
with nothing to do. Add a small compiled Auto model policy that runs after
alias resolution and before any model-dependent work: paid Quick may move
from DeepSeek V4.1 Flash to GLM 5.3 Flash and paid Powerful from GLM 5.3 to
Kimi K3 only when every route of the preferred model is unavailable under
that model's own failover policy. Free tiers keep their single target,
explicit selections never change public model, and Router V1 is untouched.

The decision consumes one health snapshot across all candidate routes,
claims nothing, and feeds the chosen model into the existing same-model
planner, first-send claim, tool-loop pinning, persistence, and usage. An
alternate is skipped when the request needs more context than its window
(Chat uses a text-only estimate with a byte bound before tokenizing, plus
tool schemas and the caller's output limit), when it lacks vision the
request needs, or, for Kimi on Chat, when tool-call ids are not in Kimi
form. Before any provider send, a chosen Auto model that cannot hold the
request's context or loses its routes earns exactly one further decision
with that model excluded; nothing is ever replayed after a send starts.

Router V2 also remembers the route a provider accepted per account,
surface, and selector for one idle hour so warmed prompt caches are reused:
the planner prefers the remembered same-model provider while eligible, and
Auto retries the remembered alternate before the preferred model while it
stays healthy. Responses now binds the user key, conversation ownership,
the usage gate, and the caller's message against the tier's own model
before the decision; its input handling is split so the budget check and
both context builds use the final model.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@AnthonyRonning

Copy link
Copy Markdown
Contributor Author

Reviewed commit 14f464698e01cf6038709a5b23d36cac559980a3 against 1ef3daaacd00d38989c4ac08bd933c877edee909.

Verdict: fix one introduced P2 before merging. The reviewed design otherwise preserves explicit model choice, V1 behavior, entitlement checks, actual-model attribution, and no replay after a provider attempt.

P2 — Preserve capacity errors when bounded Auto reselection has no alternate

This is source-confirmed; it was not reproduced through the authenticated HTTP handler.

auto_model.rs:219–228 records every excluded candidate as ContextOverflow and skips it before collecting health/retry information. However, callers also exclude a model because it became capacity-unavailable after the initial snapshot.

A free auto:quick request has only GPT OSS as a candidate. Initial selection can succeed, then its gate can close or another request can acquire its half-open probe. Chat catches the capacity error during route preparation or the first-send claim, discards it, and retries selection with that sole model excluded. Responses has the same pre-pin path.

With no candidate left, the selector returns NoEligibleCandidate { retry_after: None }, which openai.rs:1751–1768 maps to HTTP 500. The original capacity 503, Retry-After, and applicable replay-safety metadata are lost despite zero main provider sends. Paid requests whose alternate is incompatible have the same failure mode.

Suggested fix: carry the typed capacity cause and retry hint across the bounded second decision, or return the original capacity error if reselection cannot produce an eligible alternate. Keep genuine context overflow distinct. Preserve the Responses replay-safety downgrade when image helpers have already performed billed work.

Regression coverage should include free single-candidate Auto and paid Auto with an incompatible alternate, across Chat and Responses. Assert the capacity result and retry hint, zero main provider sends, bounded reselection, and the helper-related replay-safety behavior.

Other reviewed boundaries

  • Candidate availability shares one health snapshot; first-send claims remain authoritative.
  • Actual send/body failures remain Attempt failures and do not enter Chat's new pre-send reselection loop.
  • Responses runs image descriptions once, reuses them during rebuilding, and carries the final model through persistence, usage, and the pinned tool loop.
  • Remembered routes remain subject to access and health checks. Memory is bounded and lookups do not refresh expiry or eviction order.
  • Caller output limits remain intact; no new default output-token cap was introduced.

Policy and coverage notes, separate from the P2

  • Flash deliberately retains CapacityGates in this PR. Coordinate the standard circuit-policy follow-up in Router V2: apply standard circuit breakers to GLM 5.3 Flash #971; preserving the original policy here is not an accidental regression. Upstream diagnostics remain tracked in OpenSecret: log bounded, sanitized upstream inference error details #970.
  • Stickiness is per account/surface/selector, not per conversation. A healthy fallback expires after one idle hour; continuous activity can retain it indefinitely after the preferred route recovers. This should remain an explicit product choice.
  • Clarify the PR prose about the final first-send claim: Chat can perform another bounded cross-model decision there; Responses can replan same-model providers or fail safely, but does not reselect models at that late boundary. Safe failure is permitted by the intended contract.
  • Chat's smaller-window estimate excludes image token cost and framing and uses the shared text tokenizer. Image-heavy and near-window compatibility remain unverified.
  • Added tests exercise policy/executor components, but not the complete authenticated Responses sequence of helper execution, health change, reselection, persistence, and tool continuation. The existing Responses output-token reservation limitation is inherited and is not a new finding here.

Validation independently executed at the reviewed head

Through the component's pinned Nix shell with stateful hooks disabled:

  • cargo fmt --all -- --check: passed.
  • RUSTFLAGS='-D warnings' cargo clippy --locked --all-targets --all-features -- -D warnings: passed.
  • RUSTFLAGS='-D warnings' cargo test --locked --all-features: 678 passed, 0 failed, 23 ignored.
  • git diff --check: passed; tracked worktree stayed clean.

Exact-head backend and SDK CI checks were also green. Ignored database/live-provider tests and encrypted fallback smoke were not executed in this review. The earlier healthy-path smoke described in the PR remains author-reported evidence.

…ernate

A bounded second Auto decision excluded the lost model as a context
overflow even when the cause was a route that became unavailable after
the first snapshot. With no other candidate (free Quick, or a paid tier
whose alternate is incompatible) the selector reported no health rejection
and the request ended as a 500 instead of the typed capacity result, losing
the retry hint although nothing had been sent.

Carry the exclusion cause: a lost route is excluded as unavailable with the
capacity result's own retry hint, so the second decision reports it and
keeps the 503 contract and Retry-After; a context overflow stays distinct.
The Responses replay-safety downgrade after billed image helpers still
applies. Tests cover free single-candidate Auto and paid Auto with an
incompatible alternate on both surfaces, the hint fallback, the compatible
alternate still being taken once, and the helper downgrade.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@AnthonyRonning

Copy link
Copy Markdown
Contributor Author

Thanks for the review. The P2 is fixed in dbe7c6e (kept as a separate commit on top of the reviewed head so the delta is easy to see; happy to squash before merge).

What changed

  • The exclusion passed into the bounded second decision now carries its cause (ExcludedAutoCandidate::context_overflow / ::unavailable(model, retry_after)). A model that lost its routes at route preparation or at Chat's first-send claim is excluded as Unavailable with the capacity result's own hint (minimum cooldown when the hint is absent), so the selector's earliest-recovery logic keeps the typed 503 and Retry-After when nothing else is eligible. A genuine context overflow is still recorded as ContextOverflow.
  • Responses maps that error through the existing pre-persistence path, so the replay-safety downgrade after billed image helpers still applies. The compatible-alternate case is unchanged: it is taken exactly once.

Regression coverage added

  • Policy: free single-candidate Quick excluded as unavailable keeps retry_after (and the fallback hint); paid Quick with DeepSeek excluded and GLM Flash incompatible keeps DeepSeek's hint with both causes recorded; a compatible alternate still wins once.
  • Resolve stage, both surfaces: the same two cases return InferenceCapacity { 503, retry_after, client_replay_safe: true } and the rendered response carries the replay-safe, error-code, and Retry-After headers; the decision stage has no provider client, so zero sends is structural, and nothing is remembered.
  • Responses: the reselection capacity result keeps its hint and becomes not replay-safe once descriptions were billed.

Not covered: the complete authenticated Responses sequence (helper execution, health change, reselection, persistence, tool continuation) still has no end-to-end test; that remains as stated in the PR body.

PR prose: corrected the first-send-claim paragraph. Responses can only replan same-model providers or fail safely at its first-send claim; Chat can take its one bounded cross-model decision there because it has no model-dependent preparation to rebuild.

Other notes: Flash stays on CapacityGates here, with #971 as the follow-up; the per account/surface/selector stickiness with the one-hour idle expiry is the product choice we settled on and the PR body states its consequence for continuously active accounts.

Validation at dbe7c6e in the pinned Nix shell with the stateful hooks disabled: cargo fmt --all -- --check passed, RUSTFLAGS='-D warnings' cargo clippy --locked --all-targets --all-features -- -D warnings passed, RUSTFLAGS='-D warnings' cargo test --locked --all-features: 681 passed, 0 failed, 23 ignored; git diff --check clean.

@AnthonyRonning

Copy link
Copy Markdown
Contributor Author

Rereviewed dbe7c6e4a106d695f0761ba4c6878a6f15930f50 against the previously reviewed 14f464698e01cf6038709a5b23d36cac559980a3.

The previous P2 is resolved. No new findings in the follow-up.

Verified that:

  • Exclusions carry their cause: unavailable routes preserve the capacity hint; genuine context overflow remains distinct.
  • The selector includes an excluded unavailable candidate's hint in recovery accounting before skipping it. Free single-candidate Auto and paid Auto with an incompatible alternate therefore retain the 503/Retry-After contract.
  • Both Chat capacity-reselection branches and Responses' pre-pin capacity branch construct the unavailable exclusion correctly. Responses still removes replay safety after billed image-helper work.
  • Reselection remains bounded; actual provider-attempt failures do not enter this path. A compatible alternate can still be selected.
  • The PR body now accurately distinguishes Chat's final-claim reselection from Responses' safe same-model replan/failure behavior.

Independently reran the pinned, hook-disabled local gates at this exact head: format clean; strict Clippy clean; 681 tests passed, 0 failed, 23 ignored; git diff --check clean and tracked worktree unchanged. The new policy, resolution/error-header, and helper-replay-safety tests passed.

At the latest CI read, SDK integration and the Nix/application-package job were successful; the backend format/lint/test job was still running. Code-review concerns are cleared, subject to completion of required CI. This is not a deployment approval.

The previously stated limits remain accurately scoped: no complete authenticated Responses helper/reselection/persistence test was run, near-window image-heavy Chat fallback remains unverified, and Flash standard circuit policy remains the separate #971 follow-up. These are not new findings in this fix.

@AnthonyRonning

Copy link
Copy Markdown
Contributor Author

Three independent read-only reviews of dbe7c6e4 (Kimi K3 on security and trust boundaries, GLM 5.3 on control-flow correctness, Grok 4.6 on product contract and operations) found no P0 or P1. The PR body's closing section now lists the known non-blocking items they and the earlier review surfaced, and two prose inaccuracies in the body were corrected (body.model is written twice, and the context builder keeps the first user turn only when it fits). No code changed.

@AnthonyRonning
AnthonyRonning marked this pull request as ready for review September 18, 2026 22:18
@AnthonyRonning
AnthonyRonning merged commit d5f359e into master Sep 18, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant