litellm/tests/unit/models/test_alert.py
joshua-berri e42e0db034
feat(alerts): display prompt cache advisories in existing alerts (#51943)
* feat(alerts): read and show prompt cache alerts alongside the existing alert types

Saved alerts can now carry a prompt_cache type on a deployment resource,
with evidence made of opaque fingerprints and counters only. One incident
exists per deployment and cache configuration, whatever window or prefix
found it, so a dismissed or resolved one stays the only one.

The performance list, the daily summary, the free-alert allowance and the
history lookup now name the four metric types instead of excluding model
deprecations, so these rows never reach metric charts, digests or the quota.

The All view lists prompt cache alerts from their own query, leaving the
performance query and its pagination unchanged. An alert's page shows the
deployment, model, misses in a row, the proving write, the cache lifetime
and when the misses happened, in place of a metric chart, and keeps the
existing dismiss, resolve and reopen controls.

* fix(alerts): pin prompt cache evidence to what is observed and prove the readers against the database

Prompt cache evidence now only accepts the anthropic provider and the
five-minute TTL. The title says cache usage was not observed rather than
that caching stopped, and the scope copy names the checked requests:
non-streaming Anthropic Chat Completions with one five-minute breakpoint,
after a confirmed write, with never-proven prefixes left unassessed.

Alerts are presented by their evidence shape. Metric labels come from the
evidence unit and the activity link label skips deployments, so the
unrecognized-alert fallback is gone.

The real-database alert tests now round-trip a prompt cache alert, keep it
out of the performance list and the daily summary, keep a dismissed one
as the only incident, and leave it out of the free allowance. They replace
the unit tests that only checked SQL arguments. The UI tests reopen an
incident, page both lists in All from their own cursors, and drop loaded
prompt cache alerts when Performance is chosen.

* chore(ui): regenerate API types for prompt cache alerts

Alerts can now carry the prompt_cache type, the deployment resource and prompt cache evidence, so the generated dashboard types include them.

* fix(alerts): satisfy the dashboard lint and the bounded IN check for prompt cache alerts

The prompt cache list query reuses useAlerts with the prompt_cache type, so
no five-parameter helper is needed. The new prompt cache mock handling in
the Alerts integration test lives in its own function, a presentation test
names its expected details, and AlertDetail is formatted. The performance
list's IN filter over the four fixed metric types records that bound.

* fix(alerts): reject metric alerts on a deployment resource

Only prompt cache alerts use the new deployment resource. Metric alerts have no deployment history source, so a metric alert on a deployment is now invalid. Every combination accepted before this change is still accepted.

* test(alerts): match the plain token count the prompt cache evidence renders

* fix(ui): describe prompt cache alerts as advisory observed evidence

The alert reports requests the proxy observed. Delayed, missing or unlogged requests can fall between them, so the list and detail say they are not necessarily consecutive and do not prove an outage. The serialized consecutive_misses field is unchanged.

* fix(ui): title prompt cache alerts as advisories and attribute the limit to observations

The title no longer reads as a deployment-wide finding, and the limitation says delayed, missing or unlogged observations mean the requests are not necessarily consecutive and do not prove a caching outage.

* docs(alerts): describe consecutive_misses as observed requests that are not necessarily consecutive

* chore(ui): regenerate API types for the advisory prompt cache evidence description

---------

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

124 lines
4.8 KiB
Python

from collections.abc import Mapping
from datetime import timedelta, timezone
from typing import Final
import pytest
from pydantic import ValidationError
from litellm.models.alert import AlertDetection
DETECTION: Final = {
"type": "spend",
"resource_type": "team",
"resource_id": "example-team",
"window_start": "2026-01-08T00:00:00Z",
"window_end": "2026-01-09T00:00:00Z",
"evidence": {"value": 20, "baseline": 2, "unit": "usd", "sample_size": 50},
}
@pytest.mark.parametrize(
"change",
(
{"resource_id": "x" * 1025},
{"resource_id": ""},
{"resource_type": "key", "resource_id": "sk-example-not-a-real-key"},
{"resource_type": "gateway", "resource_id": "another-gateway"},
{"resource_type": "deployment", "resource_id": "claude-east"},
{
"resource_type": "gateway",
"resource_id": "gateway",
"type": "model_deprecation",
"evidence": {"deprecation_date": "2026-02-01"},
},
{"window_start": "2026-01-08T00:00:00"},
{"window_start": "2026-01-08T00:00:00.123456Z", "window_end": "2026-01-08T00:00:00.123457Z"},
{"window_end": "2026-01-08T00:00:00Z"},
{"window_end": "2026-01-07T00:00:00Z"},
{"type": "custom"},
{"type": "latency"},
{"type": "model_deprecation"},
{"evidence": {"value": float("inf"), "baseline": 2, "unit": "usd", "sample_size": 1}},
{"evidence": {"value": 2, "baseline": float("nan"), "unit": "usd", "sample_size": 1}},
{"evidence": {"value": -1, "baseline": 2, "unit": "usd", "sample_size": 1}},
{"evidence": {"value": 2, "baseline": 2, "unit": "usd", "sample_size": -1}},
{"evidence": {"value": 2, "baseline": 2, "unit": "usd", "sample_size": 1, "unbounded": "extra"}},
{"type": "reliability", "evidence": {"value": 1.1, "baseline": 0, "unit": "ratio", "sample_size": 1}},
{"type": "reliability", "evidence": {"value": 0, "baseline": 1.1, "unit": "ratio", "sample_size": 1}},
{
"resource_type": "model",
"type": "model_deprecation",
"evidence": {"deprecation_date": "2026-02-01", "replacement_model": "x" * 1025},
},
),
)
def test_invalid_or_unbounded_detection_is_rejected(change: Mapping[str, object]) -> None:
with pytest.raises(ValidationError):
AlertDetection.model_validate({**DETECTION, **change})
def test_identity_uses_instants_not_timezone_or_evidence() -> None:
original: Final = AlertDetection.model_validate(DETECTION)
revised: Final = original.model_copy(
update={
"window_start": original.window_start.astimezone(timezone(timedelta(hours=8))),
"window_end": original.window_end.astimezone(timezone(timedelta(hours=8))),
"evidence": original.evidence.model_copy(update={"value": 30}),
}
)
assert original.identity() == revised.identity()
CACHE_EVIDENCE: Final[Mapping[str, object]] = {
"config_fingerprint": "config-1",
"prefix_fingerprint": "prefix-1",
"provider": "anthropic",
"provider_model": "claude-test",
"consecutive_misses": 3,
"proven_write_tokens": 2048,
"ttl_seconds": 300,
}
PROMPT_CACHE: Final[Mapping[str, object]] = {
"type": "prompt_cache",
"resource_type": "deployment",
"resource_id": "claude-east",
"window_start": "2026-01-08T00:00:00Z",
"window_end": "2026-01-08T00:00:03Z",
"evidence": CACHE_EVIDENCE,
}
@pytest.mark.parametrize(
"change",
(
{"resource_type": "model"},
{"evidence": DETECTION["evidence"]},
{"type": "spend"},
{"evidence": {**CACHE_EVIDENCE, "consecutive_misses": 0}},
{"evidence": {**CACHE_EVIDENCE, "provider": "bedrock"}},
{"evidence": {**CACHE_EVIDENCE, "ttl_seconds": 3600}},
{"evidence": {**CACHE_EVIDENCE, "prompt": "never retained"}},
),
)
def test_prompt_cache_detection_accepts_only_its_deployment_resource_and_supported_evidence(
change: Mapping[str, object],
) -> None:
with pytest.raises(ValidationError):
AlertDetection.model_validate({**PROMPT_CACHE, **change})
def test_prompt_cache_identity_is_one_per_deployment_configuration_whatever_window_found_it() -> None:
first: Final = AlertDetection.model_validate(PROMPT_CACHE)
later: Final = AlertDetection.model_validate(
{
**PROMPT_CACHE,
"window_start": "2026-02-08T00:00:00Z",
"window_end": "2026-02-08T00:00:09Z",
"evidence": {**CACHE_EVIDENCE, "prefix_fingerprint": "prefix-2", "consecutive_misses": 4},
}
)
upgraded: Final = AlertDetection.model_validate(
{**PROMPT_CACHE, "evidence": {**CACHE_EVIDENCE, "config_fingerprint": "config-2"}}
)
assert first.identity() == later.identity()
assert first.identity() != upgraded.identity()