Skip to content

test(json_fragment_accumulator): assert peak allocation instead of a drain timing ratio - #43370

Merged
mateo-berri merged 7 commits into
mainfrom
litellm_json_drain_test_deterministic
Oct 29, 2026
Merged

mateo-berri merged 7 commits into
mainfrom
litellm_json_drain_test_deterministic

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

The test guarding the streaming JSON drain against going quadratic compared two drain timings, and on a busy CI runner that ratio jumps on its own, so it went red on PRs that never touched the drain

This PR makes the unit test measure the drain's peak memory instead of its time, which runner load cannot move. The timing half moves into the CodSpeed benchmark suite, so a drain that slows down without copying still shows up on the PR. CodSpeed is not required, so that case flags the PR without blocking it

Details

TLDR

Problem this solves:

  • test_draining_many_concatenated_values_is_not_quadratic flakes on busy runners
  • Its 3x wall-clock ratio trips under load, with no reruns in unit / core-utils
  • It failed 40 of 200 runs on a busy 8-core box

How it solves it:

  • The unit test bounds peak allocation during the drain instead of elapsed time
  • It starts measuring after the first pop, so joining the streamed fragments once is not counted
  • An honest drain peaks under 20 KB against a 320 KB bound
  • Every drain that copies on each pop allocates about 2.5 MB and fails
  • A new CodSpeed benchmark covers drains that slow down without copying

User Flow

Before: a contributor's PR goes red on a timing flake in a test their change never touched

  1. They push a commit to their PR at https://github.com/BerriAI/litellm/pulls and the GitHub Actions unit / core-utils check runs tests/unit/litellm_core_utils with no reruns
  2. When the runner is busy, the check fails on test_draining_many_concatenated_values_is_not_quadratic with an error like "doubling drained values scaled time by 3.47x (126.3 ms -> 438.5 ms)"
  3. They rerun the failed job and the same test passes on the same commit, so the PR only goes green after the rerun

After: this test stays green on a busy runner, and it still fails the moment the drain starts copying its buffer

  1. They push a commit, and unit / core-utils runs the same way
  2. The test now checks how many bytes draining 40,000 streamed values allocates at peak (under 20 KB against a 1.3 MB payload)
  3. This test passes without a rerun, and a drain that re-copies the remainder allocates about 2.5 MB and fails every time

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

Shared setup: one 8-core Linux box running both legs side by side from a 1-minute load average of 33, the drain code byte-identical at both commits. Each leg runs its test 200 times with the unit / core-utils job's own pytest flags, plus --maxfail=1000 to count every run and --cov-report= to skip the report. Logs, mutant diffs and every script behind these numbers are in this gist

Before (c6ca22e)

  1. The old test 200 times on the unmodified drain

    $ uv run --no-sync --with pytest-repeat==0.9.4 pytest tests/unit/litellm_core_utils/test_json_fragment_accumulator.py::test_draining_many_concatenated_values_is_not_quadratic --count 200 --tb=short -vv --maxfail=1000 -n 4 --dist=loadscope --reruns 0 --reruns-delay 1 --timeout=120 --rerun-except 'from pytest-timeout' --durations=5 --cov=./litellm --cov=./enterprise/litellm_enterprise --cov-report= --cov-config=pyproject.toml -p no:cacheprovider
    FAILED ...::test_draining_many_concatenated_values_is_not_quadratic[7-200] - AssertionError: doubling drained values scaled time by 3.06x (172.1 ms -> 527.2 ms)
    FAILED ...::test_draining_many_concatenated_values_is_not_quadratic[9-200] - AssertionError: doubling drained values scaled time by 3.74x (164.9 ms -> 617.2 ms)
    ...
    ================== 40 failed, 160 passed in 294.31s (0:04:54) ==================
    
