Skip to content

fix(batches): handle empty models when logging batch cost - #47155

Merged
joshua-berri merged 1 commit into
mainfrom
litellm_fix_batch_empty_model_9498
Oct 17, 2026
Merged

joshua-berri merged 1 commit into
mainfrom
litellm_fix_batch_empty_model_9498

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • All-failed batches can leave the aggregated model list empty
  • Logging then crashes before marking the batch processed

How it solves it:

  • Prefer the aggregated model, then deployment model or ID
  • Preserve costs, usage, failure counts, and existing retry behavior

User Flow

Before, an all-failed batch can repeatedly produce an error during cost reconciliation

  1. The admin has a completed batch with all-failed output and an empty configured provider model
  2. They wait for batch cost reconciliation
  3. Proxy logs repeatedly show list index out of range

After, the same batch finishes cost reconciliation with a fallback identity

  1. The admin has a completed batch with all-failed output and an empty configured provider model
  2. They wait for batch cost reconciliation
  3. The batch produces one zero-cost accounting event and stops retrying

Relevant issues

Addresses the empty-model case in #45065

Linear ticket

Resolves LIT-9498

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each finding

Verification

The parameterized regression runs the cost poller twice with all-failed, mixed, and successful output. It checks the logged identity, exact cost and tokens, success/failure counts, processed state, and one accounting callback

Both empty-model cases fail on the baseline with IndexError. All five cases pass on the candidate, and the two affected test files pass all 305 tests

Local changed executable-line coverage is 1/1. The touched function has 12/18 branches covered, with the six existing uncovered branches outside this fallback. All three identity choices are exercised

Independent Devin MCP execution at fa2effb94d1f98bc4643eca5406df72894989ae3 confirmed the same five cases using the real Router, logging pipeline, HTTP downloads and PostgreSQL. No LiteLLM function was patched. All 305 tests passed independently, and 16 existing failure/retry tests passed on both source builds

Local canonical lint, test-quality, type-discipline, OpenAPI, import checks and type-count comparison passed. All four required CI checks passed, including the affected 395-test shard. Its uploaded coverage artifact covers the changed executable line (1/1). Codecov finished processing both fresh uploads and reports 100% changed-line coverage (1/1). Repository coverage is 87.77%

Bugbot and Veria found no issues on fa2effb94d1f98bc4643eca5406df72894989ae3. LiteReview gave 5/5, ran all 128 worker tests, and confirmed both regressions fail when the fix is reverted. Greptile was requested but has not returned a review, so full readiness remains pending

Screenshots / Proof of Fix

This is a controlled replay of the reported file-download boundary, using a real HTTP fixture server and scratch PostgreSQL databases. The provider responses are synthetic. It does not demonstrate live provider batch creation, proxy HTTP routes, or insertion into LiteLLM_SpendLogs

The replay uses source builds and asserts imported paths. The complete executed harness and setup are included below, with no credentials

Executed replay harness and setup
LIT-9498 independent verification (sanitized)

Baseline b5037f28d172f6f6375ba3d08dcdf2c10deb8d2d, candidate fa2effb94d1f98bc4643eca5406df72894989ae3 (branch litellm_fix_batch_empty_model_9498)

Harness (harness/), run per worktree with `harness/run.sh <base|head> <port>`:
- fake_openai.py: stdlib HTTP server serving GET /v1/batches/{id} (status completed, output_file_id) and GET /v1/files/{id}/content from SYNTHETIC JSONL fixtures (artifacts/<w>/fixtures). Not a real provider batch
- run_cases.py: real Router (5 openai deployments, api_base = fake server), real ProxyLogging, real PrismaClient on a scratch Postgres DB per worktree (schema via prisma db push), real CheckBatchCost.check_batch_cost() polled twice. No LiteLLM function is patched. A CustomLogger records aretrieve_batch standard_logging_object. Asserts litellm and check_batch_cost import from the worktree
- Env: DATABASE_URL=<scratch db>, PYTHON_DOTENV_DISABLED=1, LITELLM_LOCAL_MODEL_COST_MAP=True, PYTHONPATH=<wt>:<wt>/enterprise
Results: artifacts/<w>/result.json, run.log, hits.log (provider request paths). Unit: artifacts/pytest_<w>.log

