Skip to content

feat: check pinned models against their context window (#136) - #163

Merged
stackbilt-admin merged 4 commits into
mainfrom
feat/136-pinned-overflow
Nov 11, 2026
Merged

stackbilt-admin merged 4 commits into
mainfrom
feat/136-pinned-overflow

Conversation

@stackbilt-admin

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

Copy link
Copy Markdown
Member

Part of #136 (long-context slice: checking pinned models against their context window).

What

New opt-in factory option, contextWindowPinCheck (off by default). It checks a pinned catalog model (request.model) against its context window before any call, using the caller's inputTokenCount when set, else the estimate.

  • When nothing else may serve the request: a pinned model too small for the input throws the new ContextWindowExceededError, and no call is made. That happens with allowFallback: false, and when no other provider with a planned model that holds the input can be called: one provider configured; reasoning.strict or an image request removed the rest; the others' planned models are too small too; or every provider that fits is unavailable (quota-exhausted, circuit open, ledger-limited). The error carries modelProvider, model, contextWindow, inputTokens, inputTokensSource ('caller', 'mixed' or 'estimate') and reason ('allowFallback-false' or 'no-other-provider'). Its message never includes the prompt.
  • Otherwise: the pinned provider is skipped as CONTEXT_WINDOW in fallback.failedAttempts, and so is every other provider whose planned model can't hold the input, with or without contextWindowRouting. The request goes only to providers that fit; if that provider then fails (for example 503 or 429), its error is thrown rather than falling through to a smaller model. A caller's fallbackRules entry brings the provider back only when it names a different fallbackModel (compared after model-ID correction), so the pinned model is never called. That different model is sent unchecked.
  • 'mixed' counts: your inputTokenCount plus the package's estimate of what it added (tool-loop turns, or the system prompt classify supplies). The mark is kept outside the request, in a WeakSet, so response cache keys aren't affected.
  • Not checked: pinned models outside the catalog, and unpinned requests.
  • Where it applies: the response and streaming paths, each turn of generateResponseWithTools (with fallback allowed, a turn that outgrows the pin moves to another provider partway through the loop), classify, analyzeImage, and the client getRoutingInfo. The option is part of the response cache key when on, so default keys don't change.

This covers the campaign-continuity need in #136 that "a request whose input estimate … passes the window fails before the call, with a typed error", for pinned models.

Design choices

  • A separate option: the README promises that contextWindowRouting never skips a pinned model ("its provider decides"), so changing that option wouldn't be additive.
  • ContextWindowExceededError extends NoRouteError and keeps code NO_ROUTE. Code that already handles the allowFallback: false routing failures keeps working, and the new class adds structured details.
  • Input only, not maxTokens: the same rule as contextWindowRouting, because providers differ on whether the requested output must also fit. Output limits are the remaining Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136 slice.
  • Estimate risk: without inputTokenCount, the check uses the characters ÷ 4 estimate, so a pin near the edge of its window could be rejected although it would fit. The README says to pass inputTokenCount when that matters.

Review fixes (after the first adversarial review)

  • A caller's fallback rule pointing at the pinned provider used to clear the skip and call the oversized pin. Now it brings the provider back only with a different fallbackModel.
  • A skip that left no other provider ended in an untyped ALL_PROVIDERS_FAILED. It now throws ContextWindowExceededError with reason: 'no-other-provider', which covers the Workers-AI-only case in Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136.
  • inputTokensSource said 'caller' for tool-loop and classify counts that are partly estimated. These are now 'mixed', and the mark carries over when an outdated model ID is corrected.
  • Tests added for the tool loop, classify, fallback rules with and without a different model, reasoning.strict, image requests, model-ID correction, and caching for marked requests.
  • README: the error-class table, the getRoutingInfo text, and the pin-check section (dead ends, fallback rules, 'mixed', tool loops stopping after earlier tools have run). The debug log wording and the sweep checkpoint are also fixed.
  • Not changed: LLMProviders.fromEnv() still can't set this option, contextWindowRouting or contextWindowModelSwitch. That's left for the existing fromEnv cleanup.

Review fixes (after the second adversarial review)

  • The fallback-rule guard compared raw strings, so a rule naming the pinned model by an outdated ID (corrected only by the adapter) brought it back and sent the oversized input. The rule's model is now corrected before the comparison.
  • A pin skip followed by every other provider being unavailable ended in ALL_PROVIDERS_FAILED (or a plain NoRouteError from getRoutingInfo). The response and streaming paths and getRoutingInfo now throw ContextWindowExceededError with reason: 'no-other-provider'.
  • Built-in fallback rules no longer rewrite the skipped pin's planned model.
  • The streaming path's request copy keeps the partly-estimated mark.
  • The README says a rule's different model is sent unchecked. The JSDoc, CHANGELOG and sweep checkpoint cover the "rest unavailable" case.
  • Kept as designed: ContextWindowExceededError extends NoRouteError (and so ConfigurationError), for compatibility with existing NoRouteError handling.

Review fixes (after the third review and two narrow re-checks)

  • A pin skip could still send the oversized input to a smaller, unpinned model: first when no other planned model fit, then when the provider that fit was unavailable. Now the "no other provider" check counts only providers whose planned model fits, and a pin skip also skips every other provider too small for the input, so the request goes only to a provider that fits or throws ContextWindowExceededError ('no-other-provider'). The last narrow re-check confirmed this on all three paths, with routing on and off and with exhausted, circuit-open and ledger-limited fitting providers, and found no remaining route except a caller's own fallbackRules (documented). Its verdict was LGTM.
  • Trade-off: if the provider that fits fails at call time (503, 429), the request fails with that error instead of falling through to a smaller model. A caller's rule that would have brought the pin back on a larger model after an overflow no longer gets the chance; the CHANGELOG notes it.
  • Docs corrected: tool loops move provider mid-loop when fallback is allowed; analyzeImage and classify are covered; the contextWindowRouting fallback-rule exception; the error's model is the corrected ID; quotaHook denials stay QuotaDeniedError.

Files

  • src/errors.ts, src/index.ts: ContextWindowExceededError, exported.
  • src/utils/input-token-count.ts (internal): the partly-estimated mark.
  • src/factory.ts: the option, a planner block after the context-window skips and before the allowFallback: false trim, the fallback-rule guard, the tool-loop and classify marks, and a cache-key entry.
  • src/__tests__/context-window-pin-check.test.ts (new, 38 tests). Disabling the rejection, either no-other-provider throw, the skip, the fallback-rule guard (including ID correction and built-in rules), the partly-estimated marks, the cache-key entry or the exact-window boundary each makes tests fail, as does dropping the fitting-model check or the extra skips. Tests cover no fitting fallback, an unavailable fitting provider (quota, circuit, ledger), chain order and the tool-loop fallback.
  • README ("Checking pinned models" under "Context windows", plus the allowFallback section), CHANGELOG [Unreleased], and the sweep checkpoint.

Validation

npm run typecheck, npm test (1,112 passing across 37 files), npm run build, bash scripts/package-smoke.sh, npm run test:worker-import, git diff --check: all passed. No live or billable requests were made.

🤖 Generated with Claude Code

kovermier and others added 4 commits November 10, 2026 12:06
New opt-in factory option, contextWindowPinCheck. A pinned catalog model
whose window can't hold the request's input (inputTokenCount, else the
estimate) is never called: with allowFallback: false the request throws
the new ContextWindowExceededError (a NoRouteError with the model, window
and token count), otherwise the pinned provider is skipped as
CONTEXT_WINDOW and the request falls back as usual. Models outside the
catalog and unpinned requests aren't checked. The option is part of the
response cache key when on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A caller's fallback rule brings a pin-check-skipped provider back only
  with a different fallbackModel, so the pinned model is never called.
- When no other provider is left in the plan (one provider configured,
  or reasoning.strict or an image request removed the rest), the request
  throws ContextWindowExceededError instead of an untyped dead end. The
  error gains `reason` ('allowFallback-false' | 'no-other-provider').
- inputTokensSource gains 'mixed' for a caller count plus the package's
  estimate (tool-loop turns, classify's system prompt), tracked in a
  WeakSet so response cache keys are unaffected.
- Tests for the tool loop, classify, fallback rules, strict reasoning,
  images, model-ID correction and caching; README and CHANGELOG updated.

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

- The fallback-rule guard compares the rule's fallbackModel after
  model-ID correction, so an outdated ID can't bring the pin back.
- When the pin is skipped and every other provider is unavailable, the
  response and streaming paths and getRoutingInfo throw
  ContextWindowExceededError (reason 'no-other-provider').
- Built-in fallback rules leave a skipped pin's plan untouched.
- The streaming path's request copy keeps the partly-estimated mark.
- README notes that a rule's different model is sent unchecked; docs and
  the sweep checkpoint updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviews found that a pin skip could still hand the oversized input to a
smaller, unpinned model: when no other planned model fit, or when the
provider that fit was unavailable. Now, when contextWindowPinCheck skips
the pin, every other provider whose planned model can't hold the input
is skipped too, with or without contextWindowRouting, and the request
throws ContextWindowExceededError ('no-other-provider') when no
provider that fits can be called.

Docs cover the tool-loop fallback, fallback-rule exceptions, analyzeImage,
the corrected model ID, and the 503/429 trade-off. Tests cover no
fitting fallback, an unavailable fitting provider (quota, circuit,
ledger), chain order and the tool-loop fallback.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@stackbilt-admin
stackbilt-admin merged commit b4f4fb4 into main Nov 11, 2026
4 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.

2 participants