Skip to content

fix(auth): report unreadable team rows as 503 and open the rust db in the spend logs parity test - #52923

Merged
mateo-berri merged 2 commits into
mainfrom
litellm_fix_spendlogs_parity_team_lookup
Nov 24, 2026
Merged

mateo-berri merged 2 commits into
mainfrom
litellm_fix_spendlogs_parity_team_lookup

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

When the proxy could not read a team from the database, it told callers the team did not exist, which sent people hunting for a deleted team during a database outage. Now an unreadable team row returns a 503 so the outage is visible, and the spend logs parity integration test opens the Rust database it needs since #52176 moved team reads onto it

Details

Link to Devin session: https://app.devin.ai/sessions/137b3aa85599475992a0f318641361ca
Open in Devin Desktop: https://app.devin.ai/desktop/session/137b3aa85599475992a0f318641361ca?variant=devin
Requested by: @narmstrong-berri

TLDR

Problem this solves:

  • test_pending_delivery_after_reset_matches_queued_legacy_spend failed 3x on scheduled integration runs
  • Its fixture connected only Prisma, so team reads raised NoDatabaseConnected
  • get_team_object reported that failed read as "Team doesn't exist in db" (404)

How it solves it:

  • The parity fixture opens and closes the Rust database with Database.open() / aclose()
  • A failed team read now raises 503 "Team policy is unavailable", chained to the real error
  • A team that is truly absent still raises TeamNotFoundError (404)

User Flow

A proxy admin sends POST /team/member_add with a team ID and a member

  1. If Postgres cannot read the existing team, the old proxy returns 404. The new proxy returns 503 Team policy is unavailable
  2. A team ID that does not exist returns 404 on both commits
  3. Once Postgres can read the team again, adding the member succeeds on both commits

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

/qa PASS at f36c4d27a3841aed8282bbd3605e9cc2056e60e0. The before and after runs used live proxies, PostgreSQL, Redis, and OpenAI for the chat control

Request or test Before After
POST /team/member_add, existing team unreadable 404 503 Team policy is unavailable
POST /team/member_add, absent team 404 404
POST /team/member_add, team readable again 200 200
Spend logs parity, two workers NoDatabaseConnected 101 passed
Auth unit tests 734 passed

The chat request returned 200 in this outage scenario on both commits

Live proxy commands and output

Run from the repository root at each commit with an initialized .venv, a working DATABASE_URL for disposable local PostgreSQL databases, a local redis-server, and OPENAI_API_KEY in the shell. Save the script below at /tmp/qa52923_live.py. It boots two proxy instances per commit and restores the scratch database schema before testing recovery

PATH="$PWD/.venv/bin:$PATH" PYTHONPATH="$PWD:$PWD/tests:$PWD/tests/e2e" LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 PYTHON_DOTENV_DISABLED=1 .venv/bin/python /tmp/qa52923_live.py /tmp/qa52923-confirmed-base
Git commit c3cd9ad5b77f3ae38e372840e7ccf5de2f4ed415
Ready: two proxy instances with two workers each
POST /team/member_add (missing team) -> HTTP 404
  {'error': "Team doesn't exist in db. Team=qa-no-such-team. Create team via `/team/new` call."}
POST /v1/chat/completions (healthy) -> HTTP 200
POST /team/member_add (team read fails) -> HTTP 404
  {'error': "Team doesn't exist in db. Team=qa-policy. Create team via `/team/new` call."}
POST /v1/chat/completions (team read fails) -> HTTP 200
POST /team/member_add (read restored) -> HTTP 200
PATH="$PWD/.venv/bin:$PATH" PYTHONPATH="$PWD:$PWD/tests:$PWD/tests/e2e" LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 PYTHON_DOTENV_DISABLED=1 .venv/bin/python /tmp/qa52923_live.py /tmp/qa52923-confirmed-head
Git commit f36c4d27a3841aed8282bbd3605e9cc2056e60e0
Ready: two proxy instances with two workers each
POST /team/member_add (missing team) -> HTTP 404
  {'error': "Team doesn't exist in db. Team=qa-no-such-team. Create team via `/team/new` call."}
POST /v1/chat/completions (healthy) -> HTTP 200
POST /team/member_add (team read fails) -> HTTP 503
  Team policy is unavailable
