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]

304 KB
Raw Blame
import asyncio
import collections
import datetime
import hashlib
import json
import re
import sqlite3
from datetime import timezone
from typing import Final
from unittest.mock import AsyncMock, MagicMock, patch

import prisma
import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient

import litellm
import litellm.proxy.proxy_server as ps
from litellm.proxy.auth.authorization import OwnedRows
from litellm.proxy.auth.authorization_dependencies import get_log_team_lookup, load_permitted_log_team_ids


def _default_date_range():
    """Return (start_date, end_date) for the common 7-day range used in UI spend tests."""
    now = datetime.datetime.now(timezone.utc)
    return (
        (now - datetime.timedelta(days=7)).strftime("%Y-%m-%d %H:%M:%S"),
        now.strftime("%Y-%m-%d %H:%M:%S"),
    )


def _filter_logs_by_date_range(logs, where):
    """Filter logs by startTime gte/lte from where conditions."""
    if "startTime" not in where:
        return logs
    date_filters = where["startTime"]
    filtered = []
    for log in logs:
        log_date = datetime.datetime.fromisoformat(log["startTime"].replace("Z", "+00:00"))
        if "gte" in date_filters:
            fd = date_filters["gte"]
            filter_date = (
                datetime.datetime.fromisoformat(fd.replace("Z", "+00:00"))
                if "T" in fd
                else datetime.datetime.strptime(fd, "%Y-%m-%d %H:%M:%S")
            )
            if log_date < filter_date:
                continue
        if "lte" in date_filters:
            fd = date_filters["lte"]
            filter_date = (
                datetime.datetime.fromisoformat(fd.replace("Z", "+00:00"))
                if "T" in fd
                else datetime.datetime.strptime(fd, "%Y-%m-%d %H:%M:%S")
            )
            if log_date > filter_date:
                continue
        filtered.append(log)
    return filtered


_SEARCH_CLAUSE_RE = re.compile(
    r'\(request_id = \$(\d+) OR \("startTime" >= \(\$(\d+)::timestamptz AT TIME ZONE \'UTC\'\) '
    r'AND "startTime" <= \(\$(\d+)::timestamptz AT TIME ZONE \'UTC\'\) '
    r'AND \(litellm_call_id = \$\1 OR api_key = \$\1 OR team_id = \$\1 OR "user" = \$\1 OR end_user = \$\1 '
    r"OR session_id = \$\1 OR model_id = \$\1\)\)\)"
)


def _matches_spend_log_search(log, search):
    """Mirror the search clause: request_id across all time, the other id columns inside the window."""
    if log.get("request_id") == search["value"]:
        return True
    if not _filter_logs_by_date_range([log], {"startTime": {"gte": search["gte"], "lte": search["lte"]}}):
        return False
    columns = ("litellm_call_id", "api_key", "team_id", "user", "end_user", "session_id", "model_id")
    return any(log.get(col) == search["value"] for col in columns)


def _reconstruct_ui_where_from_sql(sql_query, params):
    """
    Rebuild the Prisma-style ``where`` dict the filter_fns below expect from the
    raw SQL + params the endpoint emits.

    ``ui_view_spend_logs`` computes the total with a bounded
    ``SELECT COUNT(*) FROM (SELECT 1 ... LIMIT $cap+1)`` query and fetches the
    page with a separate ``ORDER BY ... LIMIT/OFFSET`` query. Both carry the
    same WHERE clause, so the terminator can be ``ORDER BY`` (page query) or
    ``LIMIT`` (bounded count query).
    """
    where: dict = {}
    clause = re.search(r"WHERE (.*?)\s+(?:ORDER BY|LIMIT)", sql_query, re.DOTALL)
    if clause is None:
        return where

    def _iso(value):
        return value.isoformat() if hasattr(value, "isoformat") else str(value)

    search_clause = _SEARCH_CLAUSE_RE.search(clause.group(1))
    if search_clause:
        raw_index, start_index, end_index = (int(g) for g in search_clause.groups())
        where["search"] = {
            "value": params[raw_index - 1],
            "gte": _iso(params[start_index - 1]),
            "lte": _iso(params[end_index - 1]),
        }
    remaining = clause.group(1) if search_clause is None else clause.group(1).replace(search_clause.group(0), "")

    eq_cols = {
        "team_id": "team_id",
        '"user"': "user",
        "api_key": "api_key",
        "request_id": "request_id",
        "model": "model",
        "model_id": "model_id",
        "model_group": "model_group",
        "end_user": "end_user",
    }
    date_bounds: dict = {}
    metadata_conds: list = []
    for cond in (c.strip() for c in remaining.split(" AND ")):
        gte = re.search(r'"startTime" >= \(\$(\d+)', cond)
        lte = re.search(r'"startTime" <= \(\$(\d+)', cond)
        alias = re.search(r"user_api_key_alias' LIKE \$(\d+)", cond)
        code = re.search(r"error_code' = \$(\d+)", cond)
        msg = re.search(r"error_message' LIKE \$(\d+)", cond)
        credential = re.fullmatch(r"metadata->>'used_client_oauth_token' = \$(\d+)", cond)
        sess = re.fullmatch(r"session_id LIKE \$(\d+)", cond)
        status = re.fullmatch(r"status = \$(\d+)", cond)
        api_key_not_in = re.fullmatch(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", cond)
        req_or_call = re.fullmatch(r"\(request_id = \$(\d+) OR litellm_call_id = \$\1\)", cond)
        if req_or_call:
            where["request_id_or_call_id"] = params[int(req_or_call.group(1)) - 1]
        elif gte:
            date_bounds["gte"] = _iso(params[int(gte.group(1)) - 1])
        elif lte:
            date_bounds["lte"] = _iso(params[int(lte.group(1)) - 1])
        elif "OR team_id = ANY" in cond:
            where["OR"] = where.get("OR", []) + [{"multi_team": True}]
        elif "status = 'success'" in cond:
            where["OR"] = where.get("OR", []) + [{"status": "success"}]
        elif cond == "LOWER(cache_hit) = 'true'":
            where["cache_hit"] = "hit"
        elif cond == "(cache_hit IS NULL OR LOWER(cache_hit) != 'true')":
            where["cache_hit"] = "miss"
        elif "call_type" in cond:
            if "call_type NOT IN" in cond:
                where["span_type"] = "llm"
            elif "call_mcp_tool" in cond:
                where["span_type"] = "mcp"
            elif "call_type = 'asend_message'" in cond:
                where["span_type"] = "agent"
            elif "acreate_batch" in cond:
                where["span_type"] = "batch"
        elif sess:
            where["session_id"] = {"contains": str(params[int(sess.group(1)) - 1]).strip("%")}
        elif status:
            where["status"] = {"equals": params[int(status.group(1)) - 1]}
        elif api_key_not_in:
            where["api_key_not_in"] = [
                params[int(api_key_not_in.group(1)) - 1],
                params[int(api_key_not_in.group(2)) - 1],
            ]
        elif alias:
            metadata_conds.append(
                {
                    "path": ["user_api_key_alias"],
                    "string_contains": str(params[int(alias.group(1)) - 1]).strip("%"),
                }
            )
        elif code:
            metadata_conds.append(
                {
                    "path": ["error_information", "error_code"],
                    "equals": params[int(code.group(1)) - 1],
                }
            )
        elif msg:
            metadata_conds.append(
                {
                    "path": ["error_information", "error_message"],
                    "string_contains": str(params[int(msg.group(1)) - 1]).strip("%"),
                }
            )
        elif credential:
            metadata_conds.append(
                {
                    "path": ["used_client_oauth_token"],
                    "equals": params[int(credential.group(1)) - 1],
                }
            )
        else:
            for sql_col, key in eq_cols.items():
                eq = re.fullmatch(rf"{re.escape(sql_col)} = \$(\d+)", cond)
                if eq:
                    where[key] = params[int(eq.group(1)) - 1]
                    break

    if date_bounds:
        where["startTime"] = date_bounds
    if len(metadata_conds) == 1:
        where["metadata"] = metadata_conds[0]
    elif len(metadata_conds) > 1:
        where["AND"] = [{"metadata": cond} for cond in metadata_conds]
    return where


def make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup_fn=None, query_observer=None):
    """
    Create a MockPrismaClient for /spend/logs/ui endpoint tests.

    Args:
        mock_spend_logs: List of mock spend log dicts.
        filter_fn: Callable[[dict], list] - receives the reconstructed
                   where_conditions, returns the filtered list of logs.
        team_lookup_fn: Optional async callable for team RBAC (find_unique).
                        If provided, adds litellm_teamtable to db.
    """

    class MockDB:
        async def count(self, *args, **kwargs):
            return len(filter_fn(kwargs.get("where", {})))

        async def group_by(self, by, where, count):
            col = by[0]
            allowed = where.get(col, {}).get("in")
            tallied = collections.Counter(
                log[col]
                for log in mock_spend_logs
                if log.get(col) is not None and (allowed is None or log[col] in allowed)
            )
            return [{col: value, "_count": {col: n}} for value, n in tallied.items()]

        async def query_raw(self, sql_query, *params):
            if query_observer is not None:
                query_observer(sql_query, params)
            if "mcp_tool_call_count" in sql_query:
                return []
            if 'SELECT DISTINCT "user", team_id' in sql_query:
                return _emulate_spend_log_owner_lookup(mock_spend_logs, sql_query, params)
            filtered = filter_fn(_reconstruct_ui_where_from_sql(sql_query, params))
            total = len(filtered)
            if "COUNT(*)" in sql_query:
                cap_plus_one = params[-1]
                return [{"total_count": min(total, cap_plus_one)}]
            page_size = params[-2] if len(params) >= 2 else 50
            skip = params[-1] if len(params) >= 1 else 0
            exact_first = re.search(r"ORDER BY \(request_id = \$(\d+)\) DESC", sql_query)
            ordered = (
                sorted(
                    filtered, key=lambda row: row["request_id"] == params[int(exact_first.group(1)) - 1], reverse=True
                )
                if exact_first
                else filtered
            )
            return [row for row in ordered[skip : skip + page_size]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()
            self.db.litellm_spendlogs = self.db
            if team_lookup_fn is not None:
                self.db.litellm_teamtable = self
                self.find_unique = team_lookup_fn

    return MockPrismaClient()


from litellm.constants import LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME
from litellm.proxy._types import (
    LitellmUserRoles,
    Member,
    ProxyException,
    SpendCalculateRequest,
    SpendLogsPayload,
    UserAPIKeyAuth,
)
from litellm.proxy.hooks.proxy_track_cost_callback import ProxyDBLogger
from litellm.proxy.management.teams import authz as team_access
from litellm.proxy.proxy_server import app
from litellm.proxy.spend_tracking import spend_management_endpoints
from litellm.proxy.utils import PrismaClient
from litellm.router import Router
from litellm.types.utils import BudgetConfig


@pytest.mark.asyncio
async def test_is_admin_view_safe_true():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user")
    assert spend_management_endpoints._is_admin_view_safe(auth) is True
    auth_view = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, user_id="admin_view")
    assert spend_management_endpoints._is_admin_view_safe(auth_view) is True


@pytest.mark.asyncio
async def test_is_admin_view_safe_false():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    assert spend_management_endpoints._is_admin_view_safe(auth) is False


@pytest.mark.asyncio
async def test_is_admin_view_safe_exception():
    # Ensure exceptions are swallowed and return False
    class ExplodingAuth:
        @property
        def user_role(self):
            raise RuntimeError("boom")

    assert spend_management_endpoints._is_admin_view_safe(ExplodingAuth()) is False  # type: ignore[arg-type]


@pytest.mark.asyncio
async def test_can_team_member_view_log_none_team_id():
    # team_id=None should immediately return False
    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return None

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, None)
    assert allowed is False


@pytest.mark.asyncio
async def test_can_team_member_view_log_team_not_found(monkeypatch):
    # Non-existent team should return False
    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return None

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    # Even if admin check would return True, no team means False
    monkeypatch.setattr(
        team_access,
        "is_team_admin",
        lambda user_api_key_dict, team_obj: True,
    )
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, "team_x")
    assert allowed is False


@pytest.mark.asyncio
async def test_can_team_member_view_log_not_admin(monkeypatch):
    # Existing team but caller is not a team admin and no /spend/logs permission -> False
    class MockTeam:
        team_id = "team_x"
        members_with_roles = [Member(user_id="user_1", role="user")]
        team_member_permissions = None

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "user_1", "role": "user"}],
                "team_member_permissions": self.team_member_permissions,
            }

    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return MockTeam()

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    monkeypatch.setattr(
        team_access,
        "is_team_admin",
        lambda user_api_key_dict, team_obj: False,
    )
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, "team_x")
    assert allowed is False


@pytest.mark.asyncio
async def test_can_team_member_view_log_admin(monkeypatch):
    # Existing team and caller is team admin -> True
    class MockTeam:
        team_id = "team_x"
        members_with_roles = [Member(user_id="user_1", role="admin")]
        team_member_permissions = None

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "user_1", "role": "admin"}],
                "team_member_permissions": self.team_member_permissions,
            }

    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return MockTeam()

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, "team_x")
    assert allowed is True


def test_can_user_view_spend_log_true_for_internal_user():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="u1")
    assert spend_management_endpoints._can_user_view_spend_log(auth) is True


def test_can_user_view_spend_log_true_for_internal_view_only():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, user_id="u1")
    assert spend_management_endpoints._can_user_view_spend_log(auth) is True


def test_can_user_view_spend_log_false_without_user_id():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id=None)
    assert spend_management_endpoints._can_user_view_spend_log(auth) is False


def test_can_user_view_spend_log_false_for_other_roles():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin")
    assert spend_management_endpoints._can_user_view_spend_log(auth) is False


def _emulate_spend_log_owner_lookup(rows, sql_query, params):
    """Emulate the ownership lookup SQL over an in-memory spend-log corpus,
    honoring DISTINCT and any literal LIMIT the query carries so a capped or
    non-distinct query produces the truncated result it would in Postgres."""
    lookup_id = params[0]
    matches = [
        {"user": row.get("user"), "team_id": row.get("team_id")}
        for row in rows
        if lookup_id in (row.get("request_id"), row.get("litellm_call_id"))
    ]
    if "DISTINCT" in sql_query:
        deduped = []
        for match in matches:
            if match not in deduped:
                deduped.append(match)
        matches = deduped
    limit = re.search(r"LIMIT\s+(\d+)", sql_query, re.IGNORECASE)
    if limit is not None:
        matches = matches[: int(limit.group(1))]
    return matches


def _make_owner_lookup_prisma(rows):
    class MockDB:
        async def query_raw(self, sql_query, *params):
            return _emulate_spend_log_owner_lookup(rows, sql_query, params)

    class MockPrisma:
        def __init__(self):
            self.db = MockDB()

    return MockPrisma()


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_rejects_both_users_none():
    """
    API keys with user_id=None must not be treated as owning a log whose user
    field is None (avoid None == None bypass).
    """
    prisma = _make_owner_lookup_prisma(
        [{"request_id": "req-none-user", "litellm_call_id": None, "user": None, "team_id": None}]
    )

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id=None)
    with pytest.raises(HTTPException) as exc_info:
        await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "req-none-user")
    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_rejects_when_no_match_is_owned():
    """An id whose every matching row belongs to other tenants is refused outright,
    so the relaxed date window of an id lookup cannot reach a foreign row."""
    prisma = _make_owner_lookup_prisma(
        [
            {"request_id": "foreign-request", "litellm_call_id": "shared-id", "user": "tenant_a", "team_id": None},
            {"request_id": "shared-id", "litellm_call_id": "other-call-id", "user": "tenant_b", "team_id": None},
        ]
    )

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")
    with pytest.raises(HTTPException) as exc_info:
        await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "shared-id")
    assert exc_info.value.status_code == 403


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_allows_owner_despite_foreign_collision():
    """
    litellm_call_id comes from the client-settable x-litellm-call-id header, so
    another tenant can mint a row whose call id equals the caller's request_id.
    That collision must not lock the caller out of their own row: the pre-check
    passes once one match is theirs, and the scoped data queries keep the foreign
    row out of the result. Regression for the every-match-must-be-owned rule that
    let any tenant deny another's lookup by reusing their id.
    """
    prisma = _make_owner_lookup_prisma(
        [
            {
                "request_id": "attacker-own-request",
                "litellm_call_id": "victim-request-id",
                "user": "attacker",
                "team_id": None,
            },
            {
                "request_id": "victim-request-id",
                "litellm_call_id": "victim-call-id",
                "user": "victim",
                "team_id": None,
            },
        ]
    )

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="victim")
    result = await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "victim-request-id")

    assert result is None


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_finds_owner_past_any_row_cap():
    """
    An attacker can mint hundreds of rows carrying the victim's request_id as
    their litellm_call_id, so a capped or sampled ownership read could exhaust
    its cap on attacker-owned rows and never see the victim's own row, locking
    the victim out of their lookup. The ownership read must consider every
    matching row's owner no matter how many rows match. Regression for the
    find_many(take=100) sample the first fix used.
    """
    rows = [
        {
            "request_id": f"attacker-request-{i}",
            "litellm_call_id": "victim-request-id",
            "user": "attacker",
            "team_id": None,
        }
        for i in range(150)
    ]
    rows.append(
        {
            "request_id": "victim-request-id",
            "litellm_call_id": "victim-call-id",
            "user": "victim",
            "team_id": None,
        }
    )
    prisma = _make_owner_lookup_prisma(rows)

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="victim")
    result = await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "victim-request-id")

    assert result is None


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_allows_when_every_match_is_owned():
    """The same ambiguous id matching more than one row is fine when every match
    belongs to the caller (e.g. two of the caller's own requests happen to share
    a request_id/litellm_call_id pairing); only a foreign match should block it."""
    prisma = _make_owner_lookup_prisma(
        [
            {
                "request_id": "shared-request-id",
                "litellm_call_id": "caller-call-a",
                "user": "caller",
                "team_id": None,
            },
            {
                "request_id": "caller-request-b",
                "litellm_call_id": "shared-request-id",
                "user": "caller",
                "team_id": None,
            },
        ]
    )

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller")
    result = await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "shared-request-id")

    assert result is None


@pytest.mark.asyncio
async def test_assert_user_can_view_request_id_rejects_missing_row():
    """
    A request_id with no spend-log row (e.g. pruned by retention) must not
    authorize reading the payload from cold storage; a missing row is not
    the same as an owned row.
    """
    prisma = _make_owner_lookup_prisma([])

    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1")
    with pytest.raises(HTTPException) as exc_info:
        await spend_management_endpoints._assert_user_can_view_request_id(prisma, auth, "req-missing-row")
    assert exc_info.value.status_code == 403


def test_ui_view_request_response_forbids_non_admin_without_db(client, monkeypatch):
    """
    Without prisma, non-admins cannot be authorized to read request/response
    payloads (including from custom loggers); do not skip RBAC silently.
    """
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="user_1",
    )
    try:
        response = client.get(
            "/spend/logs/ui/req-no-db",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        body = response.json()
        assert "database" in str(body).lower()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


ignored_keys = [
    "request_id",
    "litellm_call_id",
    "metadata.litellm_call_id",
    "session_id",
    "startTime",
    "endTime",
    "completionStartTime",
    "endTime",
    "request_duration_ms",
    "organization_id",
    "metadata.model_map_information",
    "metadata.usage_object",
    "metadata.cold_storage_object_key",
    "metadata.additional_usage_values.prompt_tokens_details.cache_creation_tokens",
    "metadata.additional_usage_values.completion_tokens_details",
    "metadata.additional_usage_values.prompt_tokens_details",
    "metadata.additional_usage_values.cache_creation_input_tokens",
    "metadata.additional_usage_values.cache_read_input_tokens",
    "metadata.additional_usage_values.inference_geo",
    "metadata.additional_usage_values.speed",
    "metadata.additional_usage_values.service_tier",
    "metadata.additional_usage_values.iterations",
    "metadata.litellm_overhead_time_ms",
    "metadata.cost_breakdown",
    "metadata.autorouter_savings",
    "metadata.user_api_key",
    "metadata.user_api_key_alias",
    "metadata.user_api_key_team_id",
    "metadata.user_api_key_project_id",
    "metadata.user_api_key_project_alias",
    "metadata.user_api_key_org_id",
    "metadata.user_api_key_user_id",
    "metadata.user_api_key_team_alias",
    "metadata.spend_logs_metadata",
    "metadata.requester_ip_address",
    "metadata.user_agent",
    "metadata.status",
    "metadata.proxy_server_request",
    "metadata.error_information",
    "metadata.attempted_retries",
    "metadata.max_retries",
    "metadata.eval_information",
]

MODEL_LIST = [
    {
        "model_name": "azure-gpt-4o",
        "litellm_params": {
            "model": "azure/gpt-4o-mini",
            "mock_response": "Hello, world!",
            "tags": ["default"],
            "base_model": "gpt-4o-mini",
        },
    },
]


@pytest.fixture
def client():
    return TestClient(app)


@pytest.fixture(autouse=True)
def add_anthropic_api_key_to_env(monkeypatch):
    monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-api03-1234567890")


@pytest.fixture
def disable_budget_sync(monkeypatch):
    """Disable periodic sync during tests"""

    async def noop(*a, **k):
        return None

    monkeypatch.setattr(
        "litellm.router_strategy.budget_limiter.RouterBudgetLimiting.periodic_sync_in_memory_spend_with_redis",
        noop,
    )


@pytest.fixture(autouse=True)
def reset_router_callbacks():
    """Ensure router budget callbacks from previous tests do not leak state."""
    litellm.logging_callback_manager._reset_all_callbacks()
    yield
    litellm.logging_callback_manager._reset_all_callbacks()


@pytest.fixture(autouse=True)
def reset_proxy_auth_globals(monkeypatch):
    """
    Pin proxy auth-related globals to a known baseline so tests don't inherit
    leaked state (master_key, prisma_client, custom auth, cached tokens) from
    earlier tests. Individual tests can still override via their own
    monkeypatch calls — those run after this fixture and revert first.
    """
    import litellm.proxy.proxy_server as ps

    monkeypatch.setattr(ps, "prisma_client", None)
    monkeypatch.setattr(ps, "master_key", None)
    monkeypatch.setattr(ps, "user_custom_auth", None)
    monkeypatch.setattr(ps, "general_settings", {})
    try:
        ps.user_api_key_cache.in_memory_cache.cache_dict.clear()
    except AttributeError:
        pass


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_user_id(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_user(where):
        if "user" in where and where["user"] == "test_user_1":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_user),
    )

    start_date, end_date = _default_date_range()

    # Make the request with user_id filter
    response = client.get(
        "/spend/logs/ui",
        params={
            "user_id": "test_user_1",
            "start_date": start_date,
            "end_date": end_date,
        },
        headers={"Authorization": "Bearer sk-test"},
    )

    # Assert response
    assert response.status_code == 200
    data = response.json()

    # Verify the response structure
    assert "data" in data
    assert "total" in data
    assert "page" in data
    assert "page_size" in data
    assert "total_pages" in data

    # Verify the filtered data
    assert data["total"] == 1
    assert len(data["data"]) == 1
    assert data["data"][0]["user"] == "test_user_1"


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "session_id_query,expected_request_ids",
    [
        ("session-filter-demo-1", {"req1", "req2"}),
        ("session-filter-demo-2", {"req3"}),
        ("session-filter", {"req1", "req2", "req3"}),
        ("demo", {"req1", "req2", "req3"}),
        ("no-such-session", set()),
    ],
)
async def test_ui_view_spend_logs_with_session_id(client, monkeypatch, session_id_query, expected_request_ids):
    def make_log(request_id, session_id):
        return {
            "id": f"log-{request_id}",
            "request_id": request_id,
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "session_id": session_id,
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        }

    mock_spend_logs = [
        make_log("req1", "session-filter-demo-1"),
        make_log("req2", "session-filter-demo-1"),
        make_log("req3", "session-filter-demo-2"),
        make_log("req4", "unrelated-abc"),
    ]

    def filter_by_session(where):
        session_filter = where.get("session_id")
        if session_filter is None:
            return mock_spend_logs
        return [log for log in mock_spend_logs if session_filter["contains"] in log["session_id"]]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_session),
    )

    start_date, end_date = _default_date_range()

    response = client.get(
        "/spend/logs/ui",
        params={
            "session_id": session_id_query,
            "start_date": start_date,
            "end_date": end_date,
        },
        headers={"Authorization": "Bearer sk-test"},
    )

    assert response.status_code == 200
    data = response.json()
    assert data["total"] == len(expected_request_ids)
    assert {log["request_id"] for log in data["data"]} == expected_request_ids
    assert all(session_id_query in log["session_id"] for log in data["data"])