Setup steps before running (not part of run.sh):

  • git worktree add --detach <H>/base b5037f28 and git worktree add --detach <H>/head fa2effb9
  • createdb v9498_base and createdb v9498_head
  • For each database, DATABASE_URL=<db> .venv/bin/prisma db push --schema .venv/lib/python3.12/site-packages/prisma/schema.prisma --skip-generate. The LiteLLM_ManagedObjectTable model there is identical to the one in both worktrees.
harness/run.sh
#!/usr/bin/env bash
# usage: run.sh <base|head> <port>
set -u; W=$1; P=$2; H=/home/ubuntu/wt9498; A=$H/artifacts/$W; mkdir -p $A; rm -f $A/hits.log
PY=/home/ubuntu/repos/litellm/.venv/bin/python; DBURL=$(echo "$DATABASE_URL" | sed 's#/litellm$##')/v9498_$W
$PY $H/harness/fake_openai.py $P $A/fixtures $A/hits.log & SRV=$!; mkdir -p $A/fixtures; sleep 1
cd $H/$W; DATABASE_URL="$DBURL" PYTHON_DOTENV_DISABLED=1 LITELLM_LOCAL_MODEL_COST_MAP=True PYTHONPATH=$H/$W:$H/$W/enterprise \
  $PY $H/harness/run_cases.py $H/$W "$DBURL" $P $A/result.json $A/hits.log > $A/run.log 2>&1; echo "exit=$?" | tee -a $A/run.log
kill $SRV
harness/fake_openai.py
# Synthetic OpenAI batch/files stand-in. Fixture JSONL is controlled test content, not a real provider batch.
import json, sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

FIX = Path(sys.argv[2])
LOG = Path(sys.argv[3])

class H(BaseHTTPRequestHandler):
    def _send(self, code, body, ctype="application/json"):
        data = body if isinstance(body, bytes) else json.dumps(body).encode()
        self.send_response(code); self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(data))); self.end_headers(); self.wfile.write(data)
    def do_GET(self):
        with LOG.open("a") as f: f.write(self.path + "\n")
        p = self.path.split("?")[0]
        if p.startswith("/v1/batches/"):
            bid = p.rsplit("/", 1)[1]
            return self._send(200, {"id": bid, "object": "batch", "endpoint": "/v1/chat/completions",
                "input_file_id": "file-in-" + bid, "completion_window": "24h", "status": "completed",
                "output_file_id": "file-out-" + bid, "created_at": 1})
        if p.startswith("/v1/files/file-out-") and p.endswith("/content"):
            bid = p.split("/")[3][len("file-out-"):]
            return self._send(200, (FIX / f"{bid}.jsonl").read_bytes(), "application/octet-stream")
        return self._send(404, {"error": {"message": "not found", "type": "invalid_request_error"}})
    def log_message(self, *a): pass

ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
harness/run_cases.py
import asyncio, base64, json, logging, os, subprocess, sys
from pathlib import Path

WT = Path(sys.argv[1]); DB = sys.argv[2]; PORT = int(sys.argv[3]); OUT = Path(sys.argv[4]); HITS = Path(sys.argv[5])
import litellm
from litellm.caching.dual_cache import DualCache
from litellm.integrations.custom_logger import CustomLogger
from litellm.proxy.utils import PrismaClient, ProxyLogging
from litellm.router import Router
from litellm.types.utils import SpecialEnums
import litellm_enterprise.proxy.common_utils.check_batch_cost as cbc
from prisma import Json

