litellm/tests/unit/rust_bridge/test_callbacks_legacy_python.py
ishaan-berri 5ed7ec8511
fix(lens): price agent traces by joining gen_ai.response.id to spend logs (#44738)
* fix(lens): price agent traces by joining gen_ai.response.id to spend logs

Trace spend now joins each model call to spend_logs on one key: the
span's response id (gen_ai.response.id or the id the normalizers read
from OpenInference/LangChain output) against spend_logs.response_id or
the upstream id embedded in a managed resp_ id. The litellm.call_id and
traceparent transport join paths and the per-row ownership gate are
removed; the spend SQL still restricts rows to what the reader can see.

A run with some unpriced calls now reports the sum of its priced calls
plus priced_calls, instead of an unknown total.

* test(lens): cover response id spend join and partial trace totals

* chore(lens): regenerate trace types for priced_calls

* feat(lens): show partial run cost as a lower bound with priced call count

* fix(lens): treat litellm.call_id as the same assigned call id for spend joins

The id LiteLLM assigned to a call is either the response id it returned
(gen_ai.response.id -> spend_logs.response_id) or its gateway call id
(litellm.call_id -> spend_logs.litellm_call_id). Both are exact ids the
gateway mints and logs, so the join stays one rule. Transport span
matching and the ownership gate stay removed.

* test(lens): cover litellm.call_id spend joins and restore captured totals

* feat(lens): link each priced model call to its spend log

Spans gain spend_log_request_id, the spend_logs.request_id the call was
priced from, and spend_match, which says whether a model call matched or
why not (no assigned id on the span, no spend log with that id, or an
ambiguous match). A model call span is priced from the same ids as the
run total, so its cost and the total agree.

* test(lens): cover spend log links on model call spans

* chore(lens): regenerate trace types for spend log links

* feat(lens): open the matched spend log from an LLM step

An LLM step's header now shows a Spend log chip with the matched
request id and cost; clicking it opens the request log drawer over the
run, fetched by the exact spend_logs.request_id instead of the span's
own response id. Unpriced steps say why (no assigned id on the span, or
no spend log with it). Tree rows show each model call's cost, and a
partial run cost shows its priced call count inline.

* test(lens): cover the spend log link and unmatched cost reasons

* feat(lens): show the spend log link as a bordered LiteLLM Spend Log button

* feat(lens): add a back link from the spend log drawer to the agent trace

* feat(lens): label the spend log back link Back to Lens trace with the Lens icon

* fix(lens): ignore assigned ids that name no spend log when pricing a call

An id that names no row no longer vetoes the call, so a span carrying
both a response id and a call id still prices from a spend row logged
before litellm_call_id existed. An id naming two or more rows makes the
call ambiguous, and the match reason comes from the same per-id result,
so a single matched row with no cost is reported as matched.

* fix(lens): price a trace only from spend logs in its own team

A reader with several teams could see the same assigned id in another
team's spend log; only rows from the trace's team now price it. The
user and key ownership gate stays removed.

* perf(lens): resolve each model call's spend once per trace

Model call matches are computed once when the trace is resolved and
looked up by span index, instead of scanning the model call list for
every span and walking the graph again for spans, agents and the run
total.

* fix(lens): hide a step's Cost fact only when its spend log link shows the cost

* chore(lens): drop narrative doc comments from the spend join

* fix(lens): price a model call only when its ids agree on one spend log per span

* fix(lens): keep pricing spend logs written before litellm_call_id by their request id

* fix(lens): price every attempt a model call's ids name when they agree
2026-10-06 19:55:26 +00:00

176 lines
6.7 KiB
Python

