Skip to content

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]

14.7 KB
Raw Blame
"""Unit tests for the AdaptiveRouter strategy class."""

from unittest.mock import AsyncMock, MagicMock

from litellm.router_strategy.adaptive_router import adaptive_router as ar_module

import pytest

from litellm.router_strategy.adaptive_router.adaptive_router import AdaptiveRouter
from litellm.router_strategy.adaptive_router.bandit import initial_cell
from litellm.router_strategy.adaptive_router.signals import Turn
from litellm.types.router import (
    AdaptiveRouterConfig,
    AdaptiveRouterPreferences,
    RequestType,
)


def _make_router() -> AdaptiveRouter:
    cfg = AdaptiveRouterConfig(available_models=["fast", "smart"])
    prefs = {
        "fast": AdaptiveRouterPreferences(quality_tier=1, strengths=[]),
        "smart": AdaptiveRouterPreferences(quality_tier=3, strengths=[RequestType.CODE_GENERATION]),
    }
    costs = {"fast": 0.0001, "smart": 0.001}
    return AdaptiveRouter(
        router_name="r1",
        config=cfg,
        model_to_prefs=prefs,
        model_to_cost=costs,
    )


@pytest.mark.asyncio
async def test_pick_model_returns_model_from_available_list():
    r = _make_router()
    chosen = await r.pick_model(RequestType.GENERAL)
    assert chosen in {"fast", "smart"}


@pytest.mark.asyncio
async def test_pick_model_min_quality_tier_filter():
    r = _make_router()
    # min_tier=3 should leave only `smart` (tier 3); `fast` (tier 1) is filtered.
    for _ in range(20):
        chosen = await r.pick_model(RequestType.GENERAL, min_quality_tier=3)
        assert chosen == "smart"


@pytest.mark.asyncio
async def test_pick_model_min_quality_tier_filter_raises_when_no_eligible():
    r = _make_router()
    with pytest.raises(ValueError, match="min_quality_tier=4"):
        await r.pick_model(RequestType.GENERAL, min_quality_tier=4)


# ---- record_turn --------------------------------------------------------


@pytest.mark.asyncio
async def test_record_turn_pushes_to_queue():
    r = _make_router()
    # Prime with 2 prior turns so satisfaction gate (MIN_TURNS_FOR_CLEAN_CREDIT=3)
    # is satisfied when the "thanks" turn arrives.
    for _ in range(2):
        await r.record_turn(
            session_id="s1",
            model_name="fast",
            request_type=RequestType.GENERAL,
            turn=Turn(user_content="hi", assistant_content="hello"),
        )

    r.queue.add_session_state = AsyncMock()
    r.queue.add_state_delta = AsyncMock()

    turn = Turn(user_content="thanks, that worked", assistant_content="ok")
    await r.record_turn(
        session_id="s1",
        model_name="fast",
        request_type=RequestType.GENERAL,
        turn=turn,
    )

    r.queue.add_session_state.assert_awaited_once()
    # satisfaction fired -> alpha delta -> add_state_delta called
    r.queue.add_state_delta.assert_awaited_once()

    # PII guard: raw conversation content must not be in the persisted snapshot.
    snapshot = r.queue.add_session_state.call_args.args[3]
    for sensitive in (
        "last_user_content",
        "last_assistant_content",
        "tool_call_history",
        "pending_tool_calls",
    ):
        assert sensitive not in snapshot, f"{sensitive} leaked into DB payload"


