Skip to content

fix(guardrails): classify only the frames each read completes in Presidio's first-frame wait - #54379

Merged
mateo-berri merged 6 commits into
BerriAI:mainfrom
izzybn:litellm_presidio_linear_first_frame_wait
Nov 25, 2026
Merged

mateo-berri merged 6 commits into
BerriAI:mainfrom
izzybn:litellm_presidio_linear_first_frame_wait

Conversation

@izzybn

@izzybn izzybn commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

When a streamed messages request goes through the Presidio guardrail and the upstream sends lots of small frames before its first real event, Presidio rescanned everything it had buffered on every read, so its CPU cost grew with the square of the number of reads. Now it only looks at the frames each read finishes, so the CPU the guardrail adds to that stream drops from about 12.7 s to about 8.6 s. This is the main copy of the same fix in #53403 for 1.108.x

Details

TLDR

Problem this solves:

  • Presidio's first-frame wait rescanned its whole buffer on every read, so 7000 leading data: 5 frames cost the proxy's Python threads a median 18.6 s of CPU against 8.7 s with no guardrail

How it solves it:

  • The wait finds frame ends and classifies frames only in the bytes each read adds
  • It buffers in a bytearray, so a read no longer copies the buffer

User Flow

No user reported this. Veria found it in review on #53403

Before: one guarded stream with thousands of tiny frames before the reply keeps the proxy's Python threads busy for seconds

  1. A developer sends POST https://litellm-domain/v1/messages with "stream": true and "guardrails": ["pii"], asking to repeat a test card
  2. Their Anthropic-format upstream sends 7000 data: 5 frames, 2 ms apart, then the real reply
  3. The reply arrives with the card masked as <CREDIT_CARD>
  4. The proxy's Python threads spent a median 18.6 s of CPU on that request, against 8.7 s with no guardrail

After: the guardrail adds about 8.6 s of CPU to that stream instead of about 12.7 s, and Python's share drops from about 10 s to about 2 s

  1. A developer sends POST https://litellm-domain/v1/messages with "stream": true and "guardrails": ["pii"], asking to repeat a test card
  2. Their Anthropic-format upstream sends 7000 data: 5 frames, 2 ms apart, then the real reply
  3. The reply arrives with the card masked as <CREDIT_CARD>
  4. The proxy's Python threads spent a median 10.5 s of CPU on that request
Decisions
  1. The wait classifies only the frames each read completes, rather than leaning on its 64 KB cap, which still let it rescan up to 64 KB on each of thousands of reads
  2. The frame-end search starts a few bytes before the new bytes, so a \r\n\r\n split across two reads is still found
  3. The unit test runs the real wait with a classifier that records the frames each read hands it, since tests/unit/AGENTS.md bans tests that depend on speed. A CodSpeed benchmark watches the cost instead.

Relevant issues

The wait came from #49088. #53403 fixes the same cost on lts/1.108.x in 1faa9404e8

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

Real Anthropic claude-haiku-5-5 sits behind a relay that sends 7000 data: 5 frames 2 ms apart, then the real reply. Presidio masks CREDIT_CARD in output. Both proxies run python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 from their own tree on one 8-core host. The scripts and every raw line are in round 9, and the relay and config.yaml in round 7

case9.sh adds up CPU by thread name across the supervisor and both workers and sends GET /v1/models every 100 ms during the stream. run9.sh runs 5 rounds per side, alternating. The live rows ran at e491e144e5. Since then the commits up to 67faf6d401 only fix a docstring, give the wait a classify parameter defaulting to _classify_completed_frames, which it called before, and change tests and benchmarks, so the rows still stand

Before (c74b785396, the merge base)

  1. ./run9.sh, then this view of summary.txt
Before rows
$ awk -F' [|] ' '/^round .* before-/ {split($1,a," "); split($3,c," "); print "round", a[2], a[5], "python", c[2], "ms |", $4, "|", $6}' summary.txt
round 1 200 python 18560 ms | load 6.37 | events 7008 text "<CREDIT_CARD>"
round 2 200 python 16990 ms | load 4.28 | events 7008 text "<CREDIT_CARD>"
round 3 200 python 19680 ms | load 5.10 | events 7008 text "<CREDIT_CARD>"
round 4 200 python 19420 ms | load 6.27 | events 7008 text "<CREDIT_CARD>"
round 5 200 python 18070 ms | load 6.58 | events 7008 text "<CREDIT_CARD>"

After (e491e144e5, carried to the tip)

  1. The same view with after-