The same failure in CI
  1. The original failure, on CircleCI before this test moved to GitHub Actions: job 2223770 recorded it as a failure on a test-only PR, and job 2223527 passed it on the same commit

    AssertionError: doubling drained values scaled time by 3.47x (126.3 ms -> 438.5 ms); expected roughly 2x for O(n); O(n^2) regression?
    assert 3.4711141506434573 < 3.0
    
  2. It still fails on GitHub Actions, as in main's unit / core-utils job 123194077063 at 93cfc52

    AssertionError: doubling drained values scaled time by 3.55x (100.6 ms -> 357.2 ms); expected roughly 2x for O(n); O(n^2) regression?
    

After (e2e5ab9)

  1. The new unit test 200 times at the tip, alongside the Before leg

    $ uv run --no-sync --with pytest-repeat==0.9.4 pytest tests/unit/litellm_core_utils/test_json_fragment_accumulator.py::test_draining_many_concatenated_values_never_copies_the_remainder --count 200 --tb=short -vv --maxfail=1000 -n 4 --dist=loadscope --reruns 0 --reruns-delay 1 --timeout=120 --rerun-except 'from pytest-timeout' --durations=5 --cov=./litellm --cov=./enterprise/litellm_enterprise --cov-report= --cov-config=pyproject.toml -p no:cacheprovider
    ======================= 200 passed in 607.88s (0:10:07) ========================
    
The tip's peak margin and the mutant runs
  1. The unmodified drain's peak, sampled 30 times under COVERAGE_CORE=sysmon coverage run

    round   1: peak= 18411 B
    round   2: peak=  1414 B
    ...
    peak min 1414 B, max 18411 B against the 325000 B bound over 30 rounds
    

    The first drain in a process pays for coverage's one-time bookkeeping, and CI runs this test once per process, so 18 KB is the number it sees, about 17x under the bound

  2. The unit test and the new benchmark against the unmodified drain and eight variants of it (source patched, each test run alone, source restored)

    unmodified                             memory PASS   bench best 73.1ms
    A: re-slice remainder on every pop     memory FAIL   bench best 126.1ms   peak 2604545 bytes over a 1300000 byte payload
    B: _materialize rebuilds on every pop  memory FAIL   bench best 147.0ms   peak 2601933 bytes
    C: remainder pushed back as a chunk    memory FAIL   bench best 205.6ms   peak 2604404 bytes
    D: re-scan consumed prefix, no copy    memory PASS   bench best 9.45s
    E: materialize joins every piece once  memory PASS   bench best 90.2ms
    F: re-slice only after whitespace      memory FAIL   bench best 160.5ms   peak 2604302 bytes
    G: per-pop snapshot of the remainder   memory FAIL   bench best 90.2ms    peak 1307534 bytes
    H: drop consumed prefix past half      memory FAIL   bench best 41.9ms    peak 981804 bytes
    

    A to C, F and G copy the remainder on pops and fail the unit test every time. E copies the buffer once, which is still linear, so it passes. H is linear too but slices, which the class's cursor contract rules out. D re-scans without copying, so only the benchmark sees it. These bench numbers are local wall-clock runs of pytest --codspeed on a shared box, while CI's CodSpeed job counts instructions instead

Type

✅ Test

Caveats (if any)

Medium

  • A drain that re-scans without copying no longer blocks a merge
    • Only the CodSpeed benchmark flags it, and that check is not required
    • A timing unit test would break the rule against speed-dependent unit tests
  • The test drains with bare pops, but Anthropic's and Gemini's stream handlers append before each pop, which still copies the remainder per value
    • That code is unchanged here and tracked separately
  • Other wall-clock tests can still turn unit / core-utils red
    • test_flagged_placement_handles_a_long_run_of_unanswered_tool_search_uses_in_linear_time fails on main too and is tracked separately

Low

  • No CodSpeed run has caught a slow variant yet, only this benchmark's baseline
  • A fragment join that concatenates one at a time passes both tests, which skip the first pop's join, as the old test did
  • The bound also fails a linear drain that slices off its consumed prefix once, breaking the class's cursor contract
  • The peak bound is process-wide, so another thread allocating 325 KB mid-drain would trip it (worst seen 15.5 KB)
  • Two other tests here keep 50 ms and 300 ms wall-clock budgets, with worst times under load of 4.8 ms and 59 ms
  • osv-scan is red here and on main's latest run, and it is not required

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
Bugbot summary