src = {"litellm": litellm.__file__, "check_batch_cost": cbc.__file__,
       "worktree_head": subprocess.check_output(["git", "-C", str(WT), "rev-parse", "HEAD"], text=True).strip(),
       "check_batch_cost_dirty": subprocess.check_output(["git", "-C", str(WT), "status", "--porcelain", "--", "enterprise", "litellm"], text=True).strip()}
assert cbc.__file__.startswith(str(WT)) and litellm.__file__.startswith(str(WT)), src

CASES = {
    "A_allfailed_openai_slash": ("openai/", 0, 2),
    "B_allfailed_empty_model": ("", 0, 2),
    "C_mixed_openai_slash": ("openai/", 2, 1),
    "D_mixed_named": ("openai/gpt-4o-mini", 2, 1),
    "E_allsuccess_control": ("openai/gpt-4o-mini", 2, 0),
}
FIX = OUT.parent / "fixtures"; FIX.mkdir(exist_ok=True)
def ok(i): return {"id": f"batch_req_ok{i}", "custom_id": f"ok-{i}", "response": {"status_code": 200, "request_id": f"r{i}",
    "body": {"id": f"chatcmpl-{i}", "object": "chat.completion", "created": 1, "model": "gpt-4o-mini",
             "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
             "usage": {"prompt_tokens": 100, "completion_tokens": 20, "total_tokens": 120}}}, "error": None}
def bad(i): return {"id": f"batch_req_bad{i}", "custom_id": f"bad-{i}", "response": {"status_code": 400, "request_id": f"b{i}",
    "body": {"error": {"message": "synthetic failure", "type": "invalid_request_error"}}}, "error": None}
for name, (_, s, f) in CASES.items():
    (FIX / f"batch_{name}.jsonl").write_text("\n".join(json.dumps(r) for r in [ok(i) for i in range(s)] + [bad(i) for i in range(f)]) + "\n")

class Rec(CustomLogger):
    def __init__(self): super().__init__(); self.calls = []
    async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
        if kwargs.get("call_type") == "aretrieve_batch": self.calls.append(kwargs["standard_logging_object"])
rec = Rec(); litellm.logging_callback_manager.add_litellm_async_success_callback(rec)

class Cap(logging.Handler):
    def __init__(self): super().__init__(); self.msgs = []
    def emit(self, r): self.msgs.append(f"{r.levelname} {r.getMessage()}")
cap = Cap(); pl = logging.getLogger("LiteLLM Proxy"); pl.addHandler(cap); pl.setLevel(logging.INFO)

def uid(dep, bid): return base64.urlsafe_b64encode(SpecialEnums.LITELLM_MANAGED_BATCH_COMPLETE_STR.value.format(dep, bid).encode()).decode().rstrip("=")