# Mock spend logs with distinct values for sorting tests.
# req_a: spend=0.10, tokens=500, start/end earliest
# req_b: spend=0.05, tokens=200, start/end 2nd
# req_c: spend=0.20, tokens=50, start/end latest
# req_d: spend=0.01, tokens=100, start/end 3rd
_SORT_TEST_LOGS = [
    {
        "request_id": "req_a",
        "api_key": "sk-test-key",
        "user": "user1",
        "spend": 0.10,
        "total_tokens": 500,
        "startTime": "2025-01-01T00:00:00+00:00",
        "endTime": "2025-01-01T00:01:00+00:00",
        "model": "gpt-3.5-turbo",
    },
    {
        "request_id": "req_b",
        "api_key": "sk-test-key",
        "user": "user1",
        "spend": 0.05,
        "total_tokens": 200,
        "startTime": "2025-01-01T00:00:01+00:00",
        "endTime": "2025-01-01T00:01:01+00:00",
        "model": "gpt-3.5-turbo",
    },
    {
        "request_id": "req_c",
        "api_key": "sk-test-key",
        "user": "user1",
        "spend": 0.20,
        "total_tokens": 50,
        "startTime": "2025-01-01T00:00:03+00:00",
        "endTime": "2025-01-01T00:01:03+00:00",
        "model": "gpt-3.5-turbo",
    },
    {
        "request_id": "req_d",
        "api_key": "sk-test-key",
        "user": "user1",
        "spend": 0.01,
        "total_tokens": 100,
        "startTime": "2025-01-01T00:00:02+00:00",
        "endTime": "2025-01-01T00:01:02+00:00",
        "model": "gpt-3.5-turbo",
    },
]


