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]

feat(ptu): daily rollup writes per-model PTU flat cost by active hour (#35343)

yucheng-berri61218f5f9f45
diff --git a/litellm/constants.py b/litellm/constants.py
index 8c8350b9548..f2ac96162eb 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1725,3 +1725,12 @@ UNSAFE_PROXY_RESPONSE_HEADERS: Final[frozenset[str]] = HTTP_FRAMING_HEADERS | BR
# spend under the table's composite unique constraint.
PTU_SENTINEL_API_KEY: Final[str] = "__ptu_flat_cost__"
PTU_ROLLUP_JOB_ID: Final[str] = "ptu_flat_cost_rollup_job"
+PTU_ROLLUP_LOCK_TTL_SECONDS: Final[int] = 900
+# Furthest back the catch-up pass looks for unpriced PTU days when a deployment
+# declares no ptu_effective_from, bounding the scan for an open-ended window.
+PTU_ROLLUP_MAX_BACKFILL_DAYS: Final[int] = 90
+# Slack allowed when deciding a sentinel row is stale. The row's updated_at and the
+# run's cutoff are stamped by different hosts, so clock skew between them must not let
+# one run delete a charge another just wrote. A stale row is hours old and a concurrent
+# one is seconds old, so a few minutes separates them.
+PTU_PRUNE_SKEW_GRACE_SECONDS: Final[int] = 300
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index ebbd5a488c3..641d294f592 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -612,7 +612,7 @@ from litellm.secret_managers.main import (
normalize_nonempty_secret_str,
str_to_bool,
)
-from litellm.types.integrations.slack_alerting import SlackAlertingArgs
+from litellm.types.integrations.slack_alerting import AlertType, SlackAlertingArgs
from litellm.types.llms.anthropic import (
AnthropicMessagesRequest,
AnthropicResponse,
@@ -8470,6 +8470,42 @@ class ProxyStartupEvent:
await cls._initialize_spend_tracking_background_jobs(scheduler=scheduler)
+ ### PTU DAILY ROLLUP ###
+ from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import (
+ PTU_ROLLUP_JOB_ID,
+ run_scheduled_ptu_rollup,
+ )
+
+ async def _alert_ptu_rollup_failure(message: str) -> None:
+ await proxy_logging_obj.alerting_handler(
+ message=message,
+ level="High",
+ alert_type=AlertType.failed_tracking_spend,
+ )
+
+ async def _scheduled_ptu_rollup() -> None:
+ # Reuse the PodLockManager from db_spend_update_writer so only one pod
+ # reconciles a day; a multi-pod race could prune another pod's fresh rows
+ await run_scheduled_ptu_rollup(
+ prisma_client,
+ pod_lock_manager=proxy_logging_obj.db_spend_update_writer.pod_lock_manager,
+ alert=_alert_ptu_rollup_failure,
+ )
+
+ scheduler.add_job(
+ _scheduled_ptu_rollup,
+ "cron",
+ hour=0,
+ minute=15,
+ timezone="UTC",
+ id=PTU_ROLLUP_JOB_ID,
+ replace_existing=True,
+ misfire_grace_time=APSCHEDULER_MISFIRE_GRACE_TIME,
+ )
+ verbose_proxy_logger.info(
+ "PTU rollup job scheduled at 00:15 UTC daily (only models with PTU config accrue flat cost)"
+ )
+
### SPEND LOG CLEANUP ###
if (
general_settings.get("maximum_spend_logs_retention_period") is not None
diff --git a/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py
new file mode 100644
index 00000000000..a77c3e29cfa
--- /dev/null
+++ b/litellm/proxy/spend_tracking/ptu_flat_cost_rollup.py
@@ -0,0 +1,654 @@
+"""
+Daily rollup for per-model PTU (provisioned throughput) flat cost.
+
+v1 reads PTU config straight off the model deployment
+(``LiteLLM_ProxyModelTable.model_info``): a deployment carrying ``ptu_count``
+and ``cost_per_ptu_per_hour`` accrues flat cost of
+``ptu_count * cost_per_ptu_per_hour * active_hours`` for a given UTC day, where
+``active_hours`` is the overlap between the day and the optional
+``[ptu_effective_from, ptu_effective_to)`` window (a window opening at 23:00
+charges one hour that day). The amount is written to ``LiteLLM_DailyTeamSpend``
+under a sentinel api_key so the rows are distinguishable from per-request rows
+and share the existing unique constraint.
+"""
+
+import asyncio
+import json
+from collections.abc import Awaitable, Callable, Mapping
+from dataclasses import dataclass
+from datetime import date, datetime, time, timedelta, timezone
+from typing import TYPE_CHECKING, Final
+
+from litellm._logging import verbose_proxy_logger
+from litellm.constants import (
+ PTU_PRUNE_SKEW_GRACE_SECONDS,
+ PTU_ROLLUP_JOB_ID,
+ PTU_ROLLUP_LOCK_TTL_SECONDS,
+ PTU_ROLLUP_MAX_BACKFILL_DAYS,
+ PTU_SENTINEL_API_KEY,
+)
+from litellm.types.router import ModelInfo
+
+if TYPE_CHECKING:
+ from litellm.proxy.db.db_transaction_queue.pod_lock_manager import PodLockManager
+ from litellm.proxy.utils import PrismaClient
+
+_HOURS_PER_DAY: Final = 24
+_UPSERT_ATTEMPTS: Final = 3
+_UPSERT_RETRY_BACKOFF_SECONDS: Final = 0.5
+
+
+@dataclass(frozen=True, slots=True)
+class RollupResult:
+ day: date
+ models_processed: int
+ rows_written: int
+ rows_failed: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class BackfillResult:
+ start: date
+ end: date
+ days_scanned: int
+ rows_written: int
+ rows_failed: int = 0
+
+
+@dataclass(frozen=True, slots=True)
+class PTUModel:
+ """A model deployment carrying valid manual PTU config."""
+
+ model_id: str
+ model_name: str
+ team_id: str
+ ptu_count: int
+ cost_per_ptu_per_hour: float
+ effective_from: datetime | None = None
+ effective_to: datetime | None = None
+
+
+def _parse_utc_datetime(value: object) -> datetime | None:
+ """Parse a model_info datetime (ISO string or datetime) into a UTC-aware datetime, else None."""
+ parsed: Final = _coerce_datetime(value)
+ if parsed is None:
+ return None
+ if parsed.tzinfo is None:
+ return parsed.replace(tzinfo=timezone.utc)
+ return parsed.astimezone(timezone.utc)
+
+
+def _coerce_datetime(value: object) -> datetime | None:
+ """``value`` as a datetime, parsing an ISO string, else None."""
+ if isinstance(value, datetime):
+ return value
+ if not isinstance(value, str):
+ return None
+ try:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def _public_model_name(row: object, model_info: Mapping[str, object]) -> str:
+ """The name an operator recognises for this deployment.
+
+ Creating a team-scoped deployment rewrites model_name to a synthetic routing key
+ (``model_name_<team_id>_<uuid4>``) and keeps the chosen name in
+ ``model_info.team_public_model_name``. PTU config is only accepted alongside a
+ team_id, so every PTU deployment carries that synthetic name; keying the sentinel
+ row on it would file each charge under a UUID that no usage view can resolve and
+ that never lines up with the same model's request rows.
+ """
+ public_name: Final = model_info.get("team_public_model_name")
+ if isinstance(public_name, str) and public_name:
+ return public_name
+ return str(getattr(row, "model_name", "") or "")
+
+
+def _decode_model_info(raw: object) -> "Mapping[str, object] | None":
+ """A deployment's model_info as a dict, decoding a JSON string, else None."""
+ if isinstance(raw, str):
+ try:
+ return json.loads(raw)
+ except (TypeError, ValueError):
+ return None
+ if isinstance(raw, dict):
+ return raw
+ return None
+
+
+def _parse_ptu_model(row: object) -> PTUModel | None:
+ """Return a PTUModel when the deployment carries valid manual PTU config, else None.
+
+ Valid means model_info has a positive ptu_count, a non-negative
+ cost_per_ptu_per_hour, and a team_id (1 model -> 1 team).
+ """
+ raw_model_info: Final = getattr(row, "model_info", None)
+ model_info: Final = _decode_model_info(raw_model_info)
+ if model_info is None:
+ return None
+ ptu_count: Final = model_info.get("ptu_count")
+ cost_per_hour: Final = model_info.get("cost_per_ptu_per_hour")
+ team_id: Final = model_info.get("team_id")
+ if ptu_count is None or cost_per_hour is None or not team_id:
+ return None
+ try:
+ ptu_count_int: Final = int(ptu_count)
+ cost_per_hour_float: Final = float(cost_per_hour)
+ except (TypeError, ValueError, OverflowError):
+ return None
+ if not 0 < ptu_count_int <= ModelInfo.MAX_PTU_COUNT:
+ return None
+ if not 0 <= cost_per_hour_float <= ModelInfo.MAX_COST_PER_PTU_PER_HOUR:
+ return None
+ if model_info.get("ptu_effective_from") is None:
+ # The endpoints require a start; a row without one predates that rule or was
+ # written around them, and inferring one would bill days the deployment did not exist
+ return None
+ raw_from: Final = model_info.get("ptu_effective_from")
+ raw_to: Final = model_info.get("ptu_effective_to")
+ effective_from: Final = _parse_utc_datetime(raw_from)
+ effective_to: Final = _parse_utc_datetime(raw_to)
+ # A present-but-unparseable bound would read as "no bound" and silently widen the
+ # window to the whole day, so the deployment is skipped until the config is fixed
+ if (raw_from is not None and effective_from is None) or (raw_to is not None and effective_to is None):
+ return None
+ if effective_from is not None and effective_to is not None and effective_to <= effective_from:
+ return None
+ return PTUModel(
+ model_id=str(getattr(row, "model_id", "") or ""),
+ model_name=_public_model_name(row, model_info),
+ team_id=str(team_id),
+ ptu_count=ptu_count_int,
+ cost_per_ptu_per_hour=cost_per_hour_float,
+ effective_from=effective_from,
+ effective_to=effective_to,
+ )
+
+
+def _active_hours_on_day(model: PTUModel, day: date) -> float:
+ """Hours the model's PTU window overlaps ``day`` (UTC), clamped to [0, 24]."""
+ day_start: Final = datetime.combine(day, time.min, tzinfo=timezone.utc)
+ day_end: Final = day_start + timedelta(days=1)
+ start: Final = max(day_start, model.effective_from) if model.effective_from else day_start
+ end: Final = min(day_end, model.effective_to) if model.effective_to else day_end
+ if end <= start:
+ return 0.0
+ return (end - start).total_seconds() / 3600.0
+
+
+def _compute_daily_flat_cost(model: PTUModel, day: date) -> float:
+ """Flat cost for ``day``: ptu_count * cost_per_ptu_per_hour * active_hours."""
+ return float(model.ptu_count) * model.cost_per_ptu_per_hour * _active_hours_on_day(model, day)
+
+
+@dataclass(frozen=True, slots=True)
+class _PTUCharge:
+ """One sentinel row's worth of flat cost for a deployment on a day.
+
+ ``model_id`` is the row's identity and goes in the unique key; ``model_name`` is what
+ an operator reads and rides alongside it. A deployment can be renamed, so keying on
+ the name would let two runs holding different config views write the same day twice.
+ """
+
+ team_id: str
+ model_id: str
+ model_name: str
+ flat_cost: float
+
+
+def _aggregate_charges(ptu_models: tuple[PTUModel, ...], day: date) -> tuple[_PTUCharge, ...]:
+ """One charge per deployment that accrues cost on ``day``. Zero-cost deployments are
+ dropped, which keeps a day outside a window from writing a row.
+
+ Deployments sharing a public name inside a team no longer need collapsing: each keys
+ its own row on its own id, and the read path merges them back under the shared name.
+ """
+ return tuple(
+ _PTUCharge(
+ team_id=model.team_id,
+ model_id=model.model_id,
+ model_name=model.model_name,
+ flat_cost=_compute_daily_flat_cost(model, day),
+ )
+ for model in sorted(ptu_models, key=lambda m: (m.team_id, m.model_id))
+ if _compute_daily_flat_cost(model, day) > 0
+ )
+
+
+async def _upsert_ptu_daily_row(
+ prisma_client: "PrismaClient",
+ *,
+ team_id: str,
+ model_id: str,
+ model_name: str,
+ date_str: str,
+ flat_cost: float,
+) -> None:
+ """Idempotent upsert of a sentinel-api_key row on LiteLLM_DailyTeamSpend.
+
+ ``model`` holds the deployment id because it is part of the table's unique key and a
+ rename must not move the row. ``model_group`` carries the operator-facing name, which
+ is outside the key and is what the usage views display.
+ """
+ where: Final = { # mutable-ok: prisma upsert filter payload
+ "team_id_date_api_key_model_custom_llm_provider_mcp_namespaced_tool_name_endpoint": { # mutable-ok: prisma composite-key filter
+ "team_id": team_id,
+ "date": date_str,
+ "api_key": PTU_SENTINEL_API_KEY,
+ "model": model_id,
+ "custom_llm_provider": "",
+ "mcp_namespaced_tool_name": "",
+ "endpoint": "",
+ }
+ }
+ now: Final = datetime.now(timezone.utc)
+ await prisma_client.db.litellm_dailyteamspend.upsert(
+ where=where,
+ data={ # mutable-ok: prisma upsert data payload
+ "create": { # mutable-ok: prisma create payload
+ "team_id": team_id,
+ "date": date_str,
+ "api_key": PTU_SENTINEL_API_KEY,
+ "model": model_id,
+ "model_group": model_name,
+ "custom_llm_provider": "",
+ "mcp_namespaced_tool_name": "",
+ "endpoint": "",
+ "ptu_flat_cost": flat_cost,
+ },
+ "update": { # mutable-ok: prisma update payload
+ "model_group": model_name,
+ "ptu_flat_cost": flat_cost,
+ "updated_at": now,
+ },
+ },
+ )
+
+
+async def _upsert_charge_with_retry(
+ prisma_client: "PrismaClient",
+ *,
+ charge: _PTUCharge,
+ date_str: str,
+) -> bool:
+ """Write one charge, retrying transient failures. Returns False once attempts are spent.
+
+ The upsert is idempotent on the sentinel unique key, so a retry can only rewrite the
+ same amount for the same day. Retrying in-run matters because the scheduled job moves
+ on to the next date: a write lost here is a day of PTU cost that no later run replays.
+ """
+ for attempt in range(1, _UPSERT_ATTEMPTS + 1):
+ try:
+ await _upsert_ptu_daily_row(
+ prisma_client,
+ team_id=charge.team_id,
+ model_id=charge.model_id,
+ model_name=charge.model_name,
+ date_str=date_str,
+ flat_cost=charge.flat_cost,
+ )
+ return True
+ except Exception as exc: # noqa: BLE001 # one bad row must not stop the batch
+ if attempt < _UPSERT_ATTEMPTS:
+ verbose_proxy_logger.warning(
+ "PTU rollup: upsert attempt %d/%d failed for team=%s model=%s day=%s: %s",
+ attempt,
+ _UPSERT_ATTEMPTS,
+ charge.team_id,
+ charge.model_name,
+ date_str,
+ exc,
+ )
+ await asyncio.sleep(_UPSERT_RETRY_BACKOFF_SECONDS * attempt)
+ continue
+ verbose_proxy_logger.error(
+ "PTU rollup: upsert failed after %d attempts for team=%s model=%s day=%s "
+ "(rerun the rollup for that date to recover): %s",
+ _UPSERT_ATTEMPTS,
+ charge.team_id,
+ charge.model_name,
+ date_str,
+ exc,
+ )
+ return False
+
+
+async def _load_ptu_models(prisma_client: "PrismaClient") -> tuple[PTUModel, ...]:
+ """Every model deployment currently carrying valid manual PTU config."""
+ rows: Final = await prisma_client.db.litellm_proxymodeltable.find_many()
+ return tuple(parsed for parsed in (_parse_ptu_model(row) for row in rows) if parsed is not None)
+
+
+async def run_ptu_flat_cost_rollup(
+ prisma_client: "PrismaClient",
+ target_date: date | None = None,
+ may_prune: bool = True,
+) -> RollupResult:
+ """Rollup one UTC day of flat PTU cost across all PTU-configured model deployments.
+
+ Defaults to yesterday UTC. Authoritative for the day: it upserts the current charges
+ first, then deletes the day's sentinel rows this run did not refresh, so a
+ since-removed, invalidated, or now-out-of-window deployment leaves no stale charge.
+
+ The prune predicate is ``updated_at < run_started`` rather than "not in the charge
+ set I computed", which matters under concurrency: whether a row is garbage becomes a
+ property of the row instead of one run's in-memory config snapshot, so a run can
+ never delete a row a concurrent run just wrote. It is still skipped when any charge
+ failed to write, since a row whose replacement never landed would look unrefreshed.
+ """
+ day: Final = target_date or (datetime.now(timezone.utc).date() - timedelta(days=1))
+
+ if prisma_client is None:
+ verbose_proxy_logger.warning("PTU rollup: prisma_client is None, skipping")
+ return RollupResult(day=day, models_processed=0, rows_written=0)
+
+ date_str: Final = day.isoformat()
+ run_started: Final = datetime.now(timezone.utc)
+
+ ptu_models: Final = await _load_ptu_models(prisma_client)
+ charges: Final = _aggregate_charges(ptu_models, day)
+
+ landed: Final = tuple(
+ [await _upsert_charge_with_retry(prisma_client, charge=charge, date_str=date_str) for charge in charges]
+ )
+ rows_written: Final = sum(landed)
+ rows_failed: Final = len(charges) - rows_written
+
+ if not may_prune:
+ verbose_proxy_logger.info(
+ "PTU rollup for %s: ran without the cross-pod lock, skipping the prune so a "
+ "concurrent pod's charges cannot be swept by this run's cutoff",
+ date_str,
+ )
+ elif rows_failed:
+ # A charge that never landed leaves its row looking unrefreshed, so the prune
+ # would delete the very row the failed write was meant to replace
+ verbose_proxy_logger.warning(
+ "PTU rollup: %d charge(s) failed for %s, skipping the prune so a row whose "
+ "replacement did not land is not deleted; rerun that date to reconcile",
+ rows_failed,
+ date_str,
+ )
+ else:
+ await _prune_unrefreshed_sentinel_rows(prisma_client, date_str=date_str, run_started=run_started)
+
+ verbose_proxy_logger.info(
+ "PTU rollup for %s: %d PTU models processed, %d rows written, %d rows failed",
+ date_str,
+ len(ptu_models),
+ rows_written,
+ rows_failed,
+ )
+ return RollupResult(
+ day=day,
+ models_processed=len(ptu_models),
+ rows_written=rows_written,
+ rows_failed=rows_failed,
+ )
+
+
+def _backfill_window(ptu_models: tuple[PTUModel, ...], end: date) -> tuple[date, ...]:
+ """The UTC days the catch-up pass considers, oldest first, through ``end`` inclusive.
+
+ Starts at the earliest declared ``ptu_effective_from``, floored at
+ ``PTU_ROLLUP_MAX_BACKFILL_DAYS`` before ``end``. A start is required alongside the
+ count and rate, so a deployment without one is not priced rather than being given the
+ floor, which would bill it for the whole cap window. Empty when there is no PTU
+ config, or when every declared window opens after ``end``.
+ """
+ floor: Final = end - timedelta(days=PTU_ROLLUP_MAX_BACKFILL_DAYS)
+ starts: Final = tuple(model.effective_from.date() for model in ptu_models if model.effective_from)
+ if not starts:
+ return ()
+ start: Final = max(min(starts), floor)
+ return tuple(start + timedelta(days=offset) for offset in range((end - start).days + 1))
+
+
+async def _existing_sentinel_keys(
+ prisma_client: "PrismaClient",
+ *,
+ start: date,
+ end: date,
+) -> frozenset[tuple[str, str, str]]:
+ """``(team_id, deployment id, date)`` of every PTU sentinel row within ``[start, end]``.
+
+ The row's ``model`` column holds the deployment id, so this is an exact identity and
+ survives a rename. Nothing here reads the display name.
+ """
+ date_range: Final = {"gte": start.isoformat(), "lte": end.isoformat()} # mutable-ok: prisma range filter
+ rows: Final = await prisma_client.db.litellm_dailyteamspend.find_many(
+ where={"api_key": PTU_SENTINEL_API_KEY, "date": date_range} # mutable-ok: prisma find filter
+ )
+ return frozenset(
+ (
+ str(getattr(row, "team_id", "") or ""),
+ str(getattr(row, "model", "") or ""),
+ str(getattr(row, "date", "") or ""),
+ )
+ for row in rows
+ )
+
+
+async def run_ptu_flat_cost_backfill(
+ prisma_client: "PrismaClient",
+ today: date | None = None,
+) -> BackfillResult:
+ """Price the elapsed days of every PTU window that carry no sentinel row yet.
+
+ Writes only the charges that are missing and never rewrites or deletes an existing
+ row, so a day already priced keeps the amount it was billed, whatever the config says
+ now. A day counts as priced when a sentinel row exists for that deployment id, so
+ renaming a deployment neither re-prices its history nor files a second charge beside
+ the row already there. Zero-cost days write nothing, which leaves a day
+ outside a window reconsidered on each run rather than recorded as done.
+
+ It deletes nothing. Removing a deployment stops it accruing new charges and leaves the
+ days it was billed for standing, since those days were incurred.
+ """
+ end: Final = (today or datetime.now(timezone.utc).date()) - timedelta(days=1)
+
+ if not prisma_client:
+ verbose_proxy_logger.warning("PTU backfill: prisma_client is None, skipping")
+ return BackfillResult(start=end, end=end, days_scanned=0, rows_written=0)
+
+ ptu_models: Final = await _load_ptu_models(prisma_client)
+ days: Final = _backfill_window(ptu_models, end)
+
+ if not days:
+ return BackfillResult(start=end, end=end, days_scanned=0, rows_written=0)
+
+ priced: Final = await _existing_sentinel_keys(prisma_client, start=days[0], end=days[-1])
+ missing: Final = tuple(
+ (day.isoformat(), charge)
+ for day in days
+ for charge in _aggregate_charges(ptu_models, day)
+ if (charge.team_id, charge.model_id, day.isoformat()) not in priced
+ )
+ if not missing:
+ return BackfillResult(start=days[0], end=days[-1], days_scanned=len(days), rows_written=0)
+
+ landed: Final = tuple(
+ [
+ await _upsert_charge_with_retry(prisma_client, charge=charge, date_str=date_str)
+ for date_str, charge in missing
+ ]
+ )
+ rows_written: Final = sum(landed)
+ verbose_proxy_logger.info(
+ "PTU backfill for %s to %s: %d unpriced charge(s) found, %d written, %d failed",
+ days[0].isoformat(),
+ days[-1].isoformat(),
+ len(missing),
+ rows_written,
+ len(missing) - rows_written,
+ )
+ return BackfillResult(
+ start=days[0],
+ end=days[-1],
+ days_scanned=len(days),
+ rows_written=rows_written,
+ rows_failed=len(missing) - rows_written,
+ )
+
+
+async def run_scheduled_ptu_rollup(
+ prisma_client: "PrismaClient",
+ pod_lock_manager: "PodLockManager | None" = None,
+ target_date: date | None = None,
+ alert: Callable[[str], Awaitable[None]] | None = None,
+) -> RollupResult | None:
+ """Run the daily rollup under a cross-pod lock so only one proxy reconciles a day.
+
+ Every proxy process schedules this cron, and the read-charge-prune sequence is not
+ atomic: two pods reading different config snapshots can have the loser's prune delete
+ a row the winner just wrote. Returns None when another pod holds the lock, since that
+ pod is doing the work. A deployment without a Redis-backed lock manager runs
+ unguarded, as ``SpendLogCleanup`` does, and so does a run that cannot reach Redis at
+ all: the lock exists to avoid duplicate work, so no lock problem may cost a day.
+
+ The lease is a fixed TTL with no renewal, so a long scan can outlive it. That costs
+ duplicate work rather than correctness: the upserts are idempotent on the sentinel
+ key and the prune reads only the row's own timestamp, so a second pod arriving
+ mid-run cannot corrupt the day.
+ """
+ if pod_lock_manager is None or pod_lock_manager.redis_cache is None:
+ return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False)
+
+ if not await pod_lock_manager.acquire_lock(cronjob_id=PTU_ROLLUP_JOB_ID, ttl=PTU_ROLLUP_LOCK_TTL_SECONDS):
+ if await _lock_is_held(pod_lock_manager):
+ verbose_proxy_logger.info("PTU rollup: another pod holds the rollup lock, skipping this run")
+ return None
+ # acquire_lock reports contention and a Redis outage the same way, so an
+ # unreachable Redis would otherwise skip the day on every pod at once. The
+ # reconcile is safe to run concurrently, so losing the lock costs duplicate
+ # work; losing the day costs a team's charges
+ verbose_proxy_logger.warning(
+ "PTU rollup: could not take the rollup lock and no other pod holds it, "
+ "running unguarded rather than skipping the day"
+ )
+ return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=False)
+
+ try:
+ return await _run_and_alert(prisma_client, target_date=target_date, alert=alert, may_prune=True)
+ finally:
+ await pod_lock_manager.release_lock(cronjob_id=PTU_ROLLUP_JOB_ID)
+
+
+async def _lock_is_held(pod_lock_manager: "PodLockManager") -> bool:
+ """True only when the rollup lock is readable and someone is holding it.
+
+ A Redis that cannot be read is reported as "not held" so the caller runs the day
+ rather than skipping it; the cost of being wrong here is a duplicate reconcile.
+ """
+ try:
+ lock_key: Final = pod_lock_manager.get_redis_lock_key(PTU_ROLLUP_JOB_ID)
+ return bool(await pod_lock_manager.redis_cache.async_get_cache(lock_key))
+ except Exception as exc: # noqa: BLE001 # an unreadable lock must not skip the day
+ verbose_proxy_logger.warning("PTU rollup: could not read the rollup lock: %s", exc)
+ return False
+
+
+async def _run_and_alert(
+ prisma_client: "PrismaClient",
+ *,
+ target_date: date | None,
+ alert: "Callable[[str], Awaitable[None]] | None",
+ may_prune: bool = True,
+) -> RollupResult:
+ """Reconcile the day, catch up any days left unpriced, and alert on charges that did not land.
+
+ A charge that exhausts its retries leaves that team showing no PTU cost for the date,
+ and the scheduled job moves on to the next day rather than replaying it. That is a
+ silent underbill unless someone is reading proxy logs, so it is escalated to whatever
+ alerting the deployment has configured.
+
+ The catch-up pass runs only on the scheduled shape, where ``target_date`` is None. An
+ explicit date means reconcile exactly that day, so it stays a single-day operation.
+ Its failure is contained: the day's own result is returned either way.
+ """
+ result: Final = await run_ptu_flat_cost_rollup(prisma_client, target_date=target_date, may_prune=may_prune)
+ if result.rows_failed:
+ await _deliver_alert(
+ alert,
+ f"PTU flat-cost rollup for {result.day.isoformat()}: {result.rows_failed} of "
+ f"{result.rows_written + result.rows_failed} team charges failed to write. Those teams show no PTU "
+ f"cost for that date until the rollup is rerun for it.",
+ )
+ if target_date is None:
+ await _backfill_and_alert(prisma_client, alert=alert)
+ return result
+
+
+async def _backfill_and_alert(
+ prisma_client: "PrismaClient",
+ *,
+ alert: "Callable[[str], Awaitable[None]] | None",
+) -> None:
+ """Catch up unpriced PTU days, alerting on charges that did not land.
+
+ Never raises: the day's own rollup has already run and its result must reach the
+ caller whatever the catch-up pass does.
+ """
+ try:
+ backfill: Final = await run_ptu_flat_cost_backfill(prisma_client)
+ except Exception as exc: # noqa: BLE001 # the catch-up pass must not fail the day's rollup
+ verbose_proxy_logger.error("PTU backfill: catch-up pass failed, the day's rollup still stands: %s", exc)
+ return
+ if backfill.rows_failed:
+ await _deliver_alert(
+ alert,
+ f"PTU flat-cost backfill for {backfill.start.isoformat()} to {backfill.end.isoformat()}: "
+ f"{backfill.rows_failed} of {backfill.rows_written + backfill.rows_failed} previously unpriced charges "
+ f"failed to write. Those days stay unpriced until a later run picks them up.",
+ )
+
+
+async def _deliver_alert(alert: "Callable[[str], Awaitable[None]] | None", message: str) -> None:
+ """Send an operator alert when one is configured, swallowing a broken channel."""
+ if alert is None:
+ return
+ try:
+ await alert(message)
+ except Exception as exc: # noqa: BLE001 # a broken alert channel must not fail the rollup
+ verbose_proxy_logger.error("PTU rollup: could not deliver the failed-charge alert: %s", exc)
+
+
+async def _prune_unrefreshed_sentinel_rows(
+ prisma_client: "PrismaClient",
+ *,
+ date_str: str,
+ run_started: datetime,
+) -> None:
+ """Delete the day's PTU sentinel rows this run did not refresh.
+
+ Every charge the run wrote bumps ``updated_at`` past ``run_started``, so anything
+ left below that mark is a (team, model) the current config no longer prices. The mark
+ is pulled back by ``PTU_PRUNE_SKEW_GRACE_SECONDS`` because the two timestamps come
+ from different hosts: a stale row is hours old, a concurrently written one is seconds
+ old, and the grace separates them without waiting on clocks agreeing. The
+ predicate reads only the row, never the caller's config snapshot, which is what
+ makes it safe to run twice, out of order, or beside another pod: a row written
+ after this run began is out of reach of its delete. Mirrors the retention predicate
+ ``SpendLogCleanup`` deletes by."""
+ cutoff: Final = run_started - timedelta(seconds=PTU_PRUNE_SKEW_GRACE_SECONDS)
+ await prisma_client.db.litellm_dailyteamspend.delete_many(
+ where={ # mutable-ok: prisma delete filter
+ "date": date_str,
+ "api_key": PTU_SENTINEL_API_KEY,
+ "updated_at": {"lt": cutoff}, # mutable-ok: prisma comparison filter
+ }
+ )
+
+
+__all__ = (
+ "PTU_ROLLUP_JOB_ID",
+ "PTU_SENTINEL_API_KEY",
+ "BackfillResult",
+ "PTUModel",
+ "RollupResult",
+ "run_ptu_flat_cost_backfill",
+ "run_ptu_flat_cost_rollup",
+ "run_scheduled_ptu_rollup",
+)
diff --git a/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py
new file mode 100644
index 00000000000..261e3f4ef76
--- /dev/null
+++ b/tests/test_litellm/proxy/spend_tracking/test_ptu_flat_cost_rollup.py
@@ -0,0 +1,1481 @@
+"""Tests for the per-model PTU flat-cost daily rollup."""
+
+import types
+from datetime import date, datetime, timedelta, timezone
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+import litellm.proxy.spend_tracking.ptu_flat_cost_rollup as ptu_rollup
+from litellm.constants import PTU_ROLLUP_MAX_BACKFILL_DAYS, PTU_SENTINEL_API_KEY
+from litellm.types.router import ModelInfo
+from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import (
+ PTUModel,
+ _active_hours_on_day,
+ _compute_daily_flat_cost,
+ _parse_ptu_model,
+ run_ptu_flat_cost_backfill,
+ run_ptu_flat_cost_rollup,
+ run_scheduled_ptu_rollup,
+)
+
+DAY = date(2026, 7, 30)
+TODAY = date(2026, 7, 31)
+
+
+# The endpoints require ptu_effective_from alongside the count and rate, so a fixture that
+# omits it would exercise a shape the write path cannot produce. Tests about the start
+# itself pass with_start=False.
+_DEFAULT_PTU_START = "2020-01-01T00:00:00Z"
+
+
+_VALID_PTU = {"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+
+
+def _model_row(model_id="m1", model_name="gpt-4o-mini-ptu", model_info=None, with_start=True):
+ row = MagicMock()
+ row.model_id = model_id
+ row.model_name = model_name
+ if (
+ with_start
+ and isinstance(model_info, dict)
+ and model_info.get("ptu_count") is not None
+ and model_info.get("cost_per_ptu_per_hour") is not None
+ and "ptu_effective_from" not in model_info
+ ):
+ model_info = {**model_info, "ptu_effective_from": _DEFAULT_PTU_START}
+ row.model_info = model_info
+ return row
+
+
+def _model(**overrides):
+ base = dict(model_id="m", model_name="x", team_id="t", ptu_count=5, cost_per_ptu_per_hour=2.0)
+ base.update(overrides)
+ return PTUModel(**base)
+
+
+def test_full_day_when_no_window():
+ # 5 PTU * $2.00/hr * 24h = $240
+ assert _compute_daily_flat_cost(_model(), DAY) == pytest.approx(240.0)
+
+
+def test_window_opening_at_2300_charges_one_hour():
+ m = _model(effective_from=datetime(2026, 7, 30, 23, 0, tzinfo=timezone.utc))
+ assert _active_hours_on_day(m, DAY) == pytest.approx(1.0)
+ # 5 * 2.0 * 1 = 10
+ assert _compute_daily_flat_cost(m, DAY) == pytest.approx(10.0)
+
+
+def test_window_closing_at_0600_charges_six_hours():
+ m = _model(effective_to=datetime(2026, 7, 30, 6, 0, tzinfo=timezone.utc))
+ assert _active_hours_on_day(m, DAY) == pytest.approx(6.0)
+ assert _compute_daily_flat_cost(m, DAY) == pytest.approx(60.0)
+
+
+def test_window_fully_covering_day_charges_24h():
+ m = _model(
+ effective_from=datetime(2026, 7, 1, tzinfo=timezone.utc),
+ effective_to=datetime(2026, 8, 1, tzinfo=timezone.utc),
+ )
+ assert _active_hours_on_day(m, DAY) == pytest.approx(24.0)
+
+
+def test_window_before_day_charges_zero():
+ m = _model(effective_to=datetime(2026, 7, 29, 12, 0, tzinfo=timezone.utc))
+ assert _active_hours_on_day(m, DAY) == 0.0
+ assert _compute_daily_flat_cost(m, DAY) == 0.0
+
+
+def test_window_after_day_charges_zero():
+ m = _model(effective_from=datetime(2026, 7, 31, 1, 0, tzinfo=timezone.utc))
+ assert _active_hours_on_day(m, DAY) == 0.0
+
+
+def test_naive_effective_from_is_treated_as_utc():
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_info={
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": "2026-07-30T23:00:00",
+ }
+ )
+ )
+ assert parsed is not None
+ assert _active_hours_on_day(parsed, DAY) == pytest.approx(1.0)
+
+
+def test_effective_from_with_z_suffix_parses():
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_info={
+ "ptu_count": 1,
+ "cost_per_ptu_per_hour": 1.0,
+ "team_id": "t",
+ "ptu_effective_from": "2026-07-30T18:00:00Z",
+ }
+ )
+ )
+ assert parsed is not None
+ assert _active_hours_on_day(parsed, DAY) == pytest.approx(6.0)
+
+
+ "model_info",
+ [
+ None,
+ {},
+ {"ptu_count": 5},
+ {"cost_per_ptu_per_hour": 2.0},
+ {"ptu_count": 5, "cost_per_ptu_per_hour": 2.0}, # missing team_id
+ {"ptu_count": 0, "cost_per_ptu_per_hour": 2.0, "team_id": "t"},
+ {"ptu_count": 5, "cost_per_ptu_per_hour": -1.0, "team_id": "t"},
+ {"ptu_count": "not-int", "cost_per_ptu_per_hour": 2.0, "team_id": "t"},
+ ],
+)
+def test_parse_ptu_model_rejects_invalid(model_info):
+ assert _parse_ptu_model(_model_row(model_info=model_info)) is None
+
+
[email protected](autouse=True)
+def _no_retry_backoff(monkeypatch):
+ """Keep the upsert retry backoff out of the test runtime."""
+ monkeypatch.setattr(ptu_rollup, "_UPSERT_RETRY_BACKOFF_SECONDS", 0)
+
+
+def _sentinel_row(row_id, team_id, model):
+ row = MagicMock()
+ row.id = row_id
+ row.team_id = team_id
+ row.model = model
+ return row
+
+
+def _prisma_with_models(rows, existing_sentinel_rows=()):
+ prisma = MagicMock()
+ model_table = MagicMock()
+ model_table.find_many = AsyncMock(return_value=rows)
+ daily = MagicMock()
+ daily.find_many = AsyncMock(return_value=list(existing_sentinel_rows))
+ daily.upsert = AsyncMock()
+ daily.delete_many = AsyncMock()
+ prisma.db = types.SimpleNamespace(litellm_proxymodeltable=model_table, litellm_dailyteamspend=daily)
+ return prisma, daily
+
+
+async def test_rollup_writes_sentinel_row_with_hourly_cost():
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "team_x"})]
+ prisma, table = _prisma_with_models(rows)
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.models_processed == 1
+ assert result.rows_written == 1
+ created = table.upsert.await_args.kwargs["data"]["create"]
+ assert created["api_key"] == PTU_SENTINEL_API_KEY
+ assert created["ptu_flat_cost"] == pytest.approx(240.0)
+ assert created["team_id"] == "team_x"
+ # identity in the key, display beside it, so a rename cannot move the row
+ assert created["model"] == "m1"
+ assert created["model_group"] == "gpt-4o-mini-ptu"
+ keyed = table.upsert.await_args.kwargs["where"][
+ "team_id_date_api_key_model_custom_llm_provider_mcp_namespaced_tool_name_endpoint"
+ ]
+ assert keyed["model"] == "m1"
+
+
+async def test_rollup_prunes_stale_row_when_config_is_gone():
+ prisma, table = _prisma_with_models(
+ [_model_row(model_info={"team_id": "team_x"})],
+ existing_sentinel_rows=[_sentinel_row("stale-1", "team_x", "gpt-4o-mini-ptu")],
+ )
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_written == 0
+ table.upsert.assert_not_awaited()
+ table.delete_many.assert_awaited_once()
+ where = table.delete_many.await_args.kwargs["where"]
+ assert where["date"] == DAY.isoformat()
+ assert where["api_key"] == PTU_SENTINEL_API_KEY
+ # the row is garbage because this run did not refresh it, not because of a key list
+ assert "lt" in where["updated_at"]
+
+
+async def test_rollup_writes_current_row_before_pruning_and_keeps_it():
+ prisma, table = _prisma_with_models(
+ [_model_row(model_id="ptu", model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "team_x"})],
+ existing_sentinel_rows=[
+ _sentinel_row("live", "team_x", "gpt-4o-mini-ptu"),
+ _sentinel_row("stale", "team_x", "removed-model"),
+ ],
+ )
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_written == 1
+ table.upsert.assert_awaited_once()
+ # the upsert lands before the cutoff is applied, so the refreshed row is out of reach
+ upsert_order = table.method_calls.index(("upsert", (), table.upsert.call_args.kwargs))
+ assert upsert_order < [c[0] for c in table.method_calls].index("delete_many")
+
+
+async def test_two_deployments_sharing_a_name_get_a_row_each():
+ """Keyed on the deployment id they no longer need collapsing, and each keeps its own
+ amount. The read path merges them back under the shared display name."""
+ rows = [
+ _model_row(model_id="dep-b", model_info={"ptu_count": 2, "cost_per_ptu_per_hour": 1.0, "team_id": "team_x"}),
+ _model_row(model_id="dep-a", model_info={"ptu_count": 3, "cost_per_ptu_per_hour": 1.0, "team_id": "team_x"}),
+ ]
+ prisma, table = _prisma_with_models(rows)
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_written == 2
+ written = {c.kwargs["data"]["create"]["model"]: c.kwargs["data"]["create"] for c in table.upsert.await_args_list}
+ assert set(written) == {"dep-a", "dep-b"}
+ assert written["dep-a"]["ptu_flat_cost"] == pytest.approx(72.0)
+ assert written["dep-b"]["ptu_flat_cost"] == pytest.approx(48.0)
+ assert {row["model_group"] for row in written.values()} == {"gpt-4o-mini-ptu"}
+
+
+async def test_rollup_skips_zero_active_hours():
+ rows = [
+ _model_row(
+ model_info={
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "team_x",
+ "ptu_effective_from": "2026-08-01T00:00:00Z",
+ }
+ )
+ ]
+ prisma, table = _prisma_with_models(rows)
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.models_processed == 1
+ assert result.rows_written == 0
+ table.upsert.assert_not_awaited()
+
+
+async def test_rollup_skips_models_without_ptu_config():
+ rows = [
+ _model_row(model_id="plain", model_info={"team_id": "team_x"}),
+ _model_row(model_id="ptu", model_info={"ptu_count": 3, "cost_per_ptu_per_hour": 1.0, "team_id": "team_y"}),
+ ]
+ prisma, table = _prisma_with_models(rows)
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.models_processed == 1
+ assert result.rows_written == 1
+
+
+def test_parse_ptu_model_skips_a_deployment_with_no_effective_start():
+ """The endpoints require a start. A row without one predates that rule or was written
+ around them, and inferring a start would bill days the deployment did not exist: before
+ this, a windowless deployment accrued the whole cap window on its first run."""
+ assert (
+ _parse_ptu_model(
+ _model_row(
+ model_info={"ptu_count": 10, "cost_per_ptu_per_hour": 2.0, "team_id": "t"},
+ with_start=False,
+ )
+ )
+ is None
+ )
+
+
+def test_parse_ptu_model_accepts_json_string_model_info():
+ # Some query paths deliver model_info as a JSON string, not a dict.
+ import json as _json
+
+ raw = _json.dumps(
+ {
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "team_x",
+ "ptu_effective_from": _DEFAULT_PTU_START,
+ }
+ )
+ parsed = _parse_ptu_model(_model_row(model_info=raw))
+ assert parsed is not None
+ assert parsed.ptu_count == 5 and parsed.team_id == "team_x"
+
+
+def test_parse_ptu_model_rejects_unparseable_string():
+ assert _parse_ptu_model(_model_row(model_info="not-json")) is None
+
+
+def test_parse_ptu_model_accepts_datetime_object_effective_from():
+ # model_info can carry a real datetime object, not just an ISO string.
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_info={
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "ptu_effective_from": datetime(2026, 7, 30, 23, 0, tzinfo=timezone.utc),
+ }
+ )
+ )
+ assert parsed is not None
+ assert _active_hours_on_day(parsed, DAY) == pytest.approx(1.0)
+
+
+ "bounds",
+ [
+ {"ptu_effective_from": "not-a-date"},
+ {"ptu_effective_to": 12345},
+ {"ptu_effective_from": "not-a-date", "ptu_effective_to": 12345},
+ ],
+)
+def test_parse_ptu_model_rejects_malformed_effective_dates(bounds):
+ # Treating an unparseable bound as "no bound" would widen the window to the whole
+ # day and overcharge, so the deployment is skipped until the config is fixed.
+ parsed = _parse_ptu_model(
+ _model_row(model_info={"ptu_count": 2, "cost_per_ptu_per_hour": 1.0, "team_id": "t", **bounds})
+ )
+ assert parsed is None
+
+
+def test_parse_ptu_model_rejects_an_inverted_window():
+ # An end at or before the start can only mean a broken config; charging it as an
+ # open-ended window would bill a full day.
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_info={
+ "ptu_count": 2,
+ "cost_per_ptu_per_hour": 1.0,
+ "team_id": "t",
+ "ptu_effective_from": "2026-07-31T12:00:00Z",
+ "ptu_effective_to": "2026-07-31T06:00:00Z",
+ }
+ )
+ )
+ assert parsed is None
+
+
+async def test_rollup_returns_empty_when_prisma_client_is_none():
+ result = await run_ptu_flat_cost_rollup(None, target_date=DAY)
+ assert result.models_processed == 0
+ assert result.rows_written == 0
+ assert result.day == DAY
+
+
+async def test_rollup_continues_after_a_failed_upsert():
+ rows = [
+ _model_row(model_id="a", model_info={"ptu_count": 1, "cost_per_ptu_per_hour": 1.0, "team_id": "team_a"}),
+ _model_row(model_id="b", model_info={"ptu_count": 2, "cost_per_ptu_per_hour": 1.0, "team_id": "team_b"}),
+ ]
+ prisma, table = _prisma_with_models(rows)
+ table.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ # both models exhausted their retries, and the batch still ran to completion
+ assert result.models_processed == 2
+ assert result.rows_written == 0
+ assert result.rows_failed == 2
+ assert table.upsert.await_count == 2 * ptu_rollup._UPSERT_ATTEMPTS
+
+
+async def test_rollup_retries_a_transient_upsert_failure_and_succeeds():
+ rows = [_model_row(model_info={"ptu_count": 1, "cost_per_ptu_per_hour": 1.0, "team_id": "team_a"})]
+ prisma, table = _prisma_with_models(rows)
+ table.upsert = AsyncMock(side_effect=[RuntimeError("connection reset"), None])
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ # the retry writes the day's charge, so nothing is left for a manual rerun
+ assert result.rows_written == 1
+ assert result.rows_failed == 0
+ assert table.upsert.await_count == 2
+
+
+def _pod_lock(acquired):
+ """A lock manager that acquires (or not) and, by default, still owns the lease."""
+ lock = MagicMock()
+ lock.pod_id = "this-pod"
+ lock.redis_cache = MagicMock()
+ lock.redis_cache.async_get_cache = AsyncMock(return_value="this-pod")
+ lock.get_redis_lock_key = MagicMock(return_value="lock-key")
+ lock.acquire_lock = AsyncMock(return_value=acquired)
+ lock.release_lock = AsyncMock()
+ return lock
+
+
+async def test_scheduled_rollup_skips_the_run_when_another_pod_holds_the_lock():
+ rows = [_model_row(model_info={"ptu_count": 1, "cost_per_ptu_per_hour": 1.0, "team_id": "team_a"})]
+ prisma, table = _prisma_with_models(rows)
+ lock = _pod_lock(acquired=False)
+
+ result = await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY)
+
+ # the losing pod must not write or prune, or it could delete the winner's fresh rows
+ assert result is None
+ assert table.upsert.await_count == 0
+ assert table.delete_many.await_count == 0
+ lock.release_lock.assert_not_awaited()
+
+
+async def test_scheduled_rollup_runs_and_releases_the_lock_when_it_wins():
+ rows = [_model_row(model_info={"ptu_count": 1, "cost_per_ptu_per_hour": 1.0, "team_id": "team_a"})]
+ prisma, table = _prisma_with_models(rows)
+ lock = _pod_lock(acquired=True)
+
+ result = await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY)
+
+ assert result is not None and result.rows_written == 1
+ lock.acquire_lock.assert_awaited_once()
+ lock.release_lock.assert_awaited_once()
+
+
+async def test_scheduled_rollup_releases_the_lock_even_when_the_run_raises():
+ prisma, table = _prisma_with_models([])
+ prisma.db.litellm_proxymodeltable.find_many = AsyncMock(side_effect=RuntimeError("db down"))
+ lock = _pod_lock(acquired=True)
+
+ with pytest.raises(RuntimeError):
+ await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY)
+
+ # a stuck lock would block every later run until its TTL expires
+ lock.release_lock.assert_awaited_once()
+
+
+async def test_scheduled_rollup_runs_unguarded_without_a_redis_backed_lock():
+ rows = [_model_row(model_info={"ptu_count": 1, "cost_per_ptu_per_hour": 1.0, "team_id": "team_a"})]
+ prisma, table = _prisma_with_models(rows)
+ lock = _pod_lock(acquired=True)
+ lock.redis_cache = None
+
+ result = await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY)
+
+ # single-writer deployments have no lock to take, and must still reconcile the day
+ assert result is not None and result.rows_written == 1
+ lock.acquire_lock.assert_not_awaited()
+
+ assert await run_scheduled_ptu_rollup(prisma, target_date=DAY) is not None
+
+
+async def test_rollup_skips_the_prune_when_a_replacement_write_failed():
+ # The deployment was renamed, so the old sentinel row is stale only once its
+ # replacement lands. Pruning against the intended charges after a failed write
+ # would delete the old row and leave the team with no charge at all.
+ prisma, table = _prisma_with_models(
+ [
+ _model_row(
+ model_name="renamed-ptu", model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+ )
+ ],
+ existing_sentinel_rows=[_sentinel_row("previous", "t", "old-name-ptu")],
+ )
+ table.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_failed == 1
+ table.delete_many.assert_not_awaited()
+
+
+class _FakeSentinelTable:
+ """In-memory LiteLLM_DailyTeamSpend that honours the sentinel key and prune predicate."""
+
+ def __init__(self, upsert_gate=None):
+ self.rows = {}
+ self._upsert_gate = upsert_gate
+ self.upsert_keys = []
+ self.delete_many_calls = []
+ self.find_many_calls = []
+
+ async def upsert(self, where, data):
+ if self._upsert_gate is not None:
+ await self._upsert_gate.wait()
+ key = where["team_id_date_api_key_model_custom_llm_provider_mcp_namespaced_tool_name_endpoint"]
+ row_key = (key["team_id"], key["date"], key["api_key"], key["model"])
+ self.upsert_keys.append(row_key)
+ self.rows[row_key] = {
+ "ptu_flat_cost": data["create"]["ptu_flat_cost"],
+ "model_group": data["create"]["model_group"],
+ "updated_at": datetime.now(timezone.utc),
+ }
+
+ async def delete_many(self, where):
+ self.delete_many_calls.append(where)
+ cutoff = where["updated_at"]["lt"]
+ doomed = [
+ k
+ for k, v in self.rows.items()
+ if k[1] == where["date"] and k[2] == where["api_key"] and v["updated_at"] < cutoff
+ ]
+ for k in doomed:
+ del self.rows[k]
+
+ async def find_many(self, where=None):
+ """Read back sentinel rows the way prisma would, honouring api_key and a date range."""
+ self.find_many_calls.append(where)
+ if not where or where.get("api_key") != PTU_SENTINEL_API_KEY:
+ return []
+ bounds = where.get("date") or {}
+ return [
+ _stored_sentinel_row(team_id, day, model_id, value.get("model_group"))
+ for (team_id, day, api_key, model_id), value in self.rows.items()
+ if api_key == PTU_SENTINEL_API_KEY and (not bounds or bounds["gte"] <= day <= bounds["lte"])
+ ]
+
+ def seed(self, team_id, day, model_id, flat_cost, updated_at=None, model_group=None):
+ """Seed a row the way the rollup writes one: keyed on the deployment id."""
+ self.rows[(team_id, day.isoformat(), PTU_SENTINEL_API_KEY, model_id)] = {
+ "ptu_flat_cost": flat_cost,
+ "model_group": model_group or model_id,
+ "updated_at": updated_at or datetime.now(timezone.utc),
+ }
+
+
+def _stored_sentinel_row(team_id, day, model_id, model_group=None):
+ row = MagicMock()
+ row.team_id = team_id
+ row.date = day
+ row.model = model_id
+ row.model_group = model_group
+ return row
+
+
+def _prisma_for(model_rows, daily_table):
+ prisma = MagicMock()
+ model_table = MagicMock()
+ model_table.find_many = AsyncMock(return_value=model_rows)
+ prisma.db = types.SimpleNamespace(litellm_proxymodeltable=model_table, litellm_dailyteamspend=daily_table)
+ return prisma
+
+
+async def test_an_older_run_cannot_delete_a_newer_runs_row():
+ """The race the absolute predicate exists for: an admin renames a PTU model while two
+ pods are mid-rollup, so each pod prices a different model name. The pod that started
+ first must not be able to delete the charge the second pod just wrote."""
+ import asyncio
+
+ gate = asyncio.Event()
+ table = _FakeSentinelTable()
+ ptu = {"ptu_count": 10, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+
+ # pod A read the config before the second deployment appeared and is stalled mid-upsert
+ slow_table = _FakeSentinelTable(upsert_gate=gate)
+ slow_table.rows = table.rows
+ pod_a = asyncio.create_task(
+ run_ptu_flat_cost_rollup(
+ _prisma_for([_model_row(model_id="dep-a", model_info=ptu)], slow_table), target_date=DAY
+ )
+ )
+ await asyncio.sleep(0) # let pod A capture run_started and reach the gate
+
+ # pod B read a config that has since replaced it, and completes first
+ await run_ptu_flat_cost_rollup(_prisma_for([_model_row(model_id="dep-b", model_info=ptu)], table), target_date=DAY)
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-b") in table.rows
+
+ gate.set()
+ await pod_a
+
+ # pod A's cutoff predates every row written during the race, so its delete reaches none
+ assert table.rows[("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-b")]["ptu_flat_cost"] == pytest.approx(480.0)
+
+
+async def test_a_later_clean_run_clears_the_row_the_race_left_behind():
+ """The race can leave a charge for a since-removed deployment in place for a day; the
+ next run, seeing only the current config, must sweep it."""
+ table = _FakeSentinelTable()
+ ptu = {"ptu_count": 10, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+ stale_key = ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-removed")
+ table.rows[stale_key] = {
+ "ptu_flat_cost": 480.0,
+ "model_group": "retired",
+ "updated_at": datetime(2020, 1, 1, tzinfo=timezone.utc),
+ }
+
+ await run_ptu_flat_cost_rollup(
+ _prisma_for([_model_row(model_id="dep-live", model_info=ptu)], table), target_date=DAY
+ )
+
+ assert stale_key not in table.rows
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-live") in table.rows
+
+
+async def test_scheduled_rollup_alerts_when_a_team_charge_never_landed():
+ """A failed charge is a silent underbill: the team shows no PTU cost for the date and
+ the next cron run moves on to the next day. It has to reach an operator."""
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
+ prisma, table = _prisma_with_models(rows)
+ table.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+ alert = AsyncMock()
+
+ result = await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ assert result.rows_failed == 1
+ alert.assert_awaited_once()
+ message = alert.await_args.args[0]
+ assert DAY.isoformat() in message
+ assert "rerun" in message
+
+
+async def test_scheduled_rollup_stays_quiet_when_every_charge_landed():
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
+ prisma, table = _prisma_with_models(rows)
+ alert = AsyncMock()
+
+ result = await run_scheduled_ptu_rollup(prisma, target_date=DAY, alert=alert)
+
+ assert result.rows_failed == 0
+ alert.assert_not_awaited()
+
+
+async def test_a_broken_alert_channel_does_not_fail_the_rollup():
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
+ prisma, table = _prisma_with_models(rows)
+ table.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+
+ result = await run_scheduled_ptu_rollup(
+ prisma, target_date=DAY, alert=AsyncMock(side_effect=RuntimeError("slack down"))
+ )
+
+ # losing the alert must not also lose the run's result or leave the lock held
+ assert result.rows_failed == 1
+
+
+async def test_scheduled_rollup_alerts_from_under_the_pod_lock_too():
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
+ prisma, table = _prisma_with_models(rows)
+ table.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+ lock = _pod_lock(acquired=True)
+ alert = AsyncMock()
+
+ await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY, alert=alert)
+
+ alert.assert_awaited_once()
+ lock.release_lock.assert_awaited_once()
+
+
+ "lock_read",
+ [
+ pytest.param(AsyncMock(side_effect=RuntimeError("redis down")), id="redis-unreachable"),
+ pytest.param(AsyncMock(return_value=None), id="lock-key-missing"),
+ ],
+)
+async def test_scheduled_rollup_runs_the_day_when_the_lock_is_unavailable_but_unheld(lock_read):
+ """acquire_lock reports contention and a Redis outage identically. Treating both as
+ "someone else has it" would skip the day on every pod at once, losing every team's
+ charge for that date; the reconcile is safe to run twice, so the day wins."""
+ rows = [_model_row(model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})]
+ prisma, table = _prisma_with_models(rows)
+ lock = _pod_lock(acquired=False)
+ lock.redis_cache.async_get_cache = lock_read
+
+ result = await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock, target_date=DAY)
+
+ assert result is not None and result.rows_written == 1
+ table.upsert.assert_awaited_once()
+
+
+def _team_scoped_row(public_name, model_id="m1", team_id="team_x", **ptu):
+ """A deployment as POST /model/new actually stores it: synthetic routing name in
+ model_name, the operator's chosen name in model_info.team_public_model_name."""
+ info = {"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": team_id, **ptu}
+ info["team_public_model_name"] = public_name
+ return _model_row(model_id=model_id, model_name=f"model_name_{team_id}_{model_id}-uuid", model_info=info)
+
+
+def test_parse_ptu_model_keys_on_the_public_name_not_the_routing_key():
+ # PTU requires a team_id, so every PTU deployment carries the synthetic model_name.
+ # Keying the charge on it files the cost under a UUID no usage view can resolve.
+ parsed = _parse_ptu_model(_team_scoped_row("gpt-4o"))
+ assert parsed is not None
+ assert parsed.model_name == "gpt-4o"
+
+
+def test_parse_ptu_model_falls_back_to_model_name_without_a_public_name():
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_name="plain-deployment", model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+ )
+ )
+ assert parsed is not None
+ assert parsed.model_name == "plain-deployment"
+
+
[email protected]("bad_public_name", ["", None, 123, {"nested": "value"}])
+def test_parse_ptu_model_ignores_an_unusable_public_name(bad_public_name):
+ row = _model_row(
+ model_name="routing-key",
+ model_info={
+ "ptu_count": 5,
+ "cost_per_ptu_per_hour": 2.0,
+ "team_id": "t",
+ "team_public_model_name": bad_public_name,
+ },
+ )
+ parsed = _parse_ptu_model(row)
+ assert parsed is not None
+ assert parsed.model_name == "routing-key"
+
+
+async def test_team_scoped_deployments_key_on_their_id_and_display_the_public_name():
+ """A team-scoped deployment's model_name is a synthetic routing key, so the row keys on
+ the stable id and carries the operator-facing name alongside it for display."""
+ rows = [
+ _team_scoped_row("gpt-4o", model_id="dep-b", ptu_count=2, cost_per_ptu_per_hour=1.0),
+ _team_scoped_row("gpt-4o", model_id="dep-a", ptu_count=3, cost_per_ptu_per_hour=1.0),
+ ]
+ prisma, table = _prisma_with_models(rows)
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_written == 2
+ written = {c.kwargs["data"]["create"]["model"]: c.kwargs["data"]["create"] for c in table.upsert.await_args_list}
+ assert set(written) == {"dep-a", "dep-b"}
+ assert {row["model_group"] for row in written.values()} == {"gpt-4o"}
+ assert sum(row["ptu_flat_cost"] for row in written.values()) == pytest.approx(120.0)
+
+
+# ---------------------------------------------------------------------------
+# Catch-up backfill: the days a once-daily "price yesterday" job never revisits
+# ---------------------------------------------------------------------------
+
+
+def _day(offset):
+ """A UTC date relative to DAY, which is the last day the backfill may price."""
+ return DAY + timedelta(days=offset)
+
+
+def _windowed_row(effective_from=None, effective_to=None, **overrides):
+ ptu = {
+ "ptu_count": overrides.pop("ptu_count", 5),
+ "cost_per_ptu_per_hour": overrides.pop("cost_per_ptu_per_hour", 2.0),
+ "team_id": overrides.pop("team_id", "t"),
+ }
+ if effective_from is not None:
+ ptu["ptu_effective_from"] = effective_from.isoformat()
+ if effective_to is not None:
+ ptu["ptu_effective_to"] = effective_to.isoformat()
+ return _model_row(model_info=ptu, **overrides)
+
+
+def _midnight(day):
+ return datetime.combine(day, datetime.min.time(), tzinfo=timezone.utc)
+
+
+def _priced_dates(table):
+ return sorted(key[1] for key in table.rows)
+
+
+# --- R1: the gap is actually closed ----------------------------------------
+
+
+async def test_backfill_prices_every_elapsed_in_window_day():
+ """The defect this exists for: an operator backdates a PTU window by 30 days, the
+ config validates and persists, and the once-daily job prices only yesterday. Every
+ elapsed day inside the declared window has to end up with a charge."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-29)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.days_scanned == 30
+ assert result.rows_written == 30
+ assert result.rows_failed == 0
+ assert _priced_dates(table) == [_day(offset).isoformat() for offset in range(-29, 1)]
+ assert all(row["ptu_flat_cost"] == pytest.approx(240.0) for row in table.rows.values())
+
+
+async def test_backfill_prices_a_day_the_daily_run_missed():
+ """A pod restart across 00:15 loses exactly one day. Only that day may be written."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-2), "m1", 240.0)
+ table.seed("t", _day(0), "m1", 240.0)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-2)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.rows_written == 1
+ assert table.upsert_keys == [("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "m1")]
+
+
+async def test_backfill_prices_the_partial_first_day_by_active_hours():
+ """A backfilled day is priced by the same hourly overlap as a live one, so a window
+ opening at 08:01 charges the remaining 15h59m rather than a whole day."""
+ table = _FakeSentinelTable()
+ opens_at = datetime(_day(-1).year, _day(-1).month, _day(-1).day, 8, 1, tzinfo=timezone.utc)
+ prisma = _prisma_for([_windowed_row(effective_from=opens_at)], table)
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ first_day = table.rows[("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "m1")]
+ assert first_day["ptu_flat_cost"] == pytest.approx(10 * (15 + 59 / 60))
+ assert table.rows[("t", _day(0).isoformat(), PTU_SENTINEL_API_KEY, "m1")]["ptu_flat_cost"] == pytest.approx(240.0)
+
+
+async def test_backfill_stops_at_yesterday():
+ """A day that has not finished cannot be billed, however far into the future the
+ declared window runs."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-2)), effective_to=_midnight(_day(30)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.end == DAY
+ assert max(_priced_dates(table)) == DAY.isoformat()
+
+
+# --- R2: history is never rewritten ----------------------------------------
+
+
+async def test_backfill_leaves_an_existing_row_untouched_when_config_changed():
+ """A priced day keeps the amount it was billed at. Re-pricing it under today's rate
+ would silently restate a closed day, which is worse than the gap being fixed."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-1), "m1", 240.0)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-1)), cost_per_ptu_per_hour=5.0)], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ already_priced = ("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "m1")
+ assert already_priced not in table.upsert_keys
+ assert table.rows[already_priced]["ptu_flat_cost"] == pytest.approx(240.0)
+ assert result.rows_written == 1
+ assert table.rows[("t", _day(0).isoformat(), PTU_SENTINEL_API_KEY, "m1")]["ptu_flat_cost"] == pytest.approx(600.0)
+
+
+def test_parse_skips_a_count_too_large_to_price():
+ """float(ptu_count) on an unbounded int raises OverflowError, which aborted the whole
+ run rather than skipping the one deployment carrying it."""
+ assert _parse_ptu_model(_model_row(model_info={**_VALID_PTU, "ptu_count": 10**400})) is None
+
+
[email protected]("rate", ["NaN", "Infinity", "-Infinity"])
+def test_parse_skips_a_non_finite_rate(rate):
+ """NaN compares False against every bound, so a bare `< 0` check passed it through and
+ the deployment accrued a flat cost of nan."""
+ assert _parse_ptu_model(_model_row(model_info={**_VALID_PTU, "cost_per_ptu_per_hour": rate})) is None
+
+
+def test_parse_still_accepts_config_at_the_bounds():
+ parsed = _parse_ptu_model(
+ _model_row(
+ model_info={
+ **_VALID_PTU,
+ "ptu_count": ModelInfo.MAX_PTU_COUNT,
+ "cost_per_ptu_per_hour": ModelInfo.MAX_COST_PER_PTU_PER_HOUR,
+ }
+ )
+ )
+ assert parsed is not None and parsed.ptu_count == ModelInfo.MAX_PTU_COUNT
+
+
+async def test_a_bad_row_does_not_abort_pricing_for_other_teams():
+ """One unusable deployment must not take the whole day's rollup down with it."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for(
+ [
+ _model_row(model_id="bad", model_info={**_VALID_PTU, "ptu_count": 10**400}),
+ _model_row(model_id="good", model_info=_VALID_PTU),
+ ],
+ table,
+ )
+
+ result = await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert result.rows_written == 1
+ assert result.models_processed == 1
+
+
+async def test_backfill_keeps_the_history_of_a_deployment_that_was_removed():
+ """Deleting a deployment stops it accruing, it does not unbill the days it ran. The
+ backfill deletes nothing, so a closed day survives its deployment."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-1), "dep-gone", 480.0, model_group="gone-model")
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-1)), model_id="dep-live")], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert table.rows[("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "dep-gone")]["ptu_flat_cost"] == 480.0
+ assert table.delete_many_calls == []
+ assert ("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "dep-live") in table.rows
+ assert result.rows_written == 2
+
+
+async def test_backfill_keeps_history_after_every_ptu_deployment_is_gone():
+ """With no PTU config left there is nothing to price, and nothing to delete either."""
+ table = _FakeSentinelTable()
+ for offset in (-2, -1):
+ table.seed("t", _day(offset), "dep-gone", 480.0, model_group="gone-model")
+ prisma = _prisma_for([_model_row(model_info={"base_model": "gpt-4o"})], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert len(table.rows) == 2
+ assert table.delete_many_calls == []
+ assert result.rows_written == 0
+
+
+async def test_backfill_keeps_history_when_a_window_is_narrowed():
+ """Editing an effective window cannot rewrite a bill that was already correct."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-3), "dep-1", 480.0, model_group="ptu-a")
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-1)), model_id="dep-1")], table)
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert ("t", _day(-3).isoformat(), PTU_SENTINEL_API_KEY, "dep-1") in table.rows
+ assert table.delete_many_calls == []
+
+
+async def test_backfill_never_prunes_by_timestamp():
+ """Retirement is by identity. The catch-up must never take the single-day path's
+ timestamp predicate, which needs the lock and agreeing clocks to be safe."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-3), "dep-1", 1.0, updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc))
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-3)), model_id="dep-1")], table)
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert all("updated_at" not in (call or {}) for call in table.delete_many_calls)
+ assert ("t", _day(-3).isoformat(), PTU_SENTINEL_API_KEY, "dep-1") in table.rows
+
+
+# --- R3: a gap is per (team, model, date), not per date ---------------------
+
+
+async def test_backfill_fills_a_second_model_on_a_day_that_already_has_a_row():
+ """A day is not covered just because something was priced on it."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-1), "a", 240.0)
+ prisma = _prisma_for(
+ [
+ _windowed_row(effective_from=_midnight(_day(-1)), model_name="model-a", model_id="a"),
+ _windowed_row(effective_from=_midnight(_day(-1)), model_name="model-b", model_id="b"),
+ ],
+ table,
+ )
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert ("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "b") in table.upsert_keys
+ assert ("t", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "a") not in table.upsert_keys
+
+
+async def test_backfill_fills_a_second_team_on_a_day_that_already_has_a_row():
+ table = _FakeSentinelTable()
+ table.seed("team-1", _day(-1), "a", 240.0)
+ prisma = _prisma_for(
+ [
+ _windowed_row(effective_from=_midnight(_day(-1)), model_name="shared-name", model_id="a", team_id="team-1"),
+ _windowed_row(effective_from=_midnight(_day(-1)), model_name="shared-name", model_id="b", team_id="team-2"),
+ ],
+ table,
+ )
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert ("team-2", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "b") in table.upsert_keys
+ assert ("team-1", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "a") not in table.upsert_keys
+
+
+async def test_backfill_keys_gaps_on_the_public_model_name():
+ """Sentinel rows are written under the public name, so a gap check reading the
+ synthetic routing key would never match one and would rewrite it on every run."""
+ table = _FakeSentinelTable()
+ table.seed("team_x", _day(-1), "m1", 240.0)
+ row = _team_scoped_row(
+ "gpt-4o",
+ ptu_count=5,
+ cost_per_ptu_per_hour=2.0,
+ ptu_effective_from=_midnight(_day(-1)).isoformat(),
+ )
+ prisma = _prisma_for([row], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert ("team_x", _day(-1).isoformat(), PTU_SENTINEL_API_KEY, "m1") not in table.upsert_keys
+ assert result.rows_written == 1
+
+
+# --- R4: bounds and convergence --------------------------------------------
+
+
+async def test_backfill_does_not_scan_before_effective_from():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-2)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.start == _day(-2)
+ assert result.days_scanned == 3
+
+
+async def test_backfill_caps_lookback_for_a_model_with_no_effective_from():
+ """An open-ended window would otherwise scan back to the beginning of the table."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row()], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.start == DAY - timedelta(days=PTU_ROLLUP_MAX_BACKFILL_DAYS)
+ assert result.days_scanned == PTU_ROLLUP_MAX_BACKFILL_DAYS + 1
+
+
+async def test_backfill_caps_lookback_for_a_window_older_than_the_cap():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-400)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.start == DAY - timedelta(days=PTU_ROLLUP_MAX_BACKFILL_DAYS)
+
+
+async def test_backfill_writes_nothing_for_out_of_window_days():
+ """A zero-cost day must write no row, or the gap check would read it as priced."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-2)), effective_to=_midnight(_day(-1)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.days_scanned == 3
+ assert result.rows_written == 1
+ assert _priced_dates(table) == [_day(-2).isoformat()]
+
+
+async def test_backfill_is_a_no_op_on_a_fully_priced_range():
+ table = _FakeSentinelTable()
+ for offset in (-2, -1, 0):
+ table.seed("t", _day(offset), "m1", 240.0)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-2)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.rows_written == 0
+ assert table.upsert_keys == []
+ assert table.delete_many_calls == []
+
+
+async def test_backfill_run_twice_is_idempotent():
+ """The second pass must be free, including leaving updated_at alone."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-3)))], table)
+
+ await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+ snapshot = {key: dict(value) for key, value in table.rows.items()}
+ table.upsert_keys.clear()
+
+ second = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert second.rows_written == 0
+ assert table.upsert_keys == []
+ assert table.rows == snapshot
+
+
+async def test_backfill_does_nothing_without_ptu_config():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_model_row(model_info={"base_model": "gpt-4o"})], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.days_scanned == 0
+ assert result.rows_written == 0
+ assert table.upsert_keys == []
+
+
+async def test_backfill_writes_nothing_for_a_window_that_opens_tomorrow():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(5)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.days_scanned == 0
+ assert table.upsert_keys == []
+
+
+async def test_backfill_returns_empty_when_prisma_client_is_none():
+ result = await run_ptu_flat_cost_backfill(None, today=TODAY)
+
+ assert result.rows_written == 0
+ assert result.days_scanned == 0
+
+
+async def test_backfill_counts_a_charge_that_never_landed():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-1)))], table)
+ prisma.db.litellm_dailyteamspend.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.rows_written == 0
+ assert result.rows_failed == 2
+
+
+# --- R5: interaction with the daily path -----------------------------------
+
+
+async def test_scheduled_rollup_backfills_after_pricing_the_day():
+ """The catch-up pass runs after the day's own rollup, so it sees yesterday already
+ priced and does not write it a second time."""
+ table = _FakeSentinelTable()
+ yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(yesterday - timedelta(days=2)))], table)
+
+ await run_scheduled_ptu_rollup(prisma)
+
+ yesterday_key = ("t", yesterday.isoformat(), PTU_SENTINEL_API_KEY, "m1")
+ assert table.upsert_keys.count(yesterday_key) == 1
+ assert len(table.rows) == 3
+
+
+async def test_scheduled_rollup_with_an_explicit_target_date_does_not_backfill():
+ """An explicit date means reconcile exactly that day, so no catch-up pass runs."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-10)))], table)
+
+ await run_scheduled_ptu_rollup(prisma, target_date=DAY)
+
+ assert _priced_dates(table) == [DAY.isoformat()]
+ assert table.find_many_calls == []
+
+
+async def test_scheduled_rollup_holds_one_lock_across_both_phases():
+ """Backfill running outside the lock would let another pod's prune race its writes."""
+ table = _FakeSentinelTable()
+ yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(yesterday - timedelta(days=3)))], table)
+ rows_at_release = []
+ lock = _pod_lock(acquired=True)
+ lock.release_lock = AsyncMock(side_effect=lambda **kwargs: rows_at_release.append(len(table.rows)))
+
+ await run_scheduled_ptu_rollup(prisma, pod_lock_manager=lock)
+
+ lock.acquire_lock.assert_awaited_once()
+ assert rows_at_release == [4]
+
+
+async def test_a_failing_backfill_does_not_lose_the_days_rollup_result():
+ """The day's rollup has already run and committed; a broken catch-up pass must not
+ swallow its result or raise into the scheduler."""
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row()], table)
+ prisma.db.litellm_dailyteamspend.find_many = AsyncMock(side_effect=RuntimeError("read replica down"))
+
+ result = await run_scheduled_ptu_rollup(prisma)
+
+ assert result is not None
+ assert result.rows_written == 1
+ assert result.rows_failed == 0
+
+
+async def test_scheduled_rollup_alerts_when_a_backfill_charge_never_landed():
+ """An unpriced day that stays unpriced is the silent underbill this work exists to
+ remove, so it has to reach an operator too."""
+ table = _FakeSentinelTable()
+ yesterday = datetime.now(timezone.utc).date() - timedelta(days=1)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(yesterday - timedelta(days=1)))], table)
+ prisma.db.litellm_dailyteamspend.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+ alert = AsyncMock()
+
+ await run_scheduled_ptu_rollup(prisma, alert=alert)
+
+ messages = [call.args[0] for call in alert.await_args_list]
+ assert any("backfill" in message for message in messages)
+ assert any("unpriced" in message for message in messages)
+
+
+async def test_a_broken_alert_channel_does_not_fail_the_backfill():
+ table = _FakeSentinelTable()
+ prisma = _prisma_for([_windowed_row()], table)
+ prisma.db.litellm_dailyteamspend.upsert = AsyncMock(side_effect=RuntimeError("db down"))
+
+ result = await run_scheduled_ptu_rollup(prisma, alert=AsyncMock(side_effect=RuntimeError("slack down")))
+
+ assert result.rows_failed == 1
+
+
+# --- R6: the shape the cron actually calls ---------------------------------
+
+
+async def test_scheduled_rollup_with_no_target_date_closes_a_backdated_window():
+ """The production call shape from proxy_server.py, on the real clock: no target_date,
+ a window backdated 30 days, and every elapsed in-window day has to end up priced with
+ no operator alert raised. Every other rollup test pins target_date, which is exactly
+ why this regression shipped."""
+ table = _FakeSentinelTable()
+ today = datetime.now(timezone.utc).date()
+ opened_on = today - timedelta(days=30)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(opened_on))], table)
+ alert = AsyncMock()
+
+ await run_scheduled_ptu_rollup(prisma, alert=alert)
+
+ expected = [(opened_on + timedelta(days=offset)).isoformat() for offset in range(30)]
+ assert _priced_dates(table) == expected
+ alert.assert_not_awaited()
+
+
+# --- R8: a rename must not re-price history under the new name ----------------
+
+
+async def test_backfill_does_not_double_price_a_day_after_a_rename():
+ """A rename does not move the row, because the key is the deployment id. Every already
+ priced day stays a single charge and only the unpriced day is written."""
+ table = _FakeSentinelTable()
+ for offset in (-2, -1):
+ table.seed("t", _day(offset), "dep-1", 240.0, model_group="old-name")
+ prisma = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-2)), model_name="new-name", model_id="dep-1")], table
+ )
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ priced_on = [key for key in table.rows if key[1] == _day(-1).isoformat()]
+ assert len(priced_on) == 1, f"day {_day(-1)} carries two charges: {priced_on}"
+ assert result.rows_written == 1
+ assert table.upsert_keys == [("t", _day(0).isoformat(), PTU_SENTINEL_API_KEY, "dep-1")]
+
+
+async def test_backfill_still_prices_a_genuinely_missing_day_for_a_renamed_deployment():
+ """Rename safety must not swallow real gaps: a day with no row for the deployment at
+ all still gets one, and it carries the current display name."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-2), "dep-1", 240.0, model_group="old-name")
+ prisma = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-2)), model_name="new-name", model_id="dep-1")], table
+ )
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.rows_written == 2
+ assert sorted(key[1] for key in table.upsert_keys) == [_day(-1).isoformat(), _day(0).isoformat()]
+ assert all(key[3] == "dep-1" for key in table.upsert_keys)
+ assert table.rows[("t", _day(0).isoformat(), PTU_SENTINEL_API_KEY, "dep-1")]["model_group"] == "new-name"
+
+
+async def test_backfill_falls_back_to_the_name_when_a_row_carries_no_source_model_id():
+ """A sentinel row whose display name is missing still counts as priced: identity is the
+ model column, so the gap check never depends on the name being present."""
+ table = _FakeSentinelTable()
+ table.seed("t", _day(-1), "m1", 240.0)
+ prisma = _prisma_for([_windowed_row(effective_from=_midnight(_day(-1)))], table)
+
+ result = await run_ptu_flat_cost_backfill(prisma, today=TODAY)
+
+ assert result.rows_written == 1
+ assert table.upsert_keys == [("t", _day(0).isoformat(), PTU_SENTINEL_API_KEY, "m1")]
+
+
+async def test_two_runs_straddling_a_rename_collapse_onto_one_row():
+ """The reported defect. Two runs holding different config views of the same deployment
+ used to write two keys for one day; keyed on the id they write the same key, so the
+ upsert collapses them instead of double charging."""
+ table = _FakeSentinelTable()
+ before = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-1)), model_name="old-name", model_id="dep-1")], table
+ )
+ after = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-1)), model_name="new-name", model_id="dep-1")], table
+ )
+
+ await run_ptu_flat_cost_backfill(before, today=TODAY)
+ await run_ptu_flat_cost_backfill(after, today=TODAY)
+
+ for offset in (-1, 0):
+ charges = [key for key in table.rows if key[1] == _day(offset).isoformat()]
+ assert len(charges) == 1, f"day {_day(offset)} carries {len(charges)} charges: {charges}"
+ assert sum(row["ptu_flat_cost"] for row in table.rows.values()) == pytest.approx(480.0)
+
+
+# --- R2: the interleaving that reproduced live on a four-pod rig -------------
+
+
+async def test_concurrent_runs_straddling_a_rename_write_one_row():
+ """The exact shape reproduced on a live multi-pod rig, which double charged a day.
+
+ Both pods read the day as unpriced before either writes, and a rename lands between
+ their config reads. Keyed on the display name they produced two different composite
+ keys and both rows survived, permanently. Keyed on the deployment id they produce the
+ same key, so the upsert collapses them.
+ """
+ import asyncio
+
+ table = _FakeSentinelTable()
+ ptu = {"ptu_count": 10, "cost_per_ptu_per_hour": 2.0, "team_id": "t"}
+ read_by_both = asyncio.Event()
+
+ real_keys = ptu_rollup._existing_sentinel_keys
+ arrivals = []
+
+ async def gated_keys(*args, **kwargs):
+ """Hold the first caller until the second has also read, so neither sees the other."""
+ keys = await real_keys(*args, **kwargs)
+ arrivals.append(1)
+ if len(arrivals) >= 2:
+ read_by_both.set()
+ await read_by_both.wait()
+ return keys
+
+ ptu_rollup._existing_sentinel_keys = gated_keys
+ try:
+ pod_a = asyncio.create_task(
+ run_ptu_flat_cost_backfill(
+ _prisma_for([_model_row(model_id="dep-1", model_name="old-name", model_info=ptu)], table),
+ today=TODAY,
+ )
+ )
+ pod_b = asyncio.create_task(
+ run_ptu_flat_cost_backfill(
+ _prisma_for([_model_row(model_id="dep-1", model_name="new-name", model_info=ptu)], table),
+ today=TODAY,
+ )
+ )
+ await asyncio.wait_for(asyncio.gather(pod_a, pod_b), timeout=5)
+ finally:
+ ptu_rollup._existing_sentinel_keys = real_keys
+
+ for day, count in sorted((key[1], 1) for key in table.rows):
+ assert count == 1
+ per_day = {}
+ for team_id, day, api_key, model_id in table.rows:
+ per_day[day] = per_day.get(day, 0) + 1
+ assert set(per_day.values()) == {1}, f"a day carries more than one charge: {per_day}"
+ assert {key[3] for key in table.rows} == {"dep-1"}
+
+
+async def test_a_rate_change_between_concurrent_runs_leaves_one_row():
+ """Two pods disagreeing on the rate, not just the name, still land on one row. Last
+ writer wins on the amount, which is self-consistent rather than a second charge."""
+ table = _FakeSentinelTable()
+ cheap = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-1)), model_id="dep-1", cost_per_ptu_per_hour=2.0)], table
+ )
+ dear = _prisma_for(
+ [_windowed_row(effective_from=_midnight(_day(-1)), model_id="dep-1", cost_per_ptu_per_hour=4.0)], table
+ )
+
+ await run_ptu_flat_cost_backfill(cheap, today=TODAY)
+ await run_ptu_flat_cost_backfill(dear, today=TODAY)
+
+ assert len(table.rows) == 2 # one per elapsed in-window day, not per config view
+ assert all(row["ptu_flat_cost"] == pytest.approx(240.0) for row in table.rows.values())
+
+
+# --- R6: the prune is the one operation that needs the lock -------------------
+
+
+async def test_an_unguarded_run_writes_but_does_not_prune():
+ """Without the cross-pod lock the upserts still run, since they are idempotent, but the
+ delete does not: its cutoff and the rows' updated_at come from different hosts, so a pod
+ whose clock runs ahead would sweep a charge a concurrent pod just wrote."""
+ table = _FakeSentinelTable()
+ table.seed("t", DAY, "dep-gone", 480.0, updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc))
+ prisma = _prisma_for(
+ [_model_row(model_id="dep-live", model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})],
+ table,
+ )
+
+ await run_scheduled_ptu_rollup(prisma, target_date=DAY)
+
+ assert table.delete_many_calls == []
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-gone") in table.rows
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-live") in table.rows
+
+
+async def test_a_run_holding_the_lock_still_prunes():
+ """Losing the sweep entirely would leave stale charges forever, so the guarded path,
+ which is the normal one, keeps it."""
+ table = _FakeSentinelTable()
+ table.seed("t", DAY, "dep-gone", 480.0, updated_at=datetime(2020, 1, 1, tzinfo=timezone.utc))
+ prisma = _prisma_for(
+ [_model_row(model_id="dep-live", model_info={"ptu_count": 5, "cost_per_ptu_per_hour": 2.0, "team_id": "t"})],
+ table,
+ )
+
+ await run_scheduled_ptu_rollup(prisma, pod_lock_manager=_pod_lock(acquired=True), target_date=DAY)
+
+ assert table.delete_many_calls != []
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-gone") not in table.rows
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-live") in table.rows
+
+
+async def test_the_prune_cutoff_allows_for_clock_skew_between_hosts():
+ """A row written seconds ago by a pod whose clock lags must survive; one written hours
+ ago by a previous run must not. The grace separates the two populations without
+ requiring the hosts' clocks to agree."""
+ table = _FakeSentinelTable()
+ just_written = datetime.now(timezone.utc) - timedelta(seconds=30)
+ table.seed("t", DAY, "dep-concurrent", 480.0, updated_at=just_written)
+ table.seed("t", DAY, "dep-stale", 480.0, updated_at=datetime.now(timezone.utc) - timedelta(hours=6))
+ prisma = _prisma_for([], table)
+
+ await run_ptu_flat_cost_rollup(prisma, target_date=DAY)
+
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-concurrent") in table.rows, (
+ "a charge written 30s ago by a lagging pod was swept"
+ )
+ assert ("t", DAY.isoformat(), PTU_SENTINEL_API_KEY, "dep-stale") not in table.rows
diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.py
index 580a58885d9..74120beb7b9 100644
--- a/tests/test_litellm/proxy/test_proxy_server.py
+++ b/tests/test_litellm/proxy/test_proxy_server.py
@@ -11278,3 +11278,40 @@ async def test_setup_prisma_client_returns_none_when_connect_itself_fails(monkey
assert result is None
assert mock_client.start_db_health_watchdog_task.await_count == 0
assert mock_client.health_check.await_count == 0
+
+
+async def test_ptu_rollup_job_registered_at_startup(monkeypatch):
+ """The PTU rollup cron is registered at startup; only models with PTU config accrue flat cost (asserted in test_ptu_flat_cost_rollup.py)."""
+ monkeypatch.delenv("STORE_MODEL_IN_DB", raising=False)
+ from litellm.proxy.proxy_server import ProxyStartupEvent
+ from litellm.proxy.spend_tracking.ptu_flat_cost_rollup import (
+ PTU_ROLLUP_JOB_ID,
+ )
+ from litellm.proxy.utils import ProxyLogging
+
+ mock_prisma_client = MagicMock()
+ mock_prisma_client.db.litellm_config.find_first = AsyncMock(return_value=None)
+
+ mock_proxy_logging = MagicMock(spec=ProxyLogging)
+ mock_proxy_logging.slack_alerting_instance = MagicMock()
+ mock_proxy_config = AsyncMock()
+
+ with (
+ patch("litellm.proxy.proxy_server.proxy_config", mock_proxy_config),
+ patch("litellm.proxy.proxy_server.store_model_in_db", True),
+ patch("litellm.proxy.proxy_server.get_secret_bool", return_value=True),
+ ):
+ await ProxyStartupEvent.initialize_scheduled_background_jobs(
+ general_settings={},
+ prisma_client=mock_prisma_client,
+ proxy_budget_rescheduler_min_time=1,
+ proxy_budget_rescheduler_max_time=2,
+ proxy_batch_write_at=5,
+ proxy_logging_obj=mock_proxy_logging,
+ )
+
+ import litellm.proxy.proxy_server as ps
+
+ assert ps.scheduler is not None
+ assert ps.scheduler.get_job(PTU_ROLLUP_JOB_ID) is not None