Skip to content

fix(spend): retain billed failure accounting when error logs are disabled - #53271

Merged
joshua-berri merged 1 commit into
mainfrom
litellm_fix_billed_failures_error_logs_53156
Nov 21, 2026
Merged

joshua-berri merged 1 commit into
mainfrom
litellm_fix_billed_failures_error_logs_53156

Conversation

@joshua-berri

@joshua-berri joshua-berri commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

  • Fix: disable_error_logs: true suppresses detailed error logs without dropping known charges.
  • Covered charges: interrupted streams, billed timeouts/retries, and charged guardrail failures.
  • Accounting: preserves outbox deliveries and existing rollup processing; also fixes the legacy accounting path.
  • Preserved behavior: zero-cost error suppression, finalized costs, successful requests, and disabled spend updates.
  • Scope: one accounting-gate change plus regression tests; no schema/config changes or historical backport.
Details

TLDR

Problem this solves:

  • Disabling error logs also drops charges from failed requests.

How it solves it:

  • Keep billable failure accounting while suppressing detailed error logs.
  • Include recovered usage, guardrail charges, and billed retry attempts.
  • Preserve existing zero-cost suppression and finalized-cost handling.

User Flow

Before, failed requests can incur charges missing from tracked spend.

  1. An operator sets disable_error_logs: true on the gateway.
  2. An application sends a request that incurs cost but fails.
  3. The operator sees no corresponding charge in tracked spend.

After, those charges remain accounted for without detailed error records.

  1. An operator sets disable_error_logs: true on the gateway.
  2. An application sends a request that incurs cost but fails.
  3. The operator sees the charge while error details remain unrecorded.

Relevant issues

Fixes #53156

Pre-Submission checklist

  • I have added meaningful tests
  • Affected test files pass on the exact source build on Devin
  • My PR passes all required CI/CD checks
  • My PR's scope is isolated to one problem
  • Every automated review on the latest commit has finished and findings are addressed

Screenshots / Proof of Fix

Baseline e7b4b5c7203197ba4be8825aa1e351d6582c6e34.

Candidate 1f4e87b5b7c2a92f5450b68477db346156652c1d.

Shared setup

Executed against source builds at the two SHAs above, with PostgreSQL and a dedicated Redis per proxy, two proxy workers, and matching native extensions. Set DATABASE_URL to a disposable local PostgreSQL admin database, VENV_BIN to the prepared proxy environment's bin directory, and ANTHROPIC_API_KEY for the real-provider case. The harness creates and drops only databases named t53156_<rig>; use an isolated verification environment.

Save the following files under harness/, then chmod +x harness/*.sh. The scripts contain the exact generated config, requests, SQL snapshots, callback tracing, and acknowledged flush commands. Fixture credentials are throwaway literals. The only portability edit from execution replaces the verifier's virtualenv path with VENV_BIN.

cd harness
# BASE_CHECKOUT and HEAD_CHECKOUT are source checkouts at the SHAs above.
./rig.sh start base_on_true "$BASE_CHECKOUT" on true on 0
./matrix.sh base_on_true 0 full
./matrix.sh base_on_true 0 retryzero
./matrix.sh base_on_true 0 respstream
./matrix.sh base_on_true 0 real
./rig.sh stop base_on_true "$BASE_CHECKOUT" on true on 0
./rig.sh start head_on_true "$HEAD_CHECKOUT" on true on 1
./matrix.sh head_on_true 1 full
./matrix.sh head_on_true 1 retryzero
./matrix.sh head_on_true 1 respstream
./matrix.sh head_on_true 1 real
./rig.sh stop head_on_true "$HEAD_CHECKOUT" on true on 1

Repeat the paired rigs with false for the error-log flag. Legacy controls use off for the ledger argument. Disabled-accounting controls use off for the spend argument. The real-provider and Responses streaming pairs ran only with ledger enabled. No build or service ran on the author's laptop.

Before (e7b4b5c7203197ba4be8825aa1e351d6582c6e34)

With disable_error_logs: true, every positive, unfinalized failure below produced zero deliveries, zero detailed logs, and zero key spend. The corresponding flag-false cases recorded the cost. Finalized-cost and successful controls already worked.

After (1f4e87b5b7c2a92f5450b68477db346156652c1d)

The same flag-true requests record these amounts, with zero detailed error logs. Entity/daily deltas match each case's flag-false control. Every case had four flushes acknowledged by both workers, with identical tables after flushes two and four.

Endpoint/case Recovered cost Applied deliveries
/v1/chat/completions, interrupted stream $0.00001155 1
/v1/chat/completions, read timeout $0.0000028 1
/v1/chat/completions, three billed failed attempts $0.0000084 3
/v1/chat/completions, billed retry then zero-cost terminal failure $0.0000028 2, including unchanged zero-cost terminal row
/v1/chat/completions, pre-call guardrail rejection $0.0003 1
/v1/chat/completions, guardrail pass then read timeout $0.0003028 1
/v1/messages, read timeout $0.0000028 1
/v1/responses, read timeout $0.0000028 1
/v1/responses, interrupted stream $0.00001155 1
Real Anthropic interrupted stream, claude-haiku-5-5 $0.0000097 1

The real-provider relay cut the stream after three text deltas. Baseline flag-true recovered the same $0.0000097 but persisted nothing; head persisted one accounting-only delivery. These amounts are LiteLLM usage estimates, not invoice reconciliation. Synthetic upstream fixtures exercise the remaining failure shapes.

Legacy accounting with the ledger disabled also retains the charges without detailed logs. Existing flag-false results, finalized guardrail rejection ($0.000314), success ($0.000014), zero-cost rejection/connect failure, and disabled-accounting behavior remain unchanged.

Read projections: key, team, user, organization, project, end-user and team-member spend; daily user/team/organization/tag/end-user rows. For Messages/Responses bodies without an end user, that counter correctly remains unchanged. Budget tables, daily agent rows and Redis counters were not inspected. Tag and organization-membership counters had no seeded rows, so they were not tested live. Daily tag spend was inspected; it is separate from TagTable spend.

Executed test command and environment provenance

Python 3.12.16, pytest 9.0.3, coverage 7.14.0, PostgreSQL 14.24, Redis server 8.10.3. The verifier reused its full proxy virtualenv and put each exact checkout first on PYTHONPATH. The native extension was built from baseline with CARGO_TARGET_DIR isolated, CARGO_PROFILE_DEV_DEBUG=0, SQLX_OFFLINE=true; the exact build invocation was not retained. Both checkouts used an identical extension, valid because the candidate changes no Rust sources. No claim is made that the shared full environment was freshly resolved from the lockfile; the lint environment used uv sync --frozen --only-group dev --no-install-project.

cd "$HEAD_CHECKOUT"
env -u DATABASE_URL \
  PYTHONPATH="$PWD:$PWD/litellm/proxy-extras:$PWD/litellm/enterprise" \
  COVERAGE_FILE="$EVIDENCE_DIR/.coverage_head" \
  "$VENV_BIN/python" -m coverage run --branch \
  --include='*/litellm/proxy/hooks/proxy_track_cost_callback.py' -m pytest \
  tests/unit/proxy/hooks/test_proxy_track_cost_callback.py \
  tests/unit/proxy/hooks/test_proxy_track_cost_callback_ledger.py \
  tests/unit/proxy/hooks/test_proxy_track_cost_callback_rust.py \
  tests/unit/proxy/spend_tracking/test_cost_finalization.py \
  tests/unit/proxy/db/test_db_spend_update_writer.py \
  tests/unit/proxy/db/test_rust_spend_log_writer.py \
  tests/unit/integrations/custom_logger_v2/test_spend_log_derivations.py \
  -q -p no:cacheprovider
