Skip to content

feat: route around models whose context window can't hold the input - #147

Merged
stackbilt-admin merged 7 commits into
mainfrom
feat/context-window-routing
Nov 8, 2026
Merged

stackbilt-admin merged 7 commits into
mainfrom
feat/context-window-routing

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Summary

First slice of the long-context work on #136 (and the "long context checked through fallback" item on #113). It adds opt-in context-window routing, contextWindowRouting: true, and a better input estimate.

Correction to the earlier premise. The #136 audit said an overflow error "doesn't fall back, so the request fails". Under the default config that is wrong. The built-in fallback rules include a catch-all error rule, so an overflow already falls back to the next provider. The overflow only ends the request with fallbackRules: []. The real cost of sending an oversized request is one failed call, which may be billed or rate-limited.

Saving that call also means a skipped provider can't absorb a transient failure of the provider that fits. That is a fair trade for some callers, but not a reason to change behaviour by default. So the check is off unless you turn it on.

With contextWindowRouting: true

  • When providers are skipped. buildProviderPlan computes the estimate once. If a provider that can be relied on right now has a planned model whose maxContextLength holds the estimate, the providers whose planned model can't hold it are marked to be skipped.
    • "Relied on" means configured, not quota-exhausted or ledger-limited, and with a fully closed circuit breaker. The breaker state is read without creating a breaker.
  • How a skip is recorded. At dispatch the skipped provider shows errorCode: 'CONTEXT_WINDOW' in fallback.failedAttempts, on the response and on StreamCompletion. This check runs after the exhausted, breaker and ledger checks, so those skip codes keep priority.
  • What doesn't change: the fallback chain, planned models and catalog ranking stay as on main. A 14,000-case buildProviderPlan probe against main found the same chain and models in every case.
  • Paths covered: generateResponse, each turn of generateResponseWithTools, generateManagedResponseStream and generateResponseStream. The client getRoutingInfo reports the first provider that wouldn't be skipped.
  • Pinned models are never skipped.
  • Fallback rules: a provider that one of the caller's own fallbackRules targets is tried as usual, including one skipped earlier in the chain, which is queued right after the provider that failed (at most once). The built-in default rules don't override a skip.
  • allowFallback: false without a pin: a skipped first provider throws NoRouteError naming CONTEXT_WINDOW. No other provider is substituted.
  • Response cache: the option is part of the cache key when it's on, so default keys don't change.

Without it (default)

Dispatch is the same as on main. Tests check that leaving the option unset or setting it to false skips nothing and falls back as before. Planning creates no breakers and calls no logger.

The estimate (always on)

  • What it counts: characters ÷ 4 of the system prompt and each message's text (or the provider-native text and thinking, when larger), plus tool-call arguments, tool results and errors.
  • What it leaves out: tool definitions, images and encrypted redacted thinking. Nothing is serialized.
  • Malformed fields count as zero.
  • Cost: a 200-turn tool loop with 60 KB tool inputs plans in about 0.13 ms (0.05 ms on main).
  • Visible effects: RoutingInfo.estimatedInputTokens and the gateway context-length warning are now higher for tool-loop requests. Use-case inference still counts message text only, and no longer throws on malformed fields.

Validation

  • Checks: npm run typecheck, npm test (946 tests), npm run build, npm run test:package, npm run test:worker-import and git diff --check all pass.
  • Equivalence probe against a main worktree: 14,000 buildProviderPlan cases with identical chain and planned models. The cases covered:
    • 8 provider sets;
    • 9 availability states;
    • preferredProvider and enableCircuitBreaker variants;
    • text, tools, tool-loop, vision, allowFallback: false, pinned and maxTokens requests;
    • 8 sizes, from 10 to 1.1M tokens.
  • Mutation checks: each of these, when disabled or broken, fails at least one test:
    • the default-off condition;
    • the built-in rule exemption;
    • the cache key, including that false keeps the default key;
    • skip-code order;
    • the availability check;
    • the rule exemption for the caller's own rules;
    • the streaming skip;
    • no breaker creation and no logging while planning;
    • tool-result counting;
    • text-only inference.
  • No live or billable requests.

Tests

