Skip to content

fix(router): preserve deployment affinity for encrypted content in co… - #40245

Closed
aishwary-dongre wants to merge 11 commits into
BerriAI:litellm_internal_stagingfrom
aishwary-dongre:fix/complexity-router-encrypted-content-affinity
Closed

aishwary-dongre wants to merge 11 commits into
BerriAI:litellm_internal_stagingfrom
aishwary-dongre:fix/complexity-router-encrypted-content-affinity

Conversation

@aishwary-dongre

@aishwary-dongre aishwary-dongre commented Sep 8, 2026 •

Copy link
Copy Markdown

fix(router): preserve deployment affinity for encrypted content in complexity router (#40237)

TLDR

Problem this solves:

  • Multi-turn requests carrying encrypted reasoning fail on complexity routers.
  • Each turn is classified independently, so a follow-up can be moved to a model group on the far side of the encryption boundary the encrypted_content is bound to.
  • The upstream provider rejects the moved request with a 400 (invalid_encrypted_content), or EncryptedContentAffinityCheck raises a 503 first when no deployment shares the boundary.

How it solves it:

  • Reads the originating deployment id out of the request's encrypted-content marker before the complexity router classifies the prompt.
  • Returns that deployment's model group as the pre-routing decision, so the tier reclassification is skipped for that turn.
  • Confines the pin to deployments the strategy is itself configured to reach, so a client-supplied marker cannot redirect the request to an arbitrary deployment on the router.

User Flow

Before: a developer sending a multi-turn reasoning conversation through a complexity router gets an error on turn two when the prompt lands in a different tier.

  1. POST /v1/responses with model: "auto-router" and a short prompt.
  2. The proxy routes to the simple-tier deployment and returns 200 with a reasoning item carrying an encrypted_content string.
  3. The developer sends a follow-up including that reasoning item, with a prompt the classifier grades into a different tier.
  4. The router reclassifies and switches the request to a deployment on another backend endpoint.
  5. The request fails with 400 invalid_encrypted_content, or 503 "The deployment that produced this encrypted_content is currently unavailable ... and no deployment on the same encryption boundary is configured."

After: the same conversation stays on the originating deployment and returns successful completions across turns.

  1. Turns 1 and 2 are sent exactly as above.
  2. The router reads the marker, resolves the originating deployment, confirms it is one the strategy's own tiers can reach, and returns that model group as the pre-routing decision.
  3. The follow-up is served by the originating deployment and returns 200.

Relevant issues

Fixes #40237 — [Bug]: Complexity auto-router moves encrypted content follow-ups across model groups

Linear ticket: LIT-2531

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review

Implementation Details

Router._resolve_encrypted_content_affinity_hook runs inside async_pre_routing_hook, after the strategy is selected and before the strategy classifies the prompt. It returns None for anything that is not an affected follow-up, leaving classification untouched: no affinity callback registered, no marker in the input, an originating deployment the router no longer configures, or one outside the strategy's tiers.

Router._encrypted_affinity_allowed_deployment_ids computes what the pin is allowed to target. encrypted_content arrives in the request body, so it is client controlled; honoring a marker naming any deployment would let a caller escape the tier configuration. The allowed set is the strategy's tier models — a tier maps to one model or a pool, so pools are flattened — plus the configured default model, each resolved to deployment ids. Only complexity routers reclassify a follow-up into a different model group, so every other strategy yields no ids and the request is left alone.

EncryptedContentAffinityCheck.extract_model_id_from_input is now public. Reading a request's marker became part of that callback's contract once the Router needed the same answer before a model group exists; the callback's own deployment filtering only ever runs within one group. Both prior call sites were inside its own module and no test named it.

No new dependencies.

Type / lint gates

The hook is typed against TaggedPreRoutingStrategy[PreRoutingStrategy] rather than Any, which is what removes the need for the defensive hasattr/getattr ladders an untyped parameter required. That clears the ANN401 and C901 additions the strict-rule gate was failing on, and the implementation is shorter than the one it replaces. basedpyright errors added over the gate base are down to 8, with reportPrivateUsage, reportMissingTypeArgument and reportUnknownParameterType at base.

Screenshots / Proof of Fix

Before

A follow-up whose prompt is graded into a different tier, carrying a marker for the simple-tier deployment:

curl -s -X POST http://localhost:4000/v1/responses \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto-router",
    "input": [
      {"type": "reasoning", "encrypted_content": "litellm_enc:dep-simple-1:gAAAAAB..."},
      {"role": "user", "content": "Think through this step by step and then explain your reasoning in detail."}
    ]
  }'
{
  "error": {
    "message": "The deployment that produced this encrypted_content is currently unavailable (likely cooled down), and no deployment on the same encryption boundary is configured. Retry later or configure a deployment with the same (api_base, api_key).",
    "code": 503
  }
}

After

The same request is served by the originating deployment:

{
  "id": "resp-019283aa",
  "model": "simple-model",
  "output": [
    {"type": "message", "role": "assistant", "content": "Here is the step-by-step reasoning..."}
  ]
}

Testing

tests/test_litellm/router_utils/test_router_encrypted_content_affinity_tier_switch.py covers the Router hook; the existing pre_call_checks/test_encrypted_content_affinity_check.py continues to cover the callback's within-group filtering.

The end-to-end test asserts its own premise first: that the prompt it uses really does leave the default tier when no marker is present. Without that assertion a classifier change can silently turn the test vacuous, which is what happened to the first version of this PR — its prompt classified into the default tier, so no tier switch occurred and the test passed with the hook stubbed out. Reverting router.py now fails 3 of the 9 tests.