POST /v1/chat/completions (team read fails) -> HTTP 200
POST /team/member_add (read restored) -> HTTP 200
import os
import secrets
import subprocess
import sys
from pathlib import Path

import httpx
import psycopg
import yaml

from tests.integration._support.client import Gateway
from tests.integration._support.database import scratch_database
from tests.integration._support.process import owned_proxy_process
from tests.integration._support.redis_process import owned_redis


def post(proxy, path, body, key, *, report=None):
    response = proxy.gateway.client.post(path, headers={"Authorization": f"Bearer {key}"}, json=body)
    if report:
        result = response.json()
        detail = result.get("detail") or result.get("error") if isinstance(result, dict) else None
        print(f"POST {path} ({report}) -> HTTP {response.status_code}", flush=True)
        if detail:
            print(f"  {detail}", flush=True)
    return response


directory = Path(sys.argv[1])
directory.mkdir(parents=True, exist_ok=True)
head = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
assert not subprocess.check_output(["git", "status", "--porcelain"], text=True)
print("Git commit", head, flush=True)
master = "sk-" + secrets.token_hex(24)
team_id = "qa-policy"
member = {"member": {"role": "user", "user_id": "qa-member"}}
chat = {"model": "qa-openai", "messages": [{"role": "user", "content": "Reply with the word hello."}]}

with (
    scratch_database("qa52923") as database,
    owned_redis(directory) as cache,
    httpx.Client(trust_env=False) as client,
):
    config = directory / "proxy.yaml"
    config.write_text(yaml.safe_dump({
        "model_list": [{"model_name": "qa-openai", "litellm_params": {
            "model": "openai/gpt-5-mini", "api_key": "os.environ/OPENAI_API_KEY",
        }}],
        "router_settings": {"redis_host": cache.host, "redis_port": cache.port, "num_retries": 0},
        "general_settings": {
            "master_key": "os.environ/LITELLM_MASTER_KEY",
            "database_url": "os.environ/DATABASE_URL",
            "coordination_redis": {"host": cache.host, "port": cache.port},
        },
    }))
    overrides = {"DATABASE_URL": database, "REDIS_HOST": cache.host, "REDIS_PORT": str(cache.port)}
    seed = Gateway(client, master, "http://127.0.0.1:1")
    with (
        owned_proxy_process(seed, directory / "primary", overrides, config=config, workers=2) as primary,
        owned_proxy_process(seed, directory / "peer", overrides, config=config, workers=2, database_setup=()) as peer,
        psycopg.connect(database, autocommit=True) as db,
    ):
        print("Ready: two proxy instances with two workers each", flush=True)
        post(primary, "/team/new", {"team_id": team_id}, master).raise_for_status()
        key = post(primary, "/key/generate", {"team_id": team_id}, master).raise_for_status().json()["key"]
        cold_key = post(primary, "/key/generate", {"team_id": team_id}, master).raise_for_status().json()["key"]
        missing = post(peer, "/team/member_add", {"team_id": "qa-no-such-team", **member}, master,
                       report="missing team")
        healthy_chat = post(primary, "/v1/chat/completions", chat, key, report="healthy")
        db.execute('ALTER TABLE "LiteLLM_TeamTable" RENAME COLUMN "allow_team_guardrail_config" TO "qa_unreadable"')
        try:
            outage_member = post(peer, "/team/member_add", {"team_id": team_id, **member}, master,
                                 report="team read fails")
            outage_chat = post(peer, "/v1/chat/completions", chat, cold_key,
                               report="team read fails")
        finally:
            db.execute('ALTER TABLE "LiteLLM_TeamTable" RENAME COLUMN "qa_unreadable" TO "allow_team_guardrail_config"')
        restored = post(primary, "/team/member_add", {"team_id": team_id, **member}, master,
                        report="read restored")
        assert missing.status_code == 404
        assert healthy_chat.status_code == 200
        assert restored.status_code == 200
        expected = 404 if head.startswith("c3cd9ad5b7") else 503
        assert outage_member.status_code == expected, outage_member.text
        if expected == 503:
            assert "Team policy is unavailable" in outage_member.text
        assert outage_chat.status_code == 200, outage_chat.text