def _sort_logs(logs, order_clause):
    """Sort logs by the given Prisma-style order clause, e.g. {'spend': 'asc'}."""
    if not order_clause:
        return list(logs)
    key, direction = next(iter(order_clause.items()))
    reverse = direction.lower() == "desc"
    return sorted(logs, key=lambda x: x.get(key, 0), reverse=reverse)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "sort_by,sort_order,expected_request_ids",
    [
        # spend: 0.01(d) < 0.05(b) < 0.10(a) < 0.20(c)
        ("spend", "asc", ["req_d", "req_b", "req_a", "req_c"]),
        ("spend", "desc", ["req_c", "req_a", "req_b", "req_d"]),
        # total_tokens: 50(c) < 100(d) < 200(b) < 500(a)
        ("total_tokens", "asc", ["req_c", "req_d", "req_b", "req_a"]),
        ("total_tokens", "desc", ["req_a", "req_b", "req_d", "req_c"]),
        # startTime: 00:00:00(a) < 00:00:01(b) < 00:00:02(d) < 00:00:03(c)
        ("startTime", "asc", ["req_a", "req_b", "req_d", "req_c"]),
        ("startTime", "desc", ["req_c", "req_d", "req_b", "req_a"]),
        # endTime: same ordering as startTime
        ("endTime", "asc", ["req_a", "req_b", "req_d", "req_c"]),
        ("endTime", "desc", ["req_c", "req_d", "req_b", "req_a"]),
        # default when sort_by not provided: startTime desc
        (None, "desc", ["req_c", "req_d", "req_b", "req_a"]),
    ],
)
async def test_ui_view_spend_logs_sort_by_and_sort_order(
    client, monkeypatch, sort_by, sort_order, expected_request_ids
):
    """Test that spend logs are returned in the correct order for each sort_by/sort_order."""
    base_logs = list(_SORT_TEST_LOGS)

    async def mock_count(*args, **kwargs):
        return len(base_logs)

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*)" in sql_query:
            return [{"total_count": len(base_logs)}]
        # Endpoint uses raw SQL with ORDER BY startTime DESC; mock returns sorted data
        order = {"startTime": "desc"} if sort_by is None else {sort_by: sort_order or "desc"}
        sorted_logs = _sort_logs(base_logs, order)
        page_size = params[-2] if len(params) >= 2 else 50
        skip = params[-1] if len(params) >= 1 else 0
        return [row for row in sorted_logs[skip : skip + page_size]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date = "2024-12-25 00:00:00"
        end_date = "2025-01-02 23:59:59"

        params = {
            "start_date": start_date,
            "end_date": end_date,
        }
        if sort_by is not None:
            params["sort_by"] = sort_by
        if sort_order is not None:
            params["sort_order"] = sort_order

        response = client.get(
            "/spend/logs/ui",
            params=params,
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200, response.text
        data = response.json()
        assert "data" in data

        actual_ids = [log["request_id"] for log in data["data"]]
        assert actual_ids == expected_request_ids, (
            f"Expected order {expected_request_ids}, got {actual_ids} (sort_by={sort_by}, sort_order={sort_order})"
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "sort_by,sort_order",
    [
        ("invalid", "asc"),
        ("spend", "invalid"),
    ],
)
async def test_ui_view_spend_logs_sort_validation_errors(client, monkeypatch, sort_by, sort_order):
    """Test that invalid sort_by and sort_order return 400."""

    async def mock_count(*args, **kwargs):
        return 0

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.find_many = AsyncMock(return_value=[])
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date = "2024-12-25 00:00:00"
        end_date = "2025-01-02 23:59:59"

        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "sort_by": sort_by,
                "sort_order": sort_order,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 400
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_sort_by_request_duration_ms(client, monkeypatch):
    """Test that request_duration_ms is accepted as a valid sort_by field."""
    base_logs = [
        {
            "request_id": "req_fast",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "request_duration_ms": 100,
            "startTime": "2025-01-01T00:00:00+00:00",
            "endTime": "2025-01-01T00:00:00.100000+00:00",
            "model": "gpt-4",
        },
        {
            "request_id": "req_slow",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.05,
            "total_tokens": 50,
            "request_duration_ms": 5000,
            "startTime": "2025-01-01T00:00:01+00:00",
            "endTime": "2025-01-01T00:00:06+00:00",
            "model": "gpt-4",
        },
    ]

    async def mock_count(*args, **kwargs):
        return len(base_logs)

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*)" in sql_query:
            return [{"total_count": len(base_logs)}]
        reverse = "DESC" in sql_query
        sorted_logs = sorted(base_logs, key=lambda x: x.get("request_duration_ms", 0), reverse=reverse)
        page_size = params[-2] if len(params) >= 2 else 50
        skip = params[-1] if len(params) >= 1 else 0
        return [row for row in sorted_logs[skip : skip + page_size]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
                "sort_by": "request_duration_ms",
                "sort_order": "asc",
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200, response.text
        data = response.json()
        actual_ids = [log["request_id"] for log in data["data"]]
        assert actual_ids == ["req_fast", "req_slow"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "sort_order,expected_request_ids",
    [
        ("asc", ["req_anthropic", "req_gpt35", "req_gpt4"]),
        ("desc", ["req_gpt4", "req_gpt35", "req_anthropic"]),
    ],
)
async def test_ui_view_spend_logs_sort_by_model(client, monkeypatch, sort_order, expected_request_ids):
    """Test that model is accepted as a valid sort_by field and orders alphabetically."""
    base_logs = [
        {
            "request_id": "req_gpt4",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:00+00:00",
            "endTime": "2025-01-01T00:00:01+00:00",
            "model": "gpt-4",
        },
        {
            "request_id": "req_anthropic",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:01+00:00",
            "endTime": "2025-01-01T00:00:02+00:00",
            "model": "claude-3-opus",
        },
        {
            "request_id": "req_gpt35",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:02+00:00",
            "endTime": "2025-01-01T00:00:03+00:00",
            "model": "gpt-3.5-turbo",
        },
    ]

    async def mock_count(*args, **kwargs):
        return len(base_logs)

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*)" in sql_query:
            return [{"total_count": len(base_logs)}]
        assert "model" in sql_query
        # model is non-nullable in the schema, so NULLS LAST should NOT be
        # appended — only ttft_ms gets that clause. This guards against
        # accidentally widening the change to all sort columns.
        assert "NULLS LAST" not in sql_query
        reverse = "DESC" in sql_query
        sorted_logs = sorted(base_logs, key=lambda x: x.get("model", ""), reverse=reverse)
        page_size = params[-2] if len(params) >= 2 else 50
        skip = params[-1] if len(params) >= 1 else 0
        return [row for row in sorted_logs[skip : skip + page_size]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
                "sort_by": "model",
                "sort_order": sort_order,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200, response.text
        data = response.json()
        actual_ids = [log["request_id"] for log in data["data"]]
        assert actual_ids == expected_request_ids
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_sort_by_ttft_ms(client, monkeypatch):
    """sort_by=ttft_ms orders streaming rows by TTFT and pushes non-streaming rows last (NULLS LAST)."""
    # req_fast_stream: TTFT = 100ms (streaming)
    # req_slow_stream: TTFT = 2000ms (streaming)
    # req_no_stream:   completionStartTime == endTime (non-streaming, treated as NULL)
    # req_null_stream: completionStartTime is null (non-streaming, NULL)
    base_logs = [
        {
            "request_id": "req_fast_stream",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:00+00:00",
            "completionStartTime": "2025-01-01T00:00:00.100000+00:00",
            "endTime": "2025-01-01T00:00:01+00:00",
            "model": "gpt-4",
            "_ttft_ms": 100,
        },
        {
            "request_id": "req_slow_stream",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:02+00:00",
            "completionStartTime": "2025-01-01T00:00:04+00:00",
            "endTime": "2025-01-01T00:00:05+00:00",
            "model": "gpt-4",
            "_ttft_ms": 2000,
        },
        {
            "request_id": "req_no_stream",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:06+00:00",
            "completionStartTime": "2025-01-01T00:00:07+00:00",
            "endTime": "2025-01-01T00:00:07+00:00",
            "model": "gpt-4",
            "_ttft_ms": None,
        },
        {
            "request_id": "req_null_stream",
            "api_key": "sk-test-key",
            "user": "user1",
            "spend": 0.10,
            "total_tokens": 100,
            "startTime": "2025-01-01T00:00:08+00:00",
            "completionStartTime": None,
            "endTime": "2025-01-01T00:00:09+00:00",
            "model": "gpt-4",
            "_ttft_ms": None,
        },
    ]

    async def mock_count(*args, **kwargs):
        return len(base_logs)

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*)" in sql_query:
            return [{"total_count": len(base_logs)}]
        # Endpoint must compute TTFT inline and use NULLS LAST.
        assert "completionStartTime" in sql_query
        assert "NULLS LAST" in sql_query
        reverse = "DESC" in sql_query
        non_null = [r for r in base_logs if r["_ttft_ms"] is not None]
        nulls = [r for r in base_logs if r["_ttft_ms"] is None]
        non_null.sort(key=lambda x: x["_ttft_ms"], reverse=reverse)
        sorted_logs = non_null + nulls
        page_size = params[-2] if len(params) >= 2 else 50
        skip = params[-1] if len(params) >= 1 else 0
        return [{k: v for k, v in row.items() if k != "_ttft_ms"} for row in sorted_logs[skip : skip + page_size]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        # asc: fast stream, slow stream, then NULLs (non-streaming) last
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
                "sort_by": "ttft_ms",
                "sort_order": "asc",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        actual_ids = [log["request_id"] for log in response.json()["data"]]
        assert actual_ids[:2] == ["req_fast_stream", "req_slow_stream"]
        assert set(actual_ids[2:]) == {"req_no_stream", "req_null_stream"}

        # desc: slow stream, fast stream, then NULLs still last
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
                "sort_by": "ttft_ms",
                "sort_order": "desc",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        actual_ids = [log["request_id"] for log in response.json()["data"]]
        assert actual_ids[:2] == ["req_slow_stream", "req_fast_stream"]
        assert set(actual_ids[2:]) == {"req_no_stream", "req_null_stream"}
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_team_id(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team2",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_team(where):
        if "team_id" in where and where["team_id"] == "team1":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_team),
    )
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()

        # Make the request with team_id filter
        response = client.get(
            "/spend/logs/ui",
            params={
                "team_id": "team1",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        # Assert response
        assert response.status_code == 200
        data = response.json()

        # Verify the filtered data
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["team_id"] == "team1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


_HEALTH_CHECK_HASHED_API_KEY = hashlib.sha256(LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME.encode()).hexdigest()


def _spend_logs_with_health_check_rows():
    now = datetime.datetime.now(timezone.utc).isoformat()
    return [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": None,
            "spend": 0.05,
            "startTime": now,
            "model": "gpt-4",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": _HEALTH_CHECK_HASHED_API_KEY,
            "user": None,
            "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
            "spend": 0.0,
            "startTime": now,
            "model": "gpt-4",
        },
        {
            "id": "log3",
            "request_id": "req3",
            "api_key": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
            "user": None,
            "team_id": LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME,
            "spend": 0.0,
            "startTime": now,
            "model": "gpt-4",
        },
    ]


@pytest.mark.asyncio
async def test_ui_view_spend_logs_exclude_internal_health_checks(client, monkeypatch):
    mock_spend_logs = _spend_logs_with_health_check_rows()

    def filter_health_checks(where):
        excluded = where.get("api_key_not_in")
        if excluded is None:
            return mock_spend_logs
        return [log for log in mock_spend_logs if log["api_key"] not in excluded]

    observed_queries = []

    def observe_query(sql_query, params):
        if 'FROM "LiteLLM_SpendLogs"' in sql_query:
            observed_queries.append((sql_query, params))

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "exclude_internal_health_checks": "true",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert [row["request_id"] for row in data["data"]] == ["req1"]

        page_sql, page_params = next((sql, params) for sql, params in observed_queries if "ORDER BY" in sql)
        not_in = re.search(r"api_key NOT IN \(\$(\d+), \$(\d+)\)", page_sql)
        assert not_in is not None
        assert LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME not in page_sql
        assert _HEALTH_CHECK_HASHED_API_KEY not in page_sql
        assert {
            page_params[int(not_in.group(1)) - 1],
            page_params[int(not_in.group(2)) - 1],
        } == {LITTELM_INTERNAL_HEALTH_SERVICE_ACCOUNT_NAME, _HEALTH_CHECK_HASHED_API_KEY}
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_includes_internal_health_checks_by_default(client, monkeypatch):
    mock_spend_logs = _spend_logs_with_health_check_rows()

    def filter_health_checks(where):
        excluded = where.get("api_key_not_in")
        if excluded is None:
            return mock_spend_logs
        return [log for log in mock_spend_logs if log["api_key"] not in excluded]

    observed_queries = []

    def observe_query(sql_query, params):
        if 'FROM "LiteLLM_SpendLogs"' in sql_query:
            observed_queries.append((sql_query, params))

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_health_checks, query_observer=observe_query),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={"start_date": start_date, "end_date": end_date},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 3
        assert [row["request_id"] for row in data["data"]] == ["req1", "req2", "req3"]
        assert all("NOT IN" not in sql for sql, _ in observed_queries)
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_internal_user_scoped_without_user_id(client, monkeypatch):
    """
    Internal users should only be able to view their own spend even if user_id is not provided.
    """
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "internal_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "internal_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_user(where):
        if "user" in where and where["user"] == "internal_user_1":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_user),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="internal_user_1"
    )

    try:
        start_date, end_date = _default_date_range()

        # No user_id provided; should auto-scope to authenticated internal user's own id
        response = client.get(
            "/spend/logs/ui",
            params={"start_date": start_date, "end_date": end_date},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["user"] == "internal_user_1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_explicit_user_filter_cannot_escape_own_scope(client, monkeypatch):
    caller_log = {
        "id": "log1",
        "request_id": "req1",
        "api_key": "sk-test-key",
        "user": "[email protected]",
        "team_id": None,
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "gpt-4",
    }
    observed_queries = []

    def observe_query(sql_query, params):
        if 'FROM "LiteLLM_SpendLogs"' in sql_query:
            observed_queries.append((sql_query, params))

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([caller_log], lambda _where: [], query_observer=observe_query),
    )
    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: AsyncMock(return_value=()))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="[email protected]"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "user_id": "[email protected]",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        assert response.json()["data"] == []
        page_sql, page_params = next((sql, params) for sql, params in observed_queries if "SELECT\n" in sql)
        assert page_sql.count('"user" = $') == 2
        assert page_params[2:4] == ("[email protected]", "[email protected]")
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_without_user_filter_includes_permitted_team_scope(client, monkeypatch):
    caller_log = {
        "id": "log1",
        "request_id": "req1",
        "api_key": "sk-test-key",
        "user": "[email protected]",
        "team_id": None,
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "gpt-4",
    }
    member_log = {**caller_log, "id": "log2", "request_id": "req2", "user": "[email protected]", "team_id": "team-9"}
    outside_log = {
        **caller_log,
        "id": "log3",
        "request_id": "req3",
        "user": "[email protected]",
        "team_id": "outside-team",
    }

    def filter_by_scope(where):
        if {"multi_team": True} in where.get("OR", []) and "user" not in where:
            return [caller_log, member_log]
        return [caller_log, member_log, outside_log]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([caller_log, member_log, outside_log], filter_by_scope),
    )
    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: AsyncMock(return_value=("team-9",)))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="[email protected]"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={"start_date": start_date, "end_date": end_date},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        assert [row["request_id"] for row in response.json()["data"]] == ["req1", "req2"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_permitted_team_scope_falls_back_to_own_user_when_lookup_fails():
    from litellm.proxy.auth.authorization import resolve_owned_read_scope

    async def unavailable():
        raise RuntimeError("database unavailable")

    assert await resolve_owned_read_scope("caller", unavailable) == OwnedRows("caller")


@pytest.mark.asyncio
async def test_ui_view_spend_logs_team_admin_can_filter_team_spend_by_user(client, monkeypatch):
    """
    Team admins should be able to view team-wide spend when team_id is provided.
    """
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "member1",
            "team_id": "team_admin_team",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "member2",
            "team_id": "team_other",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
        {
            "id": "log3",
            "request_id": "req3",
            "api_key": "sk-test-key",
            "user": "member3",
            "team_id": "team_admin_team",
            "spend": 0.15,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_team(where):
        if where.get("team_id") == "team_admin_team" and where.get("user") == "member1":
            return [mock_spend_logs[0]]
        if where.get("team_id") == "team_admin_team":
            return [mock_spend_logs[0], mock_spend_logs[2]]
        return mock_spend_logs

    class TeamTable:
        team_id = "team_admin_team"
        members_with_roles = [Member(user_id="admin_user", role="admin")]
        team_member_permissions = None

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "admin_user", "role": "admin"}],
                "team_member_permissions": self.team_member_permissions,
            }

    async def team_lookup(where):
        return TeamTable() if where == {"team_id": "team_admin_team"} else None

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_team, team_lookup),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()

        response = client.get(
            "/spend/logs/ui",
            params={
                "team_id": "team_admin_team",
                "user_id": "member1",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["team_id"] == "team_admin_team"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_user_filter_intersects_permitted_team_scope(client, monkeypatch):
    member_log = {
        "id": "log1",
        "request_id": "req1",
        "api_key": "sk-test-key",
        "user": "[email protected]",
        "team_id": "team-9",
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "gpt-4",
    }
    other_team_log = {
        **member_log,
        "id": "log2",
        "request_id": "req2",
        "team_id": "team-outside-scope",
    }
    seen_where = []

    def filter_by_user_and_scope(where):
        seen_where.append(where)
        if where.get("user") == "[email protected]" and {"multi_team": True} in where.get("OR", []):
            return [member_log]
        return [member_log, other_team_log]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([member_log, other_team_log], filter_by_user_and_scope),
    )
    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: AsyncMock(return_value=("team-9",)))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="team-admin"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "user_id": "[email protected]",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        assert [row["request_id"] for row in response.json()["data"]] == ["req1"]
        assert any(
            where.get("user") == "[email protected]" and {"multi_team": True} in where.get("OR", [])
            for where in seen_where
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_pagination(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": f"log{i}",
            "request_id": f"req{i}",
            "api_key": "sk-test-key",
            "user": f"test_user_{i % 3}",
            "team_id": f"team{i % 2 + 1}",
            "spend": 0.05 * i,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo" if i % 2 == 0 else "gpt-4",
        }
        for i in range(1, 26)  # 25 records
    ]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, lambda where: mock_spend_logs),
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()

        # Test first page
        response = client.get(
            "/spend/logs/ui",
            params={
                "page": 1,
                "page_size": 10,
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 25
        assert len(data["data"]) == 10
        assert data["page"] == 1
        assert data["page_size"] == 10
        assert data["total_pages"] == 3

        # Test second page
        response = client.get(
            "/spend/logs/ui",
            params={
                "page": 2,
                "page_size": 10,
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 25
        assert len(data["data"]) == 10
        assert data["page"] == 2
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.parametrize(
    "page_size, expected_status, expected_rows",
    [
        (1000, 200, 1000),
        (1001, 422, None),
    ],
)
@pytest.mark.asyncio
async def test_ui_view_spend_logs_page_size_upper_bound(client, monkeypatch, page_size, expected_status, expected_rows):
    mock_spend_logs = [
        {
            "id": f"log{i}",
            "request_id": f"req{i}",
            "api_key": "sk-test-key",
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        }
        for i in range(1200)
    ]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, lambda where: mock_spend_logs),
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/v2",
            params={
                "page": 1,
                "page_size": page_size,
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == expected_status
        if expected_status == 200:
            data = response.json()
            assert data["page_size"] == page_size
            assert len(data["data"]) == expected_rows
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_session_spend_logs_pagination(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "session_id": "session-123",
            "startTime": "2024-01-01T00:00:00Z",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "session_id": "session-123",
            "startTime": "2024-01-02T00:00:00Z",
        },
    ]

    class MockDB:
        async def count(self, *args, **kwargs):
            assert kwargs.get("where") == {"session_id": "session-123"}
            return len(mock_spend_logs)

        async def query_raw(self, sql_query, session_id, page_size, skip):
            # Endpoint uses raw SQL for pagination - verify params
            assert session_id == "session-123"
            assert page_size == 1
            assert skip == 1  # page=2, page_size=1
            assert 'ORDER BY "startTime" DESC' in sql_query
            assert '"user" = $4' not in sql_query
            return [mock_spend_logs[0]]

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()
            self.db.litellm_spendlogs = self.db

    mock_prisma_client = MockPrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/logs/session/ui",
            params={"session_id": "session-123", "page": 2, "page_size": 1},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 2
        assert data["page"] == 2
        assert data["page_size"] == 1
        assert data["total_pages"] == 2
        assert len(data["data"]) == 1
        assert data["data"][0]["request_id"] == "req1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_session_spend_logs_rehydrates_metadata_jsonb_text(client, monkeypatch):
    """The session sidebar reads metadata fields as object properties, so this endpoint
    must re-hydrate the JSONB column that query_raw hands back as a string, exactly as
    /spend/logs/ui does (#29674). Property access on a string is silently undefined,
    so a row's origin, status and error information all read as absent without this.
    """
    raw_row = {
        "request_id": "req-classifier-1",
        "session_id": "session-123",
        "startTime": "2024-01-01T00:00:00Z",
        "metadata": json.dumps({"internal_call_origin": "autorouter_classifier", "status": "success"}),
    }

    class MockDB:
        async def count(self, *args, **kwargs):
            return 1

        async def query_raw(self, sql_query, session_id, page_size, skip, *scope_params):
            return [dict(raw_row)]

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()
            self.db.litellm_spendlogs = self.db

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get("/spend/logs/session/ui", params={"session_id": "session-123"})
        assert response.status_code == 200
        row = response.json()["data"][0]
        assert isinstance(row["metadata"], dict)
        assert row["metadata"]["internal_call_origin"] == "autorouter_classifier"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_session_spend_logs_includes_permitted_team_logs(client, monkeypatch):
    class MockDB:
        async def count(self, *args, **kwargs):
            assert kwargs.get("where") == {
                "session_id": "session-123",
                "OR": [
                    {"user": "user-1"},
                    {"team_id": {"in": ["team-9"]}},
                ],
            }
            return 1

        async def query_raw(self, sql_query, session_id, page_size, skip, scoped_user, team_ids):
            assert session_id == "session-123"
            assert scoped_user == "user-1"
            assert tuple(team_ids) == ("team-9",)
            assert '("user" = $4 OR team_id = ANY($5::text[]))' in sql_query
            return [
                {
                    "id": "log2",
                    "request_id": "req2",
                    "session_id": "session-123",
                    "team_id": "team-9",
                    "startTime": "2024-01-02T00:00:00Z",
                }
            ]

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()
            self.db.litellm_spendlogs = self.db

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())

    async def permitted_teams(*args, **kwargs):
        return ["team-9"]

    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: permitted_teams)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user-1"
    )

    try:
        response = client.get(
            "/spend/logs/session/ui",
            params={"session_id": "session-123", "page": 1, "page_size": 50},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert [row["request_id"] for row in data["data"]] == ["req2"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_date_range_filter(client, monkeypatch):
    today = datetime.datetime.now(timezone.utc)
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": (today - datetime.timedelta(days=10)).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": (today - datetime.timedelta(days=2)).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_date(where):
        return _filter_logs_by_date_range(mock_spend_logs, where)

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_date),
    )

    # Date range that should only include the second log (log1 is 10 days ago, log2 is 2 days ago)
    start_date = (today - datetime.timedelta(days=5)).strftime("%Y-%m-%d %H:%M:%S")
    end_date = today.strftime("%Y-%m-%d %H:%M:%S")

    response = client.get(
        "/spend/logs/ui",
        params={
            "start_date": start_date,
            "end_date": end_date,
        },
        headers={"Authorization": "Bearer sk-test"},
    )

    assert response.status_code == 200
    data = response.json()
    assert data["total"] == 1
    assert len(data["data"]) == 1
    assert data["data"][0]["id"] == "log2"


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_lookup_ignores_date_window(client, monkeypatch):
    """
    LIT-3981: a request_id lookup on the UI route resolves across all time even
    when the caller sends a date window that excludes the log (the dashboard
    always sends a window). The window is dropped and request_id alone scopes
    the query. Pre-fix the window was always applied, so an id from an older
    page returned nothing.
    """
    today = datetime.datetime.now(timezone.utc)
    mock_spend_logs = [
        {
            "id": "log_old",
            "request_id": "req-old",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": (today - datetime.timedelta(days=90)).isoformat(),
            "model": "gpt-4",
        },
    ]

    captured: dict = {}

    def filter_fn(where):
        captured["where"] = where
        rows = _filter_logs_by_date_range(mock_spend_logs, where)
        rid_either = where.get("request_id_or_call_id")
        if rid_either:
            rows = [r for r in rows if rid_either in (r["request_id"], r.get("litellm_call_id"))]
        elif where.get("request_id"):
            rows = [r for r in rows if r["request_id"] == where["request_id"]]
        return rows

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn),
    )

    # A 5-day window that EXCLUDES the 90-day-old log, as the dashboard sends.
    start_date = (today - datetime.timedelta(days=5)).strftime("%Y-%m-%d %H:%M:%S")
    end_date = today.strftime("%Y-%m-%d %H:%M:%S")

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "request_id": "req-old",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert data["data"][0]["request_id"] == "req-old"
        # Query dropped the time window and scoped solely by the id lookup.
        assert "startTime" not in captured["where"]
        assert captured["where"]["request_id_or_call_id"] == "req-old"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_lookup_matches_litellm_call_id(client, monkeypatch):
    """
    LIT-6302: success rows are keyed by the upstream provider response id, so a
    lookup with the x-litellm-call-id response header value found nothing. The id
    lookup now matches request_id OR litellm_call_id, resolving the header value.
    """
    today = datetime.datetime.now(timezone.utc)
    mock_spend_logs = [
        {
            "id": "log_provider_keyed",
            "request_id": "chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm",
            "litellm_call_id": "b980eea9-5cd9-4099-93cd-8291e46c76fd",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": today.isoformat(),
            "model": "gpt-4",
        },
        {
            "id": "log_other",
            "request_id": "chatcmpl-other",
            "litellm_call_id": "11111111-2222-3333-4444-555555555555",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.01,
            "startTime": today.isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_fn(where):
        rid_either = where.get("request_id_or_call_id")
        if rid_either:
            return [r for r in mock_spend_logs if rid_either in (r["request_id"], r.get("litellm_call_id"))]
        if where.get("request_id"):
            return [r for r in mock_spend_logs if r["request_id"] == where["request_id"]]
        return list(mock_spend_logs)

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn),
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"request_id": "b980eea9-5cd9-4099-93cd-8291e46c76fd"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert data["data"][0]["request_id"] == "chatcmpl-9ZKMURhVYSi9D6r6PJ9vLcayIK0Vm"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_requires_dates_without_request_id(client, monkeypatch):
    """The date window stays mandatory on the UI route when no request_id is set."""
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([], lambda where: []),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get("/spend/logs/ui", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 400
        assert "date" in response.text.lower()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_logs_v2_still_requires_dates_with_request_id(client, monkeypatch):
    """The public /spend/logs/v2 contract is unchanged: dates remain required even
    when request_id is supplied. Only the internal UI route relaxes the window."""
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([], lambda where: []),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/v2",
            params={"request_id": "req-old"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        assert "date" in response.text.lower()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_blocks_non_owner(client, monkeypatch):
    """A non-admin looking up a request_id they do not own is rejected (403), so
    the relaxed date window cannot read another tenant's log by id."""

    prisma = _make_owner_lookup_prisma(
        [
            {
                "request_id": "foreign-req",
                "litellm_call_id": None,
                "user": "other_user",
                "team_id": None,
            }
        ]
    )

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"request_id": "foreign-req"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_collision_serves_only_callers_rows(client, monkeypatch):
    """Two tenants share one id: the attacker minted a row whose client-set
    litellm_call_id equals the victim's request_id. Each side's lookup of that id
    returns only their own row, so the collision neither leaks the other tenant's
    row nor denies the victim theirs (Veria: identifier collision could deny access)."""
    now_iso = datetime.datetime.now(timezone.utc).isoformat()
    corpus = [
        {
            "id": "log_attacker",
            "request_id": "attacker-req",
            "litellm_call_id": "victim-req",
            "api_key": "sk-attacker-key",
            "user": "attacker_user",
            "team_id": None,
            "spend": 0.05,
            "startTime": now_iso,
            "model": "gpt-4",
        },
        {
            "id": "log_victim",
            "request_id": "victim-req",
            "litellm_call_id": "victim-call-id",
            "api_key": "sk-victim-key",
            "user": "victim_user",
            "team_id": None,
            "spend": 0.07,
            "startTime": now_iso,
            "model": "gpt-4",
        },
    ]

    def filter_fn(where):
        rid_either = where.get("request_id_or_call_id")
        rows = [r for r in corpus if rid_either in (r["request_id"], r["litellm_call_id"])]
        return [r for r in rows if where.get("user") is None or r["user"] == where["user"]]

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", make_ui_spend_logs_mock_prisma(corpus, filter_fn))
    try:
        for caller, own_request_id, other in (
            ("victim_user", "victim-req", "attacker_user"),
            ("attacker_user", "attacker-req", "victim_user"),
        ):
            app.dependency_overrides[ps.user_api_key_auth] = lambda caller=caller: UserAPIKeyAuth(
                user_role=LitellmUserRoles.INTERNAL_USER, user_id=caller
            )
            response = client.get(
                "/spend/logs/ui",
                params={"request_id": "victim-req"},
                headers={"Authorization": "Bearer sk-test"},
            )
            assert response.status_code == 200, response.text
            data = response.json()
            assert data["total"] == 1
            assert data["data"][0]["request_id"] == own_request_id
            assert other not in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_id_lookup_scopes_every_non_admin_role(client, monkeypatch):
    """An org admin reaches /spend/logs/ui without the internal-user row scope. An
    id lookup still fetches only rows they own, so another tenant's row carrying
    that id as its client-set litellm_call_id neither leaks nor turns the
    org admin's own lookup into a 403 (Bugbot: non-internal id lookup 403s on collision)."""
    now_iso = datetime.datetime.now(timezone.utc).isoformat()
    corpus = [
        {
            "id": "log_attacker",
            "request_id": "attacker-req",
            "litellm_call_id": "victim-req",
            "api_key": "sk-attacker-key",
            "user": "attacker_user",
            "team_id": None,
            "spend": 0.05,
            "startTime": now_iso,
            "model": "gpt-4",
        },
        {
            "id": "log_victim",
            "request_id": "victim-req",
            "litellm_call_id": "victim-call-id",
            "api_key": "sk-victim-key",
            "user": "victim_user",
            "team_id": None,
            "spend": 0.07,
            "startTime": now_iso,
            "model": "gpt-4",
        },
    ]

    def filter_fn(where):
        rid_either = where.get("request_id_or_call_id")
        rows = [r for r in corpus if rid_either in (r["request_id"], r["litellm_call_id"])]
        return [r for r in rows if where.get("user") is None or r["user"] == where["user"]]

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", make_ui_spend_logs_mock_prisma(corpus, filter_fn))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.ORG_ADMIN, user_id="victim_user"
    )
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"request_id": "victim-req"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["total"] == 1
        assert [row["request_id"] for row in data["data"]] == ["victim-req"]
        assert "attacker_user" not in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_rejects_foreign_row_inserted_after_owner_check(client, monkeypatch):
    """The SQL scope keeps foreign rows out of an id lookup; this backstop covers a
    row the scope did not filter (the mock ignores it on purpose). The rows actually
    fetched are ownership-checked again, so the lookup answers 403 instead of serving
    the other tenant's row."""
    now_iso = datetime.datetime.now(timezone.utc).isoformat()
    owned_row = {
        "id": "log_owned",
        "request_id": "attacker-req",
        "litellm_call_id": "shared-id",
        "api_key": "sk-test-key",
        "user": "user_1",
        "team_id": None,
        "spend": 0.05,
        "startTime": now_iso,
        "model": "gpt-4",
    }
    foreign_row = {
        "id": "log_foreign",
        "request_id": "shared-id",
        "litellm_call_id": None,
        "api_key": "sk-victim-key",
        "user": "victim_user",
        "team_id": None,
        "spend": 0.07,
        "startTime": now_iso,
        "model": "gpt-4",
    }

    mock_prisma = make_ui_spend_logs_mock_prisma([owned_row], lambda where: [owned_row, foreign_row])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"request_id": "shared-id"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert "victim_user" not in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def _payload_row(request_id, litellm_call_id, user, prompt):
    return {
        "request_id": request_id,
        "litellm_call_id": litellm_call_id,
        "messages": [{"role": "user", "content": prompt}],
        "response": {"id": request_id},
        "proxy_server_request": None,
        "metadata": None,
        "user": user,
        "team_id": None,
    }


@pytest.mark.asyncio
async def test_ui_view_request_response_rejects_foreign_row_inserted_after_owner_check(client, monkeypatch):
    """Backstop behind the SQL scope on the detail endpoint (the mock ignores the
    scope on purpose): the payload row fetched by id is itself ownership-checked, so
    a foreign row the scope did not filter cannot have its payload served."""

    class MockDB:
        async def query_raw(self, sql_query, *params):
            if 'SELECT DISTINCT "user", team_id' in sql_query:
                return [{"user": "user_1", "team_id": None}]
            return [
                {
                    "messages": [{"role": "user", "content": "victim prompt"}],
                    "response": {"id": "resp-1"},
                    "proxy_server_request": None,
                    "metadata": None,
                    "user": "victim_user",
                    "team_id": None,
                }
            ]

    class MockPrisma:
        def __init__(self):
            self.db = MockDB()

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrisma())
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui/shared-id",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert "victim prompt" not in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_request_response_custom_logger_denies_foreign_payload_owner(client, monkeypatch):
    """The custom-logger payload comes straight from cold storage, written independently
    of the spend-log table and able to outlive its row. When an id lookup matches no row,
    the DB owner pre-check has nothing to verify, so the payload is authorized against the
    owner recorded inside it. A foreign tenant's stored payload is denied even though no
    spend-log row exists for the pre-check to catch."""

    class MockDB:
        async def query_raw(self, sql_query, *params):
            return []

    class MockPrisma:
        def __init__(self):
            self.db = MockDB()

    class ColdStorageLogger:
        async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):
            return {
                "messages": [{"role": "user", "content": "victim prompt"}],
                "response": {"id": "r"},
                "metadata": {"user_api_key_user_id": "victim_user", "user_api_key_team_id": None},
            }

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrisma())
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_additional_logging_utils_from_custom_logger",
        lambda: [ColdStorageLogger()],
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui/shared-id",
            params={"start_date": "2026-01-01 00:00:00"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert "victim prompt" not in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_request_response_custom_logger_is_keyed_by_callers_own_request_id(client, monkeypatch):
    """Cold storage is keyed by the provider request_id. The caller's row carries the
    lookup id only as its client-set litellm_call_id while another tenant's row owns
    that id as its request_id. The custom logger is asked for the caller's own stored
    request_id, so the caller gets their payload rather than a 403 from the foreign
    payload's owner check, and the foreign payload is never fetched."""
    prisma = MagicMock(
        db=MagicMock(
            query_raw=AsyncMock(
                side_effect=[
                    [{"user": "other_user", "team_id": None}, {"user": "caller_user", "team_id": None}],
                    [_payload_row("caller-req", "shared-id", "caller_user", "caller prompt")],
                ]
            )
        )
    )
    cold_storage = {
        "shared-id": {
            "messages": [{"role": "user", "content": "other tenant prompt"}],
            "response": {"id": "shared-id"},
            "metadata": {"user_api_key_user_id": "other_user", "user_api_key_team_id": None},
        },
        "caller-req": {
            "messages": [{"role": "user", "content": "caller prompt"}],
            "response": {"id": "caller-req"},
            "metadata": {"user_api_key_user_id": "caller_user", "user_api_key_team_id": None},
        },
    }
    requested_ids = []

    class ColdStorageLogger:
        async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):
            requested_ids.append(request_id)
            return cold_storage.get(request_id)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", prisma)
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_additional_logging_utils_from_custom_logger",
        lambda: [ColdStorageLogger()],
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller_user"
    )
    try:
        response = client.get("/spend/logs/ui/shared-id", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200, response.text
        assert "caller prompt" in response.text
        assert "other tenant prompt" not in response.text
        assert requested_ids == ["caller-req"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize("group_by_session", [False, True])
async def test_ui_view_spend_logs_id_lookup_lists_exact_request_id_row_first(client, monkeypatch, group_by_session):
    """The dashboard's deep link fetches a single row for ``?log_id=``. When a newer
    row carries that id as its client-set litellm_call_id, the row whose request_id
    is the id still comes first, so the link opens the request it names. The
    session-grouped page orders its representatives the same way."""
    today = datetime.datetime.now(timezone.utc)
    corpus = [
        {
            "id": "log_colliding",
            "request_id": "colliding-req",
            "litellm_call_id": "victim-req",
            "api_key": "sk-test-key",
            "user": "other_user",
            "team_id": None,
            "spend": 0.01,
            "startTime": today.isoformat(),
            "model": "gpt-4",
        },
        {
            "id": "log_victim",
            "request_id": "victim-req",
            "litellm_call_id": "victim-call-id",
            "api_key": "sk-test-key",
            "user": "victim_user",
            "team_id": None,
            "spend": 0.02,
            "startTime": (today - datetime.timedelta(minutes=5)).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_fn(where):
        rows = _filter_logs_by_date_range(corpus, where)
        rid_either = where.get("request_id_or_call_id")
        if rid_either:
            return [r for r in rows if rid_either in (r["request_id"], r["litellm_call_id"])]
        return rows

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", make_ui_spend_logs_mock_prisma(corpus, filter_fn))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"
    )
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"request_id": "victim-req", "page_size": 1, "group_by_session": str(group_by_session).lower()},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["total"] == 2
        assert [row["request_id"] for row in data["data"]] == ["victim-req"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_request_id_owner_lookup_drops_window_keeps_scope(client, monkeypatch):
    """A non-admin owner looking up their own request_id resolves across all time:
    the query drops the date window the dashboard sends, while the caller's own-user
    scope stays on the id lookup so a colliding foreign row can never be served."""
    today = datetime.datetime.now(timezone.utc)
    mock_spend_logs = [
        {
            "id": "log_old",
            "request_id": "req-old",
            "api_key": "sk-test-key",
            "user": "user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": (today - datetime.timedelta(days=90)).isoformat(),
            "model": "gpt-4",
        },
    ]

    captured: dict = {}

    def filter_fn(where):
        captured["where"] = where
        rows = _filter_logs_by_date_range(mock_spend_logs, where)
        rid_either = where.get("request_id_or_call_id")
        if rid_either:
            rows = [r for r in rows if rid_either in (r["request_id"], r.get("litellm_call_id"))]
        elif where.get("request_id"):
            rows = [r for r in rows if r["request_id"] == where["request_id"]]
        return rows

    mock_prisma = make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    # A 5-day window that EXCLUDES the 90-day-old log, as the dashboard sends.
    start_date = (today - datetime.timedelta(days=5)).strftime("%Y-%m-%d %H:%M:%S")
    end_date = today.strftime("%Y-%m-%d %H:%M:%S")

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "request_id": "req-old",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert data["data"][0]["request_id"] == "req-old"
        assert "startTime" not in captured["where"]
        assert captured["where"]["request_id_or_call_id"] == "req-old"
        assert captured["where"]["user"] == "user_1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_build_spend_log_search_condition_windows_every_branch_except_request_id():
    """LIT-4741: request_id matches across all time; the six other id columns only inside the window,
    all comparing the pasted value verbatim."""
    start = datetime.datetime(2026, 8, 1, tzinfo=timezone.utc)
    end = datetime.datetime(2026, 8, 2, tzinfo=timezone.utc)

    condition = spend_management_endpoints._build_spend_log_search_condition(
        search="key-hash-7", start_date=start, end_date=end, next_param_index=3
    )

    assert condition.sql == (
        "(request_id = $3 OR (\"startTime\" >= ($4::timestamptz AT TIME ZONE 'UTC') "
        "AND \"startTime\" <= ($5::timestamptz AT TIME ZONE 'UTC') "
        'AND (litellm_call_id = $3 OR api_key = $3 OR team_id = $3 OR "user" = $3 OR end_user = $3 OR session_id = $3 OR model_id = $3)))'
    )
    assert condition.params == ("key-hash-7", start, end)


def _search_fixture_logs(today):
    recent = (today - datetime.timedelta(days=1)).isoformat()
    old = (today - datetime.timedelta(days=90)).isoformat()
    base = {
        "api_key": "hashed-other",
        "user": "user-x",
        "team_id": "team-x",
        "end_user": "cust-x",
        "session_id": "sess-x",
        "model_id": "mdl-x",
        "spend": 0.01,
        "model": "gpt-4",
    }
    return [
        {**base, "request_id": "req-session", "session_id": "sess-42", "startTime": recent},
        {**base, "request_id": "req-session-old", "session_id": "sess-42", "startTime": old},
        {**base, "request_id": "req-key", "api_key": "hashed-7", "startTime": recent},
        {**base, "request_id": "req-team", "team_id": "team-7", "startTime": recent},
        {**base, "request_id": "req-user", "user": "user-7", "startTime": recent},
        {**base, "request_id": "req-end-user", "end_user": "cust-7", "startTime": recent},
        {**base, "request_id": "req-model", "model_id": "mdl-7", "startTime": recent},
        {**base, "request_id": "chatcmpl-x", "litellm_call_id": "call-recent", "startTime": recent},
        {**base, "request_id": "chatcmpl-old", "litellm_call_id": "call-old", "startTime": old},
    ]


def _search_filter_fn(logs, captured):
    def filter_fn(where):
        captured["where"] = where
        rows = _filter_logs_by_date_range(logs, where)
        if "user" in where:
            rows = [row for row in rows if row["user"] == where["user"]]
        if "search" in where:
            rows = [row for row in rows if _matches_spend_log_search(row, where["search"])]
        return rows

    return filter_fn


def _five_day_window(today):
    return {
        "start_date": (today - datetime.timedelta(days=5)).strftime("%Y-%m-%d %H:%M:%S"),
        "end_date": today.strftime("%Y-%m-%d %H:%M:%S"),
    }


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "search,expected_request_ids",
    [
        ("req-session-old", {"req-session-old"}),
        ("sess-42", {"req-session"}),
        ("hashed-7", {"req-key"}),
        ("team-7", {"req-team"}),
        ("user-7", {"req-user"}),
        ("cust-7", {"req-end-user"}),
        ("mdl-7", {"req-model"}),
        ("call-recent", {"chatcmpl-x"}),
        ("call-old", set()),
        ("no-such-id", set()),
    ],
)
async def test_ui_view_spend_logs_search_matches_any_id(client, monkeypatch, search, expected_request_ids):
    """LIT-4741: one box matches any id column. A request_id is found across all time (the 5-day
    window excludes the 90-day-old row), every other column only inside the window, and a raw
    sk- key is hashed before it is compared with api_key. The window is not applied globally."""
    today = datetime.datetime.now(timezone.utc)
    logs = _search_fixture_logs(today)
    captured = {}
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(logs, _search_filter_fn(logs, captured)),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={"search": search, **_five_day_window(today)},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert {row["request_id"] for row in data["data"]} == expected_request_ids
        assert data["total"] == len(expected_request_ids)
        assert "startTime" not in captured["where"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_logs_v2_search_keeps_global_window(client, monkeypatch):
    """The public route keeps the caller's window on the whole query, so a search only finds rows
    inside it even by request_id; the windowless request_id branch is a dashboard-only relaxation."""
    today = datetime.datetime.now(timezone.utc)
    logs = _search_fixture_logs(today)
    captured = {}
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(logs, _search_filter_fn(logs, captured)),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/v2",
            params={"search": "req-session-old", **_five_day_window(today)},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["data"] == []
        assert data["total"] == 0
        assert "startTime" in captured["where"]
        assert captured["where"]["search"]["value"] == "req-session-old"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "params",
    [
        {"search": "req-old"},
        {"search": "req-old", "request_id": "req-old"},
    ],
)
async def test_ui_view_spend_logs_search_requires_dates(client, monkeypatch, params):
    """A search needs the window for its non-request_id branches, so it stays required even
    alongside a request_id, which on its own may drop the window."""
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma([], lambda where: []),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get("/spend/logs/ui", params=params, headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 400
        assert "date" in response.text.lower()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "search,expected_request_ids",
    [("sess-9", {"req-own"}), ("req-foreign", set())],
)
async def test_ui_view_spend_logs_search_keeps_non_admin_scope(client, monkeypatch, search, expected_request_ids):
    """A search is scoped like any other listing: an internal user only sees their own rows even
    when the id is on someone else's row, and the request_id ownership shortcut is not used."""
    yesterday = (datetime.datetime.now(timezone.utc) - datetime.timedelta(days=1)).isoformat()
    base = {"api_key": "hashed-key", "team_id": None, "spend": 0.01, "startTime": yesterday, "model": "gpt-4"}
    logs = [
        {**base, "request_id": "req-own", "user": "internal_user_1", "session_id": "sess-9"},
        {**base, "request_id": "req-own-other", "user": "internal_user_1", "session_id": "sess-other"},
        {**base, "request_id": "req-foreign", "user": "internal_user_2", "session_id": "sess-9"},
    ]
    captured = {}
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(logs, _search_filter_fn(logs, captured)),
    )
    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: AsyncMock(return_value=()))
    ownership_check = AsyncMock()
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._assert_user_can_view_request_id",
        ownership_check,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="internal_user_1"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={"search": search, "start_date": start_date, "end_date": end_date},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        assert {row["request_id"] for row in response.json()["data"]} == expected_request_ids
        assert captured["where"]["user"] == "internal_user_1"
        ownership_check.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_unauthorized(client):
    # Test without authorization header
    response = client.get("/spend/logs/ui")
    assert response.status_code in (401, 403), response.text

    # Test with invalid authorization
    response = client.get(
        "/spend/logs/ui",
        headers={"Authorization": "Bearer invalid-token"},
    )
    assert response.status_code in (401, 403), response.text


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_status(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "status": "success",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "status": "failure",
        },
    ]

    def filter_by_status(where):
        if "OR" in where:
            return [mock_spend_logs[0]]  # success
        if "status" in where and where["status"].get("equals") == "failure":
            return [mock_spend_logs[1]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_status),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        # Test success status
        response = client.get(
            "/spend/logs/ui",
            params={
                "status_filter": "success",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["status"] == "success"

        # Test failure status
        response = client.get(
            "/spend/logs/ui",
            params={
                "status_filter": "failure",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["status"] == "failure"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_cache_hit_filter(client, monkeypatch):
    base = {
        "api_key": "sk-test-key",
        "user": "test_user_1",
        "team_id": "team1",
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "gpt-4",
        "status": "success",
    }
    mock_spend_logs = [
        {**base, "id": "log1", "request_id": "req-hit", "cache_hit": "True"},
        {**base, "id": "log2", "request_id": "req-miss", "cache_hit": "False"},
        {**base, "id": "log3", "request_id": "req-legacy", "cache_hit": "None"},
        {**base, "id": "log4", "request_id": "req-null", "cache_hit": None},
    ]

    def filter_by_cache(where):
        cache_filter = where.get("cache_hit")
        if cache_filter == "hit":
            return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() == "true"]
        if cache_filter == "miss":
            return [log for log in mock_spend_logs if str(log["cache_hit"]).lower() != "true"]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_cache),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "cache_hit_filter": "hit",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert [row["request_id"] for row in data["data"]] == ["req-hit"]

        response = client.get(
            "/spend/logs/ui",
            params={
                "cache_hit_filter": "miss",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 3
        assert [row["request_id"] for row in data["data"]] == ["req-miss", "req-legacy", "req-null"]

        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert response.json()["total"] == 4

        response = client.get(
            "/spend/logs/ui",
            params={
                "cache_hit_filter": "invalid",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_used_client_oauth_token_filter(client, monkeypatch):
    base = {
        "api_key": "sk-test-key",
        "user": "test_user_1",
        "team_id": "team1",
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "claude-sonnet-5",
        "status": "success",
    }
    mock_spend_logs = [
        {**base, "id": "log1", "request_id": "req-seat", "metadata": {"used_client_oauth_token": True}},
        {**base, "id": "log2", "request_id": "req-key", "metadata": {"used_client_oauth_token": False}},
        {**base, "id": "log3", "request_id": "req-legacy", "metadata": {"user_agent": "curl/8.7.1"}},
    ]

    def filter_by_credential(where):
        metadata_filter = where.get("metadata")
        if metadata_filter is None:
            return mock_spend_logs
        assert metadata_filter["path"] == ["used_client_oauth_token"]
        return [
            log
            for log in mock_spend_logs
            if json.dumps(log["metadata"].get("used_client_oauth_token")) == metadata_filter["equals"]
        ]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_credential),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        for flag, expected_ids in (("true", ["req-seat"]), ("false", ["req-key"])):
            response = client.get(
                "/spend/logs/ui",
                params={
                    "used_client_oauth_token": flag,
                    "start_date": start_date,
                    "end_date": end_date,
                },
                headers={"Authorization": "Bearer sk-test"},
            )
            assert response.status_code == 200
            data = response.json()
            assert data["total"] == len(expected_ids)
            assert [row["request_id"] for row in data["data"]] == expected_ids

        response = client.get(
            "/spend/logs/ui",
            params={"start_date": start_date, "end_date": end_date},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert response.json()["total"] == 3

        response = client.get(
            "/spend/logs/ui",
            params={
                "used_client_oauth_token": "seat",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 422
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_span_type_filter(client, monkeypatch):
    base = {
        "api_key": "sk-test-key",
        "user": "test_user_1",
        "team_id": "team1",
        "spend": 0.05,
        "startTime": datetime.datetime.now(timezone.utc).isoformat(),
        "model": "gpt-4",
        "status": "success",
    }
    mock_spend_logs = [
        {**base, "id": "log1", "request_id": "req-llm", "call_type": "acompletion"},
        {**base, "id": "log2", "request_id": "req-agent", "call_type": "asend_message"},
        {**base, "id": "log3", "request_id": "req-mcp", "call_type": "call_mcp_tool"},
        {**base, "id": "log4", "request_id": "req-batch", "call_type": "aretrieve_batch"},
    ]

    call_types_by_span = {
        "llm": lambda ct: (
            ct not in {"call_mcp_tool", "list_mcp_tools", "asend_message"}
            and ct not in {"acreate_batch", "create_batch", "aretrieve_batch", "retrieve_batch"}
        ),
        "agent": lambda ct: ct == "asend_message",
        "mcp": lambda ct: ct in {"call_mcp_tool", "list_mcp_tools"},
        "batch": lambda ct: ct in {"acreate_batch", "create_batch", "aretrieve_batch", "retrieve_batch"},
    }

    def filter_by_span_type(where):
        span_type = where.get("span_type")
        if span_type is None:
            return mock_spend_logs
        return [log for log in mock_spend_logs if call_types_by_span[span_type](log["call_type"])]

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_span_type),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        for span_type, expected_ids in [
            ("batch", ["req-batch"]),
            ("llm", ["req-llm"]),
            ("mcp", ["req-mcp"]),
            ("agent", ["req-agent"]),
        ]:
            response = client.get(
                "/spend/logs/ui",
                params={
                    "span_type": span_type,
                    "start_date": start_date,
                    "end_date": end_date,
                },
                headers={"Authorization": "Bearer sk-test"},
            )
            assert response.status_code == 200, response.text
            data = response.json()
            assert data["total"] == len(expected_ids)
            assert [row["request_id"] for row in data["data"]] == expected_ids

        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert response.json()["total"] == 4

        response = client.get(
            "/spend/logs/ui",
            params={
                "span_type": "invalid",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_model(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "status": "success",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "status": "success",
        },
    ]

    def filter_by_model(where):
        if "model" in where and where["model"] == "gpt-3.5-turbo":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_model),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        # Make the request with model filter
        response = client.get(
            "/spend/logs/ui",
            params={
                "model": "gpt-3.5-turbo",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        # Assert response
        assert response.status_code == 200
        data = response.json()

        # Verify the filtered data
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["model"] == "gpt-3.5-turbo"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_model_id(client, monkeypatch):
    """Test that the model_id query param filters spend logs by litellm model deployment id."""
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "model_id": "deployment-id-1",
            "status": "success",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "model_id": "deployment-id-2",
            "status": "success",
        },
    ]

    def filter_by_model_id(where):
        if "model_id" in where and where["model_id"] == "deployment-id-1":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_model_id),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "model_id": "deployment-id-1",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["model_id"] == "deployment-id-1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_model_group(client, monkeypatch):
    """Test that the model_group query param filters spend logs by model group."""
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "model_group": "gpt-3.5-turbo",
            "status": "success",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4-0613",
            "model_group": "gpt-4",
            "status": "success",
        },
    ]

    def filter_by_model_group(where):
        if "model_group" in where and where["model_group"] == "gpt-4":
            return [mock_spend_logs[1]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_model_group),
    )

    start_date, end_date = _default_date_range()

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "model_group": "gpt-4",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["model_group"] == "gpt-4"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_key_hash(client, monkeypatch):
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key-1",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key-2",
            "user": "test_user_2",
            "team_id": "team2",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_api_key(where):
        if "api_key" in where and where["api_key"] == "sk-test-key-1":
            return [mock_spend_logs[0]]
        return mock_spend_logs

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_api_key),
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        start_date, end_date = _default_date_range()

        # Make the request with key_hash filter
        response = client.get(
            "/spend/logs/ui",
            params={
                "api_key": "sk-test-key-1",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        # Assert response
        assert response.status_code == 200
        data = response.json()

        # Verify the filtered data
        assert data["total"] == 1
        assert len(data["data"]) == 1
        assert data["data"][0]["api_key"] == "sk-test-key-1"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


async def _wait_for_mock_call(mock, timeout=10, interval=0.1):
    """Poll until mock has been called at least once, or timeout."""
    import time

    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if mock.call_count > 0:
            return
        await asyncio.sleep(interval)
    mock.assert_called_once()  # will raise with a clear message


class TestSpendLogsPayload:
    def setup_method(self):
        self._original_callbacks = litellm.callbacks[:]
        self._original_cache = litellm.cache
        litellm.cache = None

    def teardown_method(self):
        litellm.callbacks = self._original_callbacks
        litellm.cache = self._original_cache

    @pytest.mark.asyncio
    async def test_spend_logs_payload_e2e(self):
        litellm.callbacks = [ProxyDBLogger(message_logging=False)]
        # litellm.turn_on_debug()

        with (
            patch.object(
                litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter,
                "_insert_spend_log_to_db",
            ) as mock_client,
            patch.object(litellm.proxy.proxy_server, "prisma_client"),
        ):
            response = await litellm.acompletion(
                model="gpt-4o",
                messages=[{"role": "user", "content": "Hello, world!"}],
                mock_response="Hello, world!",
                metadata={"user_api_key_end_user_id": "test_user_1"},
            )

            assert response.choices[0].message.content == "Hello, world!"

            await _wait_for_mock_call(mock_client)

            kwargs = mock_client.call_args.kwargs
            payload: SpendLogsPayload = kwargs["payload"]
            expected_payload = SpendLogsPayload(
                **{
                    "request_id": "chatcmpl-34df56d5-4807-45c1-bb99-61e52586b802",
                    "session_id": "1234567890",
                    "call_type": "acompletion",
                    "api_key": "",
                    "cache_hit": "None",
                    "startTime": datetime.datetime(2025, 3, 24, 22, 2, 42, 975883, tzinfo=datetime.timezone.utc),
                    "endTime": datetime.datetime(2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc),
                    "completionStartTime": datetime.datetime(
                        2025, 3, 24, 22, 2, 42, 989132, tzinfo=datetime.timezone.utc
                    ),
                    "model": "gpt-4o",
                    "user": "",
                    "team_id": "",
                    "metadata": '{"user_api_key_user_email": null, "actor_agent_id": null, "target_agent_id": null, "billing_agent_id": null, "agent_execution_mode": null, "verified_human_user_id": null, "applied_guardrails": [], "attempted_fallbacks": null, "original_model_group": null, "batch_models": null, "batch_successful_requests": null, "batch_failed_requests": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "internal_call_origin": null, "guardrail_information": null, "compression_savings": null, "litellm_gateway_injected_cache": null, "router_metadata": null, "autorouter_savings_estimate": null, "autorouter_baseline_observation": null, "azure_spillover": null, "used_client_oauth_token": null, "litellm_roi_estimator": false, "billed_retry_attempt": false, "usage_object": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30, "completion_tokens_details": null, "prompt_tokens_details": null}, "model_map_information": {"model_map_key": "gpt-4o", "model_map_value": {"key": "gpt-4o", "max_tokens": 16384, "max_input_tokens": 128000, "max_output_tokens": 16384, "input_cost_per_token": 2.5e-06, "cache_creation_input_token_cost": null, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": 1.25e-06, "output_cost_per_token_batches": 5e-06, "output_cost_per_token": 1e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_reasoning_token": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "openai", "mode": "chat", "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": false, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": false, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": true, "supports_reasoning": false, "search_context_cost_per_query": {"search_context_size_low": 0.03, "search_context_size_medium": 0.035, "search_context_size_high": 0.05}, "tpm": null, "rpm": null, "supported_openai_params": ["frequency_penalty", "logit_bias", "logprobs", "top_logprobs", "max_tokens", "max_completion_tokens", "modalities", "prediction", "n", "presence_penalty", "seed", "stop", "stream", "stream_options", "temperature", "top_p", "tools", "tool_choice", "function_call", "functions", "max_retries", "extra_headers", "parallel_tool_calls", "audio", "response_format", "user"]}}, "additional_usage_values": {"completion_tokens_details": null, "prompt_tokens_details": null}}',
                    "cache_key": "Cache OFF",
                    "spend": 0.00022500000000000002,
                    "total_tokens": 30,
                    "prompt_tokens": 10,
                    "completion_tokens": 20,
                    "request_tags": "[]",
                    "end_user": "test_user_1",
                    "api_base": "",
                    "model_group": "",
                    "model_id": "",
                    "requester_ip_address": None,
                    "custom_llm_provider": "openai",
                    "messages": "{}",
                    "response": "{}",
                    "proxy_server_request": "{}",
                    "status": "success",
                    "mcp_namespaced_tool_name": None,
                    "agent_id": None,
                    "billing_agent_id": None,
                }
            )

            expected_payload_with_pod_routing: Final[SpendLogsPayload] = {
                **expected_payload,
                "metadata": expected_payload["metadata"].replace(
                    '"routing_decision": null, ',
                    '"routing_decision": null, "kubernetes_pod_routing": null, ',
                ),
            }
            differences = _compare_nested_dicts(
                payload,
                expected_payload_with_pod_routing,
                ignore_keys=ignored_keys,
            )
            if differences:
                pytest.fail(f"Dictionary mismatch: {differences}")

    def mock_anthropic_response(*args, **kwargs):
        mock_response = MagicMock()
        mock_response.status_code = 200
        mock_response.headers = {"Content-Type": "application/json"}
        mock_response.json.return_value = {
            "content": [{"text": "Hi! My name is Claude.", "type": "text"}],
            "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
            "model": "claude-4-sonnet-20250514",
            "role": "assistant",
            "stop_reason": "end_turn",
            "stop_sequence": None,
            "type": "message",
            "usage": {"input_tokens": 2095, "output_tokens": 503},
        }
        return mock_response


def _compare_nested_dicts(actual: dict, expected: dict, path: str = "", ignore_keys: list[str] = []) -> list[str]:
    """Compare nested dictionaries and return a list of differences in a human-friendly format."""
    differences = []

    # Check if current path should be ignored
    if path in ignore_keys:
        return differences

    # Check for keys in actual but not in expected
    for key in actual:
        current_path = f"{path}.{key}" if path else key
        if current_path not in ignore_keys and key not in expected:
            differences.append(f"Extra key in actual: {current_path}")

    for key, expected_value in expected.items():
        current_path = f"{path}.{key}" if path else key
        if current_path in ignore_keys:
            continue
        if key not in actual:
            differences.append(f"Missing key: {current_path}")
            continue

        actual_value = actual[key]

        # Try to parse JSON strings
        if isinstance(expected_value, str):
            try:
                expected_value = json.loads(expected_value)
            except json.JSONDecodeError:
                pass
        if isinstance(actual_value, str):
            try:
                actual_value = json.loads(actual_value)
            except json.JSONDecodeError:
                pass

        if isinstance(expected_value, dict) and isinstance(actual_value, dict):
            differences.extend(_compare_nested_dicts(actual_value, expected_value, current_path, ignore_keys))
        elif isinstance(expected_value, dict) or isinstance(actual_value, dict):
            differences.append(f"Type mismatch at {current_path}: expected dict, got {type(actual_value).__name__}")
        else:
            # For non-dict values, only report if they're different
            if actual_value != expected_value:
                # Format the values to be more readable
                actual_str = str(actual_value)
                expected_str = str(expected_value)
                if len(actual_str) > 50 or len(expected_str) > 50:
                    actual_str = f"{actual_str[:50]}..."
                    expected_str = f"{expected_str[:50]}..."
                differences.append(
                    f"Value mismatch at {current_path}:\n  expected: {expected_str}\n  got:      {actual_str}"
                )
    return differences


@pytest.mark.asyncio
async def test_global_spend_keys_endpoint_limit_validation(client, monkeypatch):
    """
    Test to ensure that the global_spend_keys endpoint is protected against SQL injection attacks.
    Verifies that the limit parameter is properly parameterized and not directly interpolated.
    """
    # Create a simple mock for prisma client with empty response
    mock_prisma_client = MagicMock()
    mock_db = MagicMock()
    mock_query_raw = AsyncMock(return_value=[])
    mock_db.query_raw = mock_query_raw
    mock_prisma_client.db = mock_db
    # Apply the mock to the prisma_client module
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Override auth to bypass API key validation
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        # Call the endpoint without specifying a limit
        no_limit_response = client.get("/global/spend/keys")
        assert no_limit_response.status_code == 200
        mock_query_raw.assert_called_once_with('SELECT * FROM "Last30dKeysBySpend";')
        # Reset the mock for the next test
        mock_query_raw.reset_mock()
        # Test with valid input
        normal_limit = "10"
        good_input_response = client.get(f"/global/spend/keys?limit={normal_limit}")
        assert good_input_response.status_code == 200
        # Verify the mock was called with the correct parameters
        mock_query_raw.assert_called_once_with('SELECT * FROM "Last30dKeysBySpend" LIMIT $1 ;', 10)
        # Reset the mock for the next test
        mock_query_raw.reset_mock()
        # Test with SQL injection payload
        sql_injection_limit = "10; DROP TABLE spend_logs; --"
        response = client.get(f"/global/spend/keys?limit={sql_injection_limit}")
        # Verify the response is a validation error (422)
        assert response.status_code == 422
        # Verify the mock was not called with the SQL injection payload
        # This confirms that the validation happens before the database query
        mock_query_raw.assert_not_called()
        # Reset the mock for the next test
        mock_query_raw.reset_mock()
        # Test with non-numeric input
        non_numeric_limit = "abc"
        response = client.get(f"/global/spend/keys?limit={non_numeric_limit}")
        assert response.status_code == 422
        mock_query_raw.assert_not_called()
        mock_query_raw.reset_mock()
        # Test with negative number
        negative_limit = "-5"
        response = client.get(f"/global/spend/keys?limit={negative_limit}")
        assert response.status_code == 422
        mock_query_raw.assert_not_called()
        mock_query_raw.reset_mock()
        # Test with zero
        zero_limit = "0"
        response = client.get(f"/global/spend/keys?limit={zero_limit}")
        assert response.status_code == 422
        mock_query_raw.assert_not_called()
        mock_query_raw.reset_mock()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_summarize_parameter(client, monkeypatch):
    """Test the new summarize parameter in the /spend/logs endpoint"""
    import datetime
    from datetime import timedelta, timezone

    # Mock spend logs data
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": (datetime.datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
            "model": "gpt-3.5-turbo",
            "prompt_tokens": 100,
            "completion_tokens": 50,
            "total_tokens": 150,
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": (datetime.datetime.now(timezone.utc) - timedelta(days=1)).isoformat(),
            "model": "gpt-4",
            "prompt_tokens": 200,
            "completion_tokens": 100,
            "total_tokens": 300,
        },
    ]

    # Mock for unsummarized data (summarize=false)
    class MockDB:
        def __init__(self):
            self.litellm_spendlogs = self

        async def find_many(self, *args, **kwargs):
            # Return individual log entries when summarize=false
            return mock_spend_logs

        async def query_raw(self, sql_query, *params):
            yesterday = datetime.datetime.now(timezone.utc) - timedelta(days=1)
            return [
                {
                    "api_key": "sk-test-key",
                    "user": "test_user_1",
                    "model": "gpt-3.5-turbo",
                    "day": yesterday.date().isoformat(),
                    "spend": 0.05,
                },
                {
                    "api_key": "sk-test-key",
                    "user": "test_user_1",
                    "model": "gpt-4",
                    "day": yesterday.date().isoformat(),
                    "spend": 0.10,
                },
            ]

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

    # Apply the monkeypatch
    mock_prisma_client = MockPrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Set up test dates
    start_date = (datetime.datetime.now(timezone.utc) - timedelta(days=2)).strftime("%Y-%m-%d")
    end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d")

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        # Test 1: summarize=false should return individual log entries
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "false",
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()

        # Should return the raw log entries
        assert isinstance(data, list)
        assert len(data) == 2
        assert data[0]["id"] == "log1"
        assert data[1]["id"] == "log2"
        assert data[0]["request_id"] == "req1"
        assert data[1]["request_id"] == "req2"

        # Test 2: summarize=true should return grouped data
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "true",
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()

        # Should return grouped/summarized data
        assert isinstance(data, list)
        # The structure should be different - grouped by date with aggregated spend
        assert "startTime" in data[0]
        assert "spend" in data[0]
        assert "users" in data[0]
        assert "models" in data[0]

        # Test 3: default behavior (no summarize parameter) should maintain backward compatibility
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()

        # Should return grouped/summarized data (same as summarize=true)
        assert isinstance(data, list)
        assert "startTime" in data[0]
        assert "spend" in data[0]
        assert "users" in data[0]
        assert "models" in data[0]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_bounds_row_count(client, monkeypatch):
    """Every /spend/logs read path must send take=SPEND_LOGS_PAGINATION_COUNT_CAP to Prisma (LIT-6284)."""
    captured_find_many_kwargs = []

    class MockDB:
        def __init__(self):
            self.litellm_spendlogs = self
            self.available_rows = 0

        async def find_many(self, *args, **kwargs):
            captured_find_many_kwargs.append(kwargs)
            return [{}] * min(kwargs.get("take", 0), self.available_rows)

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

        def hash_token(self, token):
            return f"hashed-{token}"

    mock_prisma_client = MockPrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    start_date = (datetime.datetime.now(timezone.utc) - datetime.timedelta(days=2)).strftime("%Y-%m-%d")
    end_date = datetime.datetime.now(timezone.utc).strftime("%Y-%m-%d")
    try:
        response = client.get(
            "/spend/logs",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert captured_find_many_kwargs[-1].get("take") == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP
        assert "x-litellm-spend-logs-truncated" not in response.headers

        response = client.get(
            "/spend/logs",
            params={"user_id": "test-user"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert captured_find_many_kwargs[-1].get("where") == {"user": "test-user"}
        assert captured_find_many_kwargs[-1].get("take") == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP

        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "false",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert "startTime" in captured_find_many_kwargs[-1].get("where", {})
        assert captured_find_many_kwargs[-1].get("take") == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP

        mock_prisma_client.db.available_rows = spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP
        response = client.get(
            "/spend/logs",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert len(response.json()) == spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP
        assert response.headers["x-litellm-spend-logs-truncated"] == "true"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_tags(client, monkeypatch):
    """Test the /spend/tags endpoint"""

    # Mock the prisma client and get_spend_by_tags function
    mock_prisma_client = MagicMock()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)

    # Mock response data
    mock_response = [
        {"individual_request_tag": "tag1", "log_count": 10, "total_spend": 0.15},
        {"individual_request_tag": "tag2", "log_count": 5, "total_spend": 0.08},
    ]

    # Mock the get_spend_by_tags function
    async def mock_get_spend_by_tags(prisma_client, read_scope, start_date=None, end_date=None):
        return mock_response

    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints.get_spend_by_tags",
        mock_get_spend_by_tags,
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        # Test without date filters
        response = client.get(
            "/spend/tags",
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        assert len(data) == 2
        assert data[0]["individual_request_tag"] == "tag1"
        assert data[0]["log_count"] == 10
        assert data[0]["total_spend"] == 0.15

        # Test with date filters
        start_date = "2024-01-01"
        end_date = "2024-01-31"

        response = client.get(
            "/spend/tags",
            params={
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert isinstance(data, list)
        assert len(data) == 2
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def _tag_query_prisma_client(assert_query_raw):
    class MockDB:
        async def query_raw(self, sql_query, *params):
            return assert_query_raw(sql_query, params)

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

    return MockPrismaClient()


@pytest.mark.asyncio
async def test_view_spend_tags_scopes_internal_user_to_own_and_team_logs(client, monkeypatch):
    def assert_query_raw(sql_query, params):
        assert '("user" = $1 OR team_id = ANY($2::text[]))' in sql_query
        assert params[0] == "user-1"
        assert tuple(params[1]) == ("team-9",)
        return [{"individual_request_tag": "own-tag", "log_count": 1, "total_spend": 0.01}]

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", _tag_query_prisma_client(assert_query_raw))

    async def permitted_teams(*args, **kwargs):
        return ["team-9"]

    monkeypatch.setitem(app.dependency_overrides, get_log_team_lookup, lambda: permitted_teams)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user-1"
    )

    try:
        response = client.get("/spend/tags", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert [row["individual_request_tag"] for row in response.json()] == ["own-tag"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_tags_admin_sees_unscoped_aggregates_with_date_filter(client, monkeypatch):
    def assert_query_raw(sql_query, params):
        assert '"user"' not in sql_query
        assert "team_id" not in sql_query
        assert '"startTime" >= ($1' in sql_query
        assert "$2::timestamptz + INTERVAL '1 day'" in sql_query
        assert params == (
            datetime.datetime(2024, 1, 1, tzinfo=timezone.utc),
            datetime.datetime(2024, 1, 31, tzinfo=timezone.utc),
        ), "dates must be bound as UTC datetimes so the window is session-timezone independent"
        return [{"individual_request_tag": "any-tag", "log_count": 2, "total_spend": 0.05}]

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", _tag_query_prisma_client(assert_query_raw))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/tags",
            params={"start_date": "2024-01-01", "end_date": "2024-01-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert len(response.json()) == 1
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_tags_rejects_malformed_dates_with_400(client, monkeypatch):
    def assert_query_raw(sql_query, params):
        pytest.fail("malformed dates must never reach the database")

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", _tag_query_prisma_client(assert_query_raw))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/tags",
            params={"start_date": "01/31/2024"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        assert "start_date" in response.text
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_tags_key_without_user_id_gets_no_rows(client, monkeypatch):
    def assert_query_raw(sql_query, params):
        assert "WHERE FALSE" in sql_query
        assert params == ()
        return []

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", _tag_query_prisma_client(assert_query_raw))
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.TEAM, user_id=None
    )

    try:
        response = client.get("/spend/tags", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert response.json() == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_tags_no_database(client, monkeypatch):
    """Test /spend/tags endpoint when database is not connected"""

    # Mock prisma_client as None
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/tags",
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 500
        data = response.json()
        # Check the actual error message structure
        assert "error" in data
        assert "Database not connected" in data["error"]["message"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_provider_budget_under(disable_budget_sync):
    """Test that router allows completion when under budget"""
    provider_budget_config = {"azure": BudgetConfig(max_budget=0.01, budget_duration="10d")}

    router = Router(
        enable_pre_call_checks=True,
        provider_budget_config=provider_budget_config,
        model_list=MODEL_LIST,
    )

    response = await router.acompletion(
        model="azure-gpt-4o",
        messages=[{"role": "user", "content": "Hello, world!"}],
    )

    assert response is not None


@pytest.mark.asyncio
async def test_provider_budget_over(disable_budget_sync):
    """Test that router allows completion when over budget"""
    provider_budget_config = {"azure": BudgetConfig(max_budget=-0.01, budget_duration="10d")}

    router = Router(
        num_retries=0,
        enable_pre_call_checks=True,
        provider_budget_config=provider_budget_config,
        model_list=MODEL_LIST,
    )

    with pytest.raises(Exception, match="No deployments available - crossed budget: Exceeded budget") as e:
        await router.acompletion(
            model="azure-gpt-4o",
            messages=[{"role": "user", "content": "Hello, world!"}],
        )
    assert "Exceeded budget for provider" in str(e.value)


@pytest.mark.asyncio
async def test_provider_budget_provider_budgets(disable_budget_sync):
    """Test that provider_budgets() returns correct values"""
    provider = "azure"
    max_budget = -0.01
    budget_duration = "10d"
    provider_budget_config = {provider: BudgetConfig(max_budget=max_budget, budget_duration=budget_duration)}

    router = Router(
        num_retries=0,
        enable_pre_call_checks=True,
        provider_budget_config=provider_budget_config,
        model_list=MODEL_LIST,
    )

    with patch("litellm.proxy.proxy_server.llm_router", router):
        response = await spend_management_endpoints.provider_budgets()
        provider_budget_response = response.providers[provider]
        assert provider_budget_response.budget_limit == max_budget
        assert provider_budget_response.time_period == budget_duration


@pytest.mark.asyncio
async def test_view_spend_logs_with_date_range_summarized(client, monkeypatch):
    """
    Tests the /spend/logs endpoint with both start_date and end_date,
    ensuring it returns summarized data and not an empty list.
    This test specifically validates the fix for dates being passed as ISO strings.
    """
    from datetime import datetime, timedelta, timezone

    mock_summarized_response = [
        {
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "model": "gpt-4",
            "day": (datetime.now(timezone.utc) - timedelta(days=1)).date().isoformat(),
            "spend": 0.15,
        }
    ]

    class MockDB:
        async def query_raw(self, sql_query, *params):
            assert isinstance(params[0], str)
            assert isinstance(params[1], str)
            assert "T" in params[0]
            assert "T" in params[1]
            return mock_summarized_response

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())

    start_date = (datetime.now(timezone.utc) - timedelta(days=2)).strftime("%Y-%m-%d")
    end_date = datetime.now(timezone.utc).strftime("%Y-%m-%d")

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()

        assert isinstance(data, list)
        assert len(data) > 0
        assert "startTime" in data[0]
        assert "spend" in data[0]
        assert "users" in data[0]
        assert "models" in data[0]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_summarize_groups_by_day_in_sql(client, monkeypatch):
    mock_rows = [
        {
            "day": "2024-01-01",
            "api_key": "hashed::sk-abc",
            "user": "u1",
            "model": "gpt-4",
            "spend": 0.1,
        },
        {
            "day": "2024-01-01",
            "api_key": "hashed::sk-abc",
            "user": "u1",
            "model": "gpt-4o",
            "spend": 0.2,
        },
    ]

    class MockDB:
        def __init__(self):
            self.captured_sql = None
            self.captured_params = None

        async def query_raw(self, sql_query, *params):
            self.captured_sql = sql_query
            self.captured_params = params
            return mock_rows

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

        def hash_token(self, token):
            return "hashed::" + token

    mock_prisma_client = MockPrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": "2024-01-01",
                "end_date": "2024-01-03",
                "api_key": "sk-abc",
                "request_id": "req-123",
                "user_id": "u1",
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        sql = mock_prisma_client.db.captured_sql
        assert "date_trunc('day'" in sql
        assert "GROUP BY" in sql
        assert "find_many" not in sql
        assert not hasattr(mock_prisma_client.db, "group_by")
        assert mock_prisma_client.db.captured_params == (
            "2024-01-01T00:00:00+00:00",
            "2024-01-03T00:00:00+00:00",
            "hashed::sk-abc",
            "req-123",
            "u1",
        )
        assert len(data) == 3
        assert data[0]["startTime"] == "2024-01-01"
        assert data[0]["spend"] == pytest.approx(0.3)
        assert data[0]["models"] == {"gpt-4": 0.1, "gpt-4o": 0.2}
        assert data[0]["users"] == {"u1": pytest.approx(0.3)}
        assert data[0]["hashed::sk-abc"] == pytest.approx(0.3)
        assert data[1] == {
            "startTime": "2024-01-02",
            "spend": 0,
            "users": {},
            "models": {},
        }
        assert data[2] == {
            "startTime": "2024-01-03",
            "spend": 0,
            "users": {},
            "models": {},
        }
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_summarize_empty_rows(client, monkeypatch):
    class MockDB:
        async def query_raw(self, sql_query, *params):
            return []

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs",
            params={"start_date": "2024-01-01", "end_date": "2024-01-01"},
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        assert response.json() == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_summarize_unhashed_api_key_without_padding(client, monkeypatch):
    mock_rows = [
        {
            "day": "2024-01-01",
            "api_key": "plain-key",
            "user": "u1",
            "model": "gpt-4",
            "spend": 0.4,
        }
    ]

    class MockDB:
        def __init__(self):
            self.captured_params = None

        async def query_raw(self, sql_query, *params):
            self.captured_params = params
            return mock_rows

    class MockPrismaClient:
        def __init__(self):
            self.db = MockDB()

    mock_prisma_client = MockPrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN)
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": "2024-01-01",
                "end_date": "2024-01-01",
                "api_key": "plain-key",
            },
            headers={"Authorization": "Bearer sk-test"},
        )

        assert response.status_code == 200
        data = response.json()
        assert mock_prisma_client.db.captured_params == (
            "2024-01-01T00:00:00+00:00",
            "2024-01-01T00:00:00+00:00",
            "plain-key",
        )
        assert data == [
            {
                "startTime": "2024-01-01",
                "spend": pytest.approx(0.4),
                "plain-key": pytest.approx(0.4),
                "users": {"u1": pytest.approx(0.4)},
                "models": {"gpt-4": pytest.approx(0.4)},
            }
        ]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_error_code(client):
    """Test filtering spend logs by error code"""
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "metadata": '{"error_information": {"error_code": "404"}}',
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "metadata": '{"error_information": {"error_code": "500"}}',
        },
    ]

    def filter_by_error_code(where):
        if "metadata" in where:
            mf = where["metadata"]
            if mf.get("path") == ["error_information", "error_code"]:
                code = str(mf.get("equals", "")).strip('"')
                if code == "404":
                    return [mock_spend_logs[0]]
                if code == "500":
                    return [mock_spend_logs[1]]
        return mock_spend_logs

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        with patch.object(
            ps,
            "prisma_client",
            make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_error_code),
        ):
            start_date, end_date = _default_date_range()

            response = client.get(
                "/spend/logs/ui",
                params={
                    "error_code": "404",
                    "start_date": start_date,
                    "end_date": end_date,
                },
                headers={"Authorization": "Bearer sk-test"},
            )

            assert response.status_code == 200
            data = response.json()
            assert data["total"] == 1
            assert len(data["data"]) == 1
            assert data["data"][0]["id"] == "log1"
            metadata = data["data"][0]["metadata"]
            assert isinstance(metadata, dict)
            assert "error_information" in metadata
            assert metadata["error_information"]["error_code"] == "404"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_error_message(client):
    """Test filtering spend logs by error message"""
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "metadata": '{"error_information": {"error_message": "Rate limit exceeded"}}',
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "metadata": '{"error_information": {"error_message": "Invalid API key"}}',
        },
    ]

    def filter_by_error_message(where):
        if "metadata" in where:
            mf = where["metadata"]
            if mf.get("path") == ["error_information", "error_message"]:
                msg = mf.get("string_contains")
                if msg == "Rate limit":
                    return [mock_spend_logs[0]]
                if msg == "Invalid API":
                    return [mock_spend_logs[1]]
        return mock_spend_logs

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        with patch.object(
            ps,
            "prisma_client",
            make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_error_message),
        ):
            start_date, end_date = _default_date_range()

            response = client.get(
                "/spend/logs/ui",
                params={
                    "error_message": "Rate limit",
                    "start_date": start_date,
                    "end_date": end_date,
                },
                headers={"Authorization": "Bearer sk-test"},
            )

            assert response.status_code == 200
            data = response.json()
            assert data["total"] == 1
            assert len(data["data"]) == 1
            assert data["data"][0]["id"] == "log1"
            metadata = data["data"][0]["metadata"]
            assert isinstance(metadata, dict)
            assert "error_information" in metadata
            assert "Rate limit exceeded" in metadata["error_information"]["error_message"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_with_error_code_and_key_alias(client):
    """Test merging error_code and key_alias filters with AND logic"""
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-test-key",
            "user": "test_user_1",
            "team_id": "team1",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-3.5-turbo",
            "metadata": '{"user_api_key_alias": "test-key-1", "error_information": {"error_code": "404"}}',
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-test-key",
            "user": "test_user_2",
            "team_id": "team1",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "metadata": '{"user_api_key_alias": "test-key-2", "error_information": {"error_code": "500"}}',
        },
        {
            "id": "log3",
            "request_id": "req3",
            "api_key": "sk-test-key",
            "user": "test_user_3",
            "team_id": "team1",
            "spend": 0.15,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
            "metadata": '{"user_api_key_alias": "test-key-1", "error_information": {"error_code": "500"}}',
        },
    ]

    def filter_by_error_code_and_key_alias(where):
        if "AND" in where:
            key_alias = error_code = None
            for cond in where["AND"]:
                if "metadata" in cond:
                    mf = cond["metadata"]
                    if mf.get("path") == ["user_api_key_alias"]:
                        key_alias = mf.get("string_contains")
                    elif mf.get("path") == ["error_information", "error_code"]:
                        error_code = str(mf.get("equals", "")).strip('"')
            if key_alias == "test-key-1" and error_code == "500":
                return [mock_spend_logs[2]]
        return mock_spend_logs

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        with patch.object(
            ps,
            "prisma_client",
            make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_error_code_and_key_alias),
        ):
            start_date, end_date = _default_date_range()

            response = client.get(
                "/spend/logs/ui",
                params={
                    "error_code": "500",
                    "key_alias": "test-key-1",
                    "start_date": start_date,
                    "end_date": end_date,
                },
                headers={"Authorization": "Bearer sk-test"},
            )

            assert response.status_code == 200
            data = response.json()
            assert data["total"] == 1
            assert len(data["data"]) == 1
            assert data["data"][0]["id"] == "log3"
            metadata = data["data"][0]["metadata"]
            assert isinstance(metadata, dict)
            assert "user_api_key_alias" in metadata
            assert metadata["user_api_key_alias"] == "test-key-1"
            assert "error_information" in metadata
            assert metadata["error_information"]["error_code"] == "500"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_dict_rows_session_counts():
    """
    Regression test: _build_ui_spend_logs_response must enrich session_total_count
    even when rows are plain dicts (as returned by query_raw) rather than Prisma
    model instances.  Previously getattr(dict, "session_id", None) silently
    returned None, so every row got session_total_count=1 and the UI never
    grouped session rows.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-abc-123"
    api_key = "hashed-key-xyz"
    dict_rows = [
        {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key},
        {"request_id": "req-2", "session_id": session_id, "call_type": "mcp_tool_call", "api_key": api_key},
        {"request_id": "req-3", "session_id": None, "call_type": "completion", "api_key": api_key},
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.litellm_spendlogs.group_by = AsyncMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": 2,
                "session_total_spend": 15.0,
                "mcp_tool_call_count": 1,
                "mcp_tool_call_spend": 10.0,
                "session_llm_count": 1,
                "session_agent_count": 0,
                "session_models": ["claude-haiku-4-5", "gpt-5.4-nano"],
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=3,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    assert len(rows) == 3

    # Rows with the shared session_id should have session_total_count=2
    assert rows[0]["session_total_count"] == 2
    assert rows[1]["session_total_count"] == 2
    assert rows[0]["mcp_tool_call_count"] == 1
    assert rows[0]["mcp_tool_call_spend"] == 10.0
    assert rows[1]["mcp_tool_call_count"] == 1
    assert rows[1]["mcp_tool_call_spend"] == 10.0
    assert rows[0]["session_llm_count"] == 1
    assert rows[0]["session_agent_count"] == 0
    assert rows[0]["session_models"] == ["claude-haiku-4-5", "gpt-5.4-nano"]

    # Every row in the session carries the full session spend, not just its own
    assert rows[0]["session_total_spend"] == 15.0
    assert rows[1]["session_total_spend"] == 15.0

    # Row without a session_id defaults to 1
    assert rows[2]["session_total_count"] == 1
    assert "session_models" not in rows[2]

    # The count is folded into the single aggregate query; no separate group_by call.
    mock_prisma.db.litellm_spendlogs.group_by.assert_not_called()


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_caps_session_models():
    """The per-session model list is bounded server-side and flags when it was cut."""
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _SESSION_MODELS_LIMIT,
        _build_ui_spend_logs_response,
    )

    session_id = "sess-many-models"
    api_key = "hashed-key-xyz"
    over_limit_models = [f"model-{i:02d}" for i in range(_SESSION_MODELS_LIMIT + 1)]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": len(over_limit_models),
                "session_total_spend": 1.0,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_llm_count": len(over_limit_models),
                "session_agent_count": 0,
                "session_models": over_limit_models,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=[{"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key}],
        total_records=1,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    row = result["data"][0]
    assert row["session_models"] == over_limit_models[:_SESSION_MODELS_LIMIT]
    assert row["session_models_truncated"] is True

    sql, *params = mock_prisma.db.query_raw.await_args.args
    assert "LIMIT $4" in sql
    assert params[3] == _SESSION_MODELS_LIMIT + 1


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_key_split_session_gets_per_key_aggregates():
    """
    Two keys reusing one session id are separate rows under grouped pagination,
    and each row must carry ITS key's totals, never the combined session's:
    the aggregate query and its lookup are keyed by (session_id, api_key).
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-shared"
    dict_rows = [
        {"request_id": "req-a", "session_id": session_id, "call_type": "completion", "api_key": "key-a"},
        {"request_id": "req-b", "session_id": session_id, "call_type": "completion", "api_key": "key-b"},
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": "key-a",
                "session_total_count": 2,
                "session_total_spend": 0.2,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_cache_hit_count": 1,
                "session_llm_count": 2,
                "session_agent_count": 0,
            },
            {
                "session_id": session_id,
                "api_key": "key-b",
                "session_total_count": 1,
                "session_total_spend": 0.7,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_cache_hit_count": 0,
                "session_llm_count": 1,
                "session_agent_count": 0,
            },
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=2,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    assert [(r["session_total_count"], r["session_total_spend"]) for r in rows] == [(2, 0.2), (1, 0.7)]
    assert [r["session_cache_hit_count"] for r in rows] == [1, 0]
    assert [r["session_llm_count"] for r in rows] == [2, 1]

    aggregate_sql = mock_prisma.db.query_raw.mock_calls[0][1][0]
    assert "GROUP BY session_id, api_key" in aggregate_sql


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_empty_api_key_keeps_session_aggregates():
    """
    The spend-log schema defaults api_key to an empty string, which is a real
    group value and not a missing one: a multi-call session logged under an
    empty key must keep its count and spend instead of degrading to a plain
    single-call row.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-keyless"
    dict_rows = [
        {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": ""},
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": "",
                "session_total_count": 3,
                "session_total_spend": 0.09,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_cache_hit_count": 0,
                "session_llm_count": 3,
                "session_agent_count": 0,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=1,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    row = result["data"][0]
    assert row["session_total_count"] == 3
    assert row["session_total_spend"] == 0.09

    # The empty key must reach the aggregate's authorized-keys filter too.
    _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]
    assert call_args[2] == [""]


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_sums_multi_round_session_spend():
    """
    Regression test for LIT-4342: for a multi-round session the UI must show the
    summed cost of every round, not just the first call.  _build_ui_spend_logs_response
    enriches each row of a session with session_total_spend aggregated across the
    whole session, scoped to the authorized api_keys of the page.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-multi-round"
    api_key = "hashed-key-xyz"
    # Three rounds of the same chat session with different per-call spend.
    dict_rows = [
        {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.01},
        {"request_id": "req-2", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.02},
        {"request_id": "req-3", "session_id": session_id, "call_type": "completion", "api_key": api_key, "spend": 0.03},
    ]

    mock_prisma = MagicMock()
    # The raw aggregate query returns the full session spend (0.01 + 0.02 + 0.03).
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": 3,
                "session_total_spend": 0.06,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=3,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    assert [row["session_total_spend"] for row in rows] == [0.06, 0.06, 0.06]
    # No MCP calls in this session, so MCP fields must not be attached.
    assert all("mcp_tool_call_count" not in row for row in rows)

    # The aggregate must be scoped to the authorized api_keys of the page.
    _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]
    assert call_args[1] == [session_id]
    assert call_args[2] == [api_key]


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_sums_multi_round_session_tokens():
    """
    Regression test for LIT-4929: the logs table showed the summed session cost but
    only the last call's token usage.  Every row of a multi-round session must carry
    the session-wide prompt, completion and total token sums from the aggregate
    query, while rows outside a session carry none of them.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-multi-round-tokens"
    api_key = "hashed-key-xyz"
    dict_rows = [
        {
            "request_id": "req-1",
            "session_id": session_id,
            "call_type": "completion",
            "api_key": api_key,
            "total_tokens": 10,
            "prompt_tokens": 7,
            "completion_tokens": 3,
        },
        {
            "request_id": "req-2",
            "session_id": session_id,
            "call_type": "completion",
            "api_key": api_key,
            "total_tokens": 50,
            "prompt_tokens": 35,
            "completion_tokens": 15,
        },
        {
            "request_id": "req-3",
            "session_id": None,
            "call_type": "completion",
            "api_key": api_key,
            "total_tokens": 5,
            "prompt_tokens": 4,
            "completion_tokens": 1,
        },
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": 2,
                "session_total_spend": 0.06,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_total_prompt_tokens": 42,
                "session_total_completion_tokens": 18,
                "session_total_tokens": 60,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=3,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    session_rows = rows[:2]
    assert [row["session_total_tokens"] for row in session_rows] == [60, 60]
    assert [row["session_total_prompt_tokens"] for row in session_rows] == [42, 42]
    assert [row["session_total_completion_tokens"] for row in session_rows] == [18, 18]
    assert [(row["total_tokens"], row["prompt_tokens"], row["completion_tokens"]) for row in session_rows] == [
        (10, 7, 3),
        (50, 35, 15),
    ]

    token_keys = ("session_total_tokens", "session_total_prompt_tokens", "session_total_completion_tokens")
    assert all(key not in rows[2] for key in token_keys)


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_sums_multi_round_session_duration():
    """
    Regression test: a multi-round session collapses into a single UI row, so that row
    must carry the duration of every round summed, not just the representative call's.
    Rows written before request_duration_ms existed are NULL, so the aggregate falls back
    to endTime - startTime for them.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-multi-round-duration"
    api_key = "hashed-key-xyz"
    dict_rows = [
        {
            "request_id": "req-1",
            "session_id": session_id,
            "call_type": "completion",
            "api_key": api_key,
            "spend": 0.01,
            "request_duration_ms": 1200,
        },
        {
            "request_id": "req-2",
            "session_id": session_id,
            "call_type": "completion",
            "api_key": api_key,
            "spend": 0.02,
            "request_duration_ms": 4200,
        },
        {
            "request_id": "req-3",
            "session_id": None,
            "call_type": "completion",
            "api_key": api_key,
            "spend": 0.03,
            "request_duration_ms": 900,
        },
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": 2,
                "session_total_spend": 0.03,
                "session_total_duration_ms": 5400,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=3,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    session_rows = rows[:2]
    assert [row["session_total_duration_ms"] for row in session_rows] == [5400, 5400]
    assert all(isinstance(row["session_total_duration_ms"], int) for row in session_rows)
    assert [row["request_duration_ms"] for row in rows] == [1200, 4200, 900]
    assert "session_total_duration_ms" not in rows[2]

    _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]
    sql = " ".join(call_args[0].split())
    assert (
        'SUM( COALESCE( request_duration_ms, (EXTRACT(EPOCH FROM ("endTime" - "startTime")) * 1000)::INTEGER ) )' in sql
    )