After rows
round 1 200 python 10460 ms | load 6.10 | events 7008 text "<CREDIT_CARD>"
round 2 200 python 9280 ms | load 5.35 | events 7008 text "<CREDIT_CARD>"
round 3 200 python 12680 ms | load 6.23 | events 7008 text "<CREDIT_CARD>"
round 4 200 python 12290 ms | load 6.46 | events 7008 text "<CREDIT_CARD>"
round 5 200 python 10510 ms | load 6.96 | events 7013 text "4111 1111 1111 "
  1. uv run --no-sync pytest -q tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py tests/unit/proxy/common_utils/test_sse_keepalive.py prints 506 passed at 67faf6d401
What the tests and benchmarks catch

The per-read test fails when the wait drops the classifier's offset or skips it, when the classifier slices from 0 as the old code did, or without the split-terminator lookback. A direct test of last_sse_frame_end fails on the three frame-end mutants the older tests missed. Locally the new benchmarks take 8.3 s instead of 19 ms when the JSON check rescans every frame, and 84 ms instead of 9 ms when the frame-end search starts at the last classified byte

Median per stream Before After
python CPU 18560 ms 10510 ms
python CPU, no guardrail 8710 ms 8350 ms
tokio-rt-worker CPU 16060 ms 18790 ms
All threads 34770 ms 30020 ms
All threads, no guardrail 22100 ms 21450 ms
/v1/models p50 30 ms 29 ms

No-guardrail rows are 3 rounds per side from run9-noguard.sh. In every round pair Python drops 7.0 to 8.1 s and all threads 3.9 to 5.7 s, while Rust rises 2.2 to 3.1 s because Python now takes each frame from Rust on its own (round 10). After round 5 hit max_tokens mid-number, and a partial card fails the checksum, so Presidio leaves it on either side

When the relay sends three : keepalive comments ahead of the real reply instead (round 11), both sides pass all three through ahead of message_start and mask the card in all 8 replies that finished

Type

🐛 Bug Fix

Caveats (if any)

Low

  • The fix saves proxy CPU, not time a client sees
    • Time to first byte is about 15.6 s on both sides, since the wait holds the frames until the first real event
    • A concurrent GET /v1/models had the same p50 on both sides
  • Main's Rust threads spend about 2 to 3 s more CPU on that stream, since Python now takes each frame from Rust on its own. All threads together still use less
  • A return of the quadratic cost would show in CodSpeed only after it merges to main, since CodSpeed does not run on PRs
  • The per-read test checks the wait's classifier calls through a parameter only tests pass, so a different linear rewrite would fail it with no change in behavior

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
Localized streaming buffer/performance change with unit and benchmark tests; PII masking behavior is explicitly regression-tested.

Overview
Presidio’s first SSE frame coalesce no longer rescans the entire buffer on every upstream chunk. Each read only classifies newly completed frames via last_sse_frame_end in sse_keepalive.py (with delimiter lookback for split terminators), a classified byte offset, and a bytearray buffer instead of repeated bytes concatenation.

_coalesce_first_sse_frame takes an optional injectable classify hook for tests. PII masking behavior with thousands of leading non-JSON frames is covered by new unit tests and CodSpeed benchmarks.

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

…idio's first-frame wait

Presidio's wait for the first frame with a JSON object re-split and re-classified its whole buffer on every read, so a long run of leading non-object frames cost CPU quadratic in the number of reads. It now buffers in a bytearray, finds frame ends only in the newly read bytes, and classifies only the frames that read completed
# Conflicts:
#	litellm/proxy/guardrails/guardrail_hooks/presidio.py
#	tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py
@veria-ai

veria-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge, with no outstanding findings.

Summary

Presidio now checks only newly completed SSE frames while waiting for its first JSON event. It keeps buffered bytes in a bytearray instead of copying the buffer on every read.

  • Presidio's first-frame wait checks only newly completed frames.

Reviews (5) · Last reviewed commit: "test(proxy): check the SSE frame-end sea..." · Reviewed by Greptile

…yte once instead of timing it

The test guide bans checks that depend on execution speed, so the CPU-time limit on the many-leading-reads test is replaced by a test that each read is handed only the frames it completed, including frame ends split across reads
@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.

Stale Bugbot comment from a previous run.

…ead classification test

The test copied the wait's loop, so it still passed if the wait itself dropped the offset the classifier returns. The wait now takes the classifier as a parameter, defaulting to the one it called before, and the test runs the real wait with a recording classifier. The classifier docstring now says the caller relays the preface
@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.

Stale Bugbot comment from a previous run.

…ding reads and a frame split into many reads

Unit tests can't check the wait's cost without timing it, so CodSpeed now times the real wait over 6000 leading non-object reads and over one 48 KB frame in 16-byte reads. Rescanning every classified frame for a JSON object, or searching the whole unclassified tail for a frame end, makes these runs many times slower
@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.

Stale Bugbot comment from a previous run.

@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 67faf6d. 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 2c4d234 into BerriAI:main Nov 25, 2026
53 checks passed
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.

2 participants