Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
e58a561
Merge pull request #27906 from BerriAI/litellm_internal_staging
shin-berri May 14, 2026
a72414a
Merge pull request #28100 from BerriAI/litellm_internal_staging
yuneng-berri May 17, 2026
4254c4a
fix(tests): stabilize image-edit VCR cassettes to stop live gpt-image…
mateo-berri May 17, 2026
ba3915d
DIAGNOSTIC: log VCR body mismatches + per-episode body hashes
mateo-berri May 17, 2026
85430bc
DIAGNOSTIC: route VCR diagnostics through per-PID files (bypass xdist…
mateo-berri May 17, 2026
8e08272
fix(tests): coalesce iterable request bodies before matching/recording
mateo-berri May 17, 2026
9e2e5b6
fix(tests): handle bytes_iterator + never leave an exhausted body
mateo-berri May 17, 2026
1c51ad1
fix(tests): clear vcrpy's sticky _was_iter flag so materialized bodie…
mateo-berri May 17, 2026
927c554
revert(tests): drop the temp per-episode body-hash diagnostic
mateo-berri May 17, 2026
c7d6d4d
chore(tests): delete unused flush script + wire VCR diagnostic dump e…
mateo-berri May 17, 2026
78ada20
chore(tests): trim non-essential comments per project comment policy
mateo-berri May 17, 2026
a3c36f0
chore(tests): forward **kwargs in pin_httpx_multipart_boundary wrapper
mateo-berri May 17, 2026
6e3d4b0
chore(tests): canonicalize VCR matchers and surface shouldn't-happen …
mateo-berri May 17, 2026
32369ed
chore(tests): symmetrize diag-log cleanup across every VCR-using conf…
mateo-berri May 17, 2026
1957d6d
fix(tests): gate body materialization on __next__ and strip PR comments
mateo-berri May 17, 2026
bfa1cb8
fix(tests): JSON-encode dict bodies in canonical_body for stable matc…
mateo-berri May 17, 2026
f41a2b1
fix(tests): guard emit_vcr_diagnostic_log against multi-conftest re-e…
cursoragent May 17, 2026
dc59efb
fix(tests): globalize multipart-boundary pin + stabilize whisper fixt…
mateo-berri May 17, 2026
ea77162
chore(tests): drop per-episode body-hash dump and redundant emit guard
mateo-berri May 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions scripts/flush_image_edit_vcr_cassettes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
#!/usr/bin/env python3
"""Flush the bloated image-edit VCR cassettes from the cassette Redis.

Run this **once** after merging the multipart-boundary stabilization
PR. The pre-fix cassettes for the async image-edit tests have
accumulated >50 episodes (random multipart boundary on every run +
``record_mode="new_episodes"`` = monotonic growth), so the persister
refuses to save updates -- meaning every CI run after the fix would
still try to re-record against the stale 51-entry cassette, hit
``MAX_EPISODES_PER_CASSETTE`` again, get refused, and re-bill the live
provider.

Deleting these keys forces the next CI run to record a clean cassette
under the new fixed-boundary + raw-bytes fixtures (1 episode per
unique call), after which the 24-hour TTL replay loop kicks in
normally.

Scope is intentionally narrow:
* Only ``tests/image_gen_tests/test_image_edits/*`` cassette keys
are touched. Image-*generation* cassettes (TestOpenAIGPTImage1
etc.) are unaffected -- they were already in the VCR HIT state.
* Lists every match in dry-run mode before deleting anything so the
operator can confirm the impact.

Usage:
CASSETTE_REDIS_URL=redis://... \
uv run python scripts/flush_image_edit_vcr_cassettes.py --dry-run

CASSETTE_REDIS_URL=redis://... \
uv run python scripts/flush_image_edit_vcr_cassettes.py --yes

``CASSETTE_REDIS_URL`` is the same env var the persister reads at CI
start (see ``tests/_vcr_redis_persister.py``).
"""

from __future__ import annotations

import argparse
import os
import sys

import redis


CASSETTE_REDIS_URL_ENV = "CASSETTE_REDIS_URL"
REDIS_KEY_PREFIX = "litellm:vcr:cassette:"
TARGET_KEY_PATTERN = f"{REDIS_KEY_PREFIX}tests/image_gen_tests/test_image_edits/*"


def _build_client(url: str) -> redis.Redis:
return redis.Redis.from_url(
url,
socket_timeout=10,
socket_connect_timeout=10,
decode_responses=False,
)


def _scan_matching_keys(client: redis.Redis, pattern: str) -> list[bytes]:
return sorted(client.scan_iter(match=pattern, count=500))


def _delete_keys(client: redis.Redis, keys: list[bytes]) -> int:
if not keys:
return 0
# Batch into chunks so a single DEL call does not exceed the
# server's argument-count or buffer limits on large key sets.
deleted = 0
chunk_size = 200
for start in range(0, len(keys), chunk_size):
batch = keys[start : start + chunk_size]
deleted += int(client.delete(*batch))
return deleted


def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--yes",
action="store_true",
help="Actually delete the matched keys. Without this flag the script "
"runs in dry-run mode and only lists what would be deleted.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="List matched keys without deleting (default behaviour when "
"--yes is omitted; kept as an explicit flag for clarity).",
)
parser.add_argument(
"--pattern",
default=TARGET_KEY_PATTERN,
help=f"Override the SCAN match pattern. Default: {TARGET_KEY_PATTERN}",
)
args = parser.parse_args(argv)

url = os.environ.get(CASSETTE_REDIS_URL_ENV)
if not url:
print(
f"error: {CASSETTE_REDIS_URL_ENV} is not set. Set it to the "
"cassette Redis URL (same URL the persister reads in CI).",
file=sys.stderr,
)
return 2

client = _build_client(url)
try:
client.ping()
except redis.RedisError as exc:
print(f"error: cannot reach cassette Redis: {exc}", file=sys.stderr)
return 2

matches = _scan_matching_keys(client, args.pattern)
print(f"matched {len(matches)} key(s) under pattern: {args.pattern}")
for key in matches:
print(f" {key.decode('utf-8', errors='replace')}")

if not matches:
return 0

if not args.yes:
print("\ndry run -- pass --yes to actually delete these keys.")
return 0

deleted = _delete_keys(client, matches)
print(f"\ndeleted {deleted} key(s).")
return 0


if __name__ == "__main__":
raise SystemExit(main())
197 changes: 197 additions & 0 deletions tests/_vcr_conftest_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,78 @@
KEY_FINGERPRINT_MATCHER_NAME = "key_fingerprint"
KEY_FINGERPRINT_HEADER = "x-litellm-key-fp"

# Directory for per-process VCR diagnostic logs that bypass pytest's
# stdout/stderr capture. ``sys.stderr.write`` from inside vcrpy
# machinery is swallowed by xdist for any test that ultimately passes,
# so a diagnostic that fires on a body-matcher miss but the test still
# records and passes will never reach the CI log. Each xdist worker
# (or the main process) writes line-buffered to a per-PID file under
# this directory, and the controller's ``pytest_terminal_summary``
# concatenates them into the terminal at session end. ``test-results/``
# is already collected by ``store_test_results`` in CI, so the raw
# files survive as build artifacts too.
VCR_DIAG_DIR_ENV = "LITELLM_VCR_DIAG_DIR"
VCR_DIAG_DIR_DEFAULT = "test-results/vcr-diagnostics"


def _vcr_diag_dir() -> str:
return os.environ.get(VCR_DIAG_DIR_ENV) or VCR_DIAG_DIR_DEFAULT


def vcr_diag_write_line(msg: str) -> None:
"""Append a single diagnostic line to the current process's
per-PID file. Atomic against other workers in the same xdist
session because each PID owns its own file.

Errors are swallowed -- diagnostic logging must never fail a test.
"""
try:
directory = _vcr_diag_dir()
os.makedirs(directory, exist_ok=True)
path = os.path.join(directory, f"{os.getpid()}.log")
with open(path, "a", encoding="utf-8") as fh:
fh.write(msg.rstrip("\n") + "\n")
except OSError:
pass


def emit_vcr_diagnostic_log(terminalreporter) -> None:
"""Concatenate every per-PID diagnostic file into the controller's
terminal at session end. Each file is dumped under a header that
names the originating worker PID so cross-process events can still
be ordered if needed.
"""
directory = _vcr_diag_dir()
if not os.path.isdir(directory):
return
try:
files = sorted(f for f in os.listdir(directory) if f.endswith(".log"))
except OSError:
return
if not files:
return
terminalreporter.write_sep("=", "VCR DIAGNOSTIC LOG", bold=True)
terminalreporter.write_line(
f" source dir: {directory} (also archived as a CI artifact)"
)
for name in files:
path = os.path.join(directory, name)
try:
with open(path, "r", encoding="utf-8") as fh:
content = fh.read()
except OSError as exc:
terminalreporter.write_line(
f" [failed to read {name}: {type(exc).__name__}: {exc}]"
)
continue
if not content.strip():
continue
terminalreporter.write_sep("-", name, bold=False)
for line in content.splitlines():
terminalreporter.write_line(line)
terminalreporter.write_sep("=", bold=True)
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved


# Intentionally narrower than ``FILTERED_REQUEST_HEADERS``: AWS SigV4 headers
# carry secrets but their values rotate on every call, so fingerprinting them
# would defeat caching.
Expand Down Expand Up @@ -91,6 +163,55 @@
VCR_FIXED_MULTIPART_BOUNDARY = "vcr-static-boundary"


def pin_httpx_multipart_boundary(monkeypatch) -> None:
"""Force every httpx multipart request to use a constant boundary.

httpx's ``MultipartStream`` generates a fresh ``boundary=<random hex>``
via ``os.urandom(16)`` whenever the caller does not supply one
(see ``httpx._multipart.MultipartStream.__init__``). That random
boundary appears both in the ``Content-Type`` header and verbatim in
the request body between each part.

``_normalize_multipart_boundary`` rewrites the header reliably, but
on the async transport path the body is not always handed to
``before_record_request`` as a contiguous ``bytes`` object — so the
body replacement silently no-ops and the recorded cassette retains
the random boundary string. Subsequent runs generate a *different*
random boundary, the ``safe_body`` matcher misses, and
``record_mode="new_episodes"`` appends a fresh episode until the
cassette crosses ``MAX_EPISODES_PER_CASSETTE`` and the persister
refuses to save — re-billing live providers on every CI run.

Pinning the boundary at the source removes the variance entirely:
every run emits byte-identical multipart bodies, the existing
``safe_body`` matcher succeeds on the first request, and one
recorded episode per unique call satisfies replays for the cassette
TTL.

This wraps ``MultipartStream.__init__`` instead of patching the
boundary-generation helper directly because httpx inlines
``os.urandom(16).hex().encode("ascii")`` in the constructor body
rather than calling a named function. We preserve the caller's
boundary when one is explicitly supplied so production-style code
that pins its own boundary keeps working.
"""
try:
import httpx._multipart as _httpx_multipart
except ImportError: # pragma: no cover - httpx is a hard test dep
return

_original_init = _httpx_multipart.MultipartStream.__init__

def _init_with_fixed_boundary(self, data, files, boundary=None):
if boundary is None:
boundary = VCR_FIXED_MULTIPART_BOUNDARY.encode("ascii")
return _original_init(self, data=data, files=files, boundary=boundary)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

monkeypatch.setattr(
_httpx_multipart.MultipartStream, "__init__", _init_with_fixed_boundary
)


def _scrub_response(response):
if not isinstance(response, dict):
return response
Expand Down Expand Up @@ -194,6 +315,13 @@ def _safe_body_matcher(r1, r2) -> None:
(e.g. the Bedrock batch S3 PUT) before it can return "no match".
This matcher is strictly more conservative — the only equivalence
it gives up vs. the default is "JSON key order doesn't matter".

On mismatch, emits a structured diagnostic to stderr (type of each
body, length, SHA-256, first divergent offset, ±100-byte window).
Without this, vcrpy returns "request bodies differ" with zero
context, and bugs where the live request body is an unbytes-like
object (e.g. an httpx ``MultipartStream`` for async requests) look
indistinguishable from genuine content drift.
"""
body1 = getattr(r1, "body", None)
body2 = getattr(r2, "body", None)
Expand All @@ -213,9 +341,64 @@ def _to_bytes(b):
n2 = _to_bytes(body2)
if n1 is not None and n2 is not None and n1 == n2:
return
_emit_body_mismatch_diagnostic(r1, r2, body1, body2, n1, n2)
raise AssertionError("request bodies differ")


def _emit_body_mismatch_diagnostic(r1, r2, body1, body2, n1, n2) -> None:
"""Dump enough info to a single stderr block to root-cause why two
requests that look semantically identical failed the body matcher.

Always-on (matcher mismatches are signal, not noise): the volume
is bounded by the number of stored episodes a live request is
compared against, and we already log a per-test verdict line for
every test.
"""

def _describe(label, raw, asbytes):
t = type(raw).__name__
if asbytes is None:
return (
f" {label}: type={t!r} length=unknown sha256=N/A "
f"(body could not be coerced to bytes)"
)
length = len(asbytes)
digest = hashlib.sha256(asbytes).hexdigest()
preview = asbytes[:120]
return (
f" {label}: type={t!r} length={length} sha256={digest} "
f"preview={preview!r}"
)

method_a = getattr(r1, "method", "?")
method_b = getattr(r2, "method", "?")
url_a = getattr(r1, "uri", getattr(r1, "url", "?"))
url_b = getattr(r2, "uri", getattr(r2, "url", "?"))
lines = [
"[vcr-safe-body-matcher] request body mismatch",
f" request[a]: {method_a} {url_a}",
f" request[b]: {method_b} {url_b}",
_describe("body[a]", body1, n1),
_describe("body[b]", body2, n2),
]
if n1 is not None and n2 is not None and n1 != n2:
# Find the first divergent byte offset and dump a ±100 window
# around it so the human reading the CI log can see at a glance
# whether the variance is a UUID, a timestamp, a random multipart
# boundary, or something else.
offset = next(
(i for i in range(min(len(n1), len(n2))) if n1[i] != n2[i]),
min(len(n1), len(n2)),
)
start = max(0, offset - 100)
end_a = min(len(n1), offset + 100)
end_b = min(len(n2), offset + 100)
lines.append(f" first divergent byte offset: {offset}")
lines.append(f" window[a] @ {start}..{end_a}: {n1[start:end_a]!r}")
lines.append(f" window[b] @ {start}..{end_b}: {n2[start:end_b]!r}")
vcr_diag_write_line("\n".join(lines))


def _iter_header_values(headers, name: str):
if headers is None:
return
Expand Down Expand Up @@ -360,6 +543,20 @@ def _normalize_multipart_boundary(request) -> None:
elif isinstance(body, str):
new_body = body.replace(current_boundary, VCR_FIXED_MULTIPART_BOUNDARY)
else:
# The body is something other than bytes/bytearray/str -- most
# likely an httpx ``MultipartStream`` or an aiter chunked stream
# we cannot rewrite in place. Log it so a body-matcher miss on a
# multipart request can be correlated with "normalizer skipped
# because body type was X". The header was still rewritten
# above, so the recorded Content-Type stays stable; only the
# body bytes carry the random boundary verbatim.
vcr_diag_write_line(
f"[vcr-multipart-normalize] body normalization SKIPPED: "
f"body type {type(body).__name__!r} is not bytes/bytearray/str. "
f"content-type={content_type_value!r}. "
f"Recorded body will retain the random boundary substring "
f"and the safe_body matcher will miss on the next run."
)
return

try:
Expand Down
Loading
Loading