[!NOTE]
Low Risk
Test-only changes to regression guards and benchmarks; no production or streaming handler code is modified.

Overview
Replaces the flaky wall-clock ratio regression test for draining many concatenated JSON values with a tracemalloc peak-allocation check, so busy CI runners no longer fail PRs that never touched the drain.

The new test_draining_many_concatenated_values_never_copies_the_remainder streams ~40k small fragments, pops once outside the measurement window, then asserts peak extra allocation stays well below a quarter of payload size—catching drains that re-copy the remainder on every pop_next_value(). Shared helpers _popped_values, _streamed, and _drain_peak_bytes implement that setup.

Adds tests/benchmarks/test_json_fragment_accumulator_benchmarks.py with a @pytest.mark.benchmark test that drains 20k concatenated {"a": 1} values, preserving timing coverage for slow-but-non-copying regressions in CodSpeed without blocking merges.

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

…drain timing ratio

The drain regression guard compared the wall-clock time of draining 80,000 values against 40,000 and tripped its 3x bound whenever the CI runner was busy. A cursor drain allocates only per-value decode scratch while every re-slice of the remainder copies it, so the guard now bounds peak allocation during the drain, which does not move with runner load and still fails on every quadratic variant
@devin-ai-integration

devin-ai-integration Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

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

@greptile-apps

greptile-apps Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Low impact] The PR appears safe to merge

Findings

  1. P2 Quadratic drain can go undetected ▶

Summary

The PR replaces a flaky drain-timing assertion with a peak-allocation guard and adds a separate performance benchmark. The latest change alternates leading spaces between streamed values so the guard also covers copying after whitespace

Reviews (8) · Last reviewed commit: "test(json_fragment_accumulator): separat..." · Reviewed by Greptile

Comment on lines +219 to +220
peak_bytes: Final = peak - baseline
assert peak_bytes < len(payload) // 8, (

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.

P2 Quadratic drain can go undetected

This check catches large copies, but not a drain that repeatedly scans values it has already consumed. Such a drain could still return all 40,000 values with a low allocation peak, so the test would pass even though draining takes quadratic time. Keeping a drain-scaling check alongside this one would preserve that coverage.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

The timing ratio is the flake this PR removes. A Python-level re-scan of consumed text at this size blows the job's 90 s timeout instead

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.

That’s a fair constraint. Retaining a timing-based check would reintroduce the CI flake this PR is specifically removing, and a deliberately quadratic Python-level rescan is not a viable test mutant under the 90-second timeout. The allocation assertion is therefore an appropriate deterministic guard for the re-slicing regression this test targets; my suggestion to keep the timing check does not apply here.

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.

The scan-only case now has a CodSpeed benchmark in 201560a, where a rescan-only mutant runs 21x slower than the unmodified drain

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.

That addresses the scan-only gap. The new CodSpeed benchmark keeps performance coverage separate from the flaky unit-test timing ratio, and the reported 21× slowdown is a strong signal for a rescan-only regression. I withdraw my earlier concern; the allocation-based unit test can stay focused on repeated-copy regressions.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@codecov

codecov Bot commented Sep 26, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@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

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@codspeed

codspeed Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 37 untouched benchmarks
🆕 1 new benchmark

Performance Changes

Benchmark BASE HEAD Efficiency
🆕 test_draining_many_concatenated_values N/A 207.1 ms N/A

Comparing litellm_json_drain_test_deterministic (e2e5ab9) with main (b96c1f3)

Open in CodSpeed

…er is joined, so a drain that copies once passes
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

…with a space, so a copy after whitespace fails the drain test
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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.

✅ 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 e2e5ab9. Configure here.

@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

@mateo-berri
mateo-berri merged commit a66dc50 into main Oct 29, 2026
94 of 95 checks passed
@mateo-berri
mateo-berri deleted the litellm_json_drain_test_deterministic branch October 29, 2026 05:04
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.

1 participant