@pytest.mark.asyncio
async def test_build_ui_spend_logs_response_session_cache_hit_count():
    """
    Each row of a session must carry session_cache_hit_count aggregated across
    the whole session so the UI can show how many requests in the session were
    served from the response cache.
    """
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _build_ui_spend_logs_response,
    )

    session_id = "sess-cache-hits"
    api_key = "hashed-key-xyz"
    dict_rows = [
        {"request_id": "req-1", "session_id": session_id, "call_type": "completion", "api_key": api_key},
        {"request_id": "req-2", "session_id": session_id, "call_type": "completion", "api_key": api_key},
        {"request_id": "req-3", "session_id": None, "call_type": "completion", "api_key": api_key},
    ]

    mock_prisma = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(
        return_value=[
            {
                "session_id": session_id,
                "api_key": api_key,
                "session_total_count": 2,
                "session_total_spend": 0.05,
                "mcp_tool_call_count": 0,
                "mcp_tool_call_spend": 0.0,
                "session_cache_hit_count": 2,
            }
        ]
    )

    result = await _build_ui_spend_logs_response(
        prisma_client=mock_prisma,
        data=dict_rows,
        total_records=3,
        page=1,
        page_size=50,
        total_pages=1,
        enrich_session_counts=True,
    )

    rows = result["data"]
    assert rows[0]["session_cache_hit_count"] == 2
    assert rows[1]["session_cache_hit_count"] == 2
    assert "session_cache_hit_count" not in rows[2]

    # The aggregate SQL must actually compute the cache-hit count.
    _, call_args, _ = mock_prisma.db.query_raw.mock_calls[0]
    assert "session_cache_hit_count" in call_args[0]
    assert "LOWER(cache_hit) = 'true'" in call_args[0]


