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]

56.6 KB
Raw Blame
"""
Polls LiteLLM_ManagedObjectTable to check if the batch job is complete, and if the cost has been tracked.
"""

import asyncio
import json
import re
from collections.abc import Mapping, Sequence
from dataclasses import replace as dataclasses_replace
from datetime import datetime, timedelta, timezone
from types import MappingProxyType
from typing import TYPE_CHECKING, Final, List, Literal, Optional, Protocol, Tuple, cast

from litellm_enterprise.proxy.common_utils.managed_object_attribution import (
    ManagedObjectCreatorAttribution,
    ManagedObjectRow,
    row_metadata,
)

import litellm
from litellm._logging import verbose_proxy_logger
from litellm._uuid import uuid
from litellm.constants import (
    BATCH_LINE_ITEMS_MAX_PART_BYTES,
    MANAGED_OBJECT_STALENESS_CUTOFF_DAYS,
    MAX_OBJECTS_PER_POLL_CYCLE,
)
from litellm.repositories.table_repositories import ManagedObjectRepository
from litellm.repositories.team_repository import TeamRepository
from litellm.repositories.verification_token_repository import VerificationTokenRepository

if TYPE_CHECKING:
    from prisma import models as prisma_models

    from litellm.batches.batch_line_items import BatchFileProvider
    from litellm.integrations.prometheus import PrometheusLogger
    from litellm.proxy.utils import PrismaClient, ProxyLogging
    from litellm.repositories.prisma_protocols import TableActions
    from litellm.router import Router
    from litellm.types.router import Deployment
    from litellm.types.utils import LiteLLMBatch


def _error_names_resource(error: Exception, resource_id: str) -> bool:
    return resource_id in re.findall(r"""[^\s"'`]+""", str(error))


CHECK_BATCH_COST_USER_AGENT = "LiteLLM Proxy/CheckBatchCost"
RECENT_BATCH_POLL_WINDOW: Final = timedelta(hours=48)

PROVIDER_TERMINAL_BATCH_STATUSES: Final[Tuple[str, ...]] = (
    "completed",
    "complete",
    "failed",
    "expired",
    "cancelled",
)

TERMINAL_MANAGED_OBJECT_STATUSES: Final[Tuple[str, ...]] = (
    *PROVIDER_TERMINAL_BATCH_STATUSES,
    "stale_expired",
)


class _ReadableFileContent(Protocol):
    async def read(self) -> bytes: ...


class _HasFileContent(Protocol):
    @property
    def content(self) -> bytes: ...


async def _file_content_bytes(file_content: object) -> bytes:
    if hasattr(file_content, "content"):
        return cast(_HasFileContent, file_content).content
    if hasattr(file_content, "read"):
        return await cast(_ReadableFileContent, file_content).read()
    return cast(bytes, file_content)


def _managed_object_table(prisma_client: "PrismaClient") -> "TableActions[ManagedObjectRow]":
    return ManagedObjectRepository(prisma_client).table


def _token_table(prisma_client: "PrismaClient") -> "TableActions[prisma_models.LiteLLM_VerificationToken]":
    return VerificationTokenRepository(prisma_client).table


def _team_table(prisma_client: "PrismaClient") -> "TableActions[prisma_models.LiteLLM_TeamTable]":
    return TeamRepository(prisma_client).table