async def main():
    model_list = [{"model_name": f"grp-{n}", "litellm_params": {"model": m, "custom_llm_provider": "openai",
                   "api_base": f"http://127.0.0.1:{PORT}/v1", "api_key": "sk-synthetic"}, "model_info": {"id": f"dep-{n}"}}
                  for n, (m, _, _) in CASES.items()]
    router = Router(model_list=model_list)
    registered = sorted(d["model_info"]["id"] for d in router.get_model_list())
    plog = ProxyLogging(user_api_key_cache=DualCache())
    prisma = PrismaClient(database_url=DB, proxy_logging_obj=plog); await prisma.connect()
    t = prisma.db.litellm_managedobjecttable
    await t.delete_many()
    for n in CASES:
        await t.create(data={"unified_object_id": uid(f"dep-{n}", f"batch_{n}"), "model_object_id": f"batch_{n}",
            "file_object": Json({"id": f"batch_{n}", "object": "batch", "status": "completed"}), "file_purpose": "batch",
            "status": "validating", "created_by": "verifier-user"})
    poller = cbc.CheckBatchCost(proxy_logging_obj=plog, prisma_client=prisma, llm_router=router)
    per_poll = []
    for poll in (1, 2):
        before = len(rec.calls); await poller.check_batch_cost(); await asyncio.sleep(0.5)
        per_poll.append(len(rec.calls) - before)
    rows = {r.model_object_id: r for r in await t.find_many()}
    hits = HITS.read_text().splitlines() if HITS.exists() else []
    rate = litellm.model_cost["gpt-4o-mini"]
    res = {"source": src, "registered_deployments": registered, "aretrieve_batch_events_per_poll": per_poll, "cases": {}}
    for n, (m, s, f) in CASES.items():
        bid = f"batch_{n}"; ev = [c for c in rec.calls if c["id"] == uid(f"dep-{n}", bid)]; r = rows[bid]
        exp_cost = s * (100 * rate["input_cost_per_token_batches"] + 20 * rate["output_cost_per_token_batches"])
        res["cases"][n] = {"deployment_model": m, "successes": s, "failures": f, "events": len(ev),
            "logged_model": ev[0]["model"] if ev else None, "model_id": ev[0]["model_id"] if ev else None,
            "model_group": ev[0]["model_group"] if ev else None,
            "response_cost": ev[0]["response_cost"] if ev else None, "expected_cost": exp_cost,
            "prompt_tokens": ev[0]["prompt_tokens"] if ev else None, "completion_tokens": ev[0]["completion_tokens"] if ev else None,
            "batch_successful_requests": ev[0]["hidden_params"].get("batch_successful_requests") if ev else None,
            "batch_failed_requests": ev[0]["hidden_params"].get("batch_failed_requests") if ev else None,
            "batch_models": ev[0]["hidden_params"].get("batch_models") if ev else None,
            "db_batch_processed": r.batch_processed, "db_status": r.status,
            "provider_retrieve_hits": sum(h.startswith(f"/v1/batches/{bid}") for h in hits),
            "provider_content_downloads": sum(h.startswith(f"/v1/files/file-out-{bid}/content") for h in hits),
            "poller_logs": [x[:240] for x in cap.msgs if bid in x and ("fail" in x.lower() or "error" in x.lower() or "Index" in x)]}
    OUT.write_text(json.dumps(res, indent=1, default=str)); await prisma.disconnect()
asyncio.run(main())

Before (b5037f2)

All-failed output

  1. Run harness/run.sh base 18491 using the shared setup below
  2. For openai/ and the empty deployment model, observe zero accounting events, an unprocessed row, and list index out of range on both polls
  3. Both cases download the output twice

Mixed and successful output

  1. Inspect the other three cases from the same run
  2. Each logs once, processes its row, and records 200 input tokens and 40 output tokens
  3. Mixed cases record two successes and one failure; the successful control records two successes and zero failures

After (fa2effb)

All-failed output

  1. Run harness/run.sh head 18492 using the shared setup below
  2. Both cases log once with zero cost and tokens, two failures, and a processed row
  3. The logging identities are openai/ and the deployment ID respectively; each downloads once, with no repeat accounting

Mixed and successful output

  1. Inspect the other three cases from the same run
  2. Each logs once, processes its row, and records 200 input tokens and 40 output tokens
  3. All model, cost, token, count and persistence results match the baseline exactly
Measured before and after results

(b5037f2)

{"source":{"litellm":"/home/ubuntu/wt9498/base/litellm/__init__.py","check_batch_cost":"/home/ubuntu/wt9498/base/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py","worktree_head":"b5037f28d172f6f6375ba3d08dcdf2c10deb8d2d","check_batch_cost_dirty":""},"registered_deployments":["dep-A_allfailed_openai_slash","dep-B_allfailed_empty_model","dep-C_mixed_openai_slash","dep-D_mixed_named","dep-E_allsuccess_control"],"aretrieve_batch_events_per_poll":[3,0],"cases":{"A_allfailed_openai_slash":{"deployment_model":"openai/","successes":0,"failures":2,"events":0,"logged_model":null,"model_id":null,"model_group":null,"response_cost":null,"expected_cost":0.0,"prompt_tokens":null,"completion_tokens":null,"batch_successful_requests":null,"batch_failed_requests":null,"batch_models":null,"db_batch_processed":false,"db_status":"validating","provider_retrieve_hits":2,"provider_content_downloads":2,"poller_logs":["ERROR CheckBatchCost: failed to track cost for batch batch_A_allfailed_openai_slash (job e12b56af-5b63-4b37-a648-d90221e9ea3a); leaving it unprocessed so the next poll retries: list index out of range","ERROR CheckBatchCost: failed to track cost for batch batch_A_allfailed_openai_slash (job e12b56af-5b63-4b37-a648-d90221e9ea3a); leaving it unprocessed so the next poll retries: list index out of range"]},"B_allfailed_empty_model":{"deployment_model":"","successes":0,"failures":2,"events":0,"logged_model":null,"model_id":null,"model_group":null,"response_cost":null,"expected_cost":0.0,"prompt_tokens":null,"completion_tokens":null,"batch_successful_requests":null,"batch_failed_requests":null,"batch_models":null,"db_batch_processed":false,"db_status":"validating","provider_retrieve_hits":2,"provider_content_downloads":2,"poller_logs":["ERROR CheckBatchCost: failed to track cost for batch batch_B_allfailed_empty_model (job 7b41f7a6-ae42-490f-a98b-e2b23ae8a7ca); leaving it unprocessed so the next poll retries: list index out of range","ERROR CheckBatchCost: failed to track cost for batch batch_B_allfailed_empty_model (job 7b41f7a6-ae42-490f-a98b-e2b23ae8a7ca); leaving it unprocessed so the next poll retries: list index out of range"]},"C_mixed_openai_slash":{"deployment_model":"openai/","successes":2,"failures":1,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-C_mixed_openai_slash","model_group":"grp-C_mixed_openai_slash","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":1,"batch_models":["gpt-4o-mini","gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"D_mixed_named":{"deployment_model":"openai/gpt-4o-mini","successes":2,"failures":1,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-D_mixed_named","model_group":"grp-D_mixed_named","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":1,"batch_models":["gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"E_allsuccess_control":{"deployment_model":"openai/gpt-4o-mini","successes":2,"failures":0,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-E_allsuccess_control","model_group":"grp-E_allsuccess_control","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":0,"batch_models":["gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]}}}
head/result.json (fa2effb)
{"source":{"litellm":"/home/ubuntu/wt9498/head/litellm/__init__.py","check_batch_cost":"/home/ubuntu/wt9498/head/enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py","worktree_head":"fa2effb94d1f98bc4643eca5406df72894989ae3","check_batch_cost_dirty":""},"registered_deployments":["dep-A_allfailed_openai_slash","dep-B_allfailed_empty_model","dep-C_mixed_openai_slash","dep-D_mixed_named","dep-E_allsuccess_control"],"aretrieve_batch_events_per_poll":[5,0],"cases":{"A_allfailed_openai_slash":{"deployment_model":"openai/","successes":0,"failures":2,"events":1,"logged_model":"openai/","model_id":"dep-A_allfailed_openai_slash","model_group":"grp-A_allfailed_openai_slash","response_cost":0.0,"expected_cost":0.0,"prompt_tokens":0,"completion_tokens":0,"batch_successful_requests":0,"batch_failed_requests":2,"batch_models":[],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"B_allfailed_empty_model":{"deployment_model":"","successes":0,"failures":2,"events":1,"logged_model":"dep-B_allfailed_empty_model","model_id":"dep-B_allfailed_empty_model","model_group":"grp-B_allfailed_empty_model","response_cost":0.0,"expected_cost":0.0,"prompt_tokens":0,"completion_tokens":0,"batch_successful_requests":0,"batch_failed_requests":2,"batch_models":[],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"C_mixed_openai_slash":{"deployment_model":"openai/","successes":2,"failures":1,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-C_mixed_openai_slash","model_group":"grp-C_mixed_openai_slash","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":1,"batch_models":["gpt-4o-mini","gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"D_mixed_named":{"deployment_model":"openai/gpt-4o-mini","successes":2,"failures":1,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-D_mixed_named","model_group":"grp-D_mixed_named","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":1,"batch_models":["gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]},"E_allsuccess_control":{"deployment_model":"openai/gpt-4o-mini","successes":2,"failures":0,"events":1,"logged_model":"gpt-4o-mini","model_id":"dep-E_allsuccess_control","model_group":"grp-E_allsuccess_control","response_cost":2.7e-05,"expected_cost":2.7e-05,"prompt_tokens":200,"completion_tokens":40,"batch_successful_requests":2,"batch_failed_requests":0,"batch_models":["gpt-4o-mini"],"db_batch_processed":true,"db_status":"complete","provider_retrieve_hits":1,"provider_content_downloads":1,"poller_logs":[]}}}

Caveats

Low

  • Controlled provider responses; no live provider batch submission
  • Spend-log database insertion was outside this boundary replay

Type

Bug Fix

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review Please review the current commit, including fallback identity, mixed-result accounting, and the attached independent verification evidence

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai Please review this batch logging fix and regression coverage, including all-failed output, mixed results, and fallback identity

@joshua-berri

Copy link
Copy Markdown
Contributor Author

cursor review

Please review this batch logging fix, especially fallback identity, mixed-result accounting, and the regression cases

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit fa2effb. Configure here.

@litereview

litereview Bot commented Oct 17, 2026

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: full · Full PR review.

No correctness findings.

Checks and execution details
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes only enterprise/litellm_enterprise/proxy/common_utils/check_batch_cost.py and tests/unit/proxy/common_utils/test_check_batch_cost.py. It touches nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.
  • Passed · Compatibility requirements (required): No supported behavior breaks. When batch_result.models is non-empty, the logged model stays models[0], the same as before. When the list is empty (all requests failed), the old code raised IndexError and left the batch unprocessed so it retried forever. The new code logs litellm_model_name or model_id and marks the batch processed. Only a failing path changes, so the title does not need a ! marker.
  • Passed · Changed behavior and result consistency (required): I traced check_batch_cost() → _track_completed_batch_cost, where calculate_batch_cost_and_usage yields the models list. From there the value flows into LiteLLMLogging(model=...) and then async_success_handler, which builds standard_logging_object. The new test covers three identity choices: an empty list with model openai/, an empty list with an empty-string deployment model (falls back to model_id), and a non-empty list. It polls twice and asserts cost, tokens, success/failure counts, processed state and a single callback. Defect-sensitive oracle: I reverted line 760 to batch_result.models[0], and both empty-model cases failed with list index out of range; the other three passed. tests/unit/conftest.py restores the callback lists, so the callback added in the test does not leak into other tests. I found no documented standard that the change violates.
  • Passed · pytest test_check_batch_cost.py (optional): .venv/bin/python -m pytest tests/unit/proxy/common_utils/test_check_batch_cost.py -q: 128 passed. All 5 cases of the new parameterized test passed.

View review · Reviewed fa2effb94d1f

@codecov

codecov Bot commented Oct 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks!

@joshua-berri
joshua-berri merged commit 4143e08 into main Oct 17, 2026
89 of 90 checks passed
@joshua-berri
joshua-berri deleted the litellm_fix_batch_empty_model_9498 branch October 17, 2026 19:49
pamanseau pushed a commit to KubeTEE-AI/litellm that referenced this pull request Oct 25, 2026
Cartofante pushed a commit to CartoDB/litellm that referenced this pull request Oct 26, 2026
haowang1013 pushed a commit to directivegames/litellm that referenced this pull request Nov 3, 2026
DeoLeung pushed a commit to aiyou178/litellm that referenced this pull request Nov 5, 2026
)

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
(cherry picked from commit 4143e08)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Unrecoverable batch cost failures are retried indefinitely

2 participants