# Observed: 956 passed

Paths above are portable substitutions for the verifier's scratch/virtualenv paths. CI independently resolves its canonical environments.

Regression tests and gates

  • 956 affected tests passed on the exact candidate source build.
  • Changed executable lines: 3/3 covered (100%). tracks_failure_spend: 8/8 branch arcs covered. Whole touched module: 96%.
  • Regression sensitivity: candidate tests against baseline product produced 17 failures, all in the newly covered billed cases; 491 others passed.
  • Canonical pre-PR lint/format, strict-rule, type-discipline, test-quality, basedpyright, OpenAPI, lock, circular-import, migration and MCP-boundary gates passed on Devin. The type gate's initial +1 diagnostic did not reproduce; matching full-tree baseline/head reports were identical, and the canonical rerun passed without code or budget changes.
  • Current-tip GitHub CI and Buildkite E2E passed, including all applicable core unit shards, changed tests, lint, type checks and smoke builds. Contributor agreement passed.
  • Greptile: 5/5, no actionable findings at 1f4e87b5. Veria: no security issues at the same tip. Review threads and inline comments contain no findings.
  • Bugbot is unavailable because of an unpaid team invoice (bot response); its review is not passed. No completed Codecov report is available for this tip; this unit workflow does not upload one. Independent line/branch coverage is recorded above. These readiness limitations remain open.

Verification limits

  • The Messages interrupted-stream fixture recovered zero cost on both SHAs and therefore does not exercise this change.
  • Duplicate markers and route filtering have unit coverage, not separate live cases.
  • Earlier timeout costs missing when retries end in success/400 were observed on both flags and are outside this fix.
  • No schema migration, new configuration, pricing change, or historical backport.
harness/case.sh
cat > harness/case.sh <<'LITELLM_PROOF_EOF'
#!/bin/bash
# usage: case.sh <rig> <port_index> <label> <endpoint chat|messages|responses> <model> <stream true|false> [guardrail] [retries] [header]
RIG=$1; I=$2; L=$3; EP=$4; MODEL=$5; STREAM=$6; GRD=$7; RET=$8; HDR=$9
H=$(cd "$(dirname "$0")" && pwd); W=$H/../run/$RIG; E=$H/../evidence/$RIG; mkdir -p $E; PP=$((4800+I)); F=$W/trace.jsonl
B=$(wc -l < $F); UB=$(wc -l < $W/upstream_events.jsonl); RB=$(wc -l < $W/relay_events.jsonl 2>/dev/null || echo 0)
$H/snap.sh $RIG > $E/${L}_0_before.txt
X=""; [ -n "$GRD" ] && X="$X,\"guardrails\":[\"$GRD\"]"; [ -n "$RET" ] && X="$X,\"num_retries\":$RET"
P="count from one to thirty in words"
case $EP in
  chat) URL=/v1/chat/completions; BODY="{\"model\":\"$MODEL\",\"stream\":$STREAM,\"user\":\"t53156-enduser\",\"metadata\":{\"tags\":[\"t53156-tag\"]}$X,\"messages\":[{\"role\":\"user\",\"content\":\"$P\"}]}";;
  messages) URL=/v1/messages; BODY="{\"model\":\"$MODEL\",\"stream\":$STREAM,\"max_tokens\":64$X,\"messages\":[{\"role\":\"user\",\"content\":\"$P\"}]}";;
  responses) URL=/v1/responses; BODY="{\"model\":\"$MODEL\",\"stream\":$STREAM$X,\"input\":\"$P\"}";;
esac
OUT=$(curl -s -N -m90 -o $W/resp_$L.txt -w "http=%{http_code} curl_exit=%{exitcode} bytes=%{size_download}" localhost:$PP$URL -H "Authorization: Bearer $(cat $W/key.txt)" -H 'content-type: application/json' ${HDR:+-H "$HDR"} -d "$BODY")
# callback completion event: spend-callback failure input built (Rust path), legacy failure hook exit (Python path), or a success write/cost callback
DONE='"wrap\.spend_log_failure_input", "phase": "exit"|"wrap\.after_write", "phase": "exit"|"wrap\._ProxyDBLogger\.(async_post_call_failure_hook|_PROXY_track_cost_callback)", "phase": "(exit|raise)"'
for i in $(seq 1 300); do tail -n +$((B+1)) $F | grep -Eq "$DONE" && break; sleep 0.2; done
sleep 3
$H/snap.sh $RIG > $E/${L}_1_after_callback.txt
A1=$($H/flush.sh $RIG); A2=$($H/flush.sh $RIG); $H/snap.sh $RIG > $E/${L}_2_after_flush2.txt
A3=$($H/flush.sh $RIG); A4=$($H/flush.sh $RIG); $H/snap.sh $RIG > $E/${L}_3_after_flush4.txt
tail -n +$((B+1)) $F > $E/${L}_trace.jsonl; tail -n +$((UB+1)) $W/upstream_events.jsonl > $E/${L}_upstream.jsonl; [ -f $W/relay_events.jsonl ] && tail -n +$((RB+1)) $W/relay_events.jsonl > $E/${L}_relay.jsonl
head -c 300 $W/resp_$L.txt | tr '\n' ' ' > $E/${L}_response_head.txt; rm -f $W/resp_$L.txt
python3 $H/summarize.py $RIG $L "$EP $MODEL stream=$STREAM gr=${GRD:-none} retries=${RET:-0} hdr=${HDR:-none}" "$OUT" "$A1|$A2|$A3|$A4" | tee -a $E/SUMMARY.txt

