GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [FEATURE]: Configurable model fallback on transient errors and timeouts · Issue #48991 · anomalyco/opencode

[FEATURE]: Configurable model fallback on transient errors and timeouts #48991

New issue
Copy link
New issue
Copy link
Open
Open
[FEATURE]: Configurable model fallback on transient errors and timeouts#48991
Copy link
Assignees
neriousy

Description

@AndyS77
AndyS77
opened on Sep 14, 2026
Issue body actions

Feature hasn't been suggested before.

  • I have verified this feature I'm about to request hasn't been suggested before.

Describe the enhancement you want to request

Supersedes #7602 (Jan 2026) and the closed PR #20105 (Mar 2026, auto-cleaned). Incorporates lessons learned from #20105 and aligns with the current Effect-based session architecture.

Problem

When a model is unreachable, rate-limited, or times out, the session retry policy (session/retry.ts) retries the same model on the same provider with exponential backoff. After retries are exhausted, halt() is called and the session dies. There is no mechanism to fall back to a different model.

This causes long-running agent workflows to fail on transient provider issues that a different provider would handle fine.

Proposed Behavior

After the retry policy exhausts for a transient error (5xx, 429, network failure, timeout), instead of halting the session:

  1. Look up the configured fallback model(s) for the current model
  2. If a fallback exists and is available, switch to it and re-run the LLM stream
  3. Track which fallback was used for status reporting
  4. Emit a status event so the UI can show the model switch
  5. If the fallback also fails, try the next in the chain
  6. If all fallbacks are exhausted, halt as before

Triggers

  • Rate limits (429, Too Many Requests)
  • Server errors (500, 502, 503)
  • Network failures (ECONNREFUSED, ECONNRESET, ETIMEDOUT, fetch failed)
  • Timeouts (header timeout, stream timeout — the primary use case)
  • Model unavailable (404, model not found)

Not triggered by:

  • Auth errors (401 — different provider has different creds)
  • Context overflow (413 — needs compaction, not a model switch)
  • Validation/prompt errors

Config Schema

Aligns with the existing provider.models config structure:

{
  "provider": {
    "anthropic": {
      "models": {
        "claude-sonnet-4": {
          "fallback": ["openai/gpt-5", "google/gemini-3-pro"]
        }
      }
    },
    "openai": {
      "models": {
        "gpt-5": {
          "fallback": ["anthropic/claude-sonnet-4", "google/gemini-3-pro"]
        }
      }
    }
  }
}

Each entry in the fallback array is a "provider/model-id" string. The array defines an ordered fallback chain — tried in sequence until one succeeds.

Architectural Notes

PR #20105 implemented fallback as LLM middleware via wrapLanguageModel. This approach has two issues:

  1. Interacts badly with the session retry loop — middleware runs inside the AI SDK's own retry, which conflicts with the Effect-based SessionRetry.policy
  2. Only 1 fallback — hardcoded Copilot-to-Bedrock mapping, not a configurable chain

The recommended approach is to implement fallback at the session processor layer (processor.ts), after Effect.retry(SessionRetry.policy(...)) exhausts:

Effect.retry(SessionRetry.policy(...))
  -> Effect.catch(fallback)   // instead of Effect.catch(halt)
  -> Effect.catch(halt)       // if all fallbacks exhausted

This keeps fallback logic in the Effect-based session pipeline where the error context is richest.

References

  • [FEATURE]: Native Model Fallback / Failover Support #7602 — Original feature request (Jan 2026)
  • feat(provider): automatic model fallback on transient errors #20105 — Closed PR implementing Copilot-to-Bedrock fallback (Mar 2026, auto-cleaned)
  • [FEATURE]:Auto-Failover for Rate Limit Resilience #42513 — Related: API key pooling per provider
  • [FEATURE]: Per-Provider Quota-Aware Auto-Retry with Configurable Reset Schedule #43324 — Related: Per-provider quota-aware retry
Reacted by pewpil, Igor Kvachenok and Clément FLEURY

Activity

  1. github-actions
    assigned
    neriousy
    on Sep 14, 2026
  2. AndyS77
    added 4 commits that reference this issue on Sep 15, 2026

    fix(hooks): treat tsgo OOM crashes as non-blocking in pre-push

    5df684e

    fix(provider): restore schema + processor integration, revert pre-pus…

    f61077f

    feat(provider): configurable model fallback on transient errors and t…

    39ec147

    feat(provider): configurable model fallback on transient errors and t…

    415b873
  3. hd-o commented on Sep 16, 2026

    @hd-o
    hd-o
    on Sep 16, 2026
    More actions

    How about setting the models on top-level or agent?

    {
      "model": [
        "anthropic/claude-sonnet-5",
        "openai/gpt-5"
      ]
    }
    {
      "agent": {
        "plan": {
          "model": [
            "anthropic/claude-sonnet-5",
            "openai/gpt-5"
          ]
        }
      }
    }
  4. LuminairPrime
    marked [FEATURE]: Model fallback/failover #55008 as a duplicate of this issue on Oct 13, 2026
  5. tea0112 commented on Oct 22, 2026

    @tea0112
    tea0112
    on Oct 22, 2026
    More actions

    I need this because I have many providers — why bother respecting rate limits when we can automatically switch to another?

  6. opencodejr commented on Oct 28, 2026

    @opencodejr
    opencodejrBot
    on Oct 28, 2026
    Contributor
    More actions

    Thanks for the detailed write-up, @AndyS77! You're asking for a configurable, ordered chain of fallback models per model. When retries on the current model run out for a transient error (rate limit, 5xx, network failure or timeout), OpenCode would switch to the next model in the chain instead of stopping the session, and show the switch in the UI.

    Today v2 retries the same model with backoff and then stops. The plugin session.retry hook can only decide whether to retry and how long to wait, not which model to use. So this can't be built cleanly as a plugin yet. A small addition would make it possible: letting the retry decision also name a replacement model for the next attempt.

    Maintainers will consider this request. Related issues, which you already mentioned:

    • [FEATURE]: Native Model Fallback / Failover Support #7602: the original fallback request
    • feat(provider): automatic model fallback on transient errors #20105: earlier PR with a single Copilot-to-Bedrock fallback
    • [FEATURE]: Per-Provider Quota-Aware Auto-Retry with Configurable Reset Schedule #43324: per-provider quota-aware retry
    • [FEATURE]:Auto-Failover for Rate Limit Resilience #42513: API key pooling per provider
  7. moritzWa commented on Oct 30, 2026

    @moritzWa
    moritzWa
    on Oct 30, 2026
    More actions

    Use case that isn't covered here: the fallback also needs to fire when the provider's auth refresh gets throttled or its credits/quota run out ("The usage limit has been reached"), not only on 5xx/429/timeouts. Same model on another provider has separate creds, so 401 is fine to fall back on when the subscription itself is the problem.

    Also useful: once a provider reports it's out of quota, skip it for a while (I use 30 min) instead of retrying it on every turn. Without that, every chat in a fallback chain burns a failed attempt on the dead provider first.

    I run this today as a local plugin (ordered chain, cooldown on exhausted providers) and can port it to core if the processor-layer approach in the description is still the plan.

  8. opencodejr
    marked [FEATURE]: Fallback model #64123 as a duplicate of this issue on Nov 15, 2026
  9. opencodejr
    marked models: auto-fallback to another model when quota is exhausted #65404 as a duplicate of this issue on Nov 21, 2026
  10. cepice commented on Nov 28, 2026

    @cepice
    cepice
    on Nov 28, 2026
    More actions

    Following up on the bot's note that "the session.retry hook can only decide whether to retry and how long to wait, not which model to use. So this can't be built cleanly as a plugin yet."

    I built it as a plugin anyway and have been running it on 2.4.2. It works, and the exercise narrowed the required core change to something quite small. Writing up what I hit, including three bugs that are all symptoms of the same missing primitive.

    Related: #64222 adds fallback chains driven by time-based availability windows. That is complementary to this request — this is the error-driven case (429, quota, dead key), and the two should share the same chain representation rather than growing two config shapes.

    It is buildable today, with two paths

    Fast path — session.retry hook:

    await ctx.session.hook("retry", (event) => {
      if (!fallbackWorthy(event.error)) return
      void ctx.session.switchModel({ sessionID, model: next })  // fire and forget
      event.decision = { retry: true, delay: 3000 }
    })

    Safety net — when retries exhaust and the session halts, session.execution.failed plus a queued prompt resumes it:

    for await (const event of ctx.event.subscribe({ types: ["session.execution.failed"] })) {
      await ctx.session.switchModel({ sessionID, model: next })
      await ctx.session.prompt({ sessionID, text: "Continue where you left off.", delivery: "queue" })
    }

    Verified end-to-end on a session pinned to a model with an exhausted free-tier limit: it switched through two models and completed the task with no user action.

    Gap 1: the race the bot described

    Because RetryDecision has no model field, the switch and the retry are two separate operations with no ordering guarantee. switchModel is async and the retry fires after delay. I use 3000 ms as a fudge factor. If the switch is slower than that, the retry goes out on the dead model and burns another attempt.

    This is the whole reason it belongs in core: the plugin has to guess how long a state change takes.

    Proposed minimal change

    type RetryDecision =
      | { retry: false }
      | { retry: true; delay: number; model?: { providerID: string; id: string } }

    The hook names the replacement atomically and the race disappears. Backwards-compatible union widening. This is the "small addition" the bot referred to.

    Gap 2: attempt is not a useful bound across a chain

    Related and worth calling out. The retry hook gets attempt, but that counter is shared across every model in a fallback chain, so a plugin cannot tell "this is the third model" from "this is the third retry of the same model".

    I originally wrote if (event.attempt > 4) return and it silently truncated an eight-model chain at the fifth entry. The fix was to bound by chain length instead, but that is a workaround. If the decision carried the model, an attemptsPerModel notion would fall out naturally.

    Gap 3: two events racing cause a switch loop

    This one is a genuine bug that produced a visible ping-pong:

    model-switched: refuseless/x → tokenharbor/y
    model-switched: tokenharbor/y → refuseless/x
    model-switched: refuseless/x → tokenharbor/y
    

    all within ~2 seconds. Cause: I updated the plugin's notion of "current model" before switchModel resolved, so a session.execution.failed arriving mid-switch read the stale value and started a second switch. Fixed with a per-session lock that clears on the next experimental.model.resolve.

    A { retry: true, model } decision removes the class of bug entirely, because there is no window between "decide to switch" and "retry on the new model" for a second event to land in.

    Gap 4: the halt loses step context

    After retries exhaust, the session halts. The only recovery a plugin has is session.execution.failed plus a queued prompt. It works, but:

    • it appears in the transcript as a new user turn rather than a continuation
    • the in-flight step context is gone, so the model re-orients instead of resuming
    • any pending tool call in that step is dropped

    Keeping the agent loop alive across a model switch — rather than halting and re-prompting — would be worth more than the queue hack. A model on the retry decision gets this for free.

    Provider cooldown (echoing @moritzWa)

    Confirmed necessary, and it needs to outlive the process. Without it, every new chat walks the chain from the top and burns a failed request on each provider already known to be dead. I persist cooldowns through ctx.storage with a TTL: 30 min for quota/credit/dead-key, 2 min for a rate limit. A successful run clears the entry.

    Detecting a provider that has no credentials

    Worth documenting because it was not obvious and I got it wrong first.

    ctx.integration.list() returns a { location, data } envelope, not a bare array, so the obvious list.filter(...) sees nothing. The reliable call is per provider:

    const active = await ctx.integration.connection.active(providerID)  // null when unconfigured

    Skipping those before any request is valuable: a provider can sit at the top of a chain before its key is added, costing nothing. My first two attempts silently failed and wasted a request per turn against a 401.

    Free-first ordering

    The concrete reason I built this: I want free tiers tried before spending anything, then the cheapest paid model, with a specific provider order inside each tier.

    {
      "model": "tokenharbor/deepseek-v4.1-flash:free",
      "fallback": {
        "models": [
          "tokenharbor/mimo-v2.6-flash:free",
          "openrouter/google/gemma-4-31b-it:free",
          "opencode/deepseek-v4.1-flash-free",
          "refuseless/deepseek-v4.1-flash-fast",
          "opencode/deepseek-v4.1-flash",
          "openrouter/~z-ai/glm-flash-latest"
        ],
        "cooldown": "30m"
      }
    }

    Two notes on the shape:

    • A per-model chain reads better than a top-level array, because "what to fall back to" depends on what you fell back from.
    • Walk forward from the failed model rather than restarting at index 0, so a provider that is down is not retried just because it is listed first.
    • The chain has to stay shorter than the retry allowance (ten attempts per step today). Nine entries is about the practical ceiling, which is a third argument for the counter being per model.

    This is the explicit answer to #63958

    #63958 reports that OpenCode's current implicit fallback switched a user from a free model to a paid glm-5.2 they had deliberately excluded, costing $12.94 in a day.

    A configured chain fixes that by construction: the chain is authored by the user, so a paid model is only ever reached because the user listed it. Everything not in the chain is out of bounds. My plugin additionally refuses to leave the chain at all — if every entry is exhausted it stops and surfaces the error rather than improvising.

    That distinction seems worth encoding in core: implicit fallback (pick something that works) versus explicit fallback (walk the list I gave you). The bug in #63958 is the former; this request and #64222 are the latter.

    Triggers I ended up using

    Status codes are inconsistent across providers, so message matching is unavoidable:

    • status 401, 402, 403, 404, 429
    • quota, credit, balance, billing, insufficient, usage limit, limit reached, daily limit
    • rate limit, too many requests, overloaded, capacity
    • no such model, model not found, invalid api key, unavailable

    Explicitly excluded and checked first: context overflow, content filter, user abort. Those must still surface normally.


    Happy to open a PR for the RetryDecision.model widening if that shape is acceptable. It is a small change and I can include the reference plugin as a test fixture — it is a single file with no dependencies, and it now covers free-tier-first ordering, persistent cooldowns, credential-aware skipping, and the resume path.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

  • @neriousy
    neriousy

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

    You are visitor 01402775 — GeezerVison does not store the pages you look up.
    Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.