src/__tests__/context-window-routing.test.ts has 41 tests:

  • Estimate and ranking: the estimate, and unchanged catalog ranking.
  • Default behaviour: off by default (unset and false).
  • Skips: the skip record on the response and the managed stream; the tool loop, both as a raw turn and through generateResponseWithTools.
  • Availability: exhausted, open (default config and enableCircuitBreaker), degraded, recovering and ledger-limited providers; three providers with nothing skipped.
  • Side effects: none while planning.
  • Interactions:
    • skip-code order;
    • the cache key;
    • preferredProvider;
    • allowFallback: false, which throws NoRouteError;
    • strict reasoning;
    • images;
    • pinned models;
    • client routing info;
    • the caller's own rules versus the built-in default rules, including a rule target skipped earlier in the chain and fallbackRules: null;
    • turning the option on, or setting fallbackRules, through updateConfig.

API

  • Added: contextWindowRouting?: boolean on ProviderFactoryConfig. It is off by default, documented and tested.
  • No new export. estimateRequestInputTokens and fitsContextWindow are internal to model-catalog.ts.
  • Docs: the README has a "Context windows (opt-in)" section. The CHANGELOG [Unreleased] section has Added (the option) and Changed (the estimate).
  • Release: minor.

Not in this PR (later slices on #136)

  • Switching a provider to a larger model of its own.
  • Falling back after a provider's context-overflow error, for pinned models.
  • Output limits: maxOutputTokens, and the Workers AI default of 256 output tokens.
  • Letting callers pass an exact input token count.

🤖 Generated with Claude Code

kovermier and others added 6 commits November 8, 2026 12:23
The factory now skips providers whose planned model's context window is
smaller than the request's estimated input (message and system-prompt
characters / 4), on the response and streaming paths, and throws
NoRouteError before any call when no configured provider's model can hold
it. Such requests used to be sent anyway and failed with an error that
doesn't fall back. Pinned models and fallback rules that name a
fallbackModel are still tried; a rule without a model skips a provider
whose planned model can't hold the input.

Catalog ranking prefers models that can hold the input and keeps its
usual ranking when none can, so the catalog helpers still never throw.
Only the input is checked, not maxTokens. No public API is added.

Part of #113 and #136.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Skip unfitting providers only when some planned model can hold the
  estimate; when none can, routing is unchanged. This removes the new
  pre-call NoRouteError, so an overcounted estimate can't refuse a request
  that works today, and keeps getGatewayRoutePlan consistent with dispatch.
- Count tool-call arguments, tool results and errors, and provider-native
  text (thinking) in the estimate, so tool loops are covered.
- Count non-string content as zero, so the catalog helpers can't throw.
- Run the check after the strict-reasoning filter and before
  allowFallback: false trims the chain.
- Drop the redundant fallback-rule clause; document preferredProvider and
  allowFallback: false behaviour; fix README/CHANGELOG wording.
- Tests: tool loop (including generateResponseWithTools), preferredProvider,
  allowFallback: false without a pin, managed stream, strict reasoning,
  malformed content, getRecommendedModel / getProviderDefaultModel.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Second review round on #147:
- Decide whether a hop fits using only providers that can be tried now
  (configured, not quota-exhausted, circuit-open or ledger-limited), so a
  fitting provider that is down no longer drops the smaller ones.
- rankModels drops open-breaker models before narrowing to fitting ones,
  so it can't return [] (and getRecommendedModel can't throw) when healthy
  compatible models exist.
- Restore the fallback-rule guard, applied only while an available hop
  fits, so rules behave as before when nothing fits.
- Count malformed messages, toolCalls, toolResults and providerContent
  blocks as zero instead of throwing; count every provider-native block
  kind (text, thinking, redacted thinking, tool-use input).
- Use-case inference counts message text only, as before.
- Remove the stale rankModels comment; README and CHANGELOG describe the
  availability rule and the higher estimatedInputTokens for tool loops.
- Tests: exhausted and open-breaker fitting provider, open-breaker
  ranking, three-provider rule when nothing fits, malformed containers,
  block kinds, inference, image requests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Third review round on #147, simplifying the design (option A):