Spend logs parity and auth tests
PATH="$PWD/.venv/bin:$PATH" PYTHONPATH="$PWD:$PWD/tests:$PWD/tests/e2e" LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 PYTHON_DOTENV_DISABLED=1 INTEGRATION_WORKERS=2 .venv/bin/python tests/integration/run.py database --results /tmp/qa52923-base-parity tests/integration/database/test_spendlogs_ledger_parity.py
E   litellm.repositories.rust_database.NoDatabaseConnected: No db connected
============ 1 failed, 100 passed, 75 warnings in 366.30s (0:06:06) ============
PATH="$PWD/.venv/bin:$PATH" PYTHONPATH="$PWD:$PWD/tests:$PWD/tests/e2e" LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 PYTHON_DOTENV_DISABLED=1 INTEGRATION_WORKERS=2 .venv/bin/python tests/integration/run.py database --results /tmp/qa52923-final-parity tests/integration/database/test_spendlogs_ledger_parity.py
================= 101 passed, 75 warnings in 376.83s (0:06:16) =================
PATH="$PWD/.venv/bin:$PATH" PYTHONPATH="$PWD:$PWD/tests:$PWD/tests/e2e" LITELLM_LOCAL_MODEL_COST_MAP=True AWS_EC2_METADATA_DISABLED=true DO_NOT_TRACK=1 PYTHON_DOTENV_DISABLED=1 .venv/bin/python -m pytest -q tests/unit/proxy/auth/test_auth_checks_object_access_and_lookup.py
734 passed, 9 warnings in 33.61s

Type

🐛 Bug Fix
✅ Test

Caveats (if any)

Medium

  • Callers that matched on 404 for an unreadable team now get 503
    • user_api_key_auth already keys on TeamNotFoundError, so its fallback is unchanged

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

Note

Medium Risk
Changing unreadable team lookups from 404 to 503 alters client-visible behavior during DB outages; callers that treated any 404 as "team missing" must distinguish 503, though auth paths that key on TeamNotFoundError are unchanged.

Overview
Failed team database reads now return HTTP 503 with Team policy is unavailable (and the underlying error chained), instead of a 404 that looked like a missing team. Truly absent teams still raise TeamNotFoundError (404) with the existing message.

The spend logs ledger parity integration test opens the Rust Database for team reads and tears it down with aclose(), fixing failures from team lookups after team reads moved off Prisma-only connections. Unit tests were updated to expect 503 for connection / NoDatabaseConnected failures and 404 only for confirmed absences.

Reviewed by Cursor Bugbot for commit 363309b. Bugbot is set up for automated code reviews on this repo. Configure here.

@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@narmstrong-berri narmstrong-berri added the autoapprove This PR may be autoapproved by greptile. The author thinks that it does not need human review. label Nov 19, 2026
@narmstrong-berri
narmstrong-berri marked this pull request as ready for review November 19, 2026 20:02
@narmstrong-berri

Copy link
Copy Markdown
Contributor

@greptile-apps

@veria-ai

veria-ai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge.

Summary

get_team_object now reports failed team reads as 503 instead of a misleading 404. Truly absent teams still return 404.

  • Unreadable team rows now return 503, not 404.
  • Spend parity runs now open the Rust database they need.

No new actionable issues were found. Tests were not run during this review.

Reviews (3) · Last reviewed commit: "test: add types to team lookup and spend..." · Reviewed by Greptile

Comment thread litellm/proxy/auth/auth_checks.py Resolved
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@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.

Stale Bugbot comment from a previous run.

mateo-berri and others added 2 commits November 24, 2026 19:24
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration
devin-ai-integration Bot force-pushed the litellm_fix_spendlogs_parity_team_lookup branch from f36c4d2 to 363309b Compare November 24, 2026 19:29
@mateo-berri
mateo-berri enabled auto-merge (squash) November 24, 2026 19:31
@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@mateo-berri
mateo-berri merged commit 38b9faa into main Nov 24, 2026
54 checks passed
@mateo-berri
mateo-berri deleted the litellm_fix_spendlogs_parity_team_lookup branch November 24, 2026 19:34

@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 363309b. Configure here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

autoapprove This PR may be autoapproved by greptile. The author thinks that it does not need human review.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants