Repository navigation
fix(presidio): stop overlapping entity spans from corrupting numbered PII tokens - #47024
Conversation
…onymization (#42130) Mirror of #42133 by @PINYOPATTANAWASANPORN, squashed onto main with the unit test moved to tests/unit after the test tree relocation
…dd integration coverage A run of overlapping detections now takes its entity type from the highest-scoring detection that no other detection in the run contains, matching Presidio's own anonymizer, so a phone number with a date-shaped fragment inside stays PHONE_NUMBER. The resolver returns typed detections instead of Any.
|
Automatic reviews are disabled for this repository. |
|
@litereview code-review |
✅ code-review5/5 · Ready for human reviewScope: full · Full PR review. No correctness findings. I checked the partial-overlap union, empty and inverted spans, and analyzer order (both directions). I also checked token clashes across parts and same-value token reuse. A randomized round-trip of masking then unmasking over multi-part requests produced no overwritten tokens and no failed restores. Earlier entries in the restore map stayed unchanged. The new proxy-level integration file passes locally against a real proxy with Postgres and Redis. Checks and execution details
No previously successful, correct input now fails or produces different correct output, so the title needs no
Traced path: Boundary cases checked:
The spare-number invariant (no token number exceeds the map size) holds by induction, and fuzzing confirmed it.
View review · Reviewed |
|
@litereview code-review |
|
bugbot run |
Merging this PR will not alter performance
|
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
…ady holds Each message and content part numbers its tokens from 1 into one request-wide pii_tokens map. Collapsing overlapping detections made an overlapping value's token well formed, so it collided with the same type in another part and both restored as the later value. A token that maps to a different value now moves to the next free number, and a token for the same value is reused
|
@litereview code-review |
PR overviewAll previously flagged issues have been addressed. No open security concerns remain on this pull request. Security reviewNo open security issues remain on this pull request. Fixed/addressed: 1 · PR risk: 0/10 |
…ng for one Scanning upward from the clashing number probed every token an earlier part had claimed, so two parts with thousands of values of one type took seconds of synchronous work. No token in the map is numbered above the map's size, so numbers above both that size and the part's run count are always free
|
@litereview code-review |
|
bugbot run |
…yzer never returned Pick the token in one conditional expression instead of reassigning it, and have the scripted anonymizer answer 500 when the proxy forwards spans that differ from the analyzer's, so the default-scope cells check what was sent
|
@litereview code-review |
|
bugbot run |
There was a problem hiding this comment.
✅ 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 bb55d17. Configure here.
BrickerP
left a comment
There was a problem hiding this comment.
Solid fix for overlapping Presidio spans corrupting numbered PII tokens.
Verified on bb55d177:
_resolve_overlapping_spanscollapses overlap runs;_collapse_runlabels with the outermost / highest-score detection that is not strictly contained (matches the phone-with-date-fragment case).- Spare numbering (
count(max(len(pii_tokens), len(runs)) + 1)) plus same-value reuse correctly stops cross-part token swaps without changing the<TYPE_n>format. - Unit matrix covers same-span, nested, contained fragment, partial overlap, ties, empty/inverted spans, and multi-part uniqueness; integration wire tests pin provider-forwarded text and restore under
presidio_filter_scope: input.
Behavior change on masked-entity counts for overlapping detections is intentional and documented. Approve.
|
@litellm-stampbot |
litellm-stampbot: risk lowApproved at Rules (
Judge (gpt-6-luna): low, probability of high 0.09 (high at or above 0.75)
Pushes do not re-run this check. Comment |
kerry-berri
left a comment
There was a problem hiding this comment.
Low risk by rule and by judgement at bb55d17
TLDR
Problem this solves:
output_parse_pii: trueeach tag was spliced into the text on its own<PHONE_NUMBER_3>UMBER_3>_LICENSE_3>4251234567UMBER_3>_LICENSE_3>back instead of their numberHow it solves it:
User Flow
Before: a developer using the Presidio guardrail with
output_parse_pii: truegets mangled text whenever Presidio tags a value more than onceRepeat exactly: my number is 4251234567my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>my number is 4251234567UMBER_3>_LICENSE_3>After: the same request masks the number as one token and hands it back cleanly
my number is <PHONE_NUMBER_1>my number is 4251234567PHONE_NUMBERPlayground at http://localhost:4000/ui/?page=llm-playground, model
gpt-6.1-sol, same prompt. Before, then afterLogs at http://localhost:4000/ui/?page=logs, newest row, Guardrails section, click the presidio-pii evaluation. Before, then after
The whole flow, login to Playground to the Logs page, on main and then on this PR
Relevant issues
Fixes #42130. Also stops the cross-part token swap from #31959 for numbered tokens. Mirrors #42133 (credit to @PINYOPATTANAWASANPORN for the fix, adopted here as the first commit with their authorship) and covers what #42144 tests
Linear ticket
Resolves LIT-9694
Behavior changes
Only requests where Presidio returns overlapping, repeated or empty spans behave differently. For those, the text sent to the model and the restored reply are now clean, and the masked entity count reports one entity per masked run. So the Logs page, spend logs, OTel and Langfuse show
PHONE_NUMBER: 1where they used to showPHONE_NUMBER: 1, US_BANK_NUMBER: 1, US_DRIVER_LICENSE: 1for the same phone number. Empty spans no longer insert a token that maps to an empty stringWhen two detections only partly overlap, the whole union becomes one token. Presidio's own anonymizer splits at the boundary instead, so this masks a few more characters than Presidio would, never fewer
Every message and content part still numbers its tokens from 1. When a later part would reuse a token that already maps to a different value, it takes a spare number above every number the request has used so far, so
My number is 4251234567.andAlso call +1 (206) 555-0199.in two parts reach the model as<PHONE_NUMBER_1>and<PHONE_NUMBER_2>. A token for the same value is reused. Main gave both values the same token and restored both as the later value, which is why two names in two messages swap on mainSingle-text requests where no detections overlap are byte for byte the same as main. A differential over 5000 random non-overlapping span sets gave identical text, token map and counts on both trees
test_numbered_tokens_collapse_overlapping_detections_into_one_token_per_runandtest_numbered_tokens_stay_unique_across_parts_of_one_requestin tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py pin the contract, and tests/integration/observability/test_presidio_overlapping_spans.py pins it end to end through a real proxyPre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
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 moreScreenshots / Proof of Fix
Both legs ran 4 workers against real Presidio 2.2.364 (analyzer and anonymizer), real OpenAI
gpt-6.1-soland real Anthropicclaude-haiku-5-5.gpt-6.1-sol-recordedis the same OpenAI deployment behind a recorder that logs the request and forwards it, so the provider-side text below is what OpenAI actually received. Guardrail configThe MCP case adds an MCP server
echo(a tool that returns itstextargument and logs what it received) and runs the same guardrail withmode: pre_mcp_call. The last case dropspresidio_filter_scope, which is the exact config from the ticketThe chat loop is
and the streaming leg sends the same body with
"stream": trueand joins the content deltasBefore (8efb99b)
/v1/chat/completions
/v1/messages
curl -s localhost:4000/v1/messages -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model": "claude-haiku", "max_tokens": 1024, "messages": [{"role": "user", "content": "Repeat exactly: my number is 4251234567"}]}' | jq -r '.content[] | select(.type=="text") | .text'/v1/responses
curl -s localhost:4000/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model": "gpt-6.1-sol-recorded", "input": "Repeat exactly: my number is 4251234567"}' | jq -r '.output[] | select(.type=="message") | .content[0].text'/v1/responses over WebSocket
ws://localhost:4000/v1/responses?model=gpt-6.1-solwith the key and send{"type": "response.create", "input": "Repeat exactly: my number is 4251234567"}. Theresponse.output_text.doneevent carries what the model saw, andresponse.completedcarries the restored reply/guardrails/apply_guardrail
curl -s localhost:4000/guardrails/apply_guardrail -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"guardrail_name": "presidio-pii", "text": "my number is 4251234567"}'MCP tool call
curl -s localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"server_id": "<echo server id>", "name": "echo", "arguments": {"text": "my number is 4251234567"}}' | jq -c '[.content[].text]'Ticket config (no presidio_filter_scope)
Admin UI
After (bb55d17)
/v1/chat/completions
/v1/messages
curl -s localhost:4000/v1/messages -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model": "claude-haiku", "max_tokens": 1024, "messages": [{"role": "user", "content": "Repeat exactly: my number is 4251234567"}]}' | jq -r '.content[] | select(.type=="text") | .text'/v1/responses
curl -s localhost:4000/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model": "gpt-6.1-sol-recorded", "input": "Repeat exactly: my number is 4251234567"}' | jq -r '.output[] | select(.type=="message") | .content[0].text'/v1/responses over WebSocket
ws://localhost:4000/v1/responses?model=gpt-6.1-solwith the key and send{"type": "response.create", "input": "Repeat exactly: my number is 4251234567"}. Theresponse.output_text.doneevent carries what the model saw, andresponse.completedcarries the restored reply/guardrails/apply_guardrail
curl -s localhost:4000/guardrails/apply_guardrail -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"guardrail_name": "presidio-pii", "text": "my number is 4251234567"}'MCP tool call
curl -s localhost:4000/mcp-rest/tools/call -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"server_id": "<echo server id>", "name": "echo", "arguments": {"text": "my number is 4251234567"}}' | jq -c '[.content[].text]'Ticket config (no presidio_filter_scope)
Admin UI
Two values of one type in separate parts
System turn
Echo tool. Output every user text block below, in order, verbatim, joined by ' | ', modelgpt-6.1-sol-recorded, input scope, both legs at 4 workers. Sent is what OpenAI received, from the recorderMy number is 4251234567.,Also call +1 (206) 555-0199.<PHONE_NUMBER_3>UMBER_3>_LICENSE_3>,<PHONE_NUMBER_1>4251234567UMBER_3>_LICENSE_3>,+1 (206) 555-0199<PHONE_NUMBER_1>,<PHONE_NUMBER_2>4251234567,+1 (206) 555-0199<PHONE_NUMBER_1>,<PHONE_NUMBER_3>UMBER_3>_LICENSE_3>+1 (206) 555-0199,4251234567UMBER_3>_LICENSE_3><PHONE_NUMBER_1>,<PHONE_NUMBER_2>+1 (206) 555-0199,4251234567My number is 4251234567.,Her number is 2065550123.<PHONE_NUMBER_3>UMBER_3>_LICENSE_3>twice2065550123UMBER_3>_LICENSE_3>twice<PHONE_NUMBER_1>,<PHONE_NUMBER_2>4251234567,2065550123Call John Smith.,Then call Mary Jones.<PERSON_1>twiceMary Jonestwice<PERSON_1>,<PERSON_2>John Smith,Mary Jones<PHONE_NUMBER_3>UMBER_3>_LICENSE_3>,<PERSON_1>,<PHONE_NUMBER_1><PHONE_NUMBER_1>,<PERSON_1>,<PHONE_NUMBER_3>The first request on chat streaming,
/v1/messages,/v1/responses(two blocks and two input items) gives the same sent text on each leg and an exact reply on this PR./v1/messagesstreaming leaves the tokens in the reply on both legs (split across deltas, listed under Caveats). 30 concurrent two-part requests at 4 workers, half streaming, all reached OpenAI as<PHONE_NUMBER_1>then<PHONE_NUMBER_2>and all 30 replies came back exact. On main all 30 came back garbledMutation check on the fix, 17 mutants against
tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py, all 17 killed. They covered the containment check (<=to<on each edge, dropping the identical-span exclusion), the label choice (ignoring containment, score only, length only,minformax), the run bounds (end from the last detection or from the label, start from the label), keeping zero-length spans, the run boundary (>=to>, previous end instead of running max, no collapsing at all), the sort order, and bypassing the resolver. The integration test is red on main (12 of 12) and red on #42133 as submitted (the 4 contained-fragment cases, which come back as<DATE_TIME_1>). Five more mutants on the spare numbers (no spare, starting from the map size only, from the run count only, one too low, no reuse for the same value) are all killed, and the 4 cross-part integration cases are red on e28c550, where both parts reached the model as<PHONE_NUMBER_1>. A random check of 20000 multi-part requests with overlapping detections restored every part exactly. Assigning a spare number is constant time, two parts of 4000 distinct emails take 0.06s on this PR and on mainThe audit reran every cell on e28c550 against main with 4 workers. Twelve SDK cells (OpenAI and Anthropic, sync and async, streaming and not) restore the number on this PR except
/v1/messagesstreaming, which main does not restore either. Analyzer down, anonymizer down, either one answering 404, and a 2 second timeout with the analyzer paused give the same status and message on both trees. Bursts of 30 mixed requests with the analyzer paused, the anonymizer paused, or a worker killed came back exact on this PR for every request that completed. Nine edge cells (empty content, unicode before the entity, the same value twice, content parts, a system turn, 300 entities, malformed content) match main or come out cleaner. The integration test, now 16 cases, passed 20 runs in a row atINTEGRATION_WORKERS=4on dab7037, and 20 in a row on bb55d17. Its scripted anonymizer answers 500 when the proxy forwards spans the analyzer never returned, which a mutant that drops one forwarded span confirmsType
Bug Fix
Caveats (if any)
Medium
presidio_filter_scope(both), the restored reply is masked again<PHONE_NUMBER>instead of the number, same as main for any entitypresidio_filter_scope: inputto get values backLow
output_text.deltaandoutput_text.donestay masked, same as main/v1/messagesstreaming does not restore a token split across two deltas, same as main<PERSON_, restores the first token with that prefixFinal Attestation
ran /live-pr-risk and found no regressions. The one deliberate change other systems can see is the masked entity count, described under Behavior changes
REVIEWER MUST KNOW BEFORE APPROVING
The fix only changes what happens when Presidio returns spans that overlap, repeat or are empty. Each such run becomes one token, so the masked entity count that the Logs page, spend logs, OTel and Langfuse show goes down for those requests (3 to 1 for the phone number in the ticket). Nothing changes for requests whose spans do not overlap
The ticket expects the original number back in the reply. That only happens with
presidio_filter_scope: input. With the default scope the proxy scans the reply again and masks it to<PHONE_NUMBER>, which is how main already behaves for every entity and is documented. This PR does not change thatThe first commit is #42133 as its author wrote it. The second commit fixes its labelling (a phone number with a date-shaped fragment inside came back as
<DATE_TIME_1>), drops the dead numbering map, and folds its test into the parametrized regression test so every case checks the whole masked text, token map and countCollapsing the overlap made those tokens well formed, and every message and content part numbers from 1 into one restore map, so a cleanly masked phone in one part collided with a different phone in another part and came back as that other number. The last two commits give a clashing token a spare number above every number the request has used, in constant time, and reuse a token for the same value, which also stops two names in two messages from swapping (#31959). #46273 proposes value-derived tokens instead. This PR keeps main's
<TYPE_n>format and only renumbers on a clash