litellm/tests/unit/proxy/db/test_shadow_eval_funnel.py
joshua-berri 9e81aa3f40
feat(shadow-eval): skip redundant reverse evaluations on opt-in (#52192)
* feat(shadow-eval): let reverse jobs skip samples the baseline group served

A reverse shadow eval judges the router's response against baseline_model.
When the router itself sent the request to the baseline's model group, the
comparison only produces ties and still pays for a shadow and a judge call.

Reverse jobs can now opt in with skip_same_model. A sampled request whose
served group (router alias resolved, fallback hops respected) is the
baseline's own group is counted in a new same_model funnel stage instead of
being judged. It makes no provider calls, writes no attempt row, and leaves
max_turns and the eval budget untouched. When the served group is unknown
the sample is judged as before. The job detail reports
same_model_skipped_count even when nothing has been judged yet.

The flag defaults to false and is rejected on forward jobs, so existing
jobs and requests behave exactly as before. Adds two columns through an
additive, schema-only migration.

* test(shadow-eval): drive same-model skip tests off explicit completion signals

Judged cases now wait on the attempt write the injected prisma reports,
then await the pipeline task that made it. Skip cases drain only the tasks
the hook created, through a task factory scoped to the hook call, before
asserting that no provider call, attempt row, or spend was recorded. This
replaces a whole-loop task diff and the assertion on the number of tasks.

Adds a skip case with tier parameter overrides, which the policy still
treats as the same group, and a case showing a lost sampling roll counts as
not_sampled before same_model. Drops the class docstring claim that a same
group comparison only produces ties.

* style(tests): remove extra shadow evaluation test spacing

* fix(ui): send skip_same_model false from the shadow eval start form

The generated request type now requires skip_same_model, which broke the
dashboard typecheck and builds. The form sends false, the API default, so
jobs started from the UI behave exactly as before.

* fix(migrations): bound shadow evaluation schema lock waits

---------

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
2026-11-16 21:38:00 -08:00

136 lines
4.4 KiB
Python

from collections.abc import Awaitable, Callable
from typing import Final
from unittest.mock import AsyncMock, MagicMock
import pytest
from litellm.proxy.db import shadow_eval_funnel
from litellm.proxy.db.shadow_eval_funnel import (
flush_shadow_eval_funnel,
record_shadow_eval_funnel_event,
)
from tests.unit.proxy.db.fake_prisma_engine import engine_call
@pytest.fixture(autouse=True)
def _clean_queue():
shadow_eval_funnel._pending.clear()
yield
shadow_eval_funnel._pending.clear()
def _prisma() -> MagicMock:
prisma = MagicMock()
prisma.db.execute_raw = AsyncMock(return_value=1)
return prisma
@pytest.mark.asyncio
async def test_increments_aggregate_per_job_and_flush_upserts_and_clears():
record_shadow_eval_funnel_event("leg-1", "not_sampled")
record_shadow_eval_funnel_event("leg-1", "not_sampled")
record_shadow_eval_funnel_event("leg-1", "shed")
record_shadow_eval_funnel_event("leg-2", "unjudgeable")
prisma = _prisma()
await flush_shadow_eval_funnel(prisma)
calls = {call.args[1]: call.args[2:] for call in prisma.db.execute_raw.await_args_list}
assert calls == {"leg-1": (2, 0, 0, 1, 0), "leg-2": (0, 0, 1, 0, 0)}
sql = prisma.db.execute_raw.await_args_list[0].args[0]
assert "ON CONFLICT (job_id) DO UPDATE" in sql
assert '"LiteLLM_ShadowEvalFunnel".not_sampled + EXCLUDED.not_sampled' in sql
assert shadow_eval_funnel._pending == {}
@pytest.mark.asyncio
async def test_same_model_skips_flush_into_their_own_column():
record_shadow_eval_funnel_event("leg-1", "same_model")
record_shadow_eval_funnel_event("leg-1", "same_model")
record_shadow_eval_funnel_event("leg-1", "not_sampled")
prisma: Final = _prisma()
await flush_shadow_eval_funnel(prisma)
sql, job_id, *counts = prisma.db.execute_raw.await_args.args
columns: Final = sql.split("(job_id, ", 1)[1].split(")", 1)[0].split(", ")
assert job_id == "leg-1"
assert dict(zip(columns, counts)) == {
"not_sampled": 1,
"same_model": 2,
"unjudgeable": 0,
"shed": 0,
"withheld": 0,
}
assert '"LiteLLM_ShadowEvalFunnel".same_model + EXCLUDED.same_model' in sql
@pytest.mark.asyncio
async def test_empty_queue_touches_nothing():
prisma = _prisma()
await flush_shadow_eval_funnel(prisma)
prisma.db.execute_raw.assert_not_awaited()
@pytest.mark.asyncio
async def test_a_failed_upsert_drops_only_that_legs_batch():
record_shadow_eval_funnel_event("leg-bad", "not_sampled")
record_shadow_eval_funnel_event("leg-good", "shed")
prisma = _prisma()
async def execute_raw(sql, job_id, *counts):
if job_id == "leg-bad":
raise RuntimeError("db down")
return 1
prisma.db.execute_raw = AsyncMock(side_effect=execute_raw)
await flush_shadow_eval_funnel(prisma)
flushed = [call.args[1] for call in prisma.db.execute_raw.await_args_list]
assert set(flushed) == {"leg-bad", "leg-good"}
assert shadow_eval_funnel._pending == {}
@pytest.mark.asyncio
async def test_events_recorded_during_a_flush_survive_into_the_next_batch():
record_shadow_eval_funnel_event("leg-1", "not_sampled")
prisma = _prisma()
async def execute_raw(sql, job_id, *counts):
record_shadow_eval_funnel_event("leg-2", "shed")
return 1
prisma.db.execute_raw = AsyncMock(side_effect=execute_raw)
await flush_shadow_eval_funnel(prisma)
assert shadow_eval_funnel._pending == {
"leg-2": {"not_sampled": 0, "same_model": 0, "unjudgeable": 0, "shed": 1, "withheld": 0}
}
def test_pending_count_feeds_the_drain_census():
from litellm.proxy.db.shadow_eval_funnel import pending_shadow_eval_funnel_events
assert pending_shadow_eval_funnel_events() == 0
record_shadow_eval_funnel_event("leg-1", "not_sampled")
record_shadow_eval_funnel_event("leg-1", "shed")
record_shadow_eval_funnel_event("leg-2", "unjudgeable")
assert pending_shadow_eval_funnel_events() == 3
@pytest.mark.asyncio
async def test_a_funnel_flush_renders_one_postgres_upsert_span_per_job(
postgres_span_names: Callable[[], Awaitable[tuple[str, ...]]],
) -> None:
record_shadow_eval_funnel_event("job-a", "not_sampled")
record_shadow_eval_funnel_event("job-b", "not_sampled")
prisma = MagicMock()
prisma.db.execute_raw = engine_call(1)
await flush_shadow_eval_funnel(prisma)
assert await postgres_span_names() == ("postgres.upsert LiteLLM_ShadowEvalFunnel",) * 2