- Catalog ranking is back to main's code: rankModels, getRoutingInfo,
  getProviderDefaultModel and getRecommendedModel are unchanged.
- The factory computes the estimate once per plan and only removes
  providers whose planned model can't hold it, when a provider that can be
  relied on now (not exhausted or ledger-limited, breaker fully closed,
  whatever enableCircuitBreaker says) has a fitting model. Providers are
  never reordered or re-planned, so routing is unchanged otherwise.
- Fallback rules behave exactly as on main.
- The estimate no longer serialises tool-use input (the same data is in
  toolCalls arguments) and leaves out encrypted redacted thinking; a
  200-turn loop plans in about 0.13 ms (main 0.05 ms).
- Validated with a 14,000-case planning probe against a main worktree:
  same planned models everywhere, chains identical or main's chain minus
  non-fitting providers (only when an available provider fits), small
  requests identical, allowFallback: false picks the first provider of the
  full chain.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fourth review round on #147:
- Instead of removing providers from the chain at planning, record them
  in the plan and skip them at dispatch with errorCode CONTEXT_WINDOW, so
  the skip shows in fallback.failedAttempts and requestedProvider is the
  real first planned provider. The chain is now always main's chain.
- allowFallback: false without a pin: a skipped first provider throws
  NoRouteError (as for other skips) rather than substituting another.
- A provider that a fallback rule targets is tried as before.
- New factory option contextWindowRouting (default true); false routes
  without the check.
- Planning has no side effects: breaker state is read without creating a
  breaker, and the ledger check doesn't log.
- Tests: skip record on response and stream, NoRouteError, the switch,
  degraded and recovering breakers, ledger-limited provider without
  planning logs, no breaker creation. README and CHANGELOG describe the
  transient-failure trade-off and the switch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fifth review round on #147. Under the default config an overflow error
already falls back through the built-in catch-all `error` rule, so the
check's real benefit is saving one failed (possibly billed) call, while
it costs recovery from a transient failure of the fitting provider.
That doesn't justify a default-on behaviour change:
- contextWindowRouting is now off by default; with it unset or false,
  dispatch matches main.
- Only the caller's own fallbackRules override a skip; the built-in
  defaults (including the catch-all) don't.
- The option is part of the response cache key when on; default keys
  are unchanged.
- The CONTEXT_WINDOW check runs after the exhausted, breaker and ledger
  checks on both paths, so existing skip codes keep priority; skips log
  at debug level.
- Docs rewritten around the real benefit and trade-off; CHANGELOG lists
  the option under Added.
- Tests: default-off (unset and false), built-in rules, skip-code order,
  cache key, no logger calls while planning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sixth review of #147:
- A caller's own fallback rule targeting a provider that was skipped as
  CONTEXT_WINDOW earlier in the chain now queues it right after the failed
  provider (at most once), instead of never trying it.
- fallbackRules: null keeps the built-in rules and is no longer treated as
  caller-supplied.
- README: separate the pinned-provider and CONTEXT_WINDOW cases in the
  allowFallback paragraph.
- CHANGELOG: narrow the malformed-input claim; non-array messages or a null
  message still throw in catalog getRoutingInfo, as before.
- Tests for the above and for updateConfig toggles.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stackbilt-admin
stackbilt-admin merged commit 8f78d2f into main Nov 8, 2026
2 checks passed
@stackbilt-admin
stackbilt-admin deleted the feat/context-window-routing branch November 8, 2026 23:49
stackbilt-admin pushed a commit to mikemikimike/llm-providers that referenced this pull request Nov 9, 2026
Resolve the CHANGELOG conflict with 1.26.0 and Stackbilt-dev#147, describe the timeout
behaviour without naming a release (it ships in the next one), and restore
the blank line before ## [1.24.1].

Co-Authored-By: Claude Opus 5.5 <[email protected]>
stackbilt-admin added a commit that referenced this pull request Nov 9, 2026
* chore: release 1.27.0

- Opt-in context-window routing and a better input estimate (#147)
- Workers AI non-streaming binding timeout (#132)
- Checkpoint and README version references updated

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: 1.27.0 upgrade note for the Workers AI timeout and review fixes

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Kurt Overmier <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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.

2 participants