@pytest.mark.asyncio
async def test_record_turn_satisfaction_increments_alpha():
    r = _make_router()
    # Prime with 2 prior turns to clear the MIN_TURNS_FOR_CLEAN_CREDIT gate.
    # Use distinct content to avoid incidentally firing stagnation/misalignment.
    priming_turns = [
        Turn(user_content="alpha bravo charlie", assistant_content="delta echo foxtrot"),
        Turn(
            user_content="golf hotel india juliet",
            assistant_content="kilo lima mike november",
        ),
    ]
    for t in priming_turns:
        await r.record_turn(
            session_id="sX",
            model_name="fast",
            request_type=RequestType.GENERAL,
            turn=t,
        )
    cell_before = r._cells[(RequestType.GENERAL, "fast")]
    turn = Turn(user_content="that worked, thanks!")
    await r.record_turn(
        session_id="sX",
        model_name="fast",
        request_type=RequestType.GENERAL,
        turn=turn,
    )
    cell_after = r._cells[(RequestType.GENERAL, "fast")]
    assert cell_after.alpha == pytest.approx(cell_before.alpha + 1.0)
    assert cell_after.beta == pytest.approx(cell_before.beta)


@pytest.mark.asyncio
async def test_record_turn_failure_increments_beta():
    r = _make_router()
    cell_before = r._cells[(RequestType.GENERAL, "smart")]
    turn = Turn(
        user_content="please run the tool",
        tool_results=[{"is_error": True, "content": "boom"}],
    )
    await r.record_turn(
        session_id="sY",
        model_name="smart",
        request_type=RequestType.GENERAL,
        turn=turn,
    )
    cell_after = r._cells[(RequestType.GENERAL, "smart")]
    assert cell_after.beta == pytest.approx(cell_before.beta + 1.0)
    assert cell_after.alpha == pytest.approx(cell_before.alpha)


@pytest.mark.asyncio
async def test_record_turn_detects_exhaustion_in_tool_results():
    r = _make_router()

    delta = await r.record_turn(
        session_id="exhausted",
        model_name="smart",
        request_type=RequestType.GENERAL,
        turn=Turn(tool_results=[{"content": "rate limit exceeded"}]),
    )

    assert delta.exhaustion == 1
    assert r._session_states[("exhausted", "smart")].exhaustion_count == 1


@pytest.mark.asyncio
async def test_record_turn_attributes_user_feedback_to_previous_response_model():
    r = _make_router()
    fast_before = r._cells[(RequestType.CODE_GENERATION, "fast")]
    smart_before = r._cells[(RequestType.GENERAL, "smart")]

    await r.record_turn(
        session_id="feedback-switch",
        model_name="fast",
        request_type=RequestType.CODE_GENERATION,
        turn=Turn(
            user_content="fix this python retry bug",
            assistant_content="clear the cache on every retry",
        ),
    )
    await r.record_turn(
        session_id="feedback-switch",
        model_name="smart",
        request_type=RequestType.GENERAL,
        turn=Turn(
            user_content="the python fix is still broken",
            assistant_content="keep successful cache entries",
        ),
    )

    fast_after = r._cells[(RequestType.CODE_GENERATION, "fast")]
    smart_after = r._cells[(RequestType.GENERAL, "smart")]
    assert fast_after.beta == pytest.approx(fast_before.beta + 1.0)
    assert smart_after.beta == pytest.approx(smart_before.beta)
    snapshot = await r.get_state_snapshot()
    assert snapshot["feedback_attributed_total"] == 1
    assert snapshot["cross_model_feedback_total"] == 1
    assert snapshot["feedback_without_context_total"] == 0


@pytest.mark.asyncio
async def test_record_turn_attributes_satisfaction_to_previous_response_model():
    r = _make_router()
    await r.record_turn(
        session_id="satisfaction-switch",
        model_name="smart",
        request_type=RequestType.CODE_GENERATION,
        turn=Turn(
            user_content="write a python retry helper",
            assistant_content="first draft",
        ),
    )
    await r.record_turn(
        session_id="satisfaction-switch",
        model_name="fast",
        request_type=RequestType.CODE_GENERATION,
        turn=Turn(
            user_content="add exponential backoff to the python helper",
            assistant_content="updated draft",
        ),
    )
    fast_before = r._cells[(RequestType.CODE_GENERATION, "fast")]
    smart_before = r._cells[(RequestType.GENERAL, "smart")]

    await r.record_turn(
        session_id="satisfaction-switch",
        model_name="smart",
        request_type=RequestType.GENERAL,
        turn=Turn(
            user_content="thanks, that worked",
            assistant_content="glad to help",
        ),
    )

    fast_after = r._cells[(RequestType.CODE_GENERATION, "fast")]
    smart_after = r._cells[(RequestType.GENERAL, "smart")]
    assert fast_after.alpha == pytest.approx(fast_before.alpha + 1.0)
    assert smart_after.alpha == pytest.approx(smart_before.alpha)