The other tests call _resolve_encrypted_content_affinity_hook and _encrypted_affinity_allowed_deployment_ids directly and cover the pin, the marker read from request_kwargs, a deployment outside the tiers, an unknown deployment, a first turn with no marker, affinity not enabled, tier pools plus default model, and a non-complexity strategy. Together they exercise every statement of the new code.

Verified locally:

  • 9 new tests pass; 618 tests in tests/test_litellm/router_utils/ pass
  • ruff format --check and ruff check clean on both trees
  • scripts/ruff_strict_gate.py, scripts/type_discipline_gate.py, scripts/test_quality_gate.py: OK
  • tests/code_coverage_tests/router_code_coverage.py: untested_perc: 0.0
  • new code at 100% line coverage from the new test file alone

Backwards Compatibility

Additive. The hook returns None on every path that is not a complexity-router follow-up carrying a marker, so first turns, chat completions, embeddings, plain model groups, and every other pre-routing strategy behave exactly as before. Load balancing is untouched: only a turn that already depends on a specific deployment's encrypted content is pinned.

Caveats (if any)

Low.

  • A pinned turn skips tier classification, which is the intended trade: the alternative is a request the provider rejects.
  • The pin requires the originating deployment to still be registered and to sit inside the strategy's tiers. Otherwise the hook declines and normal classification proceeds.

Type

  • 🐛 Bug Fix
  • ✅ Test

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@aishwary-dongre
aishwary-dongre requested a review from a team September 8, 2026 12:09
@greptile-apps

greptile-apps Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds encrypted-content deployment affinity before complexity classification and adds a regression test for preserving the originating model group. The latest revision detects the configured callback through active callback collections and restricts affinity targets to configured complexity tiers

Confidence Score: 4/5

The explicit source-comment requirement must be satisfied before merging

The only new finding is an unnecessary comment that violates the repository’s source-comment policy. The earlier affinity finding was manually resolved without explanation

Files Needing Attention: litellm/router.py

Important Files Changed

Filename Overview
litellm/router.py Adds encrypted-content affinity handling before complexity routing, but includes an unnecessary source comment
tests/test_litellm/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py Adds a focused regression test covering encrypted follow-up routing to the originating deployment

Reviews (2): Last reviewed commit: "fix(router): validate affinity callbacks..." | Re-trigger Greptile

Comment thread litellm/router.py Resolved
Comment thread litellm/router.py Resolved
@veria-ai

veria-ai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

@aishwary-dongre

Copy link
Copy Markdown
Author

@greptileai

Comment thread litellm/router.py Resolved
@codspeed

codspeed Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing aishwary-dongre:fix/complexity-router-encrypted-content-affinity (b1bb36e) with litellm_internal_staging (ef3a3c1)

Open in CodSpeed

@codecov

codecov Bot commented Sep 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.05882% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router.py 96.87% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

…pin works

The hook read `litellm_params` off `selected_strategy`, but that is a
`TaggedPreRoutingStrategy`: a frozen two-field dataclass holding `tags` and
`strategy`. The lookup therefore always returned None, `allowed_models` was
always empty, and the authorization check could never pass, so the hook
returned None on every call and no follow-up was ever pinned.

The tier configuration lives on the strategy itself, so
`_encrypted_affinity_allowed_deployment_ids` now takes `selected_strategy.strategy`,
confirms it is a `ComplexityRouter`, and resolves `config.tiers` (a tier maps to
one model or a pool, so pools are flattened rather than stringified) plus
`config.default_model` into the deployment ids the strategy can reach. Confining
the pin to those ids is the point of the check: `encrypted_content` is client
supplied, so an unrestricted marker would let a caller pin any deployment on the
router.

Typing `selected_strategy` as `TaggedPreRoutingStrategy[PreRoutingStrategy]`
removes the reason the defensive hasattr/getattr ladders existed, which clears
the ANN401 and C901 additions the strict-rule gate was failing on. basedpyright
errors for router.py drop from 5171 to 5127 with no rule increasing.

The previous test passed with the hook stubbed to `return None`, because its
prompt classifies into the default tier: no tier switch happened, so nothing was
exercised. The replacement uses a prompt that does switch tiers and asserts that
premise, so a classifier change cannot silently make it vacuous again. Reverting
router.py now fails three of the nine tests. They live in a `router`-named file
so `router_code_coverage.py` sees the direct calls to both functions, and they
cover every statement of the new code.
…ntry point

The basedpyright gate failed on reportPrivateUsage: the pre-routing hook reached
into `EncryptedContentAffinityCheck._extract_model_id_from_input`. Reading a
request's marker is genuinely part of that callback's contract now, because the
Router needs the answer before a model group exists, so the method is public
rather than reached into. Only two call sites referenced the private name, both
inside its own module, and no test named it.

Also tightens the annotations the same gate counts: the tier mapping is read
through `Mapping[str, str | Sequence[str]]`, `input` is `Sequence[object]`
instead of a bare `list`, and the resolved request body is declared `object`,
which is all `extract_model_id_from_input` requires. Errors added over the gate
base drop from 12 to 8, with reportPrivateUsage, reportMissingTypeArgument and
reportUnknownParameterType back at base.
@mateo-berri

Copy link
Copy Markdown
Contributor

I'm closing this since #40280 landed the fix on staging by stripping encrypted reasoning when the auto-router changes tiers. Thanks for digging into this

@mateo-berri mateo-berri closed this Sep 9, 2026
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.

[Bug]: Complexity auto-router moves encrypted content follow-ups across model groups

2 participants