import datetime
import inspect
from collections.abc import Mapping
from pathlib import Path
from types import MappingProxyType
from typing import Final
import pytest
from pydantic import TypeAdapter
from litellm._internal_context import is_internal_call
from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.rust_bridge import callbacks_legacy_python as legacy
from litellm.rust_bridge.callbacks_legacy_python import failure_handler, setup
from litellm.types.utils import ModelResponse
_OCR_KWARGS: Final = MappingProxyType(
{
"model": "mistral/mistral-ocr-latest",
"document": {"type": "document_url", "document_url": "data:application/pdf;base64,YWJj"},
}
)
def _supplied_logger() -> Logging:
return Logging(
model="mistral/mistral-ocr-latest",
messages=[],
stream=False,
call_type="aocr",
start_time=datetime.datetime.now(),
litellm_call_id="supplied",
function_id="supplied",
)
def test_native_stream_headers_reach_spend_callbacks() -> None:
logger: Final = _supplied_logger()
legacy.stream_opened(logger, {"additional_headers": {"llm_provider-request-id": "req_native"}})
assert logger.stream is True
assert logger.model_call_details["response_headers"] == {"llm_provider-request-id": "req_native"}
def test_setup_reuses_a_supplied_logger() -> None:
supplied: Final = _supplied_logger()
result: Final = setup(
"aocr", (), {**_OCR_KWARGS, "litellm_logging_obj": supplied}, datetime.datetime.now(), asynchronous=True
)
assert result.logger is supplied
@pytest.mark.parametrize("explicit_provider", (None, "openai"))
def test_cache_hit_finalization_preserves_execution_provider_attribution(explicit_provider: str | None) -> None:
now: Final = datetime.datetime.now()
kwargs: Final = {
"model": "openai/cache-test-model",
"messages": [{"role": "user", "content": "hello"}],
"custom_llm_provider": explicit_provider,
"metadata": {"user_api_key": "key-hash"},
}
prepared: Final = setup("acompletion", (), kwargs, now, asynchronous=True)
legacy.update_logging(
prepared.logger,
prepared.kwargs,
"resolved-cache-model",
{},
{**prepared.logger.litellm_params, "custom_llm_provider": "azure"},
"azure",
)
prepared.logger.model_call_details.update({"cache_hit": True, "cache_key": "cached-response"})
response: Final = ModelResponse(model="cache-test-model")
legacy.finalize(response, prepared.logger, prepared.kwargs, now, now)
assert prepared.logger.model_call_details["custom_llm_provider"] == "azure"
assert prepared.logger.model_call_details["model"] == "resolved-cache-model"
assert prepared.logger.litellm_params["metadata"]["user_api_key"] == "key-hash"
assert response._hidden_params["cache_key"] == "cached-response"
assert response._hidden_params["response_cost"] == 0
@pytest.mark.parametrize(
"call_type, kwargs",
[
("aocr", _OCR_KWARGS),
("aembedding", MappingProxyType({"model": "text-embedding-3-large", "input": ["hi"]})),
],
ids=["ocr", "embedding"],
)
def test_setup_builds_a_logger_when_none_is_supplied(call_type: str, kwargs: Mapping[str, object]) -> None:
result: Final = setup(call_type, (), kwargs, datetime.datetime.now(), asynchronous=True)
assert result.logger.litellm_call_id == result.kwargs["litellm_call_id"]
def _budget_reservation() -> dict:
return {"reserved_cost": 0.5, "entries": [], "finalized": False, "callback_bound": False}
def _kwargs_with_a_budget_reservation(reservation: dict) -> dict[str, object]:
return {**_OCR_KWARGS, "metadata": {"user_api_key_budget_reservation": reservation}}
def test_setup_claims_the_budget_reservation_for_an_async_call() -> None:
reservation: Final = _budget_reservation()
setup("aocr", (), _kwargs_with_a_budget_reservation(reservation), datetime.datetime.now(), asynchronous=True)
assert reservation["callback_bound"] is True
def test_setup_claims_the_budget_reservation_a_supplied_logger_already_saw() -> None:
reservation: Final = _budget_reservation()
supplied: Final = _supplied_logger()
supplied.update_environment_variables(
litellm_params={"metadata": {"user_api_key_budget_reservation": reservation}}, optional_params={}
)
assert reservation["callback_bound"] is False
setup("aocr", (), {**_OCR_KWARGS, "litellm_logging_obj": supplied}, datetime.datetime.now(), asynchronous=True)
assert reservation["callback_bound"] is True
def test_setup_leaves_the_budget_reservation_alone_for_a_sync_call() -> None:
reservation: Final = _budget_reservation()
setup("aocr", (), _kwargs_with_a_budget_reservation(reservation), datetime.datetime.now(), asynchronous=False)
assert reservation["callback_bound"] is False
def test_setup_leaves_the_budget_reservation_alone_for_an_internal_call() -> None:
reservation: Final = _budget_reservation()
token: Final = is_internal_call.set(True)
try:
setup("aocr", (), _kwargs_with_a_budget_reservation(reservation), datetime.datetime.now(), asynchronous=True)
finally:
is_internal_call.reset(token)
assert reservation["callback_bound"] is False
def test_failure_handler_hands_the_budget_reservation_back_for_an_async_call() -> None:
reservation: Final = _budget_reservation()
now: Final = datetime.datetime.now()
result: Final = setup("aocr", (), _kwargs_with_a_budget_reservation(reservation), now, asynchronous=True)
assert reservation["callback_bound"] is True
pending: Final = failure_handler(result.logger, RuntimeError("upstream refused"), now, now, asynchronous=True)
assert reservation["callback_bound"] is False
assert pending is not None
pending.close()
def test_failure_handler_of_an_internal_call_leaves_the_outer_budget_reservation_claim_in_place() -> None:
reservation: Final = _budget_reservation()
now: Final = datetime.datetime.now()
result: Final = setup("aocr", (), _kwargs_with_a_budget_reservation(reservation), now, asynchronous=True)
token: Final = is_internal_call.set(True)
try:
pending: Final = failure_handler(result.logger, RuntimeError("inner step failed"), now, now, asynchronous=True)
finally:
is_internal_call.reset(token)
assert reservation["callback_bound"] is True
assert pending is not None
pending.close()
CONTRACT_PATH: Final = Path(__file__).parents[3] / "litellm-rust/crates/callbacks-legacy-python/python_contract.json"
def test_the_rust_contract_matches_the_shim_signatures() -> None:
contract: Final = TypeAdapter(dict[str, list[str]]).validate_json(CONTRACT_PATH.read_text())
assert contract == {name: list(inspect.signature(getattr(legacy, name)).parameters) for name in contract}