class CheckBatchCost:
    def __init__(
        self,
        proxy_logging_obj: "ProxyLogging",
        prisma_client: "PrismaClient",
        llm_router: "Router",
        track_unmanaged_batch_cost: bool = False,
    ):
        from litellm.proxy.utils import PrismaClient, ProxyLogging
        from litellm.router import Router

        self.proxy_logging_obj: ProxyLogging = proxy_logging_obj
        self.prisma_client: PrismaClient = prisma_client
        self.llm_router: Router = llm_router
        self._track_unmanaged_batch_cost = track_unmanaged_batch_cost
        self._creator_attribution: Final = ManagedObjectCreatorAttribution(prisma_client, "CheckBatchCost")
        # Cached after the first poll cycle. Once we know the column is absent we skip
        # the guaranteed-failing primary query on every subsequent cycle.
        self._has_batch_processed_column: bool = True
        self.batch_processed_support_confirmed: bool = False
        self._poll_cursor: tuple[datetime, str] | None = None
        self._poll_before: datetime = datetime.now(timezone.utc)
        self._arrival_cursor: tuple[datetime, str] | None = None
        self._arrival_before: datetime = self._poll_before
        self._poll_arrivals: bool = False
        self._line_item_stores: Final[set[asyncio.Task[None]]] = set()
        self._line_item_store_turn: Final = asyncio.Lock()
        self._poll_idle: Final = asyncio.Event()
        self._poll_idle.set()

    @staticmethod
    def _is_missing_batch_processed_column_error(err: Exception) -> bool:
        message: Final = str(err).lower()
        return "batch_processed" in message or "unknown column" in message or "does not exist" in message

    async def confirm_batch_processed_support(self) -> None:
        """
        Probe the batch_processed column before the proxy serves traffic, so the retrieve
        path never sees an unconfirmed poller on a schema that has the column and accounts
        inline for a batch the first poll cycle then accounts again.
        """
        try:
            await _managed_object_table(self.prisma_client).find_first(
                where={"file_purpose": "batch", "batch_processed": False}
            )
        except Exception as probe_err:
            if not self._is_missing_batch_processed_column_error(probe_err):
                verbose_proxy_logger.debug(
                    f"CheckBatchCost: batch_processed probe failed, the poll cycle will confirm support: {probe_err}"
                )
                return
            self._has_batch_processed_column = False
            verbose_proxy_logger.warning("CheckBatchCost: batch_processed column not found, querying without it")
            return
        self.batch_processed_support_confirmed = True

    async def _cleanup_stale_managed_objects(self) -> None:
        """
        Mark managed objects older than MANAGED_OBJECT_STALENESS_CUTOFF_DAYS days
        in non-terminal states as 'stale_expired'. These will never complete and
        should not be polled.
        """
        cutoff: Final = datetime.now(timezone.utc) - timedelta(days=MANAGED_OBJECT_STALENESS_CUTOFF_DAYS)
        result: Final = await _managed_object_table(self.prisma_client).update_many(
            where={
                "file_purpose": "batch",
                "status": {"not_in": list(TERMINAL_MANAGED_OBJECT_STATUSES)},
                "created_at": {"lt": cutoff},
            },
            data={"status": "stale_expired"},
        )
        if result > 0:
            verbose_proxy_logger.warning(
                f"CheckBatchCost: marked {result} stale managed objects "
                f"(older than {MANAGED_OBJECT_STALENESS_CUTOFF_DAYS} days) as stale_expired"
            )

    async def _fallback_find_jobs(self) -> "Sequence[ManagedObjectRow]":
        """Query batch jobs without the batch_processed filter (for older schemas)."""
        return await self._find_jobs(
            where={
                "file_purpose": "batch",
                "status": {
                    "not_in": [
                        "failed",
                        "expired",
                        "cancelled",
                        "complete",
                        "completed",
                        "stale_expired",
                    ]
                },
            },
        )

    async def _find_jobs(self, where: Mapping[str, object]) -> Sequence[ManagedObjectRow]:
        arrivals: Final = self._poll_arrivals
        page: Final = await self._find_job_page(where, arrivals=arrivals)
        self._poll_arrivals = not arrivals if page else arrivals
        if page:
            return page
        return await self._find_job_page(where, arrivals=not arrivals)

    async def _find_job_page(self, where: Mapping[str, object], *, arrivals: bool) -> Sequence[ManagedObjectRow]:
        cursor: Final = self._arrival_cursor if arrivals else self._poll_cursor
        if cursor is None:
            if arrivals:
                self._arrival_before = datetime.now(timezone.utc)
            else:
                self._poll_before = datetime.now(timezone.utc) - RECENT_BATCH_POLL_WINDOW
        before: Final = self._arrival_before if arrivals else self._poll_before
        page: Final = await _managed_object_table(self.prisma_client).find_many(
            where={
                **where,
                "created_at": {
                    "lte": before,
                    **({"gt": before - RECENT_BATCH_POLL_WINDOW} if arrivals else {}),
                },
                **(
                    {
                        "OR": [
                            {"created_at": {"gt": cursor[0]}},
                            {"created_at": cursor[0], "id": {"gt": cursor[1]}},
                        ]
                    }
                    if cursor is not None
                    else {}
                ),
            },
            take=MAX_OBJECTS_PER_POLL_CYCLE,
            order=[{"created_at": "asc"}, {"id": "asc"}],
        )
        next_cursor: Final = (page[-1].created_at, page[-1].id) if len(page) == MAX_OBJECTS_PER_POLL_CYCLE else None
        if arrivals:
            self._arrival_cursor = next_cursor
        else:
            self._poll_cursor = next_cursor
        return page

    def _unprocessed_snapshot(self, job: ManagedObjectRow) -> Mapping[str, object]:
        return {
            "id": job.id,
            "updated_at": job.updated_at,
            **({"batch_processed": False} if self._has_batch_processed_column else {}),
        }

    async def _retire_job(self, job: "ManagedObjectRow", reason: str) -> None:
        """
        Take a row that can never be costed out of the poll page. Leaving it selectable
        would burn one of the MAX_OBJECTS_PER_POLL_CYCLE slots on every future cycle, and
        once enough such rows accumulate no newer batch is ever reached. Older schemas
        without batch_processed can only be excluded through the status filter.
        """
        data: Final = {"batch_processed": True} if self._has_batch_processed_column else {"status": "stale_expired"}
        try:
            retired: Final = await _managed_object_table(self.prisma_client).update_many(
                where=self._unprocessed_snapshot(job),
                data=data,
            )
        except Exception as db_err:
            verbose_proxy_logger.error(f"CheckBatchCost: failed to retire uncostable job {job.id} ({reason}): {db_err}")
            return
        if retired == 0:
            return
        verbose_proxy_logger.warning(
            f"CheckBatchCost: job {job.id} can never be costed ({reason}), so it will no longer be polled"
        )

    async def _claim_job_for_costing(self, job: "ManagedObjectRow", response: "LiteLLMBatch") -> bool:
        """
        Atomically flip batch_processed from false to true, returning whether this pod won
        the row. Every pod and uvicorn worker schedules its own poller against the shared
        table, so without this compare-and-swap two of them can select the same completed
        batch in one window and both emit an aretrieve_batch spend log for it. Schemas
        without the column can't be claimed, so they keep the pre-existing behavior.

        Called immediately before the spend log is written rather than before the results
        fetch, because batch_processed is also what holds off deletion of the files that
        fetch reads and what keeps an unbilled row selectable by the next poll cycle.
        """
        if not self._has_batch_processed_column:
            return True
        from litellm_enterprise.proxy.hooks.managed_files import postgres_storable_json

        try:
            claimed: Final = await _managed_object_table(self.prisma_client).update_many(
                where={"id": job.id, "batch_processed": False},
                data={
                    "batch_processed": True,
                    "status": response.status if response.status != "completed" else "complete",
                    "file_object": postgres_storable_json(response),
                },
            )
        except Exception as db_err:
            verbose_proxy_logger.error(
                f"CheckBatchCost: failed to claim job {job.id} for cost tracking: {db_err}"
            )
            return False
        return claimed > 0

    async def _release_job_claim(
        self, job: "ManagedObjectRow", original_status: str | None, original_file_object: object
    ) -> None:
        """Give a claimed row back once billing it failed, so a later poll cycle retries it.

        Safe to match on batch_processed=True: while this poller is active the retrieve
        path leaves the column alone (batch_cost_poller_is_active), so a true value here
        is always this pod's own claim.
        """
        if not self._has_batch_processed_column:
            return
        try:
            await _managed_object_table(self.prisma_client).update_many(
                where={"id": job.id, "batch_processed": True},
                data={
                    "batch_processed": False,
                    "status": original_status,
                    "file_object": json.dumps(original_file_object),
                },
            )
        except Exception as db_err:
            verbose_proxy_logger.error(
                f"CheckBatchCost: failed to release the claim on job {job.id}, "
                f"so its cost will not be retried: {db_err}"
            )

    @staticmethod
    def _has_unified_id_without_model(job: "ManagedObjectRow") -> bool:
        """A unified id that decodes but carries no model_id can never be routed."""
        from litellm.proxy.openai_files_endpoints.common_utils import (
            convert_b64_uid_to_unified_uid,
            get_model_id_from_unified_batch_id,
        )

        decoded: Final = convert_b64_uid_to_unified_uid(job.unified_object_id)
        return (
            decoded != job.unified_object_id
            and get_model_id_from_unified_batch_id(decoded) is None
        )

    @staticmethod
    def _is_batch_gone_at_provider(error: Exception, batch_id: str) -> bool:
        """
        A 404 naming the batch means the provider dropped its record of it, so no later
        retrieve can ever succeed. A 404 about anything else, a renamed Azure deployment
        or a fallback deployment that never saw this batch, is still fixable in config, so
        it keeps retrying.
        """
        import openai

        from litellm.exceptions import NotFoundError

        return isinstance(error, (NotFoundError, openai.NotFoundError)) and _error_names_resource(error, batch_id)

    def _batch_deployment_exists(self, model_id: str) -> bool:
        """A 404 only proves the batch is gone when it came from the batch's own
        deployment. Once that deployment leaves the router, default fallbacks can
        silently send the retrieve to a provider that never saw the batch, so its
        404 must not retire a potentially recoverable row."""
        return self.llm_router.get_deployment(model_id=model_id) is not None

    @staticmethod
    def _is_output_file_gone_at_provider(error: Exception, output_file_id: Optional[str]) -> bool:
        """A 404 naming the output file means there is nothing to fetch on this or any
        later poll: providers like Vertex AI advertise an output path for every batch,
        including terminal ones that never wrote it. Any other failure may be
        transient, so it keeps retrying until the staleness sweep bounds it."""
        import openai

        from litellm.exceptions import NotFoundError

        if not output_file_id:
            return False
        return isinstance(error, (NotFoundError, openai.NotFoundError)) and _error_names_resource(error, output_file_id)

    async def _finalize_unbilled_terminal_job(
        self, job: "ManagedObjectRow", response: "LiteLLMBatch"
    ) -> bool:
        """Persist a terminal batch that has nothing billable, converting any raw
        provider file ids to managed ids, and take it out of the poll page. Returns whether it was persisted."""
        try:
            from litellm.proxy.openai_files_endpoints.common_utils import (
                _is_base64_encoded_unified_file_id,
                ensure_batch_response_managed_file_ids,
            )

            response.id = job.unified_object_id
            await ensure_batch_response_managed_file_ids(
                response=response,
                managed_files_obj=self.proxy_logging_obj.get_proxy_hook("managed_files"),
                prisma_client=self.prisma_client,
                verbose_proxy_logger=verbose_proxy_logger,
                db_batch_object=job,
                unified_batch_id=_is_base64_encoded_unified_file_id(job.unified_object_id),
            )
            update_data: Final[dict[str, object]] = {
                "status": response.status,
                "file_object": response.model_dump_json(),
                **({"batch_processed": True} if self._has_batch_processed_column else {}),
            }
            finalized: Final = await _managed_object_table(self.prisma_client).update_many(
                where=self._unprocessed_snapshot(job),
                data=update_data,
            )
            if finalized == 0:
                return False
            verbose_proxy_logger.info(f"CheckBatchCost: marked job {job.id} as {response.status} in DB")
            return True
        except Exception as db_err:
            verbose_proxy_logger.error(
                f"CheckBatchCost: failed to mark job {job.id} as {response.status} in DB: {db_err}"
            )
            return False

    @staticmethod
    def _record_error(
        prom_logger: Optional["PrometheusLogger"], error_type: str
    ) -> None:
        if prom_logger is not None:
            prom_logger.record_check_batch_cost_error(error_type)

    def _resolve_job_routing(
        self,
        job: "ManagedObjectRow",
        prom_logger: Optional["PrometheusLogger"],
    ) -> Optional[Tuple[str, str]]:
        """
        Resolve (model_id, batch_id) for a managed-object row, where model_id is a router
        deployment id and batch_id is the raw provider batch id.

        Managed batches encode both in a base64 unified id. Unmanaged batches (created outside
        LiteLLM's own /v1/batches with a raw input_file_id) store the raw provider job id as
        unified_object_id instead; when track_unmanaged_batch_cost is enabled the model is derived
        from the provider-specific input_file_id layout (Vertex gs:// or Bedrock s3://) and mapped
        to a matching deployment. Returns None (recording a metric) when the row can't be routed.
        """
        from litellm.proxy.openai_files_endpoints.common_utils import (
            _is_base64_encoded_unified_file_id,
            get_batch_id_from_unified_batch_id,
            get_model_id_from_unified_batch_id,
        )

        unified_object_id = job.unified_object_id
        decoded = _is_base64_encoded_unified_file_id(unified_object_id)
        if decoded:
            model_id = get_model_id_from_unified_batch_id(decoded)
            if model_id is None:
                verbose_proxy_logger.info(
                    f"Skipping job {unified_object_id} because it is not a valid model id"
                )
                self._record_error(prom_logger, "invalid_model_id")
                return None
            return model_id, get_batch_id_from_unified_batch_id(decoded)

        if self._track_unmanaged_batch_cost:
            from litellm.llms.bedrock.batches.transformation import (
                BedrockBatchesConfig,
            )
            from litellm.llms.vertex_ai.batches.transformation import (
                VertexAIBatchTransformation,
            )

            input_file_id = self._get_input_file_id(job)
            if VertexAIBatchTransformation.is_unmanaged_gcs_batch_input_file_id(
                input_file_id
            ):
                assert input_file_id is not None  # narrowed by is_unmanaged_gcs_batch_input_file_id
                return self._resolve_unmanaged_provider_routing(
                    job=job,
                    prom_logger=prom_logger,
                    llm_provider="vertex_ai",
                    bare_model_name=VertexAIBatchTransformation.get_bare_model_name_from_gcs_file(
                        input_file_id
                    ),
                )
            if BedrockBatchesConfig.is_unmanaged_s3_batch_input_file_id(input_file_id):
                assert input_file_id is not None  # narrowed by is_unmanaged_s3_batch_input_file_id
                return self._resolve_unmanaged_provider_routing(
                    job=job,
                    prom_logger=prom_logger,
                    llm_provider="bedrock",
                    bare_model_name=BedrockBatchesConfig.get_bare_model_name_from_s3_file(
                        input_file_id
                    ),
                )
            verbose_proxy_logger.info(
                f"Skipping job {unified_object_id}: not a recognized unmanaged batch "
                "(no gs:// or s3:// input_file_id with an embedded model)"
            )
            self._record_error(prom_logger, "invalid_unified_id")
            return None

        verbose_proxy_logger.info(
            f"Skipping job {unified_object_id} because it is not a valid unified object id"
        )
        self._record_error(prom_logger, "invalid_unified_id")
        return None

    def _resolve_unmanaged_provider_routing(
        self,
        job: "ManagedObjectRow",
        prom_logger: Optional["PrometheusLogger"],
        llm_provider: str,
        bare_model_name: str,
    ) -> Optional[Tuple[str, str]]:
        deployment_id = self._get_deployment_id_for_bare_model(bare_model_name, llm_provider)
        if deployment_id is None:
            verbose_proxy_logger.info(
                f"Skipping unmanaged {llm_provider} batch {job.unified_object_id}: no {llm_provider} "
                f"deployment configured for model {bare_model_name}"
            )
            self._record_error(prom_logger, "unmanaged_no_matching_deployment")
            return None

        return deployment_id, job.unified_object_id

    def _get_deployment_id_for_bare_model(
        self, bare_model_name: str, llm_provider: str
    ) -> Optional[str]:
        model_group = self.llm_router.resolve_model_name_from_model_id(bare_model_name)
        deployment_id = (
            self._get_deployment_id_for_provider(model_group, llm_provider) if model_group else None
        )
        if deployment_id is not None:
            return deployment_id

        return self._get_deployment_id_from_matching_deployments(
            bare_model_name, llm_provider
        )

    def _get_deployment_id_from_matching_deployments(
        self, bare_model_name: str, llm_provider: str
    ) -> Optional[str]:
        from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider

        for deployment in self.llm_router.get_model_list(model_name=None) or []:
            litellm_params = deployment.get("litellm_params") or {}
            actual_model = litellm_params.get("model")
            if not isinstance(actual_model, str):
                continue
            if not self._is_bare_model_match(actual_model, bare_model_name):
                continue
            try:
                _, deployment_llm_provider, _, _ = get_llm_provider(
                    model=actual_model,
                    custom_llm_provider=litellm_params.get("custom_llm_provider"),
                )
            except Exception:
                continue
            if deployment_llm_provider != llm_provider:
                continue
            model_info = deployment.get("model_info") or {}
            deployment_id = model_info.get("id")
            if isinstance(deployment_id, str):
                return deployment_id
        return None

    @staticmethod
    def _is_bare_model_match(actual_model: str, bare_model_name: str) -> bool:
        # Bedrock model ids may have ":" replaced with "-" in the S3 object key (see
        # BedrockBatchesConfig.get_bare_model_name_from_s3_file), so normalize both sides;
        # a no-op for providers like vertex_ai whose model ids never contain a colon.
        normalized_actual = actual_model.replace(":", "-")
        normalized_bare = bare_model_name.replace(":", "-")
        return (
            normalized_actual == normalized_bare
            or normalized_actual.endswith(f"/{normalized_bare}")
        )

    def _get_deployment_id_for_provider(
        self, model_group: str, llm_provider: str
    ) -> Optional[str]:
        """
        Returns the first deployment id for `model_group` whose provider is `llm_provider`,
        skipping deployments from other providers that happen to share the model group name.
        """
        from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider

        for deployment_id in self.llm_router.get_model_ids(model_name=model_group):
            deployment_info = self.llm_router.get_deployment(model_id=deployment_id)
            if deployment_info is None:
                continue
            try:
                _, deployment_llm_provider, _, _ = get_llm_provider(
                    model=deployment_info.litellm_params.model,
                    custom_llm_provider=deployment_info.litellm_params.custom_llm_provider,
                )
            except Exception:
                continue
            if deployment_llm_provider == llm_provider:
                return deployment_id
        return None

    @classmethod
    def _get_managed_file_model_name(
        cls,
        job: "ManagedObjectRow",
        deployment_info: "Deployment",
    ) -> Optional[str]:
        """
        Public model group name to encode as ``target_model_names`` on unified output file ids.

        Key model-access checks resolve a managed file id back to a model via its
        ``target_model_names``, so this must be the model group the caller requested, never the
        underlying provider model (e.g. ``gpt-5.5``), which no key is allowed to call.
        """
        from litellm.proxy.openai_files_endpoints.common_utils import (
            resolve_managed_output_file_model_name,
        )

        return resolve_managed_output_file_model_name(
            unified_input_file_id=cls._get_input_file_id(job),
            fallback_model_name=deployment_info.model_name or None,
        )

    @staticmethod
    def _get_input_file_id(job: "ManagedObjectRow") -> Optional[str]:
        from litellm.types.utils import LiteLLMBatch

        file_object: Final = job.file_object
        try:
            parsed_file_object: Final[object] = (
                json.loads(file_object) if isinstance(file_object, str) else file_object
            )
        except (json.JSONDecodeError, ValueError):
            return None
        if not isinstance(parsed_file_object, dict):
            return None
        try:
            return LiteLLMBatch.model_validate(parsed_file_object).input_file_id
        except Exception:
            return None

    async def _track_completed_batch_cost(
        self,
        job: "ManagedObjectRow",
        response: "LiteLLMBatch",
        model_id: str,
        batch_id: str,
        prom_logger: Optional["PrometheusLogger"],
    ) -> Optional[Tuple[Optional[str], Optional[str]]]:
        """
        Fetch a completed batch's results, compute cost/usage, and emit the
        aretrieve_batch spend log. Returns (model_name, llm_provider) on
        success, None when the job can't be routed to a deployment or when
        another pod claimed it. Raises on results-fetch or cost-computation
        failures so the caller can leave the job unprocessed and retry it on a
        later poll.

        """
        from litellm.batches.batch_utils import (
            calculate_batch_cost_and_usage,
            count_error_file_failed_requests,
            get_file_content_as_dictionary,
        )
        from litellm.files.main import afile_content
        from litellm.files.types import FileContentCallOptions
        from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
        from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
        from litellm.litellm_core_utils.litellm_logging import (
            deployment_pricing_model_info,
            mask_api_base_credentials,
            resolve_vertex_location_for_cost,
        )
        from litellm.proxy.openai_files_endpoints.common_utils import (
            _is_base64_encoded_unified_file_id,
        )

        verbose_proxy_logger.info(
            f"Batch ID: {batch_id} is complete, tracking cost and usage"
        )

        # aretrieve_batch is called with the raw provider batch ID, so response.id
        # is the raw provider value (e.g. "batch_20260223-0518.234"). We need the
        # unified base64 ID in the S3 log so downstream consumers can correlate it
        # back to the batch they submitted via the proxy.
        #
        # CheckBatchCost builds its own LiteLLMLogging object (logging_obj below) and
        # calls async_success_handler(result=response) directly. That handler calls
        # _build_standard_logging_payload(response, ...) which reads response.id at
        # that point — so setting response.id here is sufficient.
        #
        # The HTTP endpoint does this substitution via the managed files hook
        # (async_post_call_success_hook). CheckBatchCost bypasses that hook entirely,
        # so we do it explicitly here.
        response.id = job.unified_object_id

        # This background job runs as default_user_id, so going through the HTTP endpoint
        # would trigger check_managed_file_id_access and get 403. Instead, extract the raw
        # provider file ID and call afile_content directly with deployment credentials.
        raw_output_file_id = response.output_file_id
        decoded = _is_base64_encoded_unified_file_id(raw_output_file_id)
        if decoded:
            try:
                raw_output_file_id = decoded.split("llm_output_file_id,")[1].split(";")[0]
            except (IndexError, AttributeError):
                pass

        credentials: Final = self.llm_router.get_deployment_credentials_with_provider(model_id) or {}
        _file_content = await afile_content(
            file_id=cast(str, raw_output_file_id),
            _litellm_internal_model_credentials=MappingProxyType(dict(credentials)),
            **cast(FileContentCallOptions, credentials),
        )

        content_bytes: Final = await _file_content_bytes(_file_content)

        file_content_as_dict = get_file_content_as_dictionary(content_bytes)

        # Record output file size
        if prom_logger and content_bytes:
            try:
                prom_logger.record_managed_file_size(
                    size_bytes=len(content_bytes),
                    purpose="batch",
                    file_type="output",
                    model=model_id,
                )
            except Exception:
                pass

        deployment_info = self.llm_router.get_deployment(model_id=model_id)
        if deployment_info is None:
            verbose_proxy_logger.info(
                f"Skipping job {job.unified_object_id} because it is not a valid deployment info"
            )
            self._record_error(prom_logger, "deployment_not_found")
            return None
        custom_llm_provider = deployment_info.litellm_params.custom_llm_provider
        litellm_model_name = deployment_info.litellm_params.model

        model_name, llm_provider, _, _ = get_llm_provider(
            model=litellm_model_name,
            custom_llm_provider=custom_llm_provider,
        )

        from litellm.proxy.openai_files_endpoints.common_utils import ManagedBatchOutputFileWriter

        managed_files_hook: Final = self.proxy_logging_obj.get_proxy_hook("managed_files")
        if isinstance(managed_files_hook, ManagedBatchOutputFileWriter):
            managed_file_writer: Final = managed_files_hook
            from litellm.proxy._types import UserAPIKeyAuth

            managed_file_model_name = self._get_managed_file_model_name(job=job, deployment_info=deployment_info)
            _minimal_auth = UserAPIKeyAuth(
                user_id=job.created_by or "default-user-id",
                team_id=getattr(job, "team_id", None),
            )
            for _file_attr in ["output_file_id", "error_file_id"]:
                _raw_file_id = cast(str | None, getattr(response, _file_attr, None))
                if _raw_file_id and not _is_base64_encoded_unified_file_id(_raw_file_id):
                    try:
                        _unified_file_id = managed_file_writer.get_unified_output_file_id(
                            output_file_id=_raw_file_id,
                            model_id=model_id,
                            model_name=managed_file_model_name,
                        )
                        await managed_file_writer.store_batch_output_file(
                            unified_file_id=_unified_file_id,
                            provider_file_id=_raw_file_id,
                            model_id=model_id,
                            model_name=managed_file_model_name,
                            owner=_minimal_auth,
                            litellm_parent_otel_span=None,
                            size_bytes=len(content_bytes) if _file_attr == "output_file_id" else None,
                        )
                        setattr(response, _file_attr, _unified_file_id)
                        verbose_proxy_logger.info(
                            f"CheckBatchCost: converted {_file_attr} "
                            f"{_raw_file_id!r} -> managed ID for batch {batch_id}"
                        )
                    except Exception as _e:
                        verbose_proxy_logger.warning(
                            f"CheckBatchCost: failed to create managed file ID for {_file_attr}={_raw_file_id!r}: {_e}"
                        )

        # Pass the deployment's router-registered pricing (litellm_params custom
        # rates merged with the model's published rates) so custom batch pricing
        # (input_cost_per_token_batches etc.) is used for cost calc, exactly as
        # the inline retrieve path does.
        deployment_model_info = deployment_pricing_model_info(
            model_id=model_id,
            deployment_model=litellm_model_name,
        )
        batch_file_provider: Final = cast(
            Literal["openai", "azure", "vertex_ai", "hosted_vllm", "anthropic"], llm_provider
        )
        output_file_result: Final = await calculate_batch_cost_and_usage(
            file_content_dictionary=file_content_as_dict,
            custom_llm_provider=batch_file_provider,
            model_name=model_name,
            model_info=deployment_model_info,
            vertex_location=resolve_vertex_location_for_cost(
                custom_llm_provider=llm_provider,
                litellm_params=deployment_info.litellm_params.model_dump(exclude_none=True),
                optional_params=None,
                model=model_name,
            ),
        )
        error_file_failed_requests: Final = await count_error_file_failed_requests(
            response,
            custom_llm_provider=batch_file_provider,
            litellm_params={
                **credentials,
                "_litellm_internal_model_credentials": MappingProxyType(dict(credentials)),
            },
        )
        batch_result: Final = (
            output_file_result
            if not error_file_failed_requests
            else dataclasses_replace(
                output_file_result,
                failed_requests=output_file_result.failed_requests + error_file_failed_requests,
            )
        )
        logging_model: Final = batch_result.models[0] if batch_result.models else litellm_model_name or model_id
        logging_obj = LiteLLMLogging(
            model=logging_model,
            messages=[{"role": "user", "content": "<retrieve_batch>"}],
            stream=False,
            call_type="aretrieve_batch",
            start_time=datetime.now(),
            litellm_call_id=str(uuid.uuid4()),
            function_id=str(uuid.uuid4()),
        )

        deployment_api_base: Final = deployment_info.litellm_params.api_base
        logging_obj.update_environment_variables(
            litellm_params={
                # set the user-agent header so that S3 callback consumers can easily identify CheckBatchCost callbacks
                "proxy_server_request": {
                    "headers": {
                        "user-agent": CHECK_BATCH_COST_USER_AGENT,
                    }
                },
                **({"api_base": mask_api_base_credentials(deployment_api_base)} if deployment_api_base else {}),
                "metadata": {
                    **(await self._creator_attribution.batch_metadata(job, batch_id)),
                    # spend logs read the deployment identity off these metadata keys, so
                    # without them the batch cost row carries no model_id or model_group
                    "model_info": {"id": model_id},
                    "model_group": deployment_info.model_name,
                },
            },
            optional_params={},
            custom_llm_provider=str(llm_provider) if llm_provider else None,
        )

        original_status: Final = job.status
        original_file_object: Final = job.file_object
        if not await self._claim_job_for_costing(job, response.model_copy(update={"usage": batch_result.usage})):
            verbose_proxy_logger.info(
                f"CheckBatchCost: batch {batch_id} (job {job.id}) was claimed by another pod "
                "in this window, so its cost is already being tracked there"
            )
            return None

        from litellm.proxy.hooks.proxy_track_cost_callback import track_batch_accounting

        with track_batch_accounting(logging_obj.litellm_call_id) as accounting:
            try:
                await logging_obj.async_success_handler(
                    result=response,
                    batch_cost=batch_result.cost,
                    batch_usage=batch_result.usage,
                    batch_models=batch_result.models,
                    batch_successful_requests=batch_result.successful_requests,
                    batch_failed_requests=batch_result.failed_requests,
                    batch_prompt_cost=batch_result.prompt_cost,
                    batch_completion_cost=batch_result.completion_cost,
                )
            finally:
                if accounting.retryable_failure:
                    await self._release_job_claim(job, original_status, original_file_object)

        if accounting.retryable_failure:
            return None

        # Record batch duration (completed_at - created_at)
        if prom_logger and response.completed_at and response.created_at:
            duration_seconds = float(response.completed_at - response.created_at)
            if duration_seconds >= 0:
                prom_logger.record_managed_batch_duration(
                    duration_seconds=duration_seconds,
                    model=model_name,
                    api_provider=str(llm_provider) if llm_provider else None,
                )

        return model_name, str(llm_provider) if llm_provider else None

    async def _retire_unbilled_terminal_job(
        self, job: "ManagedObjectRow", response: "LiteLLMBatch", model_id: str, batch_id: str
    ) -> None:
        """Persist a terminal batch that has nothing billable, then store its lines, reading its input file by the id
        the provider reported rather than the managed id that was persisted."""
        provider_input_file_id: Final = response.input_file_id
        if await self._finalize_unbilled_terminal_job(job, response):
            response.input_file_id = provider_input_file_id
            self._store_batch_line_items_in_background(job, response, model_id, batch_id, billed=False)

    def _store_batch_line_items_in_background(
        self, job: "ManagedObjectRow", response: "LiteLLMBatch", model_id: str, batch_id: str, *, billed: bool
    ) -> None:
        """Store a retired batch's lines off the poll loop, one batch at a time and only between polls, so neither
        pricing the lines nor a slow or hung bucket holds up billing or retiring the other batches. While a poll
        cycle's worth of batches is still waiting, the lines of the next one are dropped with an error."""
        if not litellm.batch_line_item_callbacks:
            return
        if len(self._line_item_stores) >= MAX_OBJECTS_PER_POLL_CYCLE:
            verbose_proxy_logger.error(
                f"CheckBatchCost: {len(self._line_item_stores)} batches are still waiting to store their line items, "
                f"so the line items of batch {batch_id} (job {job.id}) were not stored"
            )
            return
        store: Final = asyncio.create_task(
            self._store_batch_line_items_in_turn(job, response, model_id, batch_id, billed=billed)
        )
        self._line_item_stores.add(store)
        store.add_done_callback(self._line_item_stores.discard)

    async def _store_batch_line_items_in_turn(
        self, job: "ManagedObjectRow", response: "LiteLLMBatch", model_id: str, batch_id: str, *, billed: bool
    ) -> None:
        async with self._line_item_store_turn:
            await self._poll_idle.wait()
            await self._store_batch_line_items(job, response, model_id, batch_id, billed=billed)

    async def _store_batch_line_items(
        self, job: "ManagedObjectRow", response: "LiteLLMBatch", model_id: str, batch_id: str, *, billed: bool
    ) -> None:
        """Send every line of a finished batch to batch_line_item_callbacks, one part at a time. A billed batch's
        output file is read again here, so nothing waiting for its turn holds a batch's files. Failures, including an
        output file that can no longer be read, are logged and never raised, so the batch stays billed and retired
        whether or not its lines were stored."""
        if not litellm.batch_line_item_callbacks:
            return
        from litellm.batches.batch_line_items import (
            BatchFileProvider,
            BatchLineItemSource,
            batch_line_item_parts,
            dispatch_batch_line_items,
            line_item_metadata,
        )
        from litellm.batches.batch_utils import fetch_batch_managed_file_content
        from litellm.litellm_core_utils.get_llm_provider_logic import get_llm_provider
        from litellm.litellm_core_utils.litellm_logging import (
            deployment_pricing_model_info,
            resolve_vertex_location_for_cost,
        )

        try:
            deployment_info: Final = self.llm_router.get_deployment(model_id=model_id)
            if deployment_info is None:
                verbose_proxy_logger.error(
                    f"CheckBatchCost: deployment {model_id} is no longer in the router, so the line items of batch "
                    f"{batch_id} (job {job.id}) were not stored"
                )
                return
            litellm_model_name: Final = deployment_info.litellm_params.model
            model_name, llm_provider, _, _ = get_llm_provider(
                model=litellm_model_name,
                custom_llm_provider=deployment_info.litellm_params.custom_llm_provider,
            )
            cost_provider: Final = cast(BatchFileProvider, llm_provider)
            credentials: Final = self.llm_router.get_deployment_credentials_with_provider(model_id) or {}
            file_access: Final = {
                **credentials,
                "_litellm_internal_model_credentials": MappingProxyType(dict(credentials)),
            }
            output_content: Final = (
                await fetch_batch_managed_file_content(
                    response.output_file_id, custom_llm_provider=cost_provider, litellm_params=file_access
                )
                if billed and response.output_file_id
                else b""
            )
            error_content: Final = await self._batch_file_content(response.error_file_id, cost_provider, file_access)
            if not output_content and not error_content:
                return
            redact_bodies: Final = await self._creator_turned_off_message_logging(job)
            source: Final = BatchLineItemSource(
                batch_id=job.unified_object_id,
                finished_at=response.completed_at
                or response.failed_at
                or response.expired_at
                or response.cancelled_at
                or response.created_at,
                model=model_name,
                custom_llm_provider=llm_provider,
                cost_provider=cost_provider,
                model_info=deployment_pricing_model_info(model_id=model_id, deployment_model=litellm_model_name),
                metadata=line_item_metadata(await self._creator_attribution.batch_metadata(job, batch_id)),
                vertex_location=resolve_vertex_location_for_cost(
                    custom_llm_provider=llm_provider,
                    litellm_params=deployment_info.litellm_params.model_dump(exclude_none=True),
                    optional_params=None,
                    model=model_name,
                ),
            )
            input_content: Final = (
                b""
                if redact_bodies
                else await self._batch_file_content(response.input_file_id, cost_provider, file_access)
            )
            parts: Final = batch_line_item_parts(
                source, input_content, (output_content, error_content), BATCH_LINE_ITEMS_MAX_PART_BYTES
            )
            handed = 0
            # pricing a part's lines is CPU-bound, so each part is built off the event loop
            while (payload := await asyncio.to_thread(next, parts, None)) is not None:
                await dispatch_batch_line_items(payload, redact_bodies=redact_bodies)
                handed += len(payload["lines"])
            if handed:
                verbose_proxy_logger.info(
                    f"CheckBatchCost: handed the {handed} line items of batch {batch_id} to batch_line_item_callbacks"
                )
        except Exception as error:  # noqa: BLE001  # storing the lines is best effort, the batch is already billed
            verbose_proxy_logger.exception(
                f"CheckBatchCost: the line items of batch {batch_id} (job {job.id}) were not stored: {error}"
            )

    @staticmethod
    async def _batch_file_content(
        file_id: str | None, custom_llm_provider: "BatchFileProvider", file_access: Mapping[str, object]
    ) -> bytes:
        """A batch file's raw JSONL, or nothing when the batch has no such file or the provider will not serve it."""
        from litellm.batches.batch_utils import fetch_batch_managed_file_content

        if not file_id:
            return b""
        try:
            return await fetch_batch_managed_file_content(
                file_id, custom_llm_provider=custom_llm_provider, litellm_params=file_access
            )
        except Exception as error:  # noqa: BLE001  # a missing input or error file leaves those lines out, not the rest
            verbose_proxy_logger.warning(f"CheckBatchCost: could not read batch file {file_id}: {error}")
            return b""

    async def _creator_turned_off_message_logging(self, job: "ManagedObjectRow") -> bool:
        """Whether the creating key's or team's logging settings turn off message logging, falling back to the
        proxy-wide setting. A batch whose saved credential is not a virtual key's hash, such as one created under JWT
        or OAuth2 auth or with the master key, has only its team's and the proxy's settings. A key or team that can no
        longer be read counts as turned off."""
        from litellm.litellm_core_utils.litellm_logging import is_valid_sha256_hash
        from litellm.proxy._types import UserAPIKeyAuth
        from litellm.proxy.litellm_pre_call_utils import get_dynamic_logging_metadata
        from litellm.proxy.proxy_server import proxy_config
        from litellm.secret_managers.main import str_to_bool

        api_key: Final = getattr(job, "api_key", None)
        team_id: Final = getattr(job, "team_id", None)
        has_key_row: Final = api_key is not None and is_valid_sha256_hash(api_key)
        try:
            key_row: Final = (
                await _token_table(self.prisma_client).find_unique(where={"token": api_key}) if has_key_row else None
            )
            team_row: Final = (
                await _team_table(self.prisma_client).find_unique(where={"team_id": team_id}) if team_id else None
            )
        except Exception as error:
            verbose_proxy_logger.error(
                f"CheckBatchCost: could not read the logging settings of batch job {job.id}'s creator, "
                f"so its line items are stored without request and response: {error}"
            )
            return True
        if (has_key_row and key_row is None) or (team_id and team_row is None):
            return True
        settings: Final = get_dynamic_logging_metadata(
            UserAPIKeyAuth(
                metadata=dict(row_metadata(key_row)), team_metadata=dict(row_metadata(team_row)), team_id=team_id
            ),
            proxy_config,
        )
        callback_vars: Final = (settings.callback_vars if settings is not None else None) or {}
        creator_setting: Final = str_to_bool(callback_vars.get("turn_off_message_logging"))
        return creator_setting if creator_setting is not None else litellm.turn_off_message_logging is True

    async def check_batch_cost(self) -> None:
        """Run one poll cycle. Batch line items wait until it has billed and retired every batch it found."""
        self._poll_idle.clear()
        try:
            await self._poll_batches()
        finally:
            self._poll_idle.set()

    async def _poll_batches(self):
        """
        Check if the batch JOB has been tracked.
        - get all status="validating" and file_purpose="batch" jobs
        - check if batch is now complete
        - if not, return False
        - if so, return True
        """
        try:
            from litellm.integrations.prometheus import PrometheusLogger

            prom_logger = PrometheusLogger.get_instance()
        except Exception as e:
            verbose_proxy_logger.error(f"CheckBatchCost: could not get Prometheus logger: {e}")
            prom_logger = None

        processed_models: List[Tuple[Optional[str], Optional[str]]] = []

        try:
            await self._cleanup_stale_managed_objects()
        except Exception as cleanup_err:
            verbose_proxy_logger.warning(
                f"CheckBatchCost: stale cleanup failed (poll will continue): {cleanup_err}"
            )

        # Look for all batches that have not yet been processed by CheckBatchCost.
        # self._has_batch_processed_column is cached after the first probe so that
        # older schemas don't pay a guaranteed-failing primary query + warning on
        # every subsequent poll cycle.
        if self._has_batch_processed_column:
            try:
                # Include "complete"/"completed" batches: the retrieve_batch
                # endpoint may transition a batch to "complete" before
                # CheckBatchCost runs.  The batch_processed=False filter
                # already prevents reprocessing finished batches.
                jobs = await self._find_jobs(
                    where={
                        "file_purpose": "batch",
                        "batch_processed": False,
                        "status": {
                            "not_in": [
                                "failed",
                                "expired",
                                "cancelled",
                                "stale_expired",
                            ]
                        },
                    },
                )
                self.batch_processed_support_confirmed = True
            except Exception as query_err:
                if not self._is_missing_batch_processed_column_error(query_err):
                    raise
                # Permanent schema gap — cache the result so future cycles skip straight to fallback
                self._has_batch_processed_column = False
                verbose_proxy_logger.warning(
                    "CheckBatchCost: batch_processed column not found, querying without it"
                )
                jobs = await self._fallback_find_jobs()
        else:
            jobs = await self._fallback_find_jobs()
        for job in jobs:
            routing = self._resolve_job_routing(job, prom_logger)
            if routing is None:
                if self._has_unified_id_without_model(job):
                    await self._retire_job(job, "unified object id has no model id")
                continue
            model_id, batch_id = routing

            verbose_proxy_logger.info(
                f"Querying model ID: {model_id} for cost and usage of batch ID: {batch_id}"
            )

            try:
                response = await self.llm_router.aretrieve_batch(
                    model=model_id,
                    batch_id=batch_id,
                    litellm_metadata={
                        "user_api_key_user_id": job.created_by or "default-user-id",
                        "batch_ignore_default_logging": True,
                    },
                )
            except Exception as e:
                verbose_proxy_logger.info(
                    f"Skipping job {job.unified_object_id} because of error querying model ID: {model_id} for cost and usage of batch ID: {batch_id}: {e}"
                )
                if prom_logger:
                    prom_logger.record_check_batch_cost_error("provider_retrieval_error")
                if self._is_batch_gone_at_provider(e, batch_id) and self._batch_deployment_exists(model_id):
                    await self._retire_job(job, f"batch {batch_id} no longer exists at the provider")
                continue

            ## RETRIEVE THE BATCH JOB OUTPUT FILE
            if response.status in PROVIDER_TERMINAL_BATCH_STATUSES and response.output_file_id is not None:
                try:
                    tracked = await self._track_completed_batch_cost(
                        job=job,
                        response=response,
                        model_id=model_id,
                        batch_id=batch_id,
                        prom_logger=prom_logger,
                    )
                except Exception as tracking_err:
                    if self._is_output_file_gone_at_provider(
                        tracking_err, response.output_file_id
                    ) and self._batch_deployment_exists(model_id):
                        verbose_proxy_logger.warning(
                            f"CheckBatchCost: output file {response.output_file_id} of batch {batch_id} "
                            f"does not exist at the provider; retiring job {job.id} unbilled"
                        )
                        await self._retire_unbilled_terminal_job(job, response, model_id, batch_id)
                        continue
                    verbose_proxy_logger.error(
                        f"CheckBatchCost: failed to track cost for batch {batch_id} "
                        f"(job {job.id}): {tracking_err}"
                    )
                    self._record_error(prom_logger, "cost_tracking_error")
                    continue
                if tracked is None:
                    continue

                # Track this job for the final metrics summary
                processed_models.append(tracked)

                if not self._has_batch_processed_column:
                    try:
                        await _managed_object_table(self.prisma_client).update(
                            where={"id": job.id},
                            data={
                                "status": response.status if response.status != "completed" else "complete",
                                "file_object": response.model_dump_json(),
                            },
                        )
                    except Exception as db_err:
                        verbose_proxy_logger.error(
                            f"CheckBatchCost: failed to mark job {job.id} complete in DB: {db_err}"
                        )
                        continue
                self._store_batch_line_items_in_background(job, response, model_id, batch_id, billed=True)

            elif response.status in PROVIDER_TERMINAL_BATCH_STATUSES:
                from litellm.proxy.openai_files_endpoints.common_utils import (
                    _completed_batch_safe_to_retire,
                )

                if response.status in ("completed", "complete") and not _completed_batch_safe_to_retire(response):
                    verbose_proxy_logger.info(
                        f"CheckBatchCost: batch {batch_id} is completed but its output file id "
                        f"has not appeared yet; leaving job {job.id} for the next poll cycle"
                    )
                    continue
                await self._retire_unbilled_terminal_job(job, response, model_id, batch_id)

        # Record polling run metrics (always, even if nothing was processed)
        if prom_logger:
            prom_logger.record_check_batch_cost_run(
                jobs_polled=len(jobs),
                processed_models=processed_models if processed_models else None,
            )