# ---------------------------------------------------------------------------
# Tests for /spend/logs team-member permission
# ---------------------------------------------------------------------------


@pytest.mark.asyncio
async def test_can_team_member_view_log_with_spend_logs_permission(monkeypatch):
    """
    Non-admin team member WITH /spend/logs permission should be allowed.
    """

    class MockTeam:
        team_id = "team_abc"
        members_with_roles = [Member(user_id="member_1", role="user")]
        team_member_permissions = ["/spend/logs"]

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "member_1", "role": "user"}],
                "team_member_permissions": self.team_member_permissions,
            }

    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return MockTeam()

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, "team_abc")
    assert allowed is True


@pytest.mark.asyncio
async def test_can_team_member_view_log_without_spend_logs_permission(monkeypatch):
    """
    Non-admin team member WITHOUT /spend/logs permission should be denied.
    """

    class MockTeam:
        team_id = "team_abc"
        members_with_roles = [Member(user_id="member_1", role="user")]
        team_member_permissions = ["/key/info"]

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "member_1", "role": "user"}],
                "team_member_permissions": self.team_member_permissions,
            }

    class MockPrisma:
        class DB:
            class TeamTable:
                async def find_unique(self, where: dict):
                    return MockTeam()

            def __init__(self):
                self.litellm_teamtable = self.TeamTable()

        def __init__(self):
            self.db = self.DB()

    prisma = MockPrisma()
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1")
    allowed = await spend_management_endpoints._can_team_member_view_log(prisma, auth, "team_abc")
    assert allowed is False