LITELLM_PROOF_EOF
harness/fake_upstream.py
cat > harness/fake_upstream.py <<'LITELLM_PROOF_EOF'
"""Round-2 task-owned fake upstream (OpenAI-compatible chat + Bedrock ApplyGuardrail). Mode is the first path segment.
Never logs headers or bodies."""
import asyncio, json, sys, time, uuid
from aiohttp import web

EVENTS = sys.argv[2]
COUNT = {}

def ev(**k):
    with open(EVENTS, "a") as f:
        f.write(json.dumps({"ts": round(time.time(), 3), **k}) + "\n")

USAGE = {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}

def ok_body(cid, model):
    return {"id": cid, "object": "chat.completion", "created": int(time.time()), "model": model,
            "choices": [{"index": 0, "message": {"role": "assistant", "content": "alpha bravo charlie delta echo foxtrot golf hotel"}, "finish_reason": "stop"}], "usage": USAGE}

async def wait_for_close(request, cap):
    t0 = time.time()
    while time.time() - t0 < cap:
        if request.transport is None or request.transport.is_closing():
            return round(time.time() - t0, 2)
        await asyncio.sleep(0.05)
    return None

async def chat(request: web.Request):
    mode = request.match_info["mode"]
    body = await request.json()
    model = body.get("model", "m")
    cid = "chatcmpl-fake-" + uuid.uuid4().hex
    n = COUNT[mode] = COUNT.get(mode, 0) + 1
    ev(event="upstream_request_accepted", mode=mode, id=cid, stream=bool(body.get("stream")), nth_for_mode=n, body_bytes=request.content_length)
    if mode == "interrupt":
        resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
        await resp.prepare(request)
        def ch(delta):
            return ("data: " + json.dumps({"id": cid, "object": "chat.completion.chunk", "created": int(time.time()), "model": model,
                    "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}) + "\n\n").encode()
        await resp.write(ch({"role": "assistant", "content": ""}))
        for w in ["alpha ", "bravo ", "charlie ", "delta ", "echo "]:
            await resp.write(ch({"content": w})); await asyncio.sleep(0.05)
        ev(event="upstream_aborting_midstream", id=cid, chunks_sent=5)
        request.transport.abort()
        return resp
    if mode == "reject" or (mode == "hangreject" and n % 2 == 0):
        ev(event="upstream_rejected_400", id=cid)
        return web.json_response({"error": {"message": "fake upstream rejects this request", "type": "invalid_request_error", "code": "fake_reject"}}, status=400)
    hang = mode in ("hang", "hangreject") or (mode == "flaky" and n % 2 == 1) or mode.startswith("hold")
    if hang:
        cap = 6 if mode.startswith("hold") else 25
        try:
            closed = await wait_for_close(request, cap)
        except asyncio.CancelledError:
            ev(event="upstream_handler_cancelled_peer_closed", id=cid)
            raise
        if closed is not None:
            ev(event="upstream_saw_peer_close_before_responding", id=cid, after_s=closed)
            return web.Response(status=499)
        ev(event="upstream_peer_still_connected_responding_200", id=cid, after_s=cap, usage=USAGE)
    else:
        ev(event="upstream_completed_nonstream", id=cid, usage=USAGE)
    return web.json_response(ok_body(cid, model))

async def guardrail(request: web.Request):
    gmode = request.match_info["gmode"]
    await request.read()
    block = gmode == "grblock"
    usage = {"topicPolicyUnits": 1, "contentPolicyUnits": 1, "wordPolicyUnits": 0, "sensitiveInformationPolicyUnits": 0,
             "sensitiveInformationPolicyFreeUnits": 0, "contextualGroundingPolicyUnits": 0}
    ev(event="guardrail_apply_called", gmode=gmode, path=request.path, action="GUARDRAIL_INTERVENED" if block else "NONE", usage=usage)
    if block:
        return web.json_response({"action": "GUARDRAIL_INTERVENED", "usage": usage, "outputs": [{"text": "blocked by t53156 fixture guardrail"}],
            "assessments": [{"topicPolicy": {"topics": [{"name": "t53156-topic", "type": "DENY", "action": "BLOCKED"}]}}]})
    return web.json_response({"action": "NONE", "usage": usage, "outputs": [], "assessments": []})

async def responses(request: web.Request):
    mode = request.match_info["mode"]
    if mode != "interrupt":
        return await chat(request)
    body = await request.json()
    rid = "resp_fake_" + uuid.uuid4().hex
    n = COUNT[mode] = COUNT.get(mode, 0) + 1
    ev(event="upstream_request_accepted", mode=mode, api="responses", id=rid, stream=bool(body.get("stream")), nth_for_mode=n, body_bytes=request.content_length)
    resp = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
    await resp.prepare(request)
    base = {"id": rid, "object": "response", "created_at": int(time.time()), "model": body.get("model", "m"), "status": "in_progress", "output": [], "usage": None}
    item = "msg_fake_" + uuid.uuid4().hex
    def sse(seq, typ, **k):
        return ("event: " + typ + "\ndata: " + json.dumps({"type": typ, "sequence_number": seq, **k}) + "\n\n").encode()
    await resp.write(sse(0, "response.created", response=base))
    await resp.write(sse(1, "response.in_progress", response=base))
    await resp.write(sse(2, "response.output_item.added", output_index=0, item={"id": item, "type": "message", "status": "in_progress", "role": "assistant", "content": []}))
    await resp.write(sse(3, "response.content_part.added", item_id=item, output_index=0, content_index=0, part={"type": "output_text", "text": "", "annotations": []}))
    for i, w in enumerate(["alpha ", "bravo ", "charlie ", "delta ", "echo "]):
        await resp.write(sse(4 + i, "response.output_text.delta", item_id=item, output_index=0, content_index=0, delta=w)); await asyncio.sleep(0.05)
    ev(event="upstream_aborting_midstream", api="responses", id=rid, deltas_sent=5)
    request.transport.abort()
    return resp


app = web.Application()
app.router.add_post("/{gmode:grblock|grpass}/guardrail/{gid}/version/{ver}/apply", guardrail)
app.router.add_post("/{mode}/v1/chat/completions", chat)
app.router.add_post("/{mode}/chat/completions", chat)
app.router.add_post("/{mode}/v1/responses", responses)
app.router.add_post("/{mode}/responses", responses)
web.run_app(app, host="127.0.0.1", port=int(sys.argv[1]), print=None, handler_cancellation=False)

LITELLM_PROOF_EOF
harness/flush.sh
cat > harness/flush.sh <<'LITELLM_PROOF_EOF'
#!/bin/bash
# usage: flush.sh <rig>  -> SIGUSR1 to both proxy workers (runs the proxy's own update_spend), waits for one kit.flush_ack per worker
H=$(cd "$(dirname "$0")" && pwd); F=$H/../run/$1/trace.jsonl
PIDS=$(grep -h '"kit.installed_wrappers"' $F | python3 -c 'import sys,json;print(" ".join(sorted({str(json.loads(l)["pid"]) for l in sys.stdin})))')
B=$(grep -c '"kit.flush_ack"' $F); N=0
for p in $PIDS; do kill -0 $p 2>/dev/null && { kill -USR1 $p; N=$((N+1)); }; done
for i in $(seq 1 300); do A=$(grep -c '"kit.flush_ack"' $F); [ $((A-B)) -ge $N ] && break; sleep 0.2; done
OK=$(grep '"kit.flush_ack"' $F | tail -$N | grep -c '"ok": true'); echo "flush $1: signalled=$N acks=$((A-B)) ok=$OK"

LITELLM_PROOF_EOF
harness/matrix.sh
cat > harness/matrix.sh <<'LITELLM_PROOF_EOF'
#!/bin/bash
# usage: matrix.sh <rig> <idx> <full|short|real>   runs the case list for one rig sequentially
RIG=$1; I=$2; MODE=$3; H=$(cd "$(dirname "$0")" && pwd); c(){ $H/case.sh $RIG $I "$@"; }
if [ $MODE = retryonly ]; then c C11_retry_only_billed_then_zero_final chat syn-hangreject false "" 1; exit; fi
if [ $MODE = retryzero ]; then c C12_retry_billed_then_total_timeout_zero_final${4:+_try$4} chat syn-readtimeout false "" 2 "x-litellm-total-timeout: 4"; exit; fi
if [ $MODE = respstream ]; then c R02_responses_stream_interrupt responses syn-interrupt true; exit; fi
if [ $MODE = real ]; then c REAL_stream_interrupt chat real-cut true; exit; fi
c C01_stream_interrupt chat syn-interrupt true
c C02_read_timeout chat syn-readtimeout false
c C03_retry_terminal chat syn-readtimeout false "" 2
c C04_guardrail_pre_block chat syn-ok false gr-pre-block
c C05_success chat syn-ok false
[ $MODE = short ] && exit
c C06_retry_only_final_zero chat syn-readtimeout false "" 2 "x-litellm-total-timeout: 3"
c C07_mixed_guardrail_pass_read_timeout chat syn-readtimeout false gr-pre-pass
c C08_finalized_post_guardrail_block chat syn-ok false gr-post-block
c C09_zero_upstream_reject chat syn-reject false
c C10_zero_connect_refused chat syn-refused false
c M01_messages_read_timeout messages syn-readtimeout false
c M02_messages_stream_interrupt messages syn-interrupt true
c R01_responses_read_timeout responses syn-readtimeout false

LITELLM_PROOF_EOF
harness/relay.py
cat > harness/relay.py <<'LITELLM_PROOF_EOF'
"""Task-owned plain-HTTP relay to a real provider. /cut/<rest> truncates the SSE body after N data events
that carry output text, then aborts the downstream connection. /pass/<rest> relays unchanged.
Never logs headers or bodies."""
import json, sys, time
import aiohttp
from aiohttp import web

PORT, TARGET, EVENTS, CUT_AFTER = int(sys.argv[1]), sys.argv[2].rstrip("/"), sys.argv[3], int(sys.argv[4])
HOP = {"host", "content-length", "transfer-encoding", "connection", "accept-encoding"}

def ev(**k):
    with open(EVENTS, "a") as f:
        f.write(json.dumps({"ts": time.time(), **k}) + "\n")

async def handle(request: web.Request):
    mode, rest = request.match_info["mode"], request.match_info["rest"]
    body = await request.read()
    headers = {k: v for k, v in request.headers.items() if k.lower() not in HOP}
    ev(event="relay_request", mode=mode, path="/" + rest)
    async with aiohttp.ClientSession(auto_decompress=True) as s:
        async with s.post(f"{TARGET}/{rest}", data=body, headers=headers) as up:
            out_headers = {k: v for k, v in up.headers.items() if k.lower() in ("content-type", "request-id", "x-request-id")}
            resp = web.StreamResponse(status=up.status, headers=out_headers)
            await resp.prepare(request)
            deltas = 0
            seen_usage = []
            async for line in up.content:
                await resp.write(line)
                if line.startswith(b"data:") and (b"content_block_delta" in line or b'"delta":{"content"' in line or b"output_text.delta" in line):
                    deltas += 1
                if line.startswith(b"data:") and b'"usage"' in line:
                    try:
                        d = json.loads(line[5:])
                        u = d.get("usage") or (d.get("message") or {}).get("usage")
                        if u:
                            seen_usage.append({k: v for k, v in u.items() if isinstance(v, int)})
                    except Exception:
                        pass
                if mode == "cut" and deltas >= CUT_AFTER:
                    ev(event="relay_aborting_midstream", provider_status=up.status, provider_request_id=up.headers.get("request-id") or up.headers.get("x-request-id"), deltas_relayed=deltas, usage_events_relayed_before_cut=seen_usage)
                    request.transport.abort()
                    return resp
            ev(event="relay_completed", provider_status=up.status, provider_request_id=up.headers.get("request-id") or up.headers.get("x-request-id"), deltas_relayed=deltas, usage_events_relayed=seen_usage)
            return resp

app = web.Application(client_max_size=8 * 2**20)
app.router.add_post("/{mode}/{rest:.*}", handle)
web.run_app(app, host="127.0.0.1", port=PORT, print=None)

LITELLM_PROOF_EOF
harness/rig.sh
cat > harness/rig.sh <<'LITELLM_PROOF_EOF'
#!/bin/bash
# usage: rig.sh start|stop <rig> <clone_dir> <ledger on|off> <flag false|true> <spend on|off> <index 0-9>
# A rig is one proxy (2 workers) with its own Redis, fake upstream, relay and Postgres database.
ACT=$1; RIG=$2; CLONE=$3; LEDGER=$4; FLAG=$5; SPEND=$6; I=$7
H=$(cd "$(dirname "$0")" && pwd); W=$H/../run/$RIG; mkdir -p $W
PP=$((4800+I)); UP=$((4820+I)); RP=$((4840+I)); LP=$((4860+I))
BASE=$(echo "$DATABASE_URL" | sed -E 's#/[^/]*$##'); DB=t53156_$RIG
if [ "$ACT" = stop ]; then
  for f in proxy upstream redis relay; do [ -f $W/$f.pid ] && kill $(cat $W/$f.pid) 2>/dev/null; done; sleep 3
  for p in $(pgrep -f "proxy_cl[i].py --config $W/config.yaml"); do kill -9 $p 2>/dev/null; done
  psql "$DATABASE_URL" -qc "drop database if exists \"$DB\"" ; exit 0
fi
M(){ echo "  - model_name: $1"; echo "    litellm_params: {model: openai/gpt-5.4-nano, api_base: \"$2\", api_key: fake-key$3}"; }
GR(){ echo "  - guardrail_name: $1"; echo "    litellm_params: {guardrail: bedrock, mode: $2, guardrailIdentifier: t53156gr, guardrailVersion: \"1\", aws_region_name: us-east-1, aws_access_key_id: fake-access-key, aws_secret_access_key: fake-secret-key, aws_bedrock_runtime_endpoint: \"http://127.0.0.1:$UP/$3\"}"; }
{ echo "model_list:"; U=http://127.0.0.1:$UP
M syn-ok $U/ok/v1 ""; M syn-reject $U/reject/v1 ""; M syn-interrupt $U/interrupt/v1 ""
M syn-readtimeout $U/hang/v1 ", timeout: 2"; M syn-hangreject $U/hangreject/v1 ", timeout: 2"; M syn-refused http://127.0.0.1:4899/v1 ", timeout: 2"
echo "  - model_name: real-cut"; echo "    litellm_params: {model: anthropic/claude-haiku-5-5, api_base: \"http://127.0.0.1:$LP/cut\", api_key: os.environ/ANTHROPIC_API_KEY}"
echo "guardrails:"; GR gr-pre-block pre_call grblock; GR gr-pre-pass pre_call grpass; GR gr-post-block post_call grblock
cat <<Y
litellm_settings:
  callbacks: ["t53156_trace.trace"]
  num_retries: 0
router_settings:
  num_retries: 0
  redis_host: 127.0.0.1
  redis_port: $RP
general_settings:
  master_key: sk-t53156-master
  use_spend_logs_ledger: $([ $LEDGER = on ] && echo true || echo false)
  disable_error_logs: $FLAG
  disable_spend_updates: $([ $SPEND = off ] && echo true || echo false)
  proxy_batch_write_at: 3600
  coordination_redis: {host: 127.0.0.1, port: $RP}
Y
} > $W/config.yaml
psql "$DATABASE_URL" -qc "drop database if exists \"$DB\"" -c "create database \"$DB\""
(cd $CLONE/litellm/proxy && DATABASE_URL="$BASE/$DB" ${VENV_BIN:?set VENV_BIN to the venv bin dir}/prisma db push --accept-data-loss --skip-generate >/dev/null 2>&1)
PY=${VENV_BIN:?set VENV_BIN to the venv bin dir}/python
(setsid redis-server --port $RP --bind 127.0.0.1 --save "" --appendonly no --dir $W --daemonize no >/dev/null 2>&1 & echo $! > $W/redis.pid)
(setsid $PY $H/fake_upstream.py $UP $W/upstream_events.jsonl > $W/upstream.log 2>&1 & echo $! > $W/upstream.pid)
(setsid $PY $H/relay.py $LP https://api.anthropic.com $W/relay_events.jsonl 3 > $W/relay.log 2>&1 & echo $! > $W/relay.pid)
: > $W/upstream_events.jsonl
( export DATABASE_URL="$BASE/$DB" PYTHONPATH="$H:$CLONE:$CLONE/litellm/proxy-extras:$CLONE/litellm/enterprise" T53156_TRACE="$W/trace.jsonl" LITELLM_LOCAL_MODEL_COST_MAP=True
  unset DIRECT_URL DATABASE_URL_READ_REPLICA; cd $CLONE
  setsid $PY litellm/proxy/proxy_cli.py --config $W/config.yaml --port $PP --num_workers 2 2>&1 | tail -c 20000000 > $W/proxy.log & )
for i in $(seq 1 120); do [ "$(curl -s -o /dev/null -w '%{http_code}' localhost:$PP/health/liveliness)" = 200 ] && break; sleep 2; done
pgrep -f "proxy_cl[i].py --config $W/config.yaml" | head -1 > $W/proxy.pid
c(){ curl -s -m30 localhost:$PP$1 -H "Authorization: Bearer sk-t53156-master" -H "content-type: application/json" -d "$2"; }
j(){ python3 -c "import sys,json;d=json.load(sys.stdin);print(d.get('$1') or '')"; }
ORG=$(c /organization/new '{"organization_alias":"t53156-org","max_budget":100}' | j organization_id)
TEAM=$(c /team/new "{\"team_alias\":\"t53156-team\",\"organization_id\":\"$ORG\"}" | j team_id)
c /user/new '{"user_id":"t53156-user","user_role":"internal_user"}' >/dev/null
c /team/member_add "{\"team_id\":\"$TEAM\",\"member\":{\"role\":\"user\",\"user_id\":\"t53156-user\"}}" >/dev/null
PROJ=$(c /project/new "{\"project_alias\":\"t53156-proj\",\"team_id\":\"$TEAM\"}" | j project_id)
c /customer/new '{"user_id":"t53156-enduser"}' >/dev/null
c /key/generate "{\"team_id\":\"$TEAM\",\"user_id\":\"t53156-user\",\"project_id\":\"$PROJ\",\"key_alias\":\"t53156-key\"}" | j key > $W/key.txt
echo "$RIG up: proxy :$PP health=$(curl -s -o /dev/null -w '%{http_code}' localhost:$PP/health/liveliness) key=$([ -s $W/key.txt ] && echo ok || echo MISSING) trace_lines=$(wc -l < $W/trace.jsonl 2>/dev/null)"

LITELLM_PROOF_EOF
harness/snap.sh
cat > harness/snap.sh <<'LITELLM_PROOF_EOF'
#!/bin/bash
# usage: snap.sh <rig>   prints sanitized accounting state (no key material)
BASE=$(echo "$DATABASE_URL" | sed -E 's#/[^/]*$##'); q(){ psql "$BASE/t53156_$1" -At -F' | ' -c "$2"; }
D=$1
echo "-- deliveries"; q $D "select delivery_id, request_id, state, attempts, is_batch, applied_at is not null as applied, (accounting_payload->>'spend') as p_spend, left(accounting_payload::text,0) from \"LiteLLM_SpendLogDelivery\" order by created_at"
echo "-- spendlogs"; q $D "select request_id, status, call_type, model_group, round(spend::numeric,10), prompt_tokens, completion_tokens, team_id is not null, organization_id is not null, \"user\", end_user, request_tags from \"LiteLLM_SpendLogs\" order by \"startTime\""
echo "-- counters"; q $D "select 'key', key_alias, round(spend::numeric,10) from \"LiteLLM_VerificationToken\" where key_alias='t53156-key' union all select 'team', team_alias, round(spend::numeric,10) from \"LiteLLM_TeamTable\" union all select 'user', user_id, round(spend::numeric,10) from \"LiteLLM_UserTable\" where user_id='t53156-user' union all select 'org', organization_alias, round(spend::numeric,10) from \"LiteLLM_OrganizationTable\" where organization_alias='t53156-org' union all select 'project', project_alias, round(spend::numeric,10) from \"LiteLLM_ProjectTable\" union all select 'end_user', user_id, round(spend::numeric,10) from \"LiteLLM_EndUserTable\" union all select 'team_member', user_id, round(spend::numeric,10) from \"LiteLLM_TeamMembership\" union all select 'org_member', user_id, round(spend::numeric,10) from \"LiteLLM_OrganizationMembership\" union all select 'tag', tag_name, round(spend::numeric,10) from \"LiteLLM_TagTable\""
echo "-- daily (table | rows | spend | prompt | completion | api_requests | successful | failed)"
for t in User Team Organization Tag EndUser; do q $D "select 'Daily$t', count(*), round(coalesce(sum(spend),0)::numeric,10), coalesce(sum(prompt_tokens),0), coalesce(sum(completion_tokens),0), coalesce(sum(api_requests),0), coalesce(sum(successful_requests),0), coalesce(sum(failed_requests),0) from \"LiteLLM_Daily${t}Spend\""; done

LITELLM_PROOF_EOF
harness/summarize.py
cat > harness/summarize.py <<'LITELLM_PROOF_EOF'
"""One-line-per-case summary from the saved snapshots and trace. usage: summarize.py <rig> <label> <desc> <http> <acks>"""
import json, os, re, sys
rig, label, desc, http, acks = sys.argv[1:6]
E = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "evidence", rig)
def snap(n):
    out = {"deliveries": [], "spendlogs": [], "counters": {}, "daily": {}}; sec = None
    for l in open(f"{E}/{label}_{n}.txt"):
        l = l.rstrip("\n")
        if l.startswith("-- "):
            sec = l[3:].split(" ")[0]; continue
        p = [x.strip() for x in l.split("|")]
        if sec == "deliveries": out["deliveries"].append((p[0], p[1], p[2], p[6]))
        elif sec == "spendlogs": out["spendlogs"].append((p[0], p[1], p[4]))
        elif sec == "counters": out["counters"][p[0] + ":" + p[1]] = float(p[2])
        elif sec == "daily": out["daily"][p[0]] = (int(p[1]), float(p[2]), int(p[5]), int(p[6]), int(p[7]))
    return out
b, a2, a4 = snap("0_before"), snap("2_after_flush2"), snap("3_after_flush4")
bd = {d[0] for d in b["deliveries"]}; bl = {s[0] for s in b["spendlogs"]}
newd = [d for d in a4["deliveries"] if d[0] not in bd]; newl = [s for s in a4["spendlogs"] if s[0] not in bl]
delta = {k: round(a4["counters"].get(k, 0) - b["counters"].get(k, 0), 10) for k in a4["counters"]}
key_delta = delta.get("key:t53156-key"); same = {k: v for k, v in delta.items() if not k.startswith("team_member:default")}
uniform = len({v for v in same.values()}) <= 1
ev = [json.loads(l) for l in open(f"{E}/{label}_trace.jsonl")]
def first(cb, phase=None):
    return next((e for e in ev if e["cb"] == cb and (phase is None or e.get("phase") == phase)), None)
t = first("wrap.tracks_failure_spend", "enter"); tx = first("wrap.tracks_failure_spend", "exit")
lf = first("wrap._ProxyDBLogger.async_post_call_failure_hook", "enter"); hk = first("hook.async_post_call_failure_hook")
src = t or lf or hk or {}
slo = src.get("slo") or {}
path = "rust" if t else ("python" if lf else ("success" if first("logger.async_log_success_event") else "?"))
up = [json.loads(l)["event"] for l in open(f"{E}/{label}_upstream.jsonl")] if os.path.exists(f"{E}/{label}_upstream.jsonl") else []
rec = {"rig": rig, "case": label, "req": desc, "http": http, "path": path,
       "exc": (hk or {}).get("exc"), "cost_finalized": slo.get("cost_finalized"), "response_cost": src.get("response_cost"),
       "failure_row_cost": src.get("failure_row_response_cost"), "billed_failed_attempts": src.get("billed_failed_attempts"),
       "tracks_failure_spend": (tx or {}).get("result"), "upstream": up,
       "new_deliveries": [(d[1][-12:], d[2], d[3]) for d in newd], "new_spendlogs": [(s[1], s[2]) for s in newl],
       "key_delta": key_delta, "all_entity_deltas_equal": uniform,
       "daily_user_delta(rows,spend,req,ok,fail)": tuple(round(x - y, 10) for x, y in zip(a4["daily"].get("DailyUser", (0,) * 5), b["daily"].get("DailyUser", (0,) * 5))),
       "stable_flush2_vs_flush4": a2 == a4, "acks": acks}
print(json.dumps(rec))

LITELLM_PROOF_EOF
harness/t53156_trace.py
cat > harness/t53156_trace.py <<'LITELLM_PROOF_EOF'
"""Task-owned passive tracing for issue #53156 verification. No product behaviour is changed:
wrappers only record arguments and call through. The one active fixture is the marker-triggered
post-call rejection (POSTCALLFAIL) and the SIGUSR1 handler that runs the proxy's own update_spend()."""
import asyncio, functools, json, os, signal, time

from fastapi import HTTPException
from litellm.integrations.custom_logger import CustomLogger

OUT = os.environ["T53156_TRACE"]

def _w(**k):
    with open(OUT, "a") as f:
        f.write(json.dumps({"ts": round(time.time(), 3), "pid": os.getpid(), **k}, default=str) + "\n")

def _usage(u):
    if u is None:
        return None
    g = (lambda n: getattr(u, n, None)) if not isinstance(u, dict) else u.get
    return {"prompt_tokens": g("prompt_tokens"), "completion_tokens": g("completion_tokens"), "total_tokens": g("total_tokens")}

def _slo(d):
    s = d.get("standard_logging_object") if isinstance(d, dict) else None
    if not isinstance(s, dict):
        return None
    return {"status": s.get("status"), "response_cost": s.get("response_cost"), "cost_finalized": s.get("cost_finalized"),
            "prompt_tokens": s.get("prompt_tokens"), "completion_tokens": s.get("completion_tokens"), "id": s.get("id")}

def _req(d):
    return {"litellm_call_id": d.get("litellm_call_id"), "model": d.get("model"), "response_cost": d.get("response_cost"),
            "combined_usage_object": _usage(d.get("combined_usage_object")), "slo": _slo(d),
            "billed_failed_attempts": len(d.get("billed_failed_attempts") or ()),
            "billed_failed_attempts_detail": [repr(x)[:400] for x in (d.get("billed_failed_attempts") or ())] or None,
            "accounting_finalized_cost": repr(d.get("_accounting_finalized_cost"))[:200] if d.get("_accounting_finalized_cost") is not None else None,
            "guardrail_info": _gr(d)}

def _gr(d):
    out = []
    md = d.get("metadata") if isinstance(d.get("metadata"), dict) else {}
    lmd = d.get("litellm_metadata") if isinstance(d.get("litellm_metadata"), dict) else {}
    slo = d.get("standard_logging_object") if isinstance(d.get("standard_logging_object"), dict) else {}
    for src, raw in (("metadata", md.get("standard_logging_guardrail_information")), ("litellm_metadata", lmd.get("standard_logging_guardrail_information")), ("slo", slo.get("guardrail_information"))):
        for e in (raw if isinstance(raw, list) else [raw] if isinstance(raw, dict) else []):
            if isinstance(e, dict):
                out.append({"src": src, "name": e.get("guardrail_name"), "mode": str(e.get("guardrail_mode")), "status": e.get("guardrail_status"),
                            "guardrail_cost": e.get("guardrail_cost"), "in_spend": e.get("guardrail_cost_in_spend"), "usage": e.get("guardrail_usage")})
    return out or None

def _chain(e):
    out, seen = [], set()
    while e is not None and id(e) not in seen and len(out) < 8:
        seen.add(id(e)); out.append(type(e).__module__.split(".")[0] + "." + type(e).__name__)
        e = e.__cause__ or e.__context__ or getattr(e, "original_exception", None)
    return out

def _marker(data):
    try:
        return any("POSTCALLFAIL" in str(m.get("content")) for m in data.get("messages") or [])
    except Exception:
        return False

class Trace(CustomLogger):
    async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
        _w(cb="logger.async_log_success_event", **_req(kwargs))

    async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):
        _w(cb="logger.async_log_failure_event", exc=type(kwargs.get("exception")).__name__, **_req(kwargs))

    async def async_post_call_failure_hook(self, request_data, original_exception, user_api_key_dict, traceback_str=None):
        _w(cb="hook.async_post_call_failure_hook", exc=type(original_exception).__name__, exc_chain=_chain(original_exception), status_code=getattr(original_exception, "status_code", None), **_req(request_data))

    async def async_post_call_success_hook(self, data, user_api_key_dict, response):
        fail = _marker(data)
        _w(cb="hook.async_post_call_success_hook", litellm_call_id=data.get("litellm_call_id"), fixture_raises=fail)
        if fail:
            raise HTTPException(status_code=400, detail={"error": "t53156 fixture: post-call processing rejected the completed response"})
        return response

trace = Trace()

def _wrap(owner, name, describe):
    orig = getattr(owner, name)
    @functools.wraps(orig)
    async def wrapper(*a, **k):
        try:
            _w(cb=f"wrap.{owner.__name__}.{name}", phase="enter", **describe(a, k))
        except Exception as e:
            _w(cb=f"wrap.{owner.__name__}.{name}", phase="enter", describe_error=repr(e))
        try:
            r = await orig(*a, **k)
        except BaseException as e:
            _w(cb=f"wrap.{owner.__name__}.{name}", phase="raise", exc=repr(e)[:200])
            raise
        _w(cb=f"wrap.{owner.__name__}.{name}", phase="exit", result=r if isinstance(r, (bool, int, float, type(None))) else type(r).__name__)
        return r
    setattr(owner, name, wrapper)

def _swrap(mod, name, describe, after=None):
    orig = getattr(mod, name)
    @functools.wraps(orig)
    def wrapper(*a, **k):
        try:
            _w(cb=f"wrap.{name}", phase="enter", **describe(a, k))
        except Exception as e:
            _w(cb=f"wrap.{name}", phase="enter", describe_error=repr(e)[:200])
        try:
            r = orig(*a, **k)
        except BaseException as e:
            _w(cb=f"wrap.{name}", phase="raise", exc=repr(e)[:200]); raise
        try:
            _w(cb=f"wrap.{name}", phase="exit", **(after(r) if after else {"result": r if isinstance(r, (bool, int, float, type(None))) else type(r).__name__}))
        except Exception as e:
            _w(cb=f"wrap.{name}", phase="exit", describe_error=repr(e)[:200])
        return r
    setattr(mod, name, wrapper)

def _install():
    installed = []
    def general():
        from litellm.proxy.proxy_server import general_settings
        return {"disable_error_logs": general_settings.get("disable_error_logs"), "use_spend_logs_ledger": general_settings.get("use_spend_logs_ledger"),
                "disable_spend_updates": general_settings.get("disable_spend_updates")}
    from litellm.proxy.hooks import proxy_track_cost_callback as ptc
    try:
        from litellm.proxy.spend_tracking import rust_spend_log_inputs as rin
        def d_tracks(a, k):
            rd, exc, completed = a[0], a[1], a[3] if len(a) > 3 else k.get("completed_cost")
            return {**_req(rd), "exc_chain": _chain(exc), "completed_cost": completed, "settings": general(),
                    "failure_row_response_cost": ptc.failure_row_response_cost(rd)}
        _swrap(rin, "tracks_failure_spend", d_tracks)
        def a_rows(r):
            return {"rows": [{"response_cost": x.get("response_cost"), "id": str(x.get("litellm_call_id") or x.get("id"))[:60]} for x in r]}
        _swrap(rin, "failure_spend_rows", lambda a, k: {}, a_rows)
        def a_input(r):
            d = getattr(r, "document", None) or {}
            return {"kind": d.get("kind"), "track": d.get("track"), "n_rows": len(d.get("rows") or ())}
        _swrap(rin, "spend_log_failure_input", lambda a, k: {}, a_input)
        _swrap(rin, "spend_log_success_input", lambda a, k: {}, a_input)
        installed.append("rust_spend_log_inputs")
    except Exception as e:
        _w(cb="kit.install_note", part="rust_spend_log_inputs", error=repr(e)[:200])
    try:
        from litellm.proxy.hooks import rust_spend_logger as rsl
        def d_host(a, k):
            q = a[1] if len(a) > 1 else {}
            return {key: q.get(key) for key in ("position", "billable_cost", "spend_logs_kept", "claimed", "cost", "team_id") if key in q} | {"has_token": bool(q.get("token"))}
        for n in ("after_write", "after_charge", "logged_cost", "failed_tracking_alert"):
            _swrap(rsl.SpendLogHost, n, d_host)
        installed.append("SpendLogHost")
    except Exception as e:
        _w(cb="kit.install_note", part="SpendLogHost", error=repr(e)[:200])
    try:
        L = ptc._ProxyDBLogger
        def d_fail(a, k):
            rd = k.get("request_data") if "request_data" in k else a[1]
            return {**_req(rd), "settings": general()}
        _wrap(L, "async_post_call_failure_hook", d_fail)
        _wrap(L, "_PROXY_track_cost_callback", lambda a, k: _req(a[1] if len(a) > 1 else k.get("kwargs")))
        installed.append("legacy _ProxyDBLogger")
    except Exception as e:
        _w(cb="kit.install_note", part="legacy", error=repr(e)[:200])
    _w(cb="kit.install_parts", parts=installed)

if os.environ.get("T53156_WRAP", "1") == "1":
    _install()
    _w(cb="kit.installed_wrappers")

_n = {"flush": 0}

async def _flush(tag):
    from litellm.proxy import proxy_server as ps
    from litellm.proxy.utils import update_spend
    try:
        await update_spend(prisma_client=ps.prisma_client, db_writer_client=None, proxy_logging_obj=ps.proxy_logging_obj)
        _w(cb="kit.flush_ack", n=tag, ok=True)
    except Exception as e:
        _w(cb="kit.flush_ack", n=tag, ok=False, error=repr(e)[:300])

def _on_usr1(signum, frame):
    _n["flush"] += 1
    tag = _n["flush"]
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError as e:
        _w(cb="kit.flush_ack", n=tag, ok=False, error="no running loop: " + repr(e))
        return
    loop.call_soon_threadsafe(lambda: loop.create_task(_flush(tag)))

signal.signal(signal.SIGUSR1, _on_usr1)

LITELLM_PROOF_EOF

Type

Bug Fix

Final Attestation

  • The tests check the right things, including relevant edge cases and customer scenarios

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@greptileai review

@joshua-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@joshua-berri

Copy link
Copy Markdown
Contributor Author

@veria-ai

@veria-ai

veria-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@cursor

cursor Bot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

Bugbot is paused — your team has an unpaid invoice

Bugbot is paused because your team has an unpaid invoice.

Pay it from the billing page in the Cursor dashboard and Bugbot resumes automatically.

(requestId: 49961743-18cc-4f44-8eba-4f9f20348f0b)

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no actionable issues found.

Summary

Keeps billed failure costs when disable_error_logs is enabled without retaining detailed error logs.

  • Billed failures stay in spend accounting when error logs are off.

Reviews (1) · Last reviewed commit: "fix(spend): retain billed failure accoun..." · Reviewed by Greptile

@joshua-berri
joshua-berri merged commit b5ff853 into main Nov 21, 2026
51 checks passed
@joshua-berri
joshua-berri deleted the litellm_fix_billed_failures_error_logs_53156 branch November 21, 2026 02:35

@surlymochan surlymochan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Checked the gate against the helpers it calls: failure_row_response_cost already covers the recovered-stream cost and the in-spend guardrail cost, and _billed_failed_attempts returns the stashed retry attempts, so _failure_billed_the_provider ORs exactly the three ways a failure can have billed the provider. The old condition dropped all three whenever error logs were off and there was no completed cost, which is the spend leak this fixes. The negative-cost and guardrail-outside-spend cases in the new tests confirm the > 0 boundary holds, nothing billed still means nothing written. The rust-side test mirrors the same matrix, which matters since the two writers have to agree on what counts as billed.

mateo-berri pushed a commit to izzybn/litellm that referenced this pull request Nov 25, 2026
…bled (BerriAI#53271)

Adapted for lts/1.108.x. This line's failure hook has no finalized-cost
branch and no tracks_failure_spend helper, so the billed check joins the
hook's own disable_error_logs gate, and the Rust spend ledger test is left
out because this line has no Rust spend ledger. The unit tests use this
line's DualCache counters.

Co-authored-by: Joshua Valluru <326636767+joshua-berri@users.noreply.github.com>
(cherry picked from commit b5ff853)
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.

Billed-but-errored requests are dropped from spend when disable_error_logs is true

3 participants