@pytest.mark.asyncio
async def test_external_default_keeps_feedback_history_without_entering_bandit_pool():
    r = _make_router()
    before = r._cells[(RequestType.GENERAL, "fast")]
    await r.record_turn(
        session_id="fallback",
        model_name="fast",
        request_type=RequestType.GENERAL,
        turn=Turn(user_content="fix this retry bug", assistant_content="clear the cache"),
    )
    await r.record_turn(
        session_id="fallback",
        model_name="external-default",
        request_type=RequestType.GENERAL,
        turn=Turn(user_content="the fix is still broken", assistant_content="keep cache entries"),
    )
    assert r._cells[(RequestType.GENERAL, "fast")].beta > before.beta
    await r.record_turn(
        session_id="fallback",
        model_name="smart",
        request_type=RequestType.GENERAL,
        turn=Turn(
            user_content="the fix is still broken",
            assistant_content="use the corrected entry",
            tool_results=[{"is_error": True, "content": "failure"}],
        ),
    )
    assert r._feedback_contexts["fallback"].model_name == "smart"
    assert all(model != "external-default" for _, model in r._cells)
    assert r.config.available_models == ["fast", "smart"]


@pytest.mark.asyncio
async def test_record_turn_bounds_feedback_contexts_and_evicts_least_recent_session():
    r = _make_router()
    context_limit = ar_module._FEEDBACK_CONTEXT_MAX_ENTRIES

    for index in range(context_limit):
        await r.record_turn(
            session_id=f"session-{index}",
            model_name="fast",
            request_type=RequestType.GENERAL,
            turn=Turn(user_content="question", assistant_content="answer"),
        )

    await r.record_turn(
        session_id="session-0",
        model_name="fast",
        request_type=RequestType.GENERAL,
        turn=Turn(user_content="follow up", assistant_content="updated answer"),
    )
    await r.record_turn(
        session_id="overflow",
        model_name="fast",
        request_type=RequestType.GENERAL,
        turn=Turn(user_content="question", assistant_content="answer"),
    )

    assert len(r._feedback_contexts) == context_limit
    assert "session-0" in r._feedback_contexts
    assert "session-1" not in r._feedback_contexts
    assert "overflow" in r._feedback_contexts


@pytest.mark.asyncio
async def test_load_state_from_db_adds_the_persisted_delta_to_the_cold_start_prior():
    """A row holds an accumulated delta, not a full posterior; loading must add it to the
    cold-start prior, not replace the cell outright."""
    r = _make_router()
    cold = r._cells[(RequestType.GENERAL, "fast")]

    fake_row = MagicMock()
    fake_row.request_type = "general"
    fake_row.model_name = "fast"
    fake_row.alpha = 42.0
    fake_row.beta = 13.0

    prisma = MagicMock()
    prisma.db.litellm_adaptiverouterstate.find_many = AsyncMock(return_value=[fake_row])
    await r.load_state_from_db(prisma)

    new_cell = r._cells[(RequestType.GENERAL, "fast")]
    assert (new_cell.alpha, new_cell.beta) == (cold.alpha + 42.0, cold.beta + 13.0)