@pytest.mark.asyncio
async def test_ui_view_spend_logs_team_member_with_spend_logs_permission(client, monkeypatch):
    """
    A non-admin team member with /spend/logs permission should see team-wide
    spend logs when filtering by that team_id.
    """
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-key-1",
            "user": "member_1",
            "team_id": "team_perm",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
        {
            "id": "log2",
            "request_id": "req2",
            "api_key": "sk-key-2",
            "user": "member_2",
            "team_id": "team_perm",
            "spend": 0.10,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_by_team(where):
        if "team_id" in where and where["team_id"] == "team_perm":
            return mock_spend_logs
        return []

    class TeamTable:
        team_id = "team_perm"
        members_with_roles = [Member(user_id="member_1", role="user")]
        team_member_permissions = ["/spend/logs"]

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "member_1", "role": "user"}],
                "team_member_permissions": self.team_member_permissions,
            }

    async def team_lookup(where):
        return TeamTable() if where == {"team_id": "team_perm"} else None

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_by_team, team_lookup),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "team_id": "team_perm",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        data = response.json()
        assert data["total"] == 2
        assert len(data["data"]) == 2
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_team_member_no_permission_blocked(client, monkeypatch):
    """
    A non-admin team member WITHOUT /spend/logs permission should be
    rejected when filtering by team_id.
    """
    mock_spend_logs = [
        {
            "id": "log1",
            "request_id": "req1",
            "api_key": "sk-key-1",
            "user": "member_1",
            "team_id": "team_noperm",
            "spend": 0.05,
            "startTime": datetime.datetime.now(timezone.utc).isoformat(),
            "model": "gpt-4",
        },
    ]

    def filter_fn(where):
        return mock_spend_logs

    class TeamTable:
        team_id = "team_noperm"
        members_with_roles = [Member(user_id="member_1", role="user")]
        team_member_permissions = ["/key/info"]

        def model_dump(self):
            return {
                "team_id": self.team_id,
                "members_with_roles": [{"user_id": "member_1", "role": "user"}],
                "team_member_permissions": self.team_member_permissions,
            }

    async def team_lookup(where):
        return TeamTable() if where == {"team_id": "team_noperm"} else None

    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        make_ui_spend_logs_mock_prisma(mock_spend_logs, filter_fn, team_lookup),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="member_1"
    )

    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "team_id": "team_noperm",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


class _CaptureFilterDB:
    """Mock DB that records the `where` filter passed to find_many."""

    def __init__(self):
        self.litellm_spendlogs = self
        self.captured_where = None
        self.captured_params = None

    async def find_many(self, *args, **kwargs):
        self.captured_where = kwargs.get("where")
        return []

    async def query_raw(self, sql_query, *params):
        self.captured_params = params
        return []


class _CapturePrismaClient:
    def __init__(self):
        self.db = _CaptureFilterDB()

    def hash_token(self, token):
        return "hashed::" + token


@pytest.mark.asyncio
async def test_view_spend_logs_internal_user_combines_user_with_api_key(client, monkeypatch):
    """Internal users must have their user filter applied alongside api_key."""
    mock_client = _CapturePrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_client)

    start_date = "2024-01-01"
    end_date = "2024-12-31"
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="internal-user-1",
    )
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "false",
                "api_key": "sk-some-raw-token",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        where = mock_client.db.captured_where
        assert where is not None
        assert where["user"] == "internal-user-1"
        assert where["api_key"] == "hashed::sk-some-raw-token"
        assert "startTime" in where
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_internal_user_combines_user_with_request_id(client, monkeypatch):
    """Internal users must have their user filter applied alongside request_id."""
    mock_client = _CapturePrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_client)

    start_date = "2024-01-01"
    end_date = "2024-12-31"
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="internal-user-2",
    )
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "false",
                "request_id": "req-abc",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        where = mock_client.db.captured_where
        assert where is not None
        assert where["user"] == "internal-user-2"
        assert where["OR"] == ({"request_id": "req-abc"}, {"litellm_call_id": "req-abc"})
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_non_date_range_combines_user_with_request_id(client, monkeypatch):
    """Non-date-range path must also combine user + request_id filters."""
    mock_client = _CapturePrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_client)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="internal-user-3",
    )
    try:
        response = client.get(
            "/spend/logs",
            params={"request_id": "req-xyz"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        where = mock_client.db.captured_where
        assert where is not None
        assert where["user"] == "internal-user-3"
        assert where["OR"] == ({"request_id": "req-xyz"}, {"litellm_call_id": "req-xyz"})
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_non_date_range_hashes_sk_api_key(client, monkeypatch):
    """Non-date-range path must hash sk- prefixed api_keys before filtering."""
    mock_client = _CapturePrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_client)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
    )
    try:
        response = client.get(
            "/spend/logs",
            params={"api_key": "sk-raw-admin-token"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        where = mock_client.db.captured_where
        assert where is not None
        assert where["api_key"] == "hashed::sk-raw-admin-token"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_view_spend_logs_date_range_hashes_sk_api_key(client, monkeypatch):
    """Date-range path must hash sk- prefixed api_keys before filtering."""
    mock_client = _CapturePrismaClient()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_client)

    start_date = "2024-01-01"
    end_date = "2024-12-31"
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN,
    )
    try:
        response = client.get(
            "/spend/logs",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "summarize": "false",
                "api_key": "sk-raw-admin-token",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        where = mock_client.db.captured_where
        assert where is not None
        assert where["api_key"] == "hashed::sk-raw-admin-token"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


class _SpendScopeMockPrismaClient:
    def __init__(self, get_data_returns=None, find_many_returns=None):
        self._get_data_returns = get_data_returns if get_data_returns is not None else []
        self._find_many_returns = find_many_returns if find_many_returns is not None else []
        self.get_data_calls = []
        self.find_many_calls = []

        client = self

        class _VerificationTokenTable:
            async def find_many(self, where=None, order=None, include=None):
                client.find_many_calls.append({"where": where, "order": order, "include": include})
                return client._find_many_returns

        class _DB:
            def __init__(self):
                self.litellm_verificationtoken = _VerificationTokenTable()

        self.db = _DB()

    async def get_data(self, table_name=None, query_type=None, **kwargs):
        self.get_data_calls.append({"table_name": table_name, "query_type": query_type, **kwargs})
        if query_type == "find_unique":
            return self._get_data_returns[0] if self._get_data_returns else None
        return self._get_data_returns


@pytest.mark.asyncio
async def test_spend_key_fn_proxy_admin_returns_all_keys(client, monkeypatch):
    """Admins keep their existing full-table view of /spend/keys."""
    mock_keys = [
        {"token": "hashed-a", "user_id": "alice", "spend": 10.0},
        {"token": "hashed-b", "user_id": "bob", "spend": 5.0},
    ]
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=mock_keys)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"
    )
    try:
        response = client.get("/spend/keys", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        # Admin path: goes through get_data (full table), never the scoped find_many
        assert len(mock_prisma.get_data_calls) == 1
        assert mock_prisma.get_data_calls[0]["table_name"] == "key"
        assert mock_prisma.get_data_calls[0]["query_type"] == "find_all"
        assert mock_prisma.find_many_calls == []
        assert response.json() == mock_keys
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_key_fn_proxy_admin_view_only_returns_all_keys(client, monkeypatch):
    """View-only admins are still admins for this endpoint."""
    mock_keys = [{"token": "hashed-a", "user_id": "alice"}]
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=mock_keys)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY, user_id="admin_viewer"
    )
    try:
        response = client.get("/spend/keys", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert mock_prisma.find_many_calls == []
        assert len(mock_prisma.get_data_calls) == 1
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "role",
    [LitellmUserRoles.INTERNAL_USER, LitellmUserRoles.INTERNAL_USER_VIEW_ONLY],
)
async def test_spend_key_fn_internal_user_scoped_to_own_keys(client, monkeypatch, role):
    """Both internal-user roles must only see keys they own."""
    caller_owned_keys = [
        {"token": "hashed-mine-1", "user_id": "alice", "spend": 2.0},
        {"token": "hashed-mine-2", "user_id": "alice", "spend": 1.0},
    ]
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=caller_owned_keys)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=role, user_id="alice")
    try:
        response = client.get("/spend/keys", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        # Non-admin path goes through the same get_data helper as admin,
        # but with a user_id scope so only the caller's rows come back.
        assert mock_prisma.find_many_calls == []
        assert len(mock_prisma.get_data_calls) == 1
        call = mock_prisma.get_data_calls[0]
        assert call["table_name"] == "key"
        assert call["query_type"] == "find_all"
        assert call["user_id"] == "alice"
        assert response.json() == caller_owned_keys
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_key_fn_internal_user_without_user_id_returns_empty(client, monkeypatch):
    """
    A non-admin key with no user_id has no tenant scope. Returning the full
    table would re-introduce the leak; return an empty list instead.
    """
    mock_prisma = _SpendScopeMockPrismaClient(
        get_data_returns=[{"token": "do-not-leak"}],
        find_many_returns=[{"token": "do-not-leak"}],
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id=None
    )
    try:
        response = client.get("/spend/keys", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert response.json() == []
        assert mock_prisma.get_data_calls == []
        assert mock_prisma.find_many_calls == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_proxy_admin_returns_all_users_without_user_id(client, monkeypatch):
    """Admins keep their existing full-table view of /spend/users."""
    mock_users = [
        {"user_id": "alice", "user_email": "[email protected]", "spend": 1.0},
        {"user_id": "bob", "user_email": "[email protected]", "spend": 2.0},
    ]
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=mock_users)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"
    )
    try:
        response = client.get("/spend/users", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert len(mock_prisma.get_data_calls) == 1
        assert mock_prisma.get_data_calls[0]["table_name"] == "user"
        assert mock_prisma.get_data_calls[0]["query_type"] == "find_all"
        assert response.json() == mock_users
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_proxy_admin_can_query_specific_user_id(client, monkeypatch):
    """Admins can still target a specific user_id."""
    mock_user = {
        "user_id": "carol",
        "user_email": "[email protected]",
        "spend": 7.0,
    }
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[mock_user])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin"
    )
    try:
        response = client.get(
            "/spend/users",
            params={"user_id": "carol"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert len(mock_prisma.get_data_calls) == 1
        assert mock_prisma.get_data_calls[0]["query_type"] == "find_unique"
        assert mock_prisma.get_data_calls[0]["user_id"] == "carol"
        assert response.json() == [mock_user]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    "role",
    [LitellmUserRoles.INTERNAL_USER, LitellmUserRoles.INTERNAL_USER_VIEW_ONLY],
)
async def test_spend_user_fn_internal_user_scoped_without_user_id(client, monkeypatch, role):
    """No user_id supplied -> must query the caller's own row, not the table."""
    own_row = {"user_id": "alice", "user_email": "[email protected]", "spend": 3.0}
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[own_row])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(user_role=role, user_id="alice")
    try:
        response = client.get("/spend/users", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert len(mock_prisma.get_data_calls) == 1
        assert mock_prisma.get_data_calls[0]["query_type"] == "find_unique"
        assert mock_prisma.get_data_calls[0]["user_id"] == "alice"
        assert response.json() == [own_row]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_internal_user_supplying_other_user_id_returns_403(client, monkeypatch):
    """
    An internal user passing user_id=victim must be rejected outright, not
    silently rewritten. A 403 makes the attempt observable in logs.
    """
    leaked_victim_row = {
        "user_id": "victim",
        "user_email": "[email protected]",
        "spend": 999.0,
    }
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[leaked_victim_row])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice"
    )
    try:
        response = client.get(
            "/spend/users",
            params={"user_id": "victim"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert mock_prisma.get_data_calls == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_internal_user_supplying_own_user_id_is_allowed(client, monkeypatch):
    """
    Passing your own user_id explicitly is fine — the 403 only fires when
    the supplied id differs from the caller's.
    """
    own_row = {"user_id": "alice", "user_email": "[email protected]", "spend": 3.0}
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[own_row])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice"
    )
    try:
        response = client.get(
            "/spend/users",
            params={"user_id": "alice"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert len(mock_prisma.get_data_calls) == 1
        assert mock_prisma.get_data_calls[0]["query_type"] == "find_unique"
        assert mock_prisma.get_data_calls[0]["user_id"] == "alice"
        assert response.json() == [own_row]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_internal_user_without_user_id_returns_empty(client, monkeypatch):
    """
    A non-admin key with no user_id has no tenant scope -> return empty,
    never the full table. Same defensive contract as /spend/keys.
    """
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[{"user_id": "do-not-leak"}])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER_VIEW_ONLY, user_id=None
    )
    try:
        response = client.get("/spend/users", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        assert response.json() == []
        assert mock_prisma.get_data_calls == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_spend_user_fn_strips_password_field(client, monkeypatch):
    """
    Existing password-redaction behavior must be preserved on the scoped
    path so we don't regress a separate disclosure when adding the fix.
    """
    own_row = {
        "user_id": "alice",
        "user_email": "[email protected]",
        "password": "hashed-password-must-not-leak",
        "spend": 1.0,
    }
    mock_prisma = _SpendScopeMockPrismaClient(get_data_returns=[own_row])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice"
    )
    try:
        response = client.get("/spend/users", headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 200
        body = response.json()
        assert len(body) == 1
        assert "password" not in body[0]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_rehydrates_metadata_jsonb_text(client, monkeypatch):
    """
    Regression for #29674: query_raw returns the JSONB `metadata` column as a
    string, so failure rows (status="failure", error_information.error_code=...)
    looked like successes at the UI layer because metadata.status was the
    string ".status" attribute lookup on a str. The endpoint must re-hydrate
    `metadata` to a dict before returning.
    """
    failure_metadata = {
        "status": "failure",
        "error_information": {
            "error_code": "403",
            "error_message": "Forbidden by upstream",
        },
        "user_api_key_alias": "alias-1",
    }

    raw_row = {
        "request_id": "req-failure-1",
        "call_type": "completion",
        "api_key": "hashed-key",
        "spend": 0.0,
        "total_tokens": 0,
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "startTime": "2025-01-01T00:00:00Z",
        "endTime": "2025-01-01T00:00:01Z",
        "completionStartTime": None,
        "model": "gpt-4o",
        "model_id": None,
        "model_group": None,
        "custom_llm_provider": "openai",
        "api_base": None,
        "user": "u",
        "metadata": json.dumps(failure_metadata),  # JSONB column comes back as str
        "cache_hit": None,
        "cache_key": None,
        "request_tags": None,
        "team_id": None,
        "organization_id": None,
        "end_user": None,
        "requester_ip_address": None,
        "session_id": None,
        "status": "failure",
        "mcp_namespaced_tool_name": None,
        "agent_id": None,
        "request_duration_ms": 1000,
    }

    async def mock_count(*args, **kwargs):
        return 1

    async def mock_query_raw(sql_query, *params):
        return [{**raw_row, "total_count": 1}]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        body = response.json()
        assert body["data"], "expected one row in data"
        row = body["data"][0]
        md = row["metadata"]
        # The bug had metadata returned as a JSON string; the fix re-hydrates
        # it so the dashboard's metadata.status / metadata.error_information
        # accessors work.
        assert isinstance(md, dict), f"metadata should be dict, got {type(md)}"
        assert md["status"] == "failure"
        assert md["error_information"]["error_code"] == "403"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_metadata_invalid_json_falls_back_to_empty_dict(client, monkeypatch):
    """
    Defensive: if `metadata` is somehow not valid JSON, fall back to {} rather
    than 500-ing the whole UI page.
    """
    raw_row = {
        "request_id": "req-bad-json",
        "call_type": "completion",
        "api_key": "hashed-key",
        "spend": 0.0,
        "total_tokens": 0,
        "prompt_tokens": 0,
        "completion_tokens": 0,
        "startTime": "2025-01-01T00:00:00Z",
        "endTime": "2025-01-01T00:00:01Z",
        "completionStartTime": None,
        "model": "gpt-4o",
        "model_id": None,
        "model_group": None,
        "custom_llm_provider": "openai",
        "api_base": None,
        "user": "u",
        "metadata": "{not-json",
        "cache_hit": None,
        "cache_key": None,
        "request_tags": None,
        "team_id": None,
        "organization_id": None,
        "end_user": None,
        "requester_ip_address": None,
        "session_id": None,
        "status": "success",
        "mcp_namespaced_tool_name": None,
        "agent_id": None,
        "request_duration_ms": 500,
    }

    async def mock_count(*args, **kwargs):
        return 1

    async def mock_query_raw(sql_query, *params):
        return [{**raw_row, "total_count": 1}]

    class MockPrismaClient:
        def __init__(self):
            self.db = MagicMock()
            self.db.litellm_spendlogs = MagicMock()
            self.db.litellm_spendlogs.count = AsyncMock(side_effect=mock_count)
            self.db.query_raw = AsyncMock(side_effect=mock_query_raw)

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MockPrismaClient())
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )

    try:
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": "2024-12-25 00:00:00",
                "end_date": "2025-01-02 23:59:59",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        body = response.json()
        assert body["data"]
        assert body["data"][0]["metadata"] == {}
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


class _FakeColdStorageLogger:
    """Injectable cold storage logger that records the object key it was asked for."""

    def __init__(self, payload):
        self._payload = payload
        self.requested_object_keys = []

    async def get_proxy_server_request_from_cold_storage_with_object_key(self, object_key):
        self.requested_object_keys.append(object_key)
        return self._payload


def _cold_storage_handler(payload):
    from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler

    logger = _FakeColdStorageLogger(payload)
    return ColdStorageHandler(cold_storage_logger=logger), logger


@pytest.mark.asyncio
@pytest.mark.parametrize("cold_has_audit", [False, True])
async def test_resolve_payload_recovers_truncated_classifier_audit_without_losing_existing_fields(cold_has_audit):
    full_audit = {"classifier_input": {"system": "full rubric"}, "originating_request_masked": {"input": "source"}}
    truncated_request = {"model": "classifier", "classifier_input": {"system": "litellm_truncated"}}
    handler, logger = _cold_storage_handler(
        {
            "proxy_server_request": {"body": {}},
            **(full_audit if cold_has_audit else {}),
        }
    )
    row = {
        "messages": '[{"role":"user","content":"ask"}]',
        "response": '{"tier":"SIMPLE"}',
        "proxy_server_request": json.dumps(truncated_request),
        "metadata": {"cold_storage_object_key": "k/audit.json"},
    }
    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)
    assert logger.requested_object_keys == ["k/audit.json"]
    assert resolved.messages == row["messages"]
    assert resolved.response == row["response"]
    if cold_has_audit:
        assert resolved.proxy_server_request["classifier_input"] == full_audit["classifier_input"]
        assert resolved.proxy_server_request["originating_request_masked"] == full_audit["originating_request_masked"]
    else:
        assert resolved.proxy_server_request == row["proxy_server_request"]


@pytest.mark.parametrize(
    "value, expected",
    [
        (None, False),
        ("", False),
        ("   ", False),
        ("{}", False),
        ("[]", False),
        ("null", False),
        ('{"a": 1}', True),
        ({}, False),
        ({"a": 1}, True),
        ([], False),
        ([1], True),
        (5, True),
    ],
)
def test_spend_log_field_has_content(value, expected):
    assert spend_management_endpoints._spend_log_field_has_content(value) is expected


@pytest.mark.parametrize(
    "metadata, expected",
    [
        (None, None),
        ("{}", None),
        ("not-json", None),
        ({"cold_storage_object_key": ""}, None),
        ({"cold_storage_object_key": "k/req-1.json"}, "k/req-1.json"),
        ('{"cold_storage_object_key": "k/req-2.json"}', "k/req-2.json"),
    ],
)
def test_cold_storage_object_key_from_metadata(metadata, expected):
    assert spend_management_endpoints._cold_storage_object_key_from_metadata(metadata) == expected


@pytest.mark.asyncio
async def test_resolve_payload_prefers_pg_and_skips_cold_storage():
    handler, logger = _cold_storage_handler({"messages": "X", "response": "Y"})
    row = {
        "messages": "{}",
        "response": '{"choices": [{"message": {"content": "hi"}}]}',
        "proxy_server_request": "{}",
        "metadata": {"cold_storage_object_key": "k/req.json"},
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert resolved.response == '{"choices": [{"message": {"content": "hi"}}]}'
    assert logger.requested_object_keys == []


@pytest.mark.asyncio
async def test_resolve_payload_fetches_from_cold_storage_when_pg_empty():
    cold_payload = {
        "messages": [{"role": "user", "content": "what is 2+2"}],
        "response": {"choices": [{"message": {"content": "4"}}]},
        "proxy_server_request": {"body": {"model": "gpt-4o-mini"}},
    }
    handler, logger = _cold_storage_handler(cold_payload)
    row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": {"cold_storage_object_key": "llm-gateway/prod/req-42.json"},
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert logger.requested_object_keys == ["llm-gateway/prod/req-42.json"]
    assert resolved.messages == cold_payload["messages"]
    assert resolved.response == cold_payload["response"]
    assert resolved.proxy_server_request == cold_payload["proxy_server_request"]


@pytest.mark.asyncio
async def test_resolve_payload_metadata_as_json_string():
    cold_payload = {"messages": "in", "response": "out", "proxy_server_request": None}
    handler, logger = _cold_storage_handler(cold_payload)
    row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": json.dumps({"cold_storage_object_key": "k/str-meta.json"}),
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert logger.requested_object_keys == ["k/str-meta.json"]
    assert resolved.response == "out"


@pytest.mark.asyncio
async def test_resolve_payload_no_object_key_returns_empty_without_fetch():
    handler, logger = _cold_storage_handler({"messages": "should-not-be-used"})
    row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": {},
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert logger.requested_object_keys == []
    assert resolved == spend_management_endpoints.RequestResponsePayload("{}", "{}", "{}")


@pytest.mark.asyncio
async def test_resolve_payload_cold_storage_miss_falls_back_to_pg_values():
    handler, logger = _cold_storage_handler(None)
    row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": {"cold_storage_object_key": "k/missing.json"},
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert logger.requested_object_keys == ["k/missing.json"]
    assert resolved == spend_management_endpoints.RequestResponsePayload("{}", "{}", "{}")


@pytest.mark.asyncio
async def test_resolve_payload_cold_storage_exception_falls_back_to_pg_values():
    """A backend error during fetch degrades to PG values instead of bubbling a 500."""

    class _RaisingLogger:
        async def get_proxy_server_request_from_cold_storage_with_object_key(self, object_key):
            raise RuntimeError("cold storage backend unavailable")

    from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler

    handler = ColdStorageHandler(cold_storage_logger=_RaisingLogger())
    row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": {"cold_storage_object_key": "k/boom.json"},
    }

    resolved = await spend_management_endpoints._resolve_request_response_payload(row, cold_storage_handler=handler)

    assert resolved == spend_management_endpoints.RequestResponsePayload("{}", "{}", "{}")


