litellm/tests/test_litellm/test_model_cost_aliases.py
Ishaan Jaff b87d1f8dad
[Feat] - Ishaan main merge branch (#23596)
* fix(bedrock): respect s3_region_name for batch file uploads (#23569)

* fix(bedrock): respect s3_region_name for batch file uploads (GovCloud fix)

* fix: s3_region_name always wins over aws_region_name for S3 signing (Greptile feedback)

* fix: _filter_headers_for_aws_signature - Bedrock KB (#23571)

* fix: _filter_headers_for_aws_signature

* fix: filter None header values in all post-signing re-merge paths

Addresses Greptile feedback: None-valued headers were being filtered
during SigV4 signing but re-merged back into the final headers dict
afterward, which would cause downstream HTTP client failures.

Made-with: Cursor

* feat(router): tag_regex routing — route by User-Agent regex without per-developer tag config (#23594)

* feat(router): add tag_regex support for header-based routing

Adds a new `tag_regex` field to litellm_params that lets operators route
requests based on regex patterns matched against request headers — primarily
User-Agent — without requiring per-developer tag configuration.

Use case: route all Claude Code traffic (User-Agent: claude-code/x.y.z) to
a dedicated deployment by setting:

  tag_regex:
    - "^User-Agent: claude-code\\/"

in the deployment's litellm_params. Works alongside existing `tags` routing;
exact tag match takes precedence over regex match. Unmatched requests fall
through to deployments tagged `default`.

The matched deployment, pattern, and user_agent are recorded in
`metadata["tag_routing"]` so they flow through to SpendLogs automatically.

* fix(tag_regex): address backwards-compat, metadata overwrite, and warning noise

Three issues from code review:

1. Backwards-compat: `has_tag_filter` was widened to activate on any non-empty
   User-Agent, which would raise ValueError for existing deployments using plain
   tags without a `default` fallback. Fix: only activate header-based regex
   filtering when at least one candidate deployment has `tag_regex` configured.

2. Metadata overwrite: `metadata["tag_routing"]` was overwritten for every
   matching deployment in the loop, leaving inaccurate provenance when multiple
   deployments match. Fix: write only for the first match.

3. Warning noise: an invalid regex pattern logged one warning per header string
   rather than once per pattern. Fix: compile first (catching re.error once),
   then iterate over header strings.

Also adds two new tests covering these cases, and adds docs page for
tag_regex routing with a Claude Code walk-through.

* refactor(tag_regex): remove unnecessary _healthy_list copy

* docs: merge tag_regex section into tag_routing.md, remove standalone page

- Add ## Regex-based tag routing (tag_regex) section to existing
  tag_routing.md instead of a separate page
- Remove tag_regex_routing.md standalone doc (odd UX to have a separate
  page for a sub-feature)
- Remove proxy/tag_regex_routing from sidebars.js
- Add match_any=False debug warning in tag_based_routing.py when regex
  routing fires under strict mode (regex always uses OR semantics)

* fix(tag_regex): address greptile review - security docs, strict-mode enforcement, validation order

- Strengthen security note in tag_routing.md: explicitly state User-Agent
  is client-supplied and can be set to any value; frame tag_regex as a
  traffic classification hint, not an access-control mechanism
- Move tag_regex startup validation before _add_deployment() so an invalid
  pattern never leaves partial router state
- Enforce match_any=False strict-tag policy: when a deployment has both
  tags and tag_regex and the strict tag check fails, skip the regex fallback
  rather than silently bypassing the operator's intent
- Extract per-deployment match logic into _match_deployment() helper to
  keep get_deployments_for_tag() readable
- Add two new tests: strict-mode blocks regex fallback, regex-only
  deployment still matches under match_any=False

* fix(ci): apply Black formatting to 14 files and stabilize flaky caplog tests

- Run Black formatter on 14 files that were failing the lint check
- Replace caplog-based assertions in TestAliasConflicts with
  unittest.mock.patch on verbose_logger.warning for xdist compatibility
- The caplog fixture can produce empty text in pytest-xdist workers
  in certain CI environments, causing flaky test failures

Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Ishaan Jaff <ishaan-jaff@users.noreply.github.com>
2026-03-14 09:40:00 -07:00

245 lines
8.6 KiB
Python

"""
Tests for the ``aliases`` feature in the model cost map.
The ``_expand_model_aliases`` function processes ``aliases`` lists from model
entries, creating shared dict references for alias entries at load time.
"""
from unittest.mock import patch
from litellm import verbose_logger
from litellm.litellm_core_utils.get_model_cost_map import _expand_model_aliases
# ---------------------------------------------------------------------------
# Core expansion behaviour
# ---------------------------------------------------------------------------
class TestExpandModelAliases:
"""Unit tests for _expand_model_aliases."""
def test_basic_expansion(self):
"""Aliases are added as top-level entries in model_cost."""
model_cost = {
"my-model-latest": {
"aliases": ["my-model-20250101"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert "my-model-20250101" in result
assert result["my-model-20250101"]["input_cost_per_token"] == 1e-06
assert result["my-model-20250101"]["litellm_provider"] == "test"
def test_multiple_aliases(self):
"""A single entry can declare multiple aliases."""
model_cost = {
"provider/model-latest": {
"aliases": ["provider/model-v1", "provider/model-v2"],
"input_cost_per_token": 5e-06,
"litellm_provider": "provider",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert "provider/model-v1" in result
assert "provider/model-v2" in result
def test_shared_dict_reference(self):
"""Alias entries share the same dict object as the canonical entry (no copy)."""
model_cost = {
"canonical-model": {
"aliases": ["alias-model"],
"input_cost_per_token": 2e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert result["alias-model"] is result["canonical-model"]
def test_aliases_key_removed(self):
"""The ``aliases`` key is removed from the entry after expansion."""
model_cost = {
"my-model": {
"aliases": ["my-model-alias"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert "aliases" not in result["my-model"]
assert "aliases" not in result["my-model-alias"]
def test_entries_without_aliases_unchanged(self):
"""Entries with no ``aliases`` key are left untouched."""
model_cost = {
"plain-model": {
"input_cost_per_token": 3e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert "plain-model" in result
assert result["plain-model"]["input_cost_per_token"] == 3e-06
assert len(result) == 1
def test_empty_aliases_list(self):
"""An empty ``aliases`` list is treated the same as no aliases."""
model_cost = {
"model-a": {
"aliases": [],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert len(result) == 1
assert "model-a" in result
assert "aliases" not in result["model-a"]
# ---------------------------------------------------------------------------
# Conflict handling
# ---------------------------------------------------------------------------
class TestAliasConflicts:
"""Tests for alias conflict detection and handling."""
def test_alias_conflicts_with_canonical_entry(self):
"""Alias that matches an existing canonical entry is skipped with a warning."""
model_cost = {
"model-latest": {
"aliases": ["model-dated"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
"model-dated": {
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
with patch.object(verbose_logger, "warning") as mock_warn:
result = _expand_model_aliases(model_cost)
# The canonical "model-dated" entry is preserved, not overwritten
assert "model-dated" in result
# Verify a warning about the alias conflict was logged
mock_warn.assert_called()
warning_messages = " ".join(str(c) for c in mock_warn.call_args_list)
assert "alias conflict" in warning_messages.lower()
def test_duplicate_alias_across_entries(self):
"""Same alias claimed by two different entries: second one is skipped."""
model_cost = {
"model-a": {
"aliases": ["shared-alias"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
"model-b": {
"aliases": ["shared-alias"],
"input_cost_per_token": 2e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
with patch.object(verbose_logger, "warning") as mock_warn:
result = _expand_model_aliases(model_cost)
# "shared-alias" should point to model-a (first one wins)
assert "shared-alias" in result
assert result["shared-alias"]["input_cost_per_token"] == 1e-06
# Verify a warning about the alias conflict was logged
mock_warn.assert_called()
warning_messages = " ".join(str(c) for c in mock_warn.call_args_list)
assert "alias conflict" in warning_messages.lower()
def test_canonical_entry_not_overwritten_by_alias(self):
"""An alias must never overwrite an existing canonical entry's data."""
original_cost = 9.99e-06
model_cost = {
"existing-model": {
"input_cost_per_token": original_cost,
"litellm_provider": "test",
"mode": "chat",
},
"other-model": {
"aliases": ["existing-model"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
# Original entry must be preserved
assert result["existing-model"]["input_cost_per_token"] == original_cost
# ---------------------------------------------------------------------------
# Integration with model_cost dict mutation
# ---------------------------------------------------------------------------
class TestAliasIntegration:
"""Higher-level tests verifying aliases work with the model_cost dict."""
def test_mutation_through_alias_visible_on_canonical(self):
"""Since alias is a shared reference, mutations are visible on both."""
model_cost = {
"canonical": {
"aliases": ["alias"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
# Mutate via alias
result["alias"]["input_cost_per_token"] = 999
assert result["canonical"]["input_cost_per_token"] == 999
def test_mixed_entries_with_and_without_aliases(self):
"""A model_cost dict with a mix of aliased and plain entries."""
model_cost = {
"model-with-alias": {
"aliases": ["alias-1", "alias-2"],
"input_cost_per_token": 1e-06,
"litellm_provider": "test",
"mode": "chat",
},
"plain-model": {
"input_cost_per_token": 2e-06,
"litellm_provider": "test",
"mode": "chat",
},
}
result = _expand_model_aliases(model_cost)
assert len(result) == 4 # 2 canonical + 2 aliases
assert "alias-1" in result
assert "alias-2" in result
assert "plain-model" in result
assert "model-with-alias" in result
def test_expand_on_empty_dict(self):
"""Expanding an empty dict returns an empty dict."""
assert _expand_model_aliases({}) == {}