@pytest.mark.asyncio
async def test_load_state_from_db_keeps_a_one_sided_delta_row_sampleable():
    """A cell whose only DB activity is one signal type persists a one-sided row (e.g.
    beta=0.0); loading it must not zero out a Beta shape parameter and crash thompson_sample()."""
    from litellm.router_strategy.adaptive_router.bandit import thompson_sample

    r = _make_router()

    one_sided_row = MagicMock()
    one_sided_row.request_type = "general"
    one_sided_row.model_name = "fast"
    one_sided_row.alpha = 1.0
    one_sided_row.beta = 0.0

    prisma = MagicMock()
    prisma.db.litellm_adaptiverouterstate.find_many = AsyncMock(return_value=[one_sided_row])
    await r.load_state_from_db(prisma)

    loaded_cell = r._cells[(RequestType.GENERAL, "fast")]
    assert loaded_cell.alpha > 0.0
    assert loaded_cell.beta > 0.0
    thompson_sample(loaded_cell)  # must not raise


@pytest.mark.asyncio
async def test_load_state_from_db_handles_unknown_request_type():
    r = _make_router()
    cold_general = r._cells[(RequestType.GENERAL, "fast")]
    cold_writing = r._cells[(RequestType.WRITING, "fast")]

    bad_row = MagicMock()
    bad_row.request_type = "nonexistent_type_v999"
    bad_row.model_name = "fast"
    bad_row.alpha = 999.0
    bad_row.beta = 999.0

    good_row = MagicMock()
    good_row.request_type = "general"
    good_row.model_name = "fast"
    good_row.alpha = 7.0
    good_row.beta = 3.0

    prisma = MagicMock()
    prisma.db.litellm_adaptiverouterstate.find_many = AsyncMock(return_value=[bad_row, good_row])
    await r.load_state_from_db(prisma)

    # Unknown skipped; good added to the cold-start prior.
    new_general = r._cells[(RequestType.GENERAL, "fast")]
    assert new_general.alpha == cold_general.alpha + 7.0
    # Other request types kept their own cold-start values.
    assert r._cells[(RequestType.WRITING, "fast")] == cold_writing


# ---- Session state eviction ---------------------------------------------


def test_session_state_is_evicted_after_ttl():
    """Entries older than OWNER_CACHE_TTL_SECONDS must be dropped when the
    sweep runs (triggered by hitting _SESSION_STATE_SWEEP_THRESHOLD)."""
    import time as _time

    from litellm.router_strategy.adaptive_router import adaptive_router as ar

    r = _make_router()
    threshold = ar._SESSION_STATE_SWEEP_THRESHOLD

    # Backdate one session so its TTL has already passed.
    stale_key = ("sess-stale", "fast")
    r.get_or_create_session_state("sess-stale", "fast", RequestType.GENERAL)
    r._session_states_expiry[stale_key] = _time.time() - 1

    # Fill cache up to the sweep threshold to force eviction on next insert.
    for i in range(threshold):
        r.get_or_create_session_state(f"sess-{i}", "fast", RequestType.GENERAL)

    # Next insert triggers the sweep; stale entry should be gone.
    r.get_or_create_session_state("sess-new", "fast", RequestType.GENERAL)
    assert stale_key not in r._session_states
    assert stale_key not in r._session_states_expiry


def test_session_state_expiry_is_refreshed_on_access():
    """Re-fetching a session state keeps it alive — TTL is a last-activity
    timeout, not an absolute TTL."""
    import time as _time

    r = _make_router()
    r.get_or_create_session_state("sess-A", "fast", RequestType.GENERAL)
    first_exp = r._session_states_expiry[("sess-A", "fast")]

    _time.sleep(0.01)  # move clock forward
    r.get_or_create_session_state("sess-A", "fast", RequestType.GENERAL)
    second_exp = r._session_states_expiry[("sess-A", "fast")]

    assert second_exp > first_exp


@pytest.mark.parametrize("model", ["fast", "smart"])
def test_cell_returns_the_cold_start_prior_for_an_available_model(model):
    r = _make_router()
    cell = r.cell(RequestType.CODE_GENERATION, model)
    assert cell == initial_cell(r.model_to_prefs[model], RequestType.CODE_GENERATION)
    assert cell.total_samples == 0