@pytest.mark.asyncio
async def test_cold_storage_handler_uses_injected_logger():
    from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler

    logger = _FakeColdStorageLogger({"messages": "in", "response": "out"})
    handler = ColdStorageHandler(cold_storage_logger=logger)

    result = await handler.get_proxy_server_request_from_cold_storage_with_object_key(object_key="k/req.json")

    assert result == {"messages": "in", "response": "out"}
    assert logger.requested_object_keys == ["k/req.json"]


@pytest.mark.asyncio
async def test_cold_storage_handler_returns_none_when_no_logger_configured(monkeypatch):
    from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler

    monkeypatch.setattr(litellm, "cold_storage_custom_logger", None, raising=False)
    handler = ColdStorageHandler()

    result = await handler.get_proxy_server_request_from_cold_storage_with_object_key(object_key="k/req.json")

    assert result is None


@pytest.mark.asyncio
async def test_cold_storage_handler_resolves_configured_logger_from_registry(
    monkeypatch,
):
    from litellm.proxy.spend_tracking.cold_storage_handler import ColdStorageHandler

    logger = _FakeColdStorageLogger({"messages": "from-registry"})
    monkeypatch.setattr(litellm, "cold_storage_custom_logger", "s3_v2", raising=False)
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_custom_logger_for_callback_name",
        lambda name: logger if name == "s3_v2" else None,
    )
    handler = ColdStorageHandler()

    result = await handler.get_proxy_server_request_from_cold_storage_with_object_key(object_key="k/req.json")

    assert result == {"messages": "from-registry"}
    assert logger.requested_object_keys == ["k/req.json"]


def test_ui_view_request_response_reads_from_cold_storage(client, monkeypatch):
    """End-to-end: a placeholder row with a cold_storage_object_key is served from
    cold storage through the detail endpoint."""
    from types import SimpleNamespace

    placeholder_row = {
        "messages": "{}",
        "response": "{}",
        "proxy_server_request": "{}",
        "metadata": {"cold_storage_object_key": "k/cold.json"},
    }

    async def _query_raw(_sql, *_args):
        return [placeholder_row]

    fake_prisma = SimpleNamespace(db=SimpleNamespace(query_raw=_query_raw))
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", fake_prisma)

    cold_logger = _FakeColdStorageLogger(
        {
            "messages": [{"role": "user", "content": "hi"}],
            "response": {"choices": [{"message": {"content": "hello"}}]},
            "proxy_server_request": None,
        }
    )
    monkeypatch.setattr(litellm, "cold_storage_custom_logger", "s3_v2", raising=False)
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_additional_logging_utils_from_custom_logger",
        lambda: [],
    )
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_custom_logger_for_callback_name",
        lambda name: cold_logger if name == "s3_v2" else None,
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_1"
    )
    try:
        response = client.get(
            "/spend/logs/ui/req-cold",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        body = response.json()
        assert body["messages"] == [{"role": "user", "content": "hi"}]
        assert body["response"] == {"choices": [{"message": {"content": "hello"}}]}
        assert cold_logger.requested_object_keys == ["k/cold.json"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


from litellm.proxy._types import (
    LiteLLM_OrganizationMembershipTable,
    LiteLLM_UserTable,
    LiteLLMRoutes,
    hash_token,
)

_SCOPED_SPEND_REPORT_PATHS = [
    "/key/spend/report",
    "/user/spend/report",
    "/team/spend/report",
    "/organization/spend/report",
]


def _spend_report_mock_prisma(query_raw_returns=None, team_rows=None, user_row=None):
    pc = MagicMock()
    pc.db.query_raw = AsyncMock(return_value=query_raw_returns if query_raw_returns is not None else [])
    pc.db.litellm_teamtable.find_many = AsyncMock(return_value=team_rows if team_rows is not None else [])
    pc.db.litellm_usertable.find_unique = AsyncMock(return_value=user_row)
    return pc


def _org_member_user_row(user_id, organization_id, membership_role):
    now = datetime.datetime.now(timezone.utc)
    return LiteLLM_UserTable(
        user_id=user_id,
        user_email=f"{user_id}@example.com",
        organization_memberships=[
            LiteLLM_OrganizationMembershipTable(
                user_id=user_id,
                organization_id=organization_id,
                user_role=membership_role,
                created_at=now,
                updated_at=now,
            )
        ],
    )


def test_scoped_spend_report_routes_reachable_by_non_admin_roles():
    """
    The whole point of the scoped report endpoints is that non-admin callers can
    reach them. If they fall out of spend_tracking_routes (and with it the
    internal-user route allowlists), user_api_key_auth rejects every non-admin
    caller before the endpoint runs.
    """
    for path in _SCOPED_SPEND_REPORT_PATHS:
        assert path in LiteLLMRoutes.spend_tracking_routes.value
        assert path in LiteLLMRoutes.internal_user_routes.value
        assert path in LiteLLMRoutes.internal_user_view_only_routes.value
        assert path in LiteLLMRoutes.org_admin_allowed_routes.value


def test_resolve_spend_report_scope_defaults_to_caller():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    resolved = spend_management_endpoints._resolve_spend_report_scope(
        user_api_key_dict=auth,
        requested=None,
        caller_value="team-blue",
        scope_name="team_id",
    )
    assert resolved == "team-blue"


def test_resolve_spend_report_scope_non_admin_override_forbidden():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    with pytest.raises(HTTPException) as exc_info:
        spend_management_endpoints._resolve_spend_report_scope(
            user_api_key_dict=auth,
            requested="team-red",
            caller_value="team-blue",
            scope_name="team_id",
        )
    assert exc_info.value.status_code == 403


def test_resolve_spend_report_scope_non_admin_matching_override_allowed():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    resolved = spend_management_endpoints._resolve_spend_report_scope(
        user_api_key_dict=auth,
        requested="team-blue",
        caller_value="team-blue",
        scope_name="team_id",
    )
    assert resolved == "team-blue"


@pytest.mark.parametrize(
    "role",
    [LitellmUserRoles.PROXY_ADMIN, LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY],
)
def test_resolve_spend_report_scope_admin_override_allowed(role):
    auth = UserAPIKeyAuth(user_role=role, user_id="admin")
    resolved = spend_management_endpoints._resolve_spend_report_scope(
        user_api_key_dict=auth,
        requested="team-red",
        caller_value="team-blue",
        scope_name="team_id",
    )
    assert resolved == "team-red"


def test_resolve_spend_report_scope_missing_caller_value_400():
    auth = UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice")
    with pytest.raises(HTTPException) as exc_info:
        spend_management_endpoints._resolve_spend_report_scope(
            user_api_key_dict=auth,
            requested=None,
            caller_value=None,
            scope_name="team_id",
        )
    assert exc_info.value.status_code == 400


@pytest.mark.parametrize("bad_column", ["metadata", "end_user", "evil; DROP TABLE", ""])
def test_scoped_spend_report_sql_rejects_unknown_column(bad_column):
    with pytest.raises(ValueError, match="Unsupported spend report scope column"):
        spend_management_endpoints._scoped_spend_report_sql(scope_column=bad_column)


def test_key_spend_report_scopes_to_caller_key(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(query_raw_returns=[{"api_key": "hashed-caller-key", "total_cost": 1.5}])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="alice",
        api_key="hashed-caller-key",
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        assert response.json() == [{"api_key": "hashed-caller-key", "total_cost": 1.5}]
        args, _ = mock_prisma.db.query_raw.await_args
        sql, start_param, end_param, scope_param = args
        assert "sl.api_key = $3" in sql
        assert scope_param == "hashed-caller-key"
        assert start_param == datetime.datetime(2026, 7, 1, tzinfo=timezone.utc)
        assert end_param == datetime.datetime(2026, 7, 31, tzinfo=timezone.utc)
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_key_spend_report_scopes_a_cli_session_to_the_per_user_alias_not_the_login_token(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(query_raw_returns=[{"api_key": "cli-session-alice", "total_cost": 1.5}])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="alice",
        api_key="cli-session-Qm7xJ2kP9sLw4vT1nR8yAa",
        key_alias="cli-session-alice",
        is_session_token=True,
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31", "api_key": "cli-session-alice"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        assert response.json() == [{"api_key": "cli-session-alice", "total_cost": 1.5}]
        args, _ = mock_prisma.db.query_raw.await_args
        assert args[3] == "cli-session-alice"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_key_spend_report_non_admin_override_403(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="alice",
        api_key="hashed-caller-key",
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={
                "start_date": "2026-07-01",
                "end_date": "2026-07-31",
                "api_key": "hashed-someone-elses-key",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_key_spend_report_admin_override_sk_key_gets_hashed(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin", api_key="hashed-admin-key"
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={
                "start_date": "2026-07-01",
                "end_date": "2026-07-31",
                "api_key": "sk-target-key",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        args, _ = mock_prisma.db.query_raw.await_args
        scope_param = args[3]
        assert scope_param == hash_token(token="sk-target-key")
        assert "sk-target-key" not in args[0]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_user_spend_report_scopes_to_caller_user_id(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(query_raw_returns=[{"api_key": "k1"}])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/user/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        args, _ = mock_prisma.db.query_raw.await_args
        sql, _, _, scope_param = args
        assert "sl.user = $3" in sql
        assert scope_param == "alice"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_user_spend_report_non_admin_override_403(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/user/spend/report",
            params={
                "start_date": "2026-07-01",
                "end_date": "2026-07-31",
                "internal_user_id": "bob",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_team_spend_report_scopes_to_key_team(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(query_raw_returns=[{"api_key": "k1"}])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id="alice",
        api_key="hashed-k",
        team_id="team-blue",
    )
    try:
        response = client.get(
            "/team/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        args, _ = mock_prisma.db.query_raw.await_args
        sql, _, _, scope_param = args
        assert "sl.team_id = $3" in sql
        assert scope_param == "team-blue"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_team_spend_report_no_team_400(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/team/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_org_spend_report_proxy_admin_override(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(
        query_raw_returns=[{"api_key": "k1"}],
        team_rows=[{"team_id": "team-a"}, {"team_id": "team-b"}],
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin", api_key="hashed-admin"
    )
    try:
        response = client.get(
            "/organization/spend/report",
            params={
                "start_date": "2026-07-01",
                "end_date": "2026-07-31",
                "organization_id": "org-x",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        args, _ = mock_prisma.db.query_raw.await_args
        sql, _, _, org_param, team_ids_param = args
        normalized_sql = " ".join(sql.split())
        assert (
            "AND ( sl.organization_id = $3 OR ( (sl.organization_id IS NULL OR sl.organization_id = '') "
            "AND sl.team_id = ANY($4::text[]) ) )"
        ) in normalized_sql
        assert org_param == "org-x"
        assert team_ids_param == ("team-a", "team-b")
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_org_spend_report_org_admin_auto_scopes_to_own_org(client, monkeypatch):
    user_id = "org-admin-auto-scope"
    mock_prisma = _spend_report_mock_prisma(
        query_raw_returns=[{"api_key": "k1"}],
        team_rows=[{"team_id": "team-a"}],
        user_row=_org_member_user_row(
            user_id=user_id,
            organization_id="org-acme",
            membership_role=LitellmUserRoles.ORG_ADMIN.value,
        ),
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=user_id,
        api_key="hashed-org-admin-key",
        org_id="org-acme",
    )
    try:
        response = client.get(
            "/organization/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        args, _ = mock_prisma.db.query_raw.await_args
        org_param, team_ids_param = args[3], args[4]
        assert org_param == "org-acme"
        assert team_ids_param == ("team-a",)
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_org_spend_report_non_org_admin_403(client, monkeypatch):
    user_id = "org-plain-member"
    mock_prisma = _spend_report_mock_prisma(
        user_row=_org_member_user_row(
            user_id=user_id,
            organization_id="org-acme",
            membership_role=LitellmUserRoles.INTERNAL_USER.value,
        ),
    )
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER,
        user_id=user_id,
        api_key="hashed-member-key",
        org_id="org-acme",
    )
    try:
        response = client.get(
            "/organization/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_org_spend_report_no_org_400(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/organization/spend/report",
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.parametrize("path", _SCOPED_SPEND_REPORT_PATHS)
def test_scoped_spend_report_not_premium_403(client, monkeypatch, path):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", False)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin", api_key="hashed-admin"
    )
    try:
        response = client.get(
            path,
            params={"start_date": "2026-07-01", "end_date": "2026-07-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.parametrize("path", _SCOPED_SPEND_REPORT_PATHS)
def test_scoped_spend_report_missing_dates_400(client, monkeypatch, path):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin", api_key="hashed-admin"
    )
    try:
        response = client.get(path, headers={"Authorization": "Bearer sk-test"})
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_scoped_spend_report_invalid_date_format_400(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin", api_key="hashed-admin"
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "07/01/2026", "end_date": "07/31/2026"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_scoped_spend_report_reversed_range_400(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "2026-08-04", "end_date": "2026-08-01"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_scoped_spend_report_range_over_max_400(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma()
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "0001-01-01", "end_date": "9999-12-31"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 400
        mock_prisma.db.query_raw.assert_not_awaited()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_scoped_spend_report_range_at_max_allowed(client, monkeypatch):
    mock_prisma = _spend_report_mock_prisma(query_raw_returns=[])
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr("litellm.proxy.proxy_server.premium_user", True)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="alice", api_key="hashed-k"
    )
    try:
        response = client.get(
            "/key/spend/report",
            params={"start_date": "2025-08-03", "end_date": "2026-08-04"},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        mock_prisma.db.query_raw.assert_awaited_once()
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_parse_session_cursor():
    from litellm.proxy.spend_tracking.spend_management_endpoints import (
        _parse_session_cursor,
    )

    assert _parse_session_cursor(None) is None
    assert _parse_session_cursor("no-delimiter") is None
    assert _parse_session_cursor("2026-08-29 10:00:00|sess-1") is None
    assert _parse_session_cursor("|hashed-key|sess-1") is None
    assert _parse_session_cursor("2026-08-29 10:00:00|hashed-key|") is None
    assert _parse_session_cursor("2026-08-29 10:00:00|hashed-key|sess-1") == (
        "2026-08-29 10:00:00",
        "sess-1",
        "hashed-key",
    )
    assert _parse_session_cursor("2026-08-29 10:00:00.123|hashed-key|sess|with|pipes") == (
        "2026-08-29 10:00:00.123",
        "sess|with|pipes",
        "hashed-key",
    )


SESSION_GROUP_KEY_SQL = "COALESCE(NULLIF(session_id, ''), request_id), api_key"


def _session_grouped_mock_prisma(session_page_rows, session_total, representative_rows):
    """Mock prisma dispatching the raw queries the keyset grouped path emits."""

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*) AS total_count" in sql_query:
            return [{"total_count": session_total}]
        if "DISTINCT ON" in sql_query:
            return representative_rows
        if "COALESCE(SUM(spend)" in sql_query:
            return [
                {
                    "session_id": "sess-1",
                    "api_key": "hashed-key",
                    "session_total_count": 3,
                    "session_total_spend": 0.03,
                    "mcp_tool_call_count": 0,
                    "mcp_tool_call_spend": 0.0,
                    "session_cache_hit_count": 0,
                    "session_llm_count": 3,
                    "session_agent_count": 0,
                    "session_models": ["gpt-4o"],
                }
            ]
        return session_page_rows

    mock_prisma = MagicMock()
    mock_prisma.db = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)
    return mock_prisma


def _session_representative_row(request_id, session_id):
    return {
        "request_id": request_id,
        "call_type": "acompletion",
        "api_key": "hashed-key",
        "spend": 0.01,
        "total_tokens": 10,
        "prompt_tokens": 5,
        "completion_tokens": 5,
        "startTime": "2026-08-29T10:00:00Z",
        "endTime": "2026-08-29T10:00:01Z",
        "model": "gpt-4o",
        "metadata": {},
        "session_id": session_id,
    }


def _session_page_row(session_key, last_activity):
    return {"session_key": session_key, "api_key": "hashed-key", "last_activity": last_activity}


def _session_grouped_paginating_prisma(sessions, counted_total=None):
    """Mock prisma serving the grouped page query out of ``sessions``, honoring the LIMIT and OFFSET it asks for."""

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*) AS total_count" in sql_query:
            return [{"total_count": min(len(sessions) if counted_total is None else counted_total, params[-1])}]
        if "DISTINCT ON" in sql_query:
            return [_session_representative_row(f"req-{session_key}", session_key) for session_key in params[-2]]
        if "COALESCE(SUM(spend)" in sql_query:
            return []
        bounds = re.search(r"LIMIT \$(\d+)(?: OFFSET \$(\d+))?", sql_query)
        limit = params[int(bounds.group(1)) - 1]
        offset = params[int(bounds.group(2)) - 1] if bounds.group(2) else 0
        return [
            _session_page_row(session_key, last_activity)
            for session_key, last_activity in sessions[offset : offset + limit]
        ]

    mock_prisma = MagicMock()
    mock_prisma.db = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)
    return mock_prisma


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_first_page(client, monkeypatch):
    """One row per (session, api_key), session-count total, and a keyset cursor for the next page."""
    page_rows = [
        _session_page_row("sess-1", "2026-08-29 10:00:00"),
        _session_page_row("req-solo", "2026-08-29 09:00:00"),
        _session_page_row("sess-extra", "2026-08-29 08:00:00"),
    ]
    reps = [
        _session_representative_row("req-solo", None),
        _session_representative_row("req-1", "sess-1"),
    ]
    mock_prisma = _session_grouped_mock_prisma(page_rows, 3, reps)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "page_size": 2,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["total"] == 3
        assert data["has_more"] is True
        assert data["next_session_cursor"] == "2026-08-29 09:00:00|hashed-key|req-solo"
        request_ids = [row["request_id"] for row in data["data"]]
        assert request_ids == ["req-1", "req-solo"], "representatives must follow the page order"
        assert data["data"][0]["session_total_count"] == 3
        assert data["data"][1]["session_total_count"] == 1

        emitted = [call.args for call in mock_prisma.db.query_raw.await_args_list]
        page_query_sql = emitted[0][0]
        assert f"GROUP BY {SESSION_GROUP_KEY_SQL}" in page_query_sql
        assert "OFFSET" not in page_query_sql
        assert "HAVING" not in page_query_sql
        assert emitted[0][-1] == 3, "page query fetches page_size + 1 sessions to detect has_more"

        count_sql = emitted[1][0]
        assert f"GROUP BY {SESSION_GROUP_KEY_SQL}" in count_sql
        assert "LIMIT" in count_sql and "FROM (" in count_sql, "the grouped count must stay bounded"

        rep_call = emitted[2]
        assert f"DISTINCT ON ({SESSION_GROUP_KEY_SQL})" in rep_call[0]
        assert (
            f"ORDER BY {SESSION_GROUP_KEY_SQL}, " + spend_management_endpoints._SESSION_REPRESENTATIVE_ORDER_SQL
        ) in rep_call[0]
        assert rep_call[-2] == ["sess-1", "req-solo"]
        assert rep_call[-1] == ["hashed-key", "hashed-key"]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_cursor_page(client, monkeypatch):
    """A session_cursor becomes a HAVING keyset predicate instead of an OFFSET."""
    page_rows = [_session_page_row("sess-2", "2026-08-29 07:00:00")]
    reps = [_session_representative_row("req-2", "sess-2")]
    mock_prisma = _session_grouped_mock_prisma(page_rows, 3, reps)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "session_cursor": "2026-08-29 09:00:00|hashed-key|req-solo",
                "page_size": 2,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["has_more"] is False
        assert data["next_session_cursor"] is None
        assert [row["request_id"] for row in data["data"]] == ["req-2"]

        page_query_call = mock_prisma.db.query_raw.await_args_list[0]
        page_query_sql = page_query_call.args[0]
        assert f'HAVING (MAX("startTime"), {SESSION_GROUP_KEY_SQL}) <' in page_query_sql
        assert "OFFSET" not in page_query_sql
        cursor_index = page_query_call.args.index("2026-08-29 09:00:00")
        assert page_query_call.args[cursor_index : cursor_index + 3] == (
            "2026-08-29 09:00:00",
            "req-solo",
            "hashed-key",
        ), "cursor params must line up with (MAX(startTime), session key, api_key)"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_jumps_to_page_without_cursor(client, monkeypatch):
    """page > 1 with no session_cursor (the UI's last-page jump) serves the sessions that page starts at."""
    sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(60))
    mock_prisma = _session_grouped_paginating_prisma(sessions)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "page": 3,
                "page_size": 25,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["page"] == 3
        assert data["total"] == 60
        assert data["has_more"] is False
        assert data["next_session_cursor"] is None
        assert [row["request_id"] for row in data["data"]] == [f"req-sess-{index:02d}" for index in range(50, 60)]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_short_page_totals_itself(client, monkeypatch):
    """A page that runs out of sessions is the end of the list, so the total comes from it and nothing is counted."""
    sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(10))
    mock_prisma = _session_grouped_paginating_prisma(sessions, counted_total=999)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "page": 1,
                "page_size": 25,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["total"] == 10, "the count query's 999 would have won if it had been asked"
        assert data["total_is_capped"] is False
        assert data["total_pages"] == 1
        assert len(data["data"]) == 10
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_page_past_the_end_keeps_the_real_total(client, monkeypatch):
    """An empty page past the last one says nothing about the total, so it is counted rather than inferred."""
    sessions = tuple((f"sess-{index:02d}", f"2026-08-29 10:{59 - index:02d}:00") for index in range(100))
    mock_prisma = _session_grouped_paginating_prisma(sessions)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "page": 4,
                "page_size": 50,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["data"] == []
        assert data["total"] == 100, "the empty page's offset is not a total"
        assert data["total_pages"] == 2
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_page_past_count_cap_is_empty(client, monkeypatch):
    """The last page inside the capped total still lists sessions; the page after it is empty and costs no query."""
    cap = spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP
    sessions = tuple((f"sess-{index:06d}", "2026-08-29 10:00:00") for index in range(cap + 50))
    mock_prisma = _session_grouped_paginating_prisma(sessions)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        params = {
            "start_date": start_date,
            "end_date": end_date,
            "group_by_session": "true",
            "page_size": 25,
        }
        last_page = client.get(
            "/spend/logs/ui",
            params={**params, "page": cap // 25},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert last_page.status_code == 200, last_page.text
        last_page_data = last_page.json()
        assert last_page_data["total"] == cap
        assert last_page_data["total_is_capped"] is True
        assert last_page_data["data"][0]["request_id"] == f"req-sess-{cap - 25:06d}"
        assert len(last_page_data["data"]) == 25

        mock_prisma.db.query_raw.reset_mock()
        past_cap = client.get(
            "/spend/logs/ui",
            params={**params, "page": cap // 25 + 1},
            headers={"Authorization": "Bearer sk-test"},
        )
        assert past_cap.status_code == 200, past_cap.text
        past_cap_data = past_cap.json()
        assert past_cap_data["data"] == []
        assert past_cap_data["has_more"] is False
        assert past_cap_data["total"] == cap
        assert mock_prisma.db.query_raw.await_count == 1, "only the bounded count query runs past the capped window"
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_last_page_stops_at_the_capped_total(client, monkeypatch):
    """A page size that does not divide the cap still ends the last page at the capped total it reports."""
    cap = spend_management_endpoints.SPEND_LOGS_PAGINATION_COUNT_CAP
    sessions = tuple((f"sess-{index:06d}", "2026-08-29 10:00:00") for index in range(cap + 50))
    mock_prisma = _session_grouped_paginating_prisma(sessions)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "page": cap // 7 + 1,
                "page_size": 7,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert data["total"] == cap
        assert [row["request_id"] for row in data["data"]] == [
            f"req-sess-{index:06d}" for index in range(cap - cap % 7, cap)
        ]
        assert data["has_more"] is True
        assert data["next_session_cursor"] is not None
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_group_by_session_offset_for_non_starttime_sort(client, monkeypatch):
    """Sorting by another column keeps session grouping but pages with OFFSET, without a keyset cursor."""
    mock_prisma = _session_grouped_mock_prisma([], 0, [])

    async def mock_query_raw(sql_query, *params):
        if "COUNT(*)" in sql_query:
            return [{"total_count": 0}]
        return []

    mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    monkeypatch.setattr(
        "litellm.proxy.spend_tracking.spend_management_endpoints._is_admin_view_safe",
        lambda user_api_key_dict: True,
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "start_date": start_date,
                "end_date": end_date,
                "group_by_session": "true",
                "session_cursor": "2026-08-29 09:00:00|hashed-key|req-solo",
                "sort_by": "spend",
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert "next_session_cursor" not in data
        emitted_sql = [call.args[0] for call in mock_prisma.db.query_raw.await_args_list]
        assert "HAVING" not in " ".join(emitted_sql)
        assert f"DISTINCT ON ({SESSION_GROUP_KEY_SQL})" in emitted_sql[1]
        assert "OFFSET" in emitted_sql[1]
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.asyncio
async def test_ui_view_spend_logs_search_returns_flat_rows_when_grouping_by_session(client, monkeypatch):
    """The dashboard lists sessions by default; a search for an id lists every matching row instead,
    so both calls of a session show up rather than one representative, and no session cursor is returned."""
    rows = [_session_representative_row("req-1", "sess-1"), _session_representative_row("req-2", "sess-1")]

    async def mock_query_raw(sql_query, *params):
        if "mcp_tool_call_count" in sql_query:
            return []
        grouped = "DISTINCT ON" in sql_query or "GROUP BY" in sql_query
        visible = rows[:1] if grouped else rows
        if "COUNT(*)" in sql_query:
            return [{"total_count": len(visible)}]
        return visible

    mock_prisma = MagicMock()
    mock_prisma.db = MagicMock()
    mock_prisma.db.query_raw = AsyncMock(side_effect=mock_query_raw)
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma)
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user"
    )
    try:
        start_date, end_date = _default_date_range()
        response = client.get(
            "/spend/logs/ui",
            params={
                "search": "sess-1",
                "group_by_session": "true",
                "start_date": start_date,
                "end_date": end_date,
            },
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200, response.text
        data = response.json()
        assert [row["request_id"] for row in data["data"]] == ["req-1", "req-2"]
        assert data["total"] == 2
        assert "next_session_cursor" not in data
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def _fake_prisma_with_owned_spend_log(owner_user_id, messages_json, response_json):
    class _DB:
        async def query_raw(self, sql, *_args):
            if 'SELECT DISTINCT "user", team_id' in sql:
                return [{"user": owner_user_id, "team_id": None}]
            return [
                {
                    "request_id": "req-owned-by-user-a",
                    "messages": messages_json,
                    "response": response_json,
                    "proxy_server_request": "{}",
                    "metadata": "{}",
                    "user": owner_user_id,
                    "team_id": None,
                }
            ]

    class _Prisma:
        def __init__(self):
            self.db = _DB()

    return _Prisma()


def test_ui_view_request_response_internal_user_owner_gets_payload(client, monkeypatch):
    """
    An internal_user who owns the spend-log row can fetch the Logs drawer
    detail payload for their own request (regression for #34099, where the
    route was blocked for INTERNAL_USER before reaching this ownership check).
    """
    messages_json = json.dumps([{"role": "user", "content": "hi"}])
    response_json = json.dumps({"choices": [{"message": {"content": "hello"}}]})
    monkeypatch.setattr(
        "litellm.proxy.proxy_server.prisma_client",
        _fake_prisma_with_owned_spend_log("user_a", messages_json, response_json),
    )
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_a"
    )
    try:
        response = client.get(
            "/spend/logs/ui/req-owned-by-user-a",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 200
        body = response.json()
        assert json.loads(body["messages"]) == [{"role": "user", "content": "hi"}]
        assert json.loads(body["response"]) == {"choices": [{"message": {"content": "hello"}}]}
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


class _RecordingAdditionalLoggingUtils:
    """Injectable custom logger that records every request_id it's asked for."""

    def __init__(self, payload):
        self._payload = payload
        self.requested_ids = []

    async def get_request_response_payload(self, request_id, start_time_utc, end_time_utc):
        self.requested_ids.append(request_id)
        return self._payload


def test_ui_view_request_response_internal_user_non_owner_forbidden(client, monkeypatch):
    """
    A different internal_user requesting someone else's row is forbidden;
    guards against _assert_user_can_view_request_id being skipped in the
    detail-drawer handler. Also proves the handler stops at the owner lookup,
    before it ever asks a custom logger or the DB for the payload.
    """
    messages_json = json.dumps([{"role": "user", "content": "hi"}])
    response_json = json.dumps({"choices": [{"message": {"content": "hello"}}]})
    fake_prisma = _fake_prisma_with_owned_spend_log("user_a", messages_json, response_json)
    original_query_raw = fake_prisma.db.query_raw
    query_raw_calls = []

    async def _spy_query_raw(*args, **kwargs):
        query_raw_calls.append((args, kwargs))
        return await original_query_raw(*args, **kwargs)

    fake_prisma.db.query_raw = _spy_query_raw
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", fake_prisma)

    custom_logger = _RecordingAdditionalLoggingUtils({"messages": "should-not-be-returned"})
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_additional_logging_utils_from_custom_logger",
        lambda: [custom_logger],
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_b"
    )
    try:
        response = client.get(
            "/spend/logs/ui/req-owned-by-user-a",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert custom_logger.requested_ids == []
        assert [args[0] for args, _kwargs in query_raw_calls if "messages" in args[0]] == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


def test_ui_view_request_response_internal_user_missing_row_forbidden(client, monkeypatch):
    """
    Regression for the fail-open in _assert_user_can_view_request_id: a
    request_id with no spend-log row (e.g. pruned by retention) must be
    denied before the handler ever consults a custom logger, otherwise a
    non-admin who guesses/obtains a request_id could read another tenant's
    payload out of cold storage, and an existing payload that is not theirs
    would still confirm the id exists. Even a payload recorded as the caller's
    own is never fetched once the row is gone. Fails if an empty owner lookup
    is allowed to fall through to the loggers.
    """

    class _DB:
        async def query_raw(self, _sql, *_args):
            return []

    from types import SimpleNamespace

    fake_prisma = SimpleNamespace(db=_DB())
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", fake_prisma)

    custom_logger = _RecordingAdditionalLoggingUtils(
        {
            "messages": "should-not-be-returned",
            "metadata": {"user_api_key_user_id": "user_a", "user_api_key_team_id": None},
        }
    )
    monkeypatch.setattr(
        litellm.logging_callback_manager,
        "get_active_additional_logging_utils_from_custom_logger",
        lambda: [custom_logger],
    )

    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_a"
    )
    try:
        response = client.get(
            "/spend/logs/ui/req-pruned",
            headers={"Authorization": "Bearer sk-test"},
        )
        assert response.status_code == 403
        assert custom_logger.requested_ids == []
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)


@pytest.mark.parametrize(
    ("parent_status", "child_status", "expected"),
    [("failure", "success", "failure"), ("success", "failure", "success")],
)
def test_session_representative_uses_completed_agent_outcome(parent_status, child_status, expected):
    with sqlite3.connect(":memory:") as connection:
        connection.execute(
            'CREATE TABLE logs (request_id TEXT, call_type TEXT, status TEXT, "startTime" TEXT, "endTime" TEXT)'
        )
        connection.executemany(
            "INSERT INTO logs VALUES (?, ?, ?, ?, ?)",
            (
                ("parent", "asend_message", parent_status, "10:00:00", "10:00:05"),
                ("nested-agent", "asend_message", child_status, "10:00:01", "10:00:03"),
                ("llm", "acompletion", "success", "10:00:02", "10:00:04"),
                ("tool", "call_mcp_tool", child_status, "10:00:04", "10:00:04"),
            ),
        )
        result = connection.execute(
            "SELECT request_id, status FROM logs ORDER BY "
            + spend_management_endpoints._SESSION_REPRESENTATIVE_ORDER_SQL
            + " LIMIT 1"
        ).fetchone()
        assert result == ("parent", expected)
        connection.execute("DELETE FROM logs WHERE call_type = 'asend_message'")
        fallback = connection.execute(
            "SELECT request_id, status FROM logs ORDER BY "
            + spend_management_endpoints._SESSION_REPRESENTATIVE_ORDER_SQL
            + " LIMIT 1"
        ).fetchone()
        assert fallback == ("llm", "success")


@pytest.mark.asyncio
async def test_calculate_spend_unpriced_model_returns_400():
    model = "openrouter/unit-test-unpriced-model"
    with patch("litellm.proxy.proxy_server.llm_router", None):
        with pytest.raises(ProxyException) as exc_info:
            await spend_management_endpoints.calculate_spend(
                SpendCalculateRequest(model=model, messages=[{"role": "user", "content": "hi"}])
            )

    assert exc_info.value.code == "400"
    assert exc_info.value.type == "invalid_request_error"
    assert exc_info.value.param == "model"
    assert model in exc_info.value.message


@pytest.mark.asyncio
async def test_spend_calc_model_messages():
    cost_obj: Final = await spend_management_endpoints.calculate_spend(
        request=SpendCalculateRequest(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "user", "content": "What is the capital of France?"},
            ],
        )
    )

    cost: Final = cost_obj["cost"]
    assert cost > 0.0


@pytest.mark.asyncio
async def test_spend_calc_model_on_router_messages(monkeypatch):
    temp_llm_router: Final = Router(
        model_list=[
            {
                "model_name": "special-llama-model",
                "litellm_params": {
                    "model": "groq/openai/gpt-oss-20b",
                },
            }
        ]
    )

    monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", temp_llm_router)

    cost_obj: Final = await spend_management_endpoints.calculate_spend(
        request=SpendCalculateRequest(
            model="special-llama-model",
            messages=[
                {"role": "user", "content": "What is the capital of France?"},
            ],
        )
    )

    _cost: Final = cost_obj["cost"]

    assert _cost > 0.0


@pytest.mark.asyncio
async def test_spend_calc_using_response():
    cost_obj: Final = await spend_management_endpoints.calculate_spend(
        request=SpendCalculateRequest(
            completion_response={
                "id": "chatcmpl-3bc7abcd-f70b-48ab-a16c-dfba0b286c86",
                "choices": [
                    {
                        "finish_reason": "stop",
                        "index": 0,
                        "message": {
                            "content": "Yooo! What's good?",
                            "role": "assistant",
                        },
                    }
                ],
                "created": "1677652288",
                "model": "groq/openai/gpt-oss-20b",
                "object": "chat.completion",
                "system_fingerprint": "fp_873a560973",
                "usage": {
                    "completion_tokens": 8,
                    "prompt_tokens": 12,
                    "total_tokens": 20,
                },
            }
        )
    )

    cost: Final = cost_obj["cost"]
    assert cost > 0.0


@pytest.mark.asyncio
async def test_spend_calc_model_alias_on_router_messages(monkeypatch):
    temp_llm_router: Final = Router(
        model_list=[
            {
                "model_name": "gpt-4o",
                "litellm_params": {
                    "model": "gpt-4o",
                },
            }
        ],
        model_group_alias={
            "gpt4o": "gpt-4o",
        },
    )

    monkeypatch.setattr(litellm.proxy.proxy_server, "llm_router", temp_llm_router)

    cost_obj: Final = await spend_management_endpoints.calculate_spend(
        request=SpendCalculateRequest(
            model="gpt4o",
            messages=[
                {"role": "user", "content": "What is the capital of France?"},
            ],
        )
    )

    _cost: Final = cost_obj["cost"]

    assert _cost > 0.0


def _admin_auth() -> UserAPIKeyAuth:
    return UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, user_id="admin_user")


def test_capture_rate_is_admin_only(client, monkeypatch):
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())
    app.dependency_overrides[ps.user_api_key_auth] = lambda: UserAPIKeyAuth(
        user_role=LitellmUserRoles.INTERNAL_USER, user_id="user_1"
    )
    try:
        response = client.get(
            "/spend/capture_rate?start_date=2026-09-17&end_date=2026-09-23",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert response.status_code == 403


def test_capture_rate_without_the_admin_key_is_503(client, monkeypatch):
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())
    monkeypatch.delenv("OPENAI_ADMIN_KEY", raising=False)
    app.dependency_overrides[ps.user_api_key_auth] = _admin_auth
    try:
        response = client.get(
            "/spend/capture_rate?start_date=2026-09-17&end_date=2026-09-23",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert response.status_code == 503
    assert "OPENAI_ADMIN_KEY" in response.json()["detail"]


def test_capture_rate_rejects_a_reversed_range(client, monkeypatch):
    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())
    app.dependency_overrides[ps.user_api_key_auth] = _admin_auth
    try:
        response = client.get(
            "/spend/capture_rate?start_date=2026-09-23&end_date=2026-09-17",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert response.status_code == 400


def test_capture_rate_rejects_a_range_over_the_maximum(client, monkeypatch):
    from litellm.constants import SPEND_CAPTURE_RATE_MAX_RANGE_DAYS
    from litellm.proxy.spend_tracking.spend_capture_rate import compute_capture_rate

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())
    windows = []

    async def fake_report(prisma_client, *, provider, start_date, end_date, threshold, openai_project_ids=()):
        windows.append((start_date, end_date))
        return compute_capture_rate(
            provider=provider,
            start_date=start_date,
            end_date=end_date,
            captured_by_day={},
            billed_by_day={},
            threshold=threshold,
        )

    monkeypatch.setattr(spend_management_endpoints, "capture_rate_report", fake_report)
    start = datetime.date(2026, 1, 1)
    widest_end = start + datetime.timedelta(days=SPEND_CAPTURE_RATE_MAX_RANGE_DAYS - 1)
    app.dependency_overrides[ps.user_api_key_auth] = _admin_auth
    try:
        too_wide = client.get(
            f"/spend/capture_rate?start_date={start}&end_date={widest_end + datetime.timedelta(days=1)}",
            headers={"Authorization": "Bearer sk-test"},
        )
        widest = client.get(
            f"/spend/capture_rate?start_date={start}&end_date={widest_end}",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert too_wide.status_code == 400
    assert str(SPEND_CAPTURE_RATE_MAX_RANGE_DAYS) in too_wide.json()["detail"]
    assert widest.status_code == 200
    assert windows == [(start, widest_end)]
    assert len(widest.json()["days"]) == SPEND_CAPTURE_RATE_MAX_RANGE_DAYS


def test_capture_rate_returns_the_report_for_the_requested_window(client, monkeypatch):
    from litellm.proxy.spend_tracking.spend_capture_rate import compute_capture_rate

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())
    seen = {}

    async def fake_report(prisma_client, **kwargs):
        seen.update(kwargs)
        return compute_capture_rate(
            provider=kwargs["provider"],
            start_date=kwargs["start_date"],
            end_date=kwargs["end_date"],
            captured_by_day={"2026-09-17": 8.0},
            billed_by_day={"2026-09-17": 10.0},
            threshold=kwargs["threshold"],
        )

    monkeypatch.setattr(spend_management_endpoints, "capture_rate_report", fake_report)
    app.dependency_overrides[ps.user_api_key_auth] = _admin_auth
    try:
        response = client.get(
            "/spend/capture_rate?start_date=2026-09-17&end_date=2026-09-18&threshold=0.5&project_ids=p1&project_ids=p2",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert response.status_code == 200
    body = response.json()
    assert (body["provider"], body["start_date"], body["end_date"]) == ("openai", "2026-09-17", "2026-09-18")
    assert (body["captured_spend"], body["provider_spend"], body["capture_rate"]) == (8.0, 10.0, 0.8)
    assert (body["threshold"], body["below_threshold"]) == (0.5, False)
    assert [d["date"] for d in body["days"]] == ["2026-09-17", "2026-09-18"]
    assert seen["openai_project_ids"] == ("p1", "p2")


def test_capture_rate_reports_an_unreadable_bill_as_502(client, monkeypatch):
    from litellm.proxy.spend_tracking.spend_capture_rate import ProviderBillingRequestFailed

    monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", MagicMock())

    async def fake_report(prisma_client, **kwargs):
        return ProviderBillingRequestFailed("openai", "HTTP 401: Incorrect API key provided")

    monkeypatch.setattr(spend_management_endpoints, "capture_rate_report", fake_report)
    app.dependency_overrides[ps.user_api_key_auth] = _admin_auth
    try:
        response = client.get(
            "/spend/capture_rate?start_date=2026-09-17&end_date=2026-09-23",
            headers={"Authorization": "Bearer sk-test"},
        )
    finally:
        app.dependency_overrides.pop(ps.user_api_key_auth, None)
    assert response.status_code == 502
    assert "HTTP 401" in response.json()["detail"]


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("user_id", "owner_user", "owner_team", "permitted", "expected"),
    [
        ("caller", "caller", "broken", False, True),
        ("caller", "other", "allowed", True, True),
        ("caller", "other", "allowed", False, False),
        ("caller", "other", None, True, False),
        (None, None, None, True, False),
        (None, None, "allowed", True, True),
    ],
)
async def test_shared_owner_policy_preserves_own_user_and_team_access(
    user_id, owner_user, owner_team, permitted, expected
):
    from litellm.proxy.auth.authorization import can_read_log_owner

    async def lookup(team_id):
        if team_id == "broken":
            raise RuntimeError("team lookup failed")
        return permitted

    assert await can_read_log_owner(user_id, owner_user, owner_team, lookup) is expected


@pytest.mark.asyncio
async def test_shared_owner_policy_propagates_team_lookup_failure():
    from litellm.proxy.auth.authorization import can_read_log_owner

    async def unavailable(team_id):
        raise RuntimeError("team lookup failed")

    with pytest.raises(RuntimeError, match="team lookup failed"):
        await can_read_log_owner("caller", "other", "team", unavailable)


@pytest.mark.asyncio
@pytest.mark.parametrize(
    ("params", "expected_status"),
    [
        ({"start_date": "invalid", "end_date": "invalid"}, 400),
        ({"request_id": "foreign"}, 403),
    ],
)
async def test_log_team_dependency_preserves_checks_before_permission_lookup(
    client, monkeypatch, params, expected_status
):
    from litellm.proxy._types import LiteLLM_UserTable
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache

    team_reads = []

    class TeamTable:
        async def find_many(self, where):
            team_reads.append(where)
            return []

    cache = UserApiKeyCache()
    await cache.async_set_cache(
        key="caller", value=LiteLLM_UserTable(user_id="caller", teams=["team"]), model_type=LiteLLM_UserTable
    )
    prisma = MagicMock(
        db=MagicMock(
            query_raw=AsyncMock(return_value=[{"user": "other", "team_id": None}]),
            litellm_teamtable=TeamTable(),
        )
    )
    monkeypatch.setattr(ps, "prisma_client", prisma)
    monkeypatch.setattr(ps, "user_api_key_cache", cache)
    monkeypatch.setitem(
        app.dependency_overrides,
        ps.user_api_key_auth,
        lambda: UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, user_id="caller"),
    )

    response = client.get("/spend/logs/ui", params=params, headers={"Authorization": "Bearer sk-test"})

    assert response.status_code == expected_status, response.text
    assert team_reads == []


@pytest.mark.asyncio
async def test_management_team_lookup_without_memberships_keeps_own_user_scope():
    from litellm.proxy._types import LiteLLM_UserTable
    from litellm.proxy.auth.authorization import resolve_owned_read_scope
    from litellm.proxy.common_utils.user_api_key_cache import UserApiKeyCache

    cache = UserApiKeyCache()
    await cache.async_set_cache(
        key="caller", value=LiteLLM_UserTable(user_id="caller", teams=[]), model_type=LiteLLM_UserTable
    )
    auth = UserAPIKeyAuth(user_id="caller", user_role=LitellmUserRoles.INTERNAL_USER)
    team_reads = []

    class TeamTable:
        async def find_many(self, where):
            team_reads.append(where)
            return []

    prisma = MagicMock(db=MagicMock(litellm_teamtable=TeamTable()))

    async def lookup():
        return await load_permitted_log_team_ids(
            auth, prisma_client=prisma, user_api_key_cache=cache, proxy_logging_obj=ps.proxy_logging_obj
        )

    assert await lookup() == ()
    scope = await resolve_owned_read_scope(auth.user_id, lookup)
    assert scope == OwnedRows("caller")
    assert team_reads == []


class _PrismaJournal:
    def __init__(self) -> None:
        self.statements: tuple[tuple[str, str], ...] = ()

    def __call__(self, **kwargs: object) -> "_ReadOnlyReplicaPrisma":
        return _ReadOnlyReplicaPrisma(self, "reader" if "datasource" in kwargs else "writer")

    def record(self, role: str, query: str) -> None:
        self.statements = (*self.statements, (role, query.strip()))


class _ReadOnlyReplicaPrisma:
    def __init__(self, journal: _PrismaJournal, role: str) -> None:
        self.journal = journal
        self.role = role

    def is_connected(self) -> bool:
        return False

    async def connect(self, timeout: object = None) -> None:
        return None

    def _run(self, query: str) -> None:
        self.journal.record(self.role, query)
        if self.role == "reader" and not query.lstrip().upper().startswith("SELECT"):
            raise Exception(f"cannot execute {query.split()[0]} in a read-only transaction")

    async def query_raw(self, query: str, *args: object) -> list[dict[str, str]]:
        self._run(query)
        return [{"relname": "MonthlyGlobalSpend", "relkind": "m"}]

    async def execute_raw(self, query: str, *args: object) -> int:
        self._run(query)
        return 0


@pytest.mark.asyncio
async def test_global_spend_refresh_runs_the_refresh_on_the_writer_when_a_reader_is_configured(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    journal: Final = _PrismaJournal()
    monkeypatch.setattr(prisma, "Prisma", journal)
    monkeypatch.setenv("DATABASE_URL", "postgresql://writer@localhost/litellm")
    monkeypatch.setenv("DATABASE_URL_READ_REPLICA", "postgresql://reader@localhost/litellm")
    monkeypatch.setattr(
        ps,
        "prisma_client",
        PrismaClient(database_url="postgresql://writer@localhost/litellm", proxy_logging_obj=ps.proxy_logging_obj),
    )

    response: Final = await spend_management_endpoints.global_spend_refresh()

    assert response == {"message": "MonthlyGlobalSpend view refreshed", "status": "success"}, journal.statements
    assert [statement for statement in journal.statements if statement[1].startswith("REFRESH")] == [
        ("writer", 'REFRESH MATERIALIZED VIEW "MonthlyGlobalSpend";')
    ]