The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(shadow_eval): add reverse-direction shadow eval jobs (#36865)
tin-berri2d3c3e30986a
diff --git a/litellm-proxy-extras/litellm_proxy_extras/migrations/20260813180408_add_shadow_eval_direction/migration.sql b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260813180408_add_shadow_eval_direction/migration.sqlnew file mode 100644index 00000000000..57c9abab07d--- /dev/null+++ b/litellm-proxy-extras/litellm_proxy_extras/migrations/20260813180408_add_shadow_eval_direction/migration.sql@@ -0,0 +1,8 @@+-- AlterTable+ALTER TABLE "LiteLLM_ShadowEvalJob" ADD COLUMN "baseline_model" TEXT,+ADD COLUMN "direction" TEXT NOT NULL DEFAULT 'forward';++DROP INDEX IF EXISTS "LiteLLM_ShadowEvalJob_one_active_per_key";++CREATE UNIQUE INDEX IF NOT EXISTS "LiteLLM_ShadowEvalJob_one_active_per_key_direction"+ ON "LiteLLM_ShadowEvalJob"("api_key_id", "direction") WHERE "stopped_at" IS NULL;diff --git a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma b/litellm-proxy-extras/litellm_proxy_extras/schema.prismaindex 79d778fb464..71345d2ccde 100644--- a/litellm-proxy-extras/litellm_proxy_extras/schema.prisma+++ b/litellm-proxy-extras/litellm_proxy_extras/schema.prisma@@ -1450,15 +1450,20 @@ model LiteLLM_AutoRouterSession {@@index([last_turn_at], map: "idx_autorouter_session_last_turn")}-// Shadow eval: pre-adoption evaluation of an auto-router against a key's live traffic.-// A sampled slice of requests is duplicated through the router in a detached task and an-// LLM judge compares real vs shadow responses blind. The job row is immutable config plus+// Shadow eval: evaluation of an auto-router against a key's live traffic, in either+// direction. forward duplicates the requests the key did not route through the router+// through it, answering whether the key should adopt it; reverse duplicates the requests+// the router did serve against a fixed baseline model, answering whether a key already on+// it still benefits. Either way a sampled slice runs in a detached task and an LLM judge+// compares real vs shadow responses blind. The job row is immutable config plus// stopped_at; every count, status, and spend figure is derived from the append-only// attempt rows, so nothing can disagree across pods or stop races.model LiteLLM_ShadowEvalJob {id String @id @default(cuid())api_key_id String // hashed virtual key whose traffic is shadowed- router_name String+ router_name String // the auto-router under evaluation, in either direction+ direction String @default("forward") // forward | reverse+ baseline_model String? // reverse only: the fixed model the router is judged againstjudge_model Stringshadow_percentage Floatmax_turns Int // sample budget: judge at most this many turnsdiff --git a/litellm/integrations/shadow_eval_logger.py b/litellm/integrations/shadow_eval_logger.pyindex c7b89e0e9b0..ca9b6982414 100644--- a/litellm/integrations/shadow_eval_logger.py+++ b/litellm/integrations/shadow_eval_logger.py@@ -1,5 +1,6 @@"""Shadow Eval Logger: samples a shadowed key's successful chat requests, duplicates each-through the auto-router in a detached task, blind-judges real vs shadow, and appends one+against the job's other arm in a detached task (the auto-router for a forward job, the+fixed baseline model for a reverse one), blind-judges real vs shadow, and appends one``LiteLLM_ShadowEvalAttempt`` row (verdict or error) as the feature's only hot-path write.Counts, status, and spend derive from those rows at read time, so nothing can disagreeacross pods or stop races; the hook reads active jobs through a short-TTL cache."""@@ -10,10 +11,12 @@ import randomfrom collections.abc import Callable, Mapping, Sequencefrom dataclasses import dataclassfrom datetime import datetime, timezone+from itertools import groupby+from operator import itemgetterfrom types import MappingProxyTypefrom typing import TYPE_CHECKING, Final-from pydantic import BaseModel+from pydantic import BaseModel, ConfigDict, ValidationError, field_validator, model_validatorfrom litellm._logging import verbose_loggerfrom litellm.caching.in_memory_cache import InMemoryCache@@ -28,6 +31,7 @@ from litellm.litellm_core_utils.llm_judge import (parse_json_verdict,)from litellm.litellm_core_utils.redact_messages import should_redact_message_logging+from litellm.types.management_endpoints.auto_router_endpoints import ShadowEvalDirectionfrom litellm.types.utils import SHADOW_EVAL_JUDGE_CALL_ORIGIN, SHADOW_EVAL_ROUTER_CALL_ORIGINif TYPE_CHECKING:@@ -161,13 +165,26 @@ async def _key_or_team_is_over_budget(metadata: Mapping[str, object]) -> bool:return False+def _routing_decision(metadata: Mapping[str, object]) -> Mapping[str, object]:+ """The routing decision a pre-routing strategy wrote to a call's metadata, empty when+ a plain model served it. Read off the sampled request for the control arm, and off the+ shadow call's own write-back for the shadow arm."""+ decision: Final = metadata.get("routing_decision")+ return decision if isinstance(decision, Mapping) else _EMPTY_METADATA+++def _routed_tier(metadata: Mapping[str, object]) -> str | None:+ decision: Final = _routing_decision(metadata)+ raw: Final = decision.get("tier_label") or decision.get("tier")+ return str(raw) if raw is not None else None++def _request_was_routed_by(request_metadata: Mapping[str, object], router_name: str) -> bool:- """Duplicating a request the shadowed router already served compares the router to- itself: guaranteed ties, judge spend for zero information."""- decision: Final = request_metadata.get("routing_decision")- if not isinstance(decision, Mapping):- return False- return decision.get("router_model_name") == router_name+ """Whether the router under evaluation served this request, which is what decides+ the direction it belongs to. A forward job skips its own router's traffic, since+ duplicating it would compare the router to itself: guaranteed ties, judge spend for+ zero information. A reverse job samples exactly that traffic and nothing else."""+ return _routing_decision(request_metadata).get("router_model_name") == router_name@dataclass(frozen=True, slots=True)@@ -197,22 +214,53 @@ class _JudgeVerdict:cost: float-@dataclass(frozen=True, slots=True)-class ActiveShadowEvalJob:- """One active job as the sampling path needs it: immutable config plus the attempt- count as of the cache fill (the turn budget's staleness is bounded by the cache TTL)."""+class ActiveShadowEvalJob(BaseModel):+ """One active job as the sampling path needs it, validated straight off the untyped+ job row: immutable config plus the attempt count as of the cache fill (the turn+ budget's staleness is bounded by the cache TTL). Every way a row can be unsamplable+ is a validation error here, so a bad row is skipped rather than sampled wrongly."""++ model_config = ConfigDict(frozen=True, from_attributes=True)id: strrouter_name: str+ direction: ShadowEvalDirection = "forward"+ baseline_model: str | None = Noneshadow_percentage: floatjudge_model: strmax_turns: intends_at: datetime- attempts: int---def _as_utc(value: datetime) -> datetime:- return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value+ attempts: int = 0++ @field_validator("ends_at")+ @classmethod+ def _as_utc(cls, value: datetime) -> datetime:+ return value.replace(tzinfo=timezone.utc) if value.tzinfo is None else value++ @model_validator(mode="after")+ def _baseline_model_matches_direction(self) -> "ActiveShadowEvalJob":+ if (self.baseline_model is not None) != (self.direction == "reverse"):+ raise ValueError("baseline_model is set for exactly the reverse jobs")+ return self++ @property+ def shadow_target(self) -> str:+ """The model the duplicated arm calls: the router itself for a forward job, the+ fixed baseline for a reverse one. Total because the validator above pins+ baseline_model to reverse jobs and only those."""+ return self.baseline_model or self.router_name+++def _as_active_job(record: object, attempts: int) -> ActiveShadowEvalJob | None:+ """The sampling path's view of one job row, or None for a row it cannot sample: an+ unknown direction, or a reverse job with no baseline model to duplicate against.+ Failing closed here is what keeps the dispatch path total."""+ try:+ job: Final = ActiveShadowEvalJob.model_validate(record)+ except ValidationError as e:+ verbose_logger.debug("shadow_eval: skipping unsamplable job row: %s", e)+ return None+ return job.model_copy(update={"attempts": attempts})_jobs_cache: Final = InMemoryCache(max_size_in_memory=4, default_ttl=_JOBS_CACHE_TTL_SECONDS)@@ -238,8 +286,9 @@ class ShadowEvalLogger(CustomLogger):# generation; the refill absorbs written rows and resets.self._job_starts: dict[str, int] = {} # mutable-ok: per-generation counter- async def _active_jobs(self) -> Mapping[str, ActiveShadowEvalJob]:- """Active jobs by api_key_id, cache-first. A DB fault returns empty without+ async def _active_jobs(self) -> Mapping[str, tuple[ActiveShadowEvalJob, ...]]:+ """Active jobs by api_key_id, cache-first. A key holds at most one job per+ direction, so the value is a collection. A DB fault returns empty withoutcaching, so sampling pauses for that request and the next one retries."""cached: Final = await self._jobs_cache.async_get_cache(_JOBS_CACHE_KEY)if cached is not None:@@ -264,18 +313,19 @@ class ShadowEvalLogger(CustomLogger):else ())attempt_counts: Final = {str(row["job_id"]): int(row["_count"]["_all"]) for row in grouped or []}- jobs: Final = {- str(record.api_key_id): ActiveShadowEvalJob(- id=str(record.id),- router_name=str(record.router_name),- shadow_percentage=float(record.shadow_percentage),- judge_model=str(record.judge_model),- max_turns=int(record.max_turns),- ends_at=_as_utc(record.ends_at),- attempts=attempt_counts.get(str(record.id), 0),+ by_key: Final = tuple(+ sorted(+ (+ (str(record.api_key_id), job)+ for record in records or []+ if (job := _as_active_job(record, attempt_counts.get(str(record.id), 0))) is not None+ ),+ key=itemgetter(0),)- for record in records or []- }+ )+ jobs: Final = MappingProxyType(+ {key: tuple(job for _, job in group) for key, group in groupby(by_key, key=itemgetter(0))}+ )await self._jobs_cache.async_set_cache(_JOBS_CACHE_KEY, jobs)self._job_starts = {} # rebind-ok: new generation, counts absorbed into the fillreturn jobs@@ -308,43 +358,46 @@ class ShadowEvalLogger(CustomLogger):api_key_hash: Final = metadata.get("user_api_key_hash")if not api_key_hash:return- job: Final = (await self._active_jobs()).get(str(api_key_hash))- if job is None:- return- if datetime.now(timezone.utc) >= job.ends_at:- return- if job.attempts + self._job_starts.get(job.id, 0) >= job.max_turns:- returnrequest_id: Final = payload.get("id") or ""if not request_id:return- if not _sample_hits(request_id, job.id, job.shadow_percentage):- returnif payload.get("call_type") not in _SAMPLED_CALL_TYPES:return # only known chat-shaped traffic is comparable; unknown or missing types fail closed- if _request_was_routed_by(request_metadata, job.router_name):- return- if self._inflight_shadow_tasks >= _MAX_CONCURRENT_SHADOW_TASKS:- returnraw_messages: Final = kwargs.get("messages")- self._job_starts[job.id] = self._job_starts.get(job.id, 0) + 1- self._inflight_shadow_tasks += 1- task: Final = asyncio.create_task(- self._run_shadow_eval(- job=job,- request_id=request_id,- messages=tuple(m for m in raw_messages if isinstance(m, Mapping))- if isinstance(raw_messages, Sequence)- else (),- response_obj=response_obj,- real_model=payload.get("model") or "",- model_parameters=MappingProxyType(- dict(payload.get("model_parameters") or {}) # mutable-ok: frozen snapshot- ),- parent_metadata=MappingProxyType(dict(request_metadata)), # mutable-ok: frozen snapshot- )+ messages: Final = (+ tuple(m for m in raw_messages if isinstance(m, Mapping)) if isinstance(raw_messages, Sequence) else ())- task.add_done_callback(self._release_shadow_slot)+ control_tier: Final = _routed_tier(request_metadata)+ # A key can hold one job per direction, and a request routed by one job's+ # router while bypassing the other's qualifies for both. Each is separately+ # budgeted, so both fire.+ for job in (await self._active_jobs()).get(str(api_key_hash), ()):+ if datetime.now(timezone.utc) >= job.ends_at:+ continue+ if job.attempts + self._job_starts.get(job.id, 0) >= job.max_turns:+ continue+ if not _sample_hits(request_id, job.id, job.shadow_percentage):+ continue+ if _request_was_routed_by(request_metadata, job.router_name) != (job.direction == "reverse"):+ continue+ if self._inflight_shadow_tasks >= _MAX_CONCURRENT_SHADOW_TASKS:+ return+ self._job_starts[job.id] = self._job_starts.get(job.id, 0) + 1+ self._inflight_shadow_tasks += 1+ asyncio.create_task(+ self._run_shadow_eval(+ job=job,+ request_id=request_id,+ messages=messages,+ response_obj=response_obj,+ real_model=payload.get("model") or "",+ control_tier=control_tier,+ model_parameters=MappingProxyType(+ dict(payload.get("model_parameters") or {}) # mutable-ok: frozen snapshot+ ),+ parent_metadata=MappingProxyType(dict(request_metadata)), # mutable-ok: frozen snapshot+ )+ ).add_done_callback(self._release_shadow_slot)except Exception as e: # noqa: BLE001 # logging hooks must never fail the requestverbose_logger.debug("shadow_eval: failed to schedule task: %s", e)@@ -360,6 +413,7 @@ class ShadowEvalLogger(CustomLogger):messages: Sequence[Mapping[str, object]],response_obj: object,real_model: str,+ control_tier: str | None,model_parameters: Mapping[str, object],parent_metadata: Mapping[str, object],) -> None:@@ -376,9 +430,11 @@ class ShadowEvalLogger(CustomLogger):if await _key_or_team_is_over_budget(parent_metadata):return- shadow: Final = await self._call_router_shadow(job.router_name, messages, model_parameters, parent_metadata)+ shadow: Final = await self._call_router_shadow(+ job.shadow_target, messages, model_parameters, parent_metadata+ )if isinstance(shadow, _CallFailure):- await self._record_attempt(prisma, job, request_id, outcome="error", error=shadow.error)+ await self._record_attempt(prisma, job, request_id, control_tier, outcome="error", error=shadow.error)returnverdict: Final = await self._call_judge(@@ -393,6 +449,7 @@ class ShadowEvalLogger(CustomLogger):prisma,job,request_id,+ control_tier,outcome="error",error=verdict.error,shadow=shadow,@@ -403,6 +460,7 @@ class ShadowEvalLogger(CustomLogger):prisma,job,request_id,+ control_tier,outcome=verdict.preference,shadow=shadow,real_model=real_model,@@ -411,13 +469,16 @@ class ShadowEvalLogger(CustomLogger):)except Exception as e: # noqa: BLE001 # detached task: record what happened, never raiseverbose_logger.debug("shadow_eval: pipeline failed for %s: %s", request_id, e)- await self._record_attempt(prisma, job, request_id, outcome="error", error=f"pipeline error: {e}")+ await self._record_attempt(+ prisma, job, request_id, control_tier, outcome="error", error=f"pipeline error: {e}"+ )@staticmethodasync def _record_attempt(prisma: "PrismaClient | None",job: ActiveShadowEvalJob,request_id: str,+ control_tier: str | None,*,outcome: str,shadow: _ShadowResponse | None = None,@@ -434,7 +495,7 @@ class ShadowEvalLogger(CustomLogger):"job_id": job.id,"request_id": request_id,"outcome": outcome,- "tier": shadow.tier if shadow else None,+ "tier": control_tier if job.direction == "reverse" else (shadow.tier if shadow else None),"real_model": real_model or None,"shadow_model": shadow.model if shadow else None,"confidence": confidence,@@ -447,14 +508,15 @@ class ShadowEvalLogger(CustomLogger):async def _call_router_shadow(self,- router_name: str,+ target_model: str,messages: Sequence[Mapping[str, object]],model_parameters: Mapping[str, object],parent_metadata: Mapping[str, object],) -> "_ShadowResponse | _CallFailure":- """Send the prompt through the auto-router being evaluated. The metadata carries- the shadowed key's identity (spend attribution) and receives the router's routing- decision write-back, read back for tier attribution."""+ """Send the prompt through the arm nobody was served: the auto-router under+ evaluation, or a reverse job's fixed baseline model. The metadata carries the+ shadowed key's identity (spend attribution) and receives a routing decision+ write-back, which a plain baseline model simply never makes."""router: Final = self._router_provider()if router is None:return _CallFailure("no router configured on this pod")@@ -466,7 +528,7 @@ class ShadowEvalLogger(CustomLogger):}try:response: Final = await router.acompletion(- model=router_name,+ model=target_model,messages=messages, # pyright: ignore[reportArgumentType] # snapshot of the SDK's own message dictsmetadata=shadow_metadata,num_retries=0,@@ -479,13 +541,10 @@ class ShadowEvalLogger(CustomLogger):text: Final = self._extract_response_text(response)if not text:return _CallFailure("shadow router returned an empty response")- raw_decision: Final = shadow_metadata.get("routing_decision")- routing_decision: Final = raw_decision if isinstance(raw_decision, Mapping) else _EMPTY_METADATA- raw_tier: Final = routing_decision.get("tier_label") or routing_decision.get("tier")return _ShadowResponse(text=text,- model=str(getattr(response, "model", None) or routing_decision.get("routed_model") or ""),- tier=str(raw_tier) if raw_tier is not None else None,+ model=str(getattr(response, "model", None) or _routing_decision(shadow_metadata).get("routed_model") or ""),+ tier=_routed_tier(shadow_metadata),)async def _call_judge(@@ -552,7 +611,7 @@ class ShadowEvalLogger(CustomLogger):return extract_text_from_content(content)-_EMPTY_JOBS: Final[Mapping[str, ActiveShadowEvalJob]] = MappingProxyType({})+_EMPTY_JOBS: Final[Mapping[str, tuple[ActiveShadowEvalJob, ...]]] = MappingProxyType({})def _default_prisma_provider() -> "PrismaClient | None":diff --git a/litellm/proxy/management_endpoints/auto_router_endpoints.py b/litellm/proxy/management_endpoints/auto_router_endpoints.pyindex cb0e8dba62a..4b2569fa9fa 100644--- a/litellm/proxy/management_endpoints/auto_router_endpoints.py+++ b/litellm/proxy/management_endpoints/auto_router_endpoints.py@@ -464,35 +464,38 @@ def _is_configured_pre_routing_strategy(llm_router: "Router", router_name: str))-def _validate_judge_model(llm_router: "Router | None", judge_model: str) -> None:- """Reject a judge model the dispatch path cannot resolve, at start rather than as a- silently growing error count once the job is already sampling and billing."""- if llm_router is not None and _is_configured_pre_routing_strategy(llm_router, judge_model):+def _validate_plain_model(llm_router: "Router | None", model: str, field_name: str) -> None:+ """Reject a model the dispatch path cannot resolve, at start rather than as a silently+ growing error count once the job is already sampling and billing. Both the judge and a+ reverse job's baseline must be plain models: an auto-router in either slot would+ re-route per turn, so the comparison would have no fixed arm to attribute results to."""+ if llm_router is not None and _is_configured_pre_routing_strategy(llm_router, model):raise HTTPException(status_code=400,- detail=f"judge_model '{judge_model}' is an auto-router; the judge must be a plain model",+ detail=f"{field_name} '{model}' is an auto-router; it must be a plain model",)- if router_resolves_model(llm_router, judge_model):+ if router_resolves_model(llm_router, model):returnimport litellmtry:- litellm.get_llm_provider(model=judge_model)+ litellm.get_llm_provider(model=model)except Exception as e:raise HTTPException(status_code=400,detail=(- f"judge_model '{judge_model}' is neither a model configured on this proxy nor a "+ f"{field_name} '{model}' is neither a model configured on this proxy nor a ""provider-qualified public model name (e.g. 'anthropic/claude-sonnet-5')"),) from edef _is_unique_violation(error: Exception) -> bool:- """Whether a Prisma create failed on a unique index. One active job per key lives in- a partial unique index (raw SQL in the migration; schema.prisma cannot express partial- indexes), so the read-then-create check above it is advisory: two concurrent starts- pass the read, and the loser must surface as the same 409 rather than a 500."""+ """Whether a Prisma create failed on a unique index. One active job per key and+ direction lives in a partial unique index (raw SQL in the migration; schema.prisma+ cannot express partial indexes), so the read-then-create check above it is advisory:+ two concurrent starts pass the read, and the loser must surface as the same 409+ rather than a 500."""try:from prisma.errors import UniqueViolationErrorexcept ImportError:@@ -573,8 +576,10 @@ def _slices(rows: Sequence[_AttemptAggRow]) -> tuple[ShadowEvalSlice, ...]:async def _shadow_eval_results(prisma_client: "PrismaClient", job_id: str) -> ShadowEvalResult | None:"""Both stratifications of one job's verdicts. Tier answers "where does the router do- well"; current-model answers "which of the models this key uses today would the router- beat". Reads are bounded by the job's own attempts (<= max_turns) via the job_id index."""+ well"; the model stratification groups by whichever model served the real arm, so it+ answers "which of the models this key uses today would the router beat" forward, and+ "for the turns the router sent to X, did X beat the baseline" in reverse. Reads are+ bounded by the job's own attempts (<= max_turns) via the job_id index."""by_tier: Final = _ATTEMPT_AGG_ROWS.validate_python(await prisma_client.db.query_raw(_ATTEMPT_AGG_BY_TIER_SQL, job_id) or ())@@ -604,9 +609,15 @@ async def start_shadow_eval(user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],) -> ShadowEvalJobResponse:"""- Start a pre-adoption shadow eval: duplicate a sampled slice of a key's live traffic- through an auto-router, judge real vs. shadow responses blind, and stratify win rates- by the router's tier classification and by the incumbent model.+ Start a shadow eval: duplicate a sampled slice of a key's live traffic against a second+ arm, judge the two responses blind, and stratify win rates by tier and by the model that+ served the real arm.++ A forward job answers whether the key should adopt router_name: it samples the requests+ the router did not serve and duplicates them through it. A reverse job answers whether a+ key already on the router still gains from it: it samples the requests the router did+ serve and duplicates them against baseline_model. A key can hold one active job per+ direction, so both questions can run at once.Shadow responses are never served to users. The job samples until it has judgedmax_turns turns, reaches the end of its window, or is stopped; sampling changes@@ -620,7 +631,9 @@ async def start_shadow_eval(raise HTTPException(status_code=500, detail=CommonProxyErrors.db_not_connected_error.value)if llm_router is None or not _is_configured_pre_routing_strategy(llm_router, data.router_name):raise HTTPException(status_code=400, detail=f"'{data.router_name}' is not a configured auto-router")- _validate_judge_model(llm_router, data.judge_model)+ _validate_plain_model(llm_router, data.judge_model, "judge_model")+ if data.baseline_model is not None:+ _validate_plain_model(llm_router, data.baseline_model, "baseline_model")key_row: Final = await prisma_client.db.litellm_verificationtoken.find_unique(where={"token": data.api_key_id} # mutable-ok: Prisma filter)@@ -634,16 +647,20 @@ async def start_shadow_eval()# A job that expired or exhausted its turn budget stopped sampling on its own, but- # still holds the one-active-per-key partial unique index until stamped; free it so- # a new eval can start.+ # still holds its slot in the per-key, per-direction partial unique index until+ # stamped; free it so a new eval can start. Sweeping both directions is deliberate.await prisma_client.db.execute_raw(_SWEEP_FINISHED_JOBS_SQL, data.api_key_id)active: Final = await prisma_client.db.litellm_shadowevaljob.find_first(- where={"api_key_id": data.api_key_id, "stopped_at": None}, # mutable-ok: Prisma filter+ where={ # mutable-ok: Prisma filter+ "api_key_id": data.api_key_id,+ "direction": data.direction,+ "stopped_at": None,+ },)if active is not None:raise HTTPException(status_code=409,- detail=f"Key already has an active shadow eval job ({active.id}). Stop it first.",+ detail=f"Key already has an active {data.direction} shadow eval job ({active.id}). Stop it first.",)now: Final = datetime.now(timezone.utc)try:@@ -651,6 +668,8 @@ async def start_shadow_eval(data={ # mutable-ok: Prisma payload"api_key_id": data.api_key_id,"router_name": data.router_name,+ "direction": data.direction,+ "baseline_model": data.baseline_model,"judge_model": data.judge_model,"shadow_percentage": data.shadow_percentage,"max_turns": data.max_turns,@@ -663,7 +682,9 @@ async def start_shadow_eval(raiseraise HTTPException(status_code=409,- detail="Key already has an active shadow eval job (started concurrently). Stop it first.",+ detail=(+ f"Key already has an active {data.direction} shadow eval job (started concurrently). Stop it first."+ ),) from ereturn ShadowEvalJobResponse.model_validate(job, from_attributes=True)diff --git a/litellm/proxy/schema.prisma b/litellm/proxy/schema.prismaindex 79d778fb464..71345d2ccde 100644--- a/litellm/proxy/schema.prisma+++ b/litellm/proxy/schema.prisma@@ -1450,15 +1450,20 @@ model LiteLLM_AutoRouterSession {@@index([last_turn_at], map: "idx_autorouter_session_last_turn")}-// Shadow eval: pre-adoption evaluation of an auto-router against a key's live traffic.-// A sampled slice of requests is duplicated through the router in a detached task and an-// LLM judge compares real vs shadow responses blind. The job row is immutable config plus+// Shadow eval: evaluation of an auto-router against a key's live traffic, in either+// direction. forward duplicates the requests the key did not route through the router+// through it, answering whether the key should adopt it; reverse duplicates the requests+// the router did serve against a fixed baseline model, answering whether a key already on+// it still benefits. Either way a sampled slice runs in a detached task and an LLM judge+// compares real vs shadow responses blind. The job row is immutable config plus// stopped_at; every count, status, and spend figure is derived from the append-only// attempt rows, so nothing can disagree across pods or stop races.model LiteLLM_ShadowEvalJob {id String @id @default(cuid())api_key_id String // hashed virtual key whose traffic is shadowed- router_name String+ router_name String // the auto-router under evaluation, in either direction+ direction String @default("forward") // forward | reverse+ baseline_model String? // reverse only: the fixed model the router is judged againstjudge_model Stringshadow_percentage Floatmax_turns Int // sample budget: judge at most this many turnsdiff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.pyindex bf8a3d34098..1b0c7476fc3 100644--- a/litellm/types/management_endpoints/auto_router_endpoints.py+++ b/litellm/types/management_endpoints/auto_router_endpoints.py@@ -6,7 +6,7 @@ from collections.abc import Mappingfrom datetime import datetime, timezonefrom typing import Final, Literal, TypeAlias-from pydantic import AliasChoices, BaseModel, ConfigDict, Field, computed_field, field_validator+from pydantic import AliasChoices, BaseModel, ConfigDict, Field, computed_field, field_validator, model_validatorfrom litellm.router_strategy.complexity_router.config import ComplexityRouterConfigfrom litellm.types.utils import StandardLoggingRoutingDecision@@ -146,11 +146,13 @@ class AutoRouterBenchmarksResponse(BaseModel):ShadowEvalStatus: TypeAlias = Literal["running", "completed", "stopped"]+ShadowEvalDirection: TypeAlias = Literal["forward", "reverse"]+DEFAULT_SHADOW_EVAL_JUDGE_MODEL: Final[str] = "anthropic/claude-sonnet-5"class StartShadowEvalRequest(BaseModel):- """Start shadowing a key's traffic through an auto-router for blind comparison."""+ """Start duplicating a key's traffic for blind comparison against an auto-router."""api_key_id: str = Field(description=(@@ -158,7 +160,23 @@ class StartShadowEvalRequest(BaseModel):"key's traffic; requests made with any other key are not sampled."))- router_name: str = Field(description="The auto-router config to shadow requests through")+ router_name: str = Field(description="The auto-router under evaluation, in either direction")+ direction: ShadowEvalDirection = Field(+ default="forward",+ description=(+ "forward answers 'should this key adopt router_name': it samples the requests the key did NOT "+ "route through the router and duplicates them through it. reverse answers 'is the router still "+ "worth it for a key already on it': it samples the requests the router did serve and duplicates "+ "them against baseline_model. The response the caller received is always the real arm"+ ),+ )+ baseline_model: str | None = Field(+ default=None,+ description=(+ "Required when direction is reverse and rejected otherwise: the fixed model the router's own "+ "responses are judged against. Must be a plain model rather than another auto-router"+ ),+ )shadow_percentage: float = Field(ge=0.1,le=100.0,@@ -193,15 +211,33 @@ class StartShadowEvalRequest(BaseModel):def _round_percentage(cls, value: float) -> float:return round(value, 2)+ @model_validator(mode="after")+ def _baseline_model_matches_direction(self) -> "StartShadowEvalRequest":+ if self.direction == "reverse" and self.baseline_model is None:+ raise ValueError("baseline_model is required when direction is 'reverse'")+ if self.direction == "forward" and self.baseline_model is not None:+ raise ValueError("baseline_model is only meaningful when direction is 'reverse'")+ return self+class ShadowEvalSlice(BaseModel):"""Judge outcomes for one slice of a job's verdicts (a router tier, or one of the- models the shadowed key currently uses)."""+ models that served the real arm)."""group: strturn_count: int- real_win_rate_pct: float = Field(description="Share of judged turns where the real (control) model won")- shadow_win_rate_pct: float = Field(description="Share of judged turns where the shadowed router's pick won")+ real_win_rate_pct: float = Field(+ description=(+ "Share of judged turns the real arm won, meaning the response the caller actually received: "+ "the key's own model in forward mode, the router's pick in reverse"+ )+ )+ shadow_win_rate_pct: float = Field(+ description=(+ "Share of judged turns the shadow arm won, meaning the duplicated response nobody was served: "+ "the router's pick in forward mode, baseline_model in reverse"+ )+ )tie_rate_pct: floatavg_judge_confidence: float@@ -210,7 +246,12 @@ class ShadowEvalResult(BaseModel):"""Stratified results of a shadow-eval job's verdicts so far."""by_tier: tuple[ShadowEvalSlice, ...]- by_current_model: tuple[ShadowEvalSlice, ...]+ by_current_model: tuple[ShadowEvalSlice, ...] = Field(+ description=(+ "Sliced by the model that served the real arm: the key's incumbent models in forward mode, "+ "and in reverse the models the router itself picked"+ )+ )overall_shadow_win_rate_pct: floatoverall_tie_rate_pct: float@@ -226,6 +267,8 @@ class ShadowEvalJobResponse(BaseModel):job_id: str = Field(validation_alias=AliasChoices("id", "job_id"))api_key_id: str = Field(description="The hashed virtual key whose traffic this job evaluates, and only that key's")router_name: str+ direction: ShadowEvalDirection = "forward"+ baseline_model: str | None = Nonejudge_model: strshadow_percentage: floatmax_turns: intdiff --git a/schema.prisma b/schema.prismaindex 79d778fb464..71345d2ccde 100644--- a/schema.prisma+++ b/schema.prisma@@ -1450,15 +1450,20 @@ model LiteLLM_AutoRouterSession {@@index([last_turn_at], map: "idx_autorouter_session_last_turn")}-// Shadow eval: pre-adoption evaluation of an auto-router against a key's live traffic.-// A sampled slice of requests is duplicated through the router in a detached task and an-// LLM judge compares real vs shadow responses blind. The job row is immutable config plus+// Shadow eval: evaluation of an auto-router against a key's live traffic, in either+// direction. forward duplicates the requests the key did not route through the router+// through it, answering whether the key should adopt it; reverse duplicates the requests+// the router did serve against a fixed baseline model, answering whether a key already on+// it still benefits. Either way a sampled slice runs in a detached task and an LLM judge+// compares real vs shadow responses blind. The job row is immutable config plus// stopped_at; every count, status, and spend figure is derived from the append-only// attempt rows, so nothing can disagree across pods or stop races.model LiteLLM_ShadowEvalJob {id String @id @default(cuid())api_key_id String // hashed virtual key whose traffic is shadowed- router_name String+ router_name String // the auto-router under evaluation, in either direction+ direction String @default("forward") // forward | reverse+ baseline_model String? // reverse only: the fixed model the router is judged againstjudge_model Stringshadow_percentage Floatmax_turns Int // sample budget: judge at most this many turnsdiff --git a/tests/test_litellm/integrations/test_shadow_eval_logger.py b/tests/test_litellm/integrations/test_shadow_eval_logger.pyindex e1c56db21af..3a69340109d 100644--- a/tests/test_litellm/integrations/test_shadow_eval_logger.py+++ b/tests/test_litellm/integrations/test_shadow_eval_logger.py@@ -6,6 +6,7 @@ from datetime import datetime, timedelta, timezonefrom unittest.mock import AsyncMock, MagicMockimport pytest+from pydantic import ValidationErrorfrom litellm.caching.in_memory_cache import InMemoryCachefrom litellm.constants import INTERNAL_CALL_ORIGIN_METADATA_KEY@@ -19,7 +20,7 @@ from litellm.integrations.shadow_eval_logger import (_sample_hits,_unmask_preference,)-from litellm.types.utils import SHADOW_EVAL_JUDGE_CALL_ORIGIN, SHADOW_EVAL_ROUTER_CALL_ORIGIN+from litellm.types.utils import SHADOW_EVAL_JUDGE_CALL_ORIGIN, SHADOW_EVAL_ROUTER_CALL_ORIGIN, ModelResponsedef _job(**overrides) -> ActiveShadowEvalJob:@@ -51,6 +52,8 @@ def _job_record(job: ActiveShadowEvalJob, api_key_id="key-hash") -> MagicMock:id=job.id,api_key_id=api_key_id,router_name=job.router_name,+ direction=job.direction,+ baseline_model=job.baseline_model,shadow_percentage=job.shadow_percentage,judge_model=job.judge_model,max_turns=job.max_turns,@@ -61,40 +64,55 @@ def _job_record(job: ActiveShadowEvalJob, api_key_id="key-hash") -> MagicMock:def _router(shadow_text="shadow answer", judge_json='{"preference": "A", "confidence": 0.9, "reasoning": "x"}'):- """One mock router serving the shadow call first, the judge call second. The shadow- call's metadata receives the routing decision write-back, like the real router."""+ """One mock router serving the shadow call first, the judge call second, told apart by+ the internal-origin stamp rather than the model, since a reverse job's shadow arm names+ a plain model. Only the auto-router writes a routing decision back, and only a plain+ model reports the model it served on the response, which is how each direction learns+ which model answered."""router = MagicMock()router.model_group_alias = {}router.get_model_list = MagicMock(return_value=[{"litellm_params": {"model": "openai/gpt-4o-mini"}}])async def acompletion(**kwargs):+ if kwargs["metadata"].get(INTERNAL_CALL_ORIGIN_METADATA_KEY) != SHADOW_EVAL_ROUTER_CALL_ORIGIN:+ return {"choices": [{"message": {"content": judge_json}}]}if kwargs["model"] == "my-router":kwargs["metadata"]["routing_decision"] = {"tier_label": "SIMPLE", "routed_model": "cheap-model"}return {"choices": [{"message": {"content": shadow_text}}], "usage": {"completion_tokens": 5}}- return {"choices": [{"message": {"content": judge_json}}]}+ return ModelResponse(+ model=kwargs["model"],+ choices=[{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": shadow_text}}],+ )router.acompletion = MagicMock(side_effect=acompletion)return router-def _logger(router=None, prisma=None, job=None) -> ShadowEvalLogger:+def _logger(router=None, prisma=None, jobs=()) -> ShadowEvalLogger:cache = InMemoryCache(max_size_in_memory=4, default_ttl=60)logger = ShadowEvalLogger(router_provider=lambda: router,prisma_provider=lambda: prisma,jobs_cache=cache,)- if job is not None:- cache.set_cache("shadow_eval:active_jobs", {"key-hash": job})+ if jobs:+ cache.set_cache("shadow_eval:active_jobs", {"key-hash": tuple(jobs)})return logger-def _success_kwargs(request_id="req-1", api_key_hash="key-hash", request_metadata=None, call_type="acompletion"):+def _routed_by(router_name="my-router", tier="COMPLEX"):+ """Metadata as a pre-routing strategy leaves it on the request it served."""+ return {"routing_decision": {"router_model_name": router_name, "tier_label": tier, "routed_model": "router-pick"}}+++def _success_kwargs(+ request_id="req-1", api_key_hash="key-hash", request_metadata=None, call_type="acompletion", model="claude-opus"+):return {"standard_logging_object": {"id": request_id,"call_type": call_type,- "model": "claude-opus",+ "model": model,"metadata": {"user_api_key_hash": api_key_hash},"model_parameters": {"temperature": 0.5, "stream": True},},@@ -164,7 +182,7 @@ class TestSuccessHookSkipChain:monkeypatch.setattr(litellm_module, "completion_cost", lambda completion_response: 0.005)prisma = _prisma()router = _router()- logger = _logger(router=router, prisma=prisma, job=_job())+ logger = _logger(router=router, prisma=prisma, jobs=(_job(),))await logger.async_log_success_event(_success_kwargs(), RESPONSE, None, None)await _drain(logger)@@ -209,7 +227,7 @@ class TestSuccessHookSkipChain:async def test_skip_paths_store_nothing(self, kwargs_mutation, job_mutation):starts = job_mutation.pop("_starts", 0)prisma = _prisma()- logger = _logger(router=_router(), prisma=prisma, job=_job(**job_mutation))+ logger = _logger(router=_router(), prisma=prisma, jobs=(_job(**job_mutation),))logger._job_starts = {"job-1": starts}await logger.async_log_success_event(_success_kwargs(**kwargs_mutation), RESPONSE, None, None)@@ -222,7 +240,7 @@ class TestSuccessHookSkipChain:"""A finished pipeline frees its concurrency slot but not its slice of the turnbudget; the budget only reopens when a cache refill absorbs the written rows."""prisma = _prisma()- logger = _logger(router=_router(), prisma=prisma, job=_job(attempts=199, max_turns=200))+ logger = _logger(router=_router(), prisma=prisma, jobs=(_job(attempts=199, max_turns=200),))await logger.async_log_success_event(_success_kwargs(request_id="req-1"), RESPONSE, None, None)await _drain(logger)@@ -237,7 +255,7 @@ class TestSuccessHookSkipChain:identity to the shadow and judge calls."""prisma = _prisma()router = _router()- logger = _logger(router=router, prisma=prisma, job=_job())+ logger = _logger(router=router, prisma=prisma, jobs=(_job(),))hook_kwargs = _success_kwargs()hook_kwargs["litellm_params"] = {@@ -256,7 +274,7 @@ class TestSuccessHookSkipChain:predicate, so every redaction source counts."""prisma = _prisma()router = _router()- logger = _logger(router=router, prisma=prisma, job=_job())+ logger = _logger(router=router, prisma=prisma, jobs=(_job(),))hook_kwargs = _success_kwargs()hook_kwargs["standard_callback_dynamic_params"] = {"turn_off_message_logging": True}@@ -268,7 +286,7 @@ class TestSuccessHookSkipChain:async def test_inflight_cap_sheds_instead_of_queueing(self):prisma = _prisma()- logger = _logger(router=_router(), prisma=prisma, job=_job())+ logger = _logger(router=_router(), prisma=prisma, jobs=(_job(),))logger._inflight_shadow_tasks = _MAX_CONCURRENT_SHADOW_TASKSawait logger.async_log_success_event(_success_kwargs(), RESPONSE, None, None)@@ -291,8 +309,8 @@ class TestActiveJobsCache:first = await logger._active_jobs()second = await logger._active_jobs()- assert first["key-hash"].id == "job-1"- assert second["key-hash"].attempts == 7+ assert [job.id for job in first["key-hash"]] == ["job-1"]+ assert second["key-hash"][0].attempts == 7assert prisma.db.litellm_shadowevaljob.find_many.await_count == 1where = prisma.db.litellm_shadowevaljob.find_many.call_args.kwargs["where"]assert where["stopped_at"] is None@@ -353,6 +371,7 @@ class TestShadowPipeline:messages=({"role": "user", "content": "hi"},),response_obj=RESPONSE,real_model="claude-opus",+ control_tier=None,model_parameters={},parent_metadata={},)@@ -381,6 +400,7 @@ class TestShadowPipeline:messages=({"role": "user", "content": "hi"},),response_obj=RESPONSE,real_model="claude-opus",+ control_tier=None,model_parameters={},parent_metadata={"user_api_key_auth": UserAPIKeyAuth(api_key="sk-abc", max_budget=10.0)},)@@ -411,6 +431,7 @@ class TestShadowPipeline:messages=({"role": "user", "content": "hi"},),response_obj=RESPONSE,real_model="claude-opus",+ control_tier=None,model_parameters={},parent_metadata={},)@@ -438,6 +459,7 @@ class TestShadowPipeline:messages=({"role": "user", "content": "hi"},),response_obj=RESPONSE,real_model="claude-opus",+ control_tier=None,model_parameters={"stream": True, "temperature": 0.2, "metadata": {"x": 1}},parent_metadata=parent_metadata,)@@ -458,6 +480,164 @@ class TestShadowPipeline:assert judge_call["max_tokens"] == JUDGE_MAX_OUTPUT_TOKENS+def _reverse_job(**overrides) -> ActiveShadowEvalJob:+ return _job(**{"direction": "reverse", "baseline_model": "baseline-model", **overrides})+++class TestJobValidation:+ @pytest.mark.parametrize(+ "overrides",+ [+ {"direction": "reverse"},+ {"baseline_model": "baseline-model"},+ {"direction": "sideways", "baseline_model": "baseline-model"},+ ],+ ids=["reverse-without-baseline", "forward-with-baseline", "unknown-direction"],+ )+ def test_unsamplable_shapes_are_rejected(self, overrides):+ with pytest.raises(ValidationError):+ _job(**overrides)++ def test_shadow_target_follows_direction(self):+ assert _job().shadow_target == "my-router"+ assert _reverse_job().shadow_target == "baseline-model"+++class TestDirection:+ @pytest.mark.parametrize(+ "job,routed_by,sampled",+ [+ (_job(), None, True),+ (_job(), "my-router", False),+ (_job(), "other-router", True),+ (_reverse_job(), "my-router", True),+ (_reverse_job(), None, False),+ (_reverse_job(), "other-router", False),+ ],+ ids=[+ "forward-samples-unrouted",+ "forward-skips-its-own-router",+ "forward-samples-another-router",+ "reverse-samples-its-own-router",+ "reverse-skips-unrouted",+ "reverse-skips-another-router",+ ],+ )+ async def test_direction_decides_which_traffic_is_sampled(self, job, routed_by, sampled):+ """The two directions partition the key's traffic: whatever one samples, the other+ skips, so a key running both never judges the same turn twice for the same reason."""+ prisma = _prisma()+ logger = _logger(router=_router(), prisma=prisma, jobs=(job,))++ await logger.async_log_success_event(+ _success_kwargs(request_metadata=_routed_by(routed_by) if routed_by else {}), RESPONSE, None, None+ )+ await _drain(logger)++ assert prisma.db.litellm_shadowevalattempt.create.await_count == int(sampled)++ async def test_reverse_duplicates_against_the_baseline_model(self):+ prisma = _prisma()+ router = _router()+ logger = _logger(router=router, prisma=prisma, jobs=(_reverse_job(),))++ await logger.async_log_success_event(+ _success_kwargs(request_metadata=_routed_by()), RESPONSE, None, None+ )+ await _drain(logger)++ assert router.acompletion.call_args_list[0].kwargs["model"] == "baseline-model"++ async def test_reverse_row_orients_arms_and_reads_tier_off_the_served_request(self):+ """real is what the caller received, so in reverse it is the router's own pick and+ the tier that produced it; only the shadow arm moves to the baseline."""+ prisma = _prisma()+ logger = _logger(router=_router(), prisma=prisma, jobs=(_reverse_job(),))++ await logger.async_log_success_event(+ _success_kwargs(request_metadata=_routed_by(tier="COMPLEX"), model="router-pick"), RESPONSE, None, None+ )+ await _drain(logger)++ row = prisma.db.litellm_shadowevalattempt.create.call_args.kwargs["data"]+ assert row["real_model"] == "router-pick"+ assert row["shadow_model"] == "baseline-model"+ assert row["tier"] == "COMPLEX"++ async def test_forward_row_still_reads_tier_off_the_shadow_call(self):+ """A forward job's tier describes the arm being evaluated, which is the shadow one,+ so a routing decision on the incumbent request must not leak into it."""+ prisma = _prisma()+ logger = _logger(router=_router(), prisma=prisma, jobs=(_job(),))++ await logger.async_log_success_event(+ _success_kwargs(request_metadata=_routed_by("other-router", tier="CONTROL_TIER")), RESPONSE, None, None+ )+ await _drain(logger)++ row = prisma.db.litellm_shadowevalattempt.create.call_args.kwargs["data"]+ assert row["tier"] == "SIMPLE"+ assert row["shadow_model"] == "cheap-model"++ async def test_a_key_running_both_directions_dispatches_both(self):+ """One request can qualify for a forward job on a router that did not serve it and a+ reverse job on the router that did. The two are separately budgeted experiments, so+ both fire rather than one silently losing the turn."""+ prisma = _prisma()+ logger = _logger(+ router=_router(),+ prisma=prisma,+ jobs=(_job(id="forward-job", router_name="other-router"), _reverse_job(id="reverse-job")),+ )++ await logger.async_log_success_event(+ _success_kwargs(request_metadata=_routed_by()), RESPONSE, None, None+ )+ await _drain(logger)++ rows = [call.kwargs["data"] for call in prisma.db.litellm_shadowevalattempt.create.call_args_list]+ assert sorted(row["job_id"] for row in rows) == ["forward-job", "reverse-job"]+ assert logger._job_starts == {"forward-job": 1, "reverse-job": 1}+++class TestActiveJobsFailClosed:+ async def test_a_row_the_sampler_cannot_read_is_dropped_not_guessed(self):+ """A reverse row with no baseline model has no second arm to call, so it is skipped+ rather than silently dispatched at the router it is supposed to be judging."""+ broken = _job_record(_job(id="job-broken"))+ broken.direction = "reverse"+ broken.baseline_model = None+ prisma = _prisma(jobs=[broken, _job_record(_job(id="job-ok"))], attempt_counts=[("job-ok", 1)])+ logger = ShadowEvalLogger(+ router_provider=lambda: None,+ prisma_provider=lambda: prisma,+ jobs_cache=InMemoryCache(max_size_in_memory=4, default_ttl=60),+ )++ assert [job.id for job in (await logger._active_jobs())["key-hash"]] == ["job-ok"]++ async def test_both_of_a_key_s_jobs_survive_the_lookup(self):+ records = [+ _job_record(_job(id="job-forward")),+ _job_record(_reverse_job(id="job-reverse")),+ _job_record(_job(id="job-other"), api_key_id="other-key"),+ ]+ prisma = _prisma(jobs=records, attempt_counts=[("job-reverse", 3)])+ logger = ShadowEvalLogger(+ router_provider=lambda: None,+ prisma_provider=lambda: prisma,+ jobs_cache=InMemoryCache(max_size_in_memory=4, default_ttl=60),+ )++ jobs = await logger._active_jobs()++ assert sorted(job.id for job in jobs["key-hash"]) == ["job-forward", "job-reverse"]+ assert [job.id for job in jobs["other-key"]] == ["job-other"]+ assert {job.id: job.attempts for job in jobs["key-hash"]}["job-reverse"] == 3++def _failing_router():router = MagicMock()router.model_group_alias = {}diff --git a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.pyindex 16e82bc3bda..dbde7c461b8 100644--- a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py@@ -559,7 +559,7 @@ def _start_request(**overrides: object) -> StartShadowEvalRequest:@pytest.mark.asyncioasync def test_start_shadow_eval_creates_job_and_frees_expired_or_exhausted_ones(monkeypatch: pytest.MonkeyPatch):"""Expiry and turn-budget exhaustion both end sampling on their own; either must- release the one-active-per-key index so a new eval can start."""+ release the key's slot in the active-job index so a new eval can start."""import litellm.proxy.proxy_server as proxy_serverprisma = _shadow_prisma()@@ -592,8 +592,21 @@ async def test_start_shadow_eval_creates_job_and_frees_expired_or_exhausted_ones(ADMIN, {"judge_model": "not/a real model!"}, None, 400),(ADMIN, {"judge_model": "my-router"}, None, 400),(ADMIN, {}, "active", 409),+ (ADMIN, {"direction": "reverse", "baseline_model": "my-router"}, None, 400),+ (ADMIN, {"direction": "reverse", "baseline_model": "not/a real model!"}, None, 400),+ (ADMIN, {"direction": "reverse", "baseline_model": "openai/gpt-4o", "router_name": "not-a-router"}, None, 400),+ ],+ ids=[+ "non-admin",+ "view-only",+ "unknown-router",+ "unresolvable-judge",+ "router-as-judge",+ "already-active",+ "router-as-baseline",+ "unresolvable-baseline",+ "reverse-still-needs-an-auto-router",],- ids=["non-admin", "view-only", "unknown-router", "unresolvable-judge", "router-as-judge", "already-active"],)async def test_start_shadow_eval_rejections(monkeypatch: pytest.MonkeyPatch, caller, request_overrides, active, expected_status@@ -609,6 +622,68 @@ async def test_start_shadow_eval_rejections(assert exc.value.status_code == expected_status+ "overrides",+ [+ {"direction": "reverse"},+ {"baseline_model": "openai/gpt-4o"},+ {"direction": "sideways", "baseline_model": "openai/gpt-4o"},+ ],+ ids=["reverse-without-baseline", "forward-with-baseline", "unknown-direction"],+)+def test_start_request_pins_baseline_model_to_reverse(overrides):+ """A forward job has no second arm to name and a reverse job cannot run without one,+ so neither shape reaches the endpoint to be half-validated there."""+ with pytest.raises(ValidationError):+ _start_request(**overrides)+++async def test_start_shadow_eval_reverse_records_its_arms_and_holds_its_own_slot(monkeypatch: pytest.MonkeyPatch):+ """The two directions ask opposite questions of the same key, so a forward job holding+ the slot must not block a reverse one. The second reverse start still 409s."""+ import litellm.proxy.proxy_server as proxy_server++ prisma = _shadow_prisma()+ active = {"forward": _job_record()}+ prisma.db.litellm_shadowevaljob.find_first = AsyncMock(+ side_effect=lambda where, **_: active.get(str(where.get("direction")))+ )+ prisma.db.litellm_shadowevaljob.create = AsyncMock(+ return_value=_job_record(direction="reverse", baseline_model="openai/gpt-4o")+ )+ monkeypatch.setattr(proxy_server, "prisma_client", prisma)+ monkeypatch.setattr(proxy_server, "llm_router", _shadow_router())++ reverse = _start_request(direction="reverse", baseline_model="openai/gpt-4o")+ response = await start_shadow_eval(reverse, ADMIN)++ assert (response.direction, response.baseline_model) == ("reverse", "openai/gpt-4o")+ create_data = prisma.db.litellm_shadowevaljob.create.call_args.kwargs["data"]+ assert create_data["direction"] == "reverse"+ assert create_data["baseline_model"] == "openai/gpt-4o"++ active["reverse"] = _job_record(id="job-2", direction="reverse")+ with pytest.raises(HTTPException) as exc:+ await start_shadow_eval(reverse, ADMIN)+ assert exc.value.status_code == 409+++async def test_start_shadow_eval_forward_leaves_the_baseline_column_empty(monkeypatch: pytest.MonkeyPatch):+ import litellm.proxy.proxy_server as proxy_server++ prisma = _shadow_prisma()+ monkeypatch.setattr(proxy_server, "prisma_client", prisma)+ monkeypatch.setattr(proxy_server, "llm_router", _shadow_router())++ await start_shadow_eval(_start_request(), ADMIN)++ create_data = prisma.db.litellm_shadowevaljob.create.call_args.kwargs["data"]+ assert create_data["direction"] == "forward"+ assert create_data["baseline_model"] is None++@pytest.mark.asyncioasync def test_start_shadow_eval_rejects_a_key_this_proxy_does_not_know(monkeypatch: pytest.MonkeyPatch):"""A typo'd api_key_id would otherwise create a job no traffic can ever match."""diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.test.tsxindex 467439122dd..d4d26650086 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.test.tsx@@ -358,6 +358,7 @@ describe("ShadowEvalSection", () => {const expectedBody = {api_key_id: "hash-alpha",router_name: "gpt-auto",+ direction: "forward",shadow_percentage: 10,duration_days: 7,max_turns: 200,diff --git a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.tsx b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.tsxindex 6bb00933218..711fc1af539 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/cost-optimization/_components/ShadowEvalSection.tsx@@ -308,6 +308,7 @@ const StartForm: React.FC = () => {const startBody = {api_key_id: apiKeyId,router_name: routerName,+ direction: "forward" as const,shadow_percentage: parsedPct,duration_days: Number.parseInt(durationDays, 10),max_turns: parsedMaxTurns,diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 2cbc7fd6220..eeea16f3ccd 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -838,9 +838,15 @@ export interface paths {put?: never;/*** Start Shadow Eval- * @description Start a pre-adoption shadow eval: duplicate a sampled slice of a key's live traffic- * through an auto-router, judge real vs. shadow responses blind, and stratify win rates- * by the router's tier classification and by the incumbent model.+ * @description Start a shadow eval: duplicate a sampled slice of a key's live traffic against a second+ * arm, judge the two responses blind, and stratify win rates by tier and by the model that+ * served the real arm.+ *+ * A forward job answers whether the key should adopt router_name: it samples the requests+ * the router did not serve and duplicates them through it. A reverse job answers whether a+ * key already on the router still gains from it: it samples the requests the router did+ * serve and duplicates them against baseline_model. A key can hold one active job per+ * direction, so both questions can run at once.** Shadow responses are never served to users. The job samples until it has judged* max_turns turns, reaches the end of its window, or is stopped; sampling changes@@ -32737,11 +32743,19 @@ export interface components {* @description The hashed virtual key whose traffic this job evaluates, and only that key's*/api_key_id: string;+ /** Baseline Model */+ baseline_model?: string | null;/*** Created At* Format: date-time*/created_at: string;+ /**+ * Direction+ * @default forward+ * @enum {string}+ */+ direction: "forward" | "reverse";/*** Ends At* Format: date-time@@ -32794,7 +32808,10 @@ export interface components {* @description Stratified results of a shadow-eval job's verdicts so far.*/ShadowEvalResult: {- /** By Current Model */+ /**+ * By Current Model+ * @description Sliced by the model that served the real arm: the key's incumbent models in forward mode, and in reverse the models the router itself picked+ */by_current_model: components["schemas"]["ShadowEvalSlice"][];/** By Tier */by_tier: components["schemas"]["ShadowEvalSlice"][];@@ -32806,7 +32823,7 @@ export interface components {/*** ShadowEvalSlice* @description Judge outcomes for one slice of a job's verdicts (a router tier, or one of the- * models the shadowed key currently uses).+ * models that served the real arm).*/ShadowEvalSlice: {/** Avg Judge Confidence */@@ -32815,12 +32832,12 @@ export interface components {group: string;/*** Real Win Rate Pct- * @description Share of judged turns where the real (control) model won+ * @description Share of judged turns the real arm won, meaning the response the caller actually received: the key's own model in forward mode, the router's pick in reverse*/real_win_rate_pct: number;/*** Shadow Win Rate Pct- * @description Share of judged turns where the shadowed router's pick won+ * @description Share of judged turns the shadow arm won, meaning the duplicated response nobody was served: the router's pick in forward mode, baseline_model in reverse*/shadow_win_rate_pct: number;/** Tie Rate Pct */@@ -33003,7 +33020,7 @@ export interface components {};/*** StartShadowEvalRequest- * @description Start shadowing a key's traffic through an auto-router for blind comparison.+ * @description Start duplicating a key's traffic for blind comparison against an auto-router.*/StartShadowEvalRequest: {/**@@ -33011,6 +33028,18 @@ export interface components {* @description The hashed virtual key whose traffic will be shadowed. Shadow evaluation runs ONLY on this key's traffic; requests made with any other key are not sampled.*/api_key_id: string;+ /**+ * Baseline Model+ * @description Required when direction is reverse and rejected otherwise: the fixed model the router's own responses are judged against. Must be a plain model rather than another auto-router+ */+ baseline_model?: string | null;+ /**+ * Direction+ * @description forward answers 'should this key adopt router_name': it samples the requests the key did NOT route through the router and duplicates them through it. reverse answers 'is the router still worth it for a key already on it': it samples the requests the router did serve and duplicates them against baseline_model. The response the caller received is always the real arm+ * @default forward+ * @enum {string}+ */+ direction: "forward" | "reverse";/*** Duration Days* @description How many days the job samples traffic before completing on its own@@ -33031,7 +33060,7 @@ export interface components {max_turns: number;/*** Router Name- * @description The auto-router config to shadow requests through+ * @description The auto-router under evaluation, in either direction*/router_name: string;/**