Skip to content

fix(presidio): stop overlapping entity spans from corrupting numbered PII tokens - #47024

Merged
yucheng-berri merged 6 commits into
mainfrom
litellm_presidio_overlapping_spans
Oct 17, 2026
Merged

yucheng-berri merged 6 commits into
mainfrom
litellm_presidio_overlapping_spans

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Presidio often tags one value as several entities, like phone, bank number and license
  • With output_parse_pii: true each tag was spliced into the text on its own
  • The splices overlapped, so the model saw <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
  • The user got 4251234567UMBER_3>_LICENSE_3> back instead of their number

How it solves it:

User Flow

Before: a developer using the Presidio guardrail with output_parse_pii: true gets mangled text whenever Presidio tags a value more than once

  1. They send POST https://litellm-domain/v1/chat/completions with the message Repeat exactly: my number is 4251234567
  2. The model receives my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
  3. The reply comes back as my number is 4251234567UMBER_3>_LICENSE_3>
  4. https://litellm-domain/ui/?page=logs shows the request with 3 masked entities for one phone number

After: the same request masks the number as one token and hands it back cleanly

  1. They send the same POST https://litellm-domain/v1/chat/completions
  2. The model receives my number is <PHONE_NUMBER_1>
  3. The reply comes back as my number is 4251234567
  4. https://litellm-domain/ui/?page=logs shows 1 masked entity, PHONE_NUMBER

Playground at http://localhost:4000/ui/?page=llm-playground, model gpt-6.1-sol, same prompt. Before, then after

playground before

playground after

Logs at http://localhost:4000/ui/?page=logs, newest row, Guardrails section, click the presidio-pii evaluation. Before, then after

logs before

logs after

The whole flow, login to Playground to the Logs page, on main and then on this PR

flow on main 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: 1 where they used to show PHONE_NUMBER: 1, US_BANK_NUMBER: 1, US_DRIVER_LICENSE: 1 for the same phone number. Empty spans no longer insert a token that maps to an empty string

When 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. and Also 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 main

Single-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_run and test_numbered_tokens_stay_unique_across_parts_of_one_request in 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 proxy

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

Screenshots / Proof of Fix

Both legs ran 4 workers against real Presidio 2.2.364 (analyzer and anonymizer), real OpenAI gpt-6.1-sol and real Anthropic claude-haiku-5-5. gpt-6.1-sol-recorded is 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 config

guardrails:
  - guardrail_name: presidio-pii
    litellm_params:
      guardrail: presidio
      mode: pre_call
      output_parse_pii: true
      default_on: true
      presidio_filter_scope: input

The MCP case adds an MCP server echo (a tool that returns its text argument and logs what it received) and runs the same guardrail with mode: pre_mcp_call. The last case drops presidio_filter_scope, which is the exact config from the ticket

The chat loop is

for text in "my number is 4251234567" "contact john.smith@example.com today" "her phone is +33 1 42 68 53 00."; do
  curl -s localhost:4000/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \
    -d "{\"model\": \"gpt-6.1-sol-recorded\", \"messages\": [{\"role\": \"user\", \"content\": \"Repeat exactly: $text\"}]}" | jq -r '.choices[0].message.content'
done

and the streaming leg sends the same body with "stream": true and joins the content deltas

Before (8efb99b)

/v1/chat/completions

  1. Run the chat loop above, non-streaming then streaming. Replies, in order
    my number is 4251234567UMBER_3>_LICENSE_3>
    my number is 4251234567UMBER_3>_LICENSE_3>
    contact john.smith@example.comTE_TIME_4>
    contact john.smith@example.comTE_TIME_4>
    her phone is +33 1 42 68 53 00_TIME_2>.
    her phone is +33 1 42 68 53 00_TIME_2>.
    
  2. What OpenAI received for each of those six requests, from the recorder
    Repeat exactly: my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
    Repeat exactly: my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
    Repeat exactly: contact <EMAIL_ADDRESS_1>TE_TIME_4>
    Repeat exactly: contact <EMAIL_ADDRESS_1>TE_TIME_4>
    Repeat exactly: her phone is <PHONE_NUMBER_1>_TIME_2>.
    Repeat exactly: her phone is <PHONE_NUMBER_1>_TIME_2>.
    

/v1/messages

  1. 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'
    my number is 4251234567UMBER_3>_LICENSE_3>
    
    This looks like a garbled placeholder rather than an actual phone number. If you meant to share a real number, please type it out and I'll repeat it back.
    

/v1/responses

  1. 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'
    my number is 4251234567UMBER_3>_LICENSE_3>
    
  2. What OpenAI received
    Repeat exactly: my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
    

/v1/responses over WebSocket

  1. Connect to ws://localhost:4000/v1/responses?model=gpt-6.1-sol with the key and send {"type": "response.create", "input": "Repeat exactly: my number is 4251234567"}. The response.output_text.done event carries what the model saw, and response.completed carries the restored reply
    output_text.done: 'my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>'
    completed: ['my number is 4251234567UMBER_3>_LICENSE_3>']
    

/guardrails/apply_guardrail

  1. 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"}'
    {"response_text":"my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>"}
    

MCP tool call

  1. 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]'
    ["my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>"]
    
  2. What the MCP server received, from its own log
    {"received": "my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>"}
    

Ticket config (no presidio_filter_scope)

  1. Run the chat loop above, non-streaming then streaming. Replies, in order
    my number is 4251234567UMBER_3>_LICENSE_3>
    my number is 4251234567UMBER_3>_LICENSE_3>
    contact <PERSON>>
    contact <PERSON>>
    her phone is <PHONE_NUMBER>_TIME_2>.
    her phone is <PHONE_NUMBER>_TIME_2>.
    
  2. What OpenAI received for each of those six requests, from the recorder
    Repeat exactly: my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
    Repeat exactly: my number is <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>
    Repeat exactly: contact <EMAIL_ADDRESS_1>TE_TIME_4>
    Repeat exactly: contact <EMAIL_ADDRESS_1>TE_TIME_4>
    Repeat exactly: her phone is <PHONE_NUMBER_1>_TIME_2>.
    Repeat exactly: her phone is <PHONE_NUMBER_1>_TIME_2>.
    

Admin UI

  1. Playground and Logs screenshots are the Before images under User Flow

After (bb55d17)

/v1/chat/completions

  1. Run the chat loop above, non-streaming then streaming. Replies, in order
    my number is 4251234567
    my number is 4251234567
    contact john.smith@example.com today
    contact john.smith@example.com today
    her phone is +33 1 42 68 53 00.
    her phone is +33 1 42 68 53 00.
    
  2. What OpenAI received for each of those six requests, from the recorder
    Repeat exactly: my number is <PHONE_NUMBER_1>
    Repeat exactly: my number is <PHONE_NUMBER_1>
    Repeat exactly: contact <EMAIL_ADDRESS_1> <DATE_TIME_2>
    Repeat exactly: contact <EMAIL_ADDRESS_1> <DATE_TIME_2>
    Repeat exactly: her phone is <PHONE_NUMBER_1>.
    Repeat exactly: her phone is <PHONE_NUMBER_1>.
    

/v1/messages

  1. 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'
    my number is 4251234567
    

/v1/responses

  1. 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'
    my number is 4251234567
    
  2. What OpenAI received
    Repeat exactly: my number is <PHONE_NUMBER_1>
    

/v1/responses over WebSocket

  1. Connect to ws://localhost:4000/v1/responses?model=gpt-6.1-sol with the key and send {"type": "response.create", "input": "Repeat exactly: my number is 4251234567"}. The response.output_text.done event carries what the model saw, and response.completed carries the restored reply
    output_text.done: 'my number is <PHONE_NUMBER_1>'
    completed: ['my number is 4251234567']
    

/guardrails/apply_guardrail

  1. 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"}'
    {"response_text":"my number is <PHONE_NUMBER_1>"}
    

MCP tool call

  1. 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]'
    ["my number is <PHONE_NUMBER_1>"]
    
  2. What the MCP server received, from its own log
    {"received": "my number is <PHONE_NUMBER_1>"}
    

Ticket config (no presidio_filter_scope)

  1. Run the chat loop above, non-streaming then streaming. Replies, in order
    my number is <PHONE_NUMBER>
    my number is <PHONE_NUMBER>
    contact <EMAIL_ADDRESS> <DATE_TIME>
    contact <EMAIL_ADDRESS> <DATE_TIME>
    her phone is <PHONE_NUMBER>.
    her phone is <PHONE_NUMBER>.
    
  2. What OpenAI received for each of those six requests, from the recorder
    Repeat exactly: my number is <PHONE_NUMBER_1>
    Repeat exactly: my number is <PHONE_NUMBER_1>
    Repeat exactly: contact <EMAIL_ADDRESS_1> <DATE_TIME_2>
    Repeat exactly: contact <EMAIL_ADDRESS_1> <DATE_TIME_2>
    Repeat exactly: her phone is <PHONE_NUMBER_1>.
    Repeat exactly: her phone is <PHONE_NUMBER_1>.
    

Admin UI

  1. Playground and Logs screenshots are the After images under User Flow (taken on e28c550, the commit before the cross-part change, which does not touch single-text requests)

Two values of one type in separate parts

System turn Echo tool. Output every user text block below, in order, verbatim, joined by ' | ', model gpt-6.1-sol-recorded, input scope, both legs at 4 workers. Sent is what OpenAI received, from the recorder

Request Main sent Main reply This PR sent This PR reply
parts My 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
same two texts as two user messages same as above same as above same as above same as above
same two texts in the other order <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, 4251234567
parts My number is 4251234567., Her number is 2065550123. <PHONE_NUMBER_3>UMBER_3>_LICENSE_3> twice 2065550123UMBER_3>_LICENSE_3> twice <PHONE_NUMBER_1>, <PHONE_NUMBER_2> 4251234567, 2065550123
parts Call John Smith., Then call Mary Jones. <PERSON_1> twice Mary Jones twice <PERSON_1>, <PERSON_2> John Smith, Mary Jones
three parts, phone, name, phone <PHONE_NUMBER_3>UMBER_3>_LICENSE_3>, <PERSON_1>, <PHONE_NUMBER_1> first number garbled <PHONE_NUMBER_1>, <PERSON_1>, <PHONE_NUMBER_3> all three exact

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/messages streaming 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 garbled

Mutation 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, min for max), 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 main

The 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/messages streaming, 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 at INTEGRATION_WORKERS=4 on 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 confirms

Type

Bug Fix

Caveats (if any)

Medium

  • With the default presidio_filter_scope (both), the restored reply is masked again
    • The client sees <PHONE_NUMBER> instead of the number, same as main for any entity
    • This is documented in pii_masking_v2, set presidio_filter_scope: input to get values back

Low

  • Partly overlapping spans mask their union, Presidio would split them
  • When two parts clash, the part whose masking finishes first keeps the lower number
    • The proxy's shared Presidio session lock makes that the part order, 30 of 30 concurrent requests above
  • Responses WebSocket output_text.delta and output_text.done stay masked, same as main
  • MCP tool results are not unmasked, same as main
  • /v1/messages streaming does not restore a token split across two deltas, same as main
  • A reply cut off mid-token, like <PERSON_, restores the first token with that prefix
    • With two names in separate parts that can be either name, every value is from the caller's own request
    • Main does the same for two names in one message, and for separate parts it restores the later name
  • The new integration test first runs on CircleCI after merge

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

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 that

The 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 count

Collapsing 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

PINYOPATTANAWASANPORN and others added 2 commits October 16, 2026 17:03
…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.
@greptile-apps

greptile-apps Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Automatic reviews are disabled for this repository.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@devin-ai-integration devin-ai-integration 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.

Devin Review found 2 potential issues.

Devin Review

@litereview

litereview Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

✅ code-review

5/5 · Ready for human review

Scope: 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
  • Passed · Real testing evidence (required): Not applicable: no LLM translation changes in the scoped paths. The PR changes litellm/proxy/guardrails/guardrail_hooks/presidio.py and tests only. It touches nothing under litellm/llms/** or litellm/litellm_core_utils/prompt_templates/**.

  • Passed · Compatibility requirements (required): No supported behavior breaks.

  • Non-overlapping spans in one text: output is unchanged. Tokens are still numbered &lt;TYPE_n> left to right.

  • Overlapping spans: before, the proxy produced corrupted text such as &lt;PHONE_NUMBER_3>UMBER_3>_LICENSE_3> and a restore map with fragments. Now it produces one token per run.

  • Multi-part requests: before, a clashing token was overwritten and restored as the wrong value. Now the clashing part gets a spare number.

  • masked_entity_count: it drops (for example, 3 to 1) only for inputs that previously produced corrupted output. The PR documents this under Behavior changes.

No previously successful, correct input now fails or produces different correct output, so the title needs no ! marker.

  • Passed · Changed behavior and result consistency (required): Standards read: tests/AGENTS.md, tests/integration/AGENTS.md and tests/integration/README.md. The new integration file sits in observability/ (extensions group, CircleCI) and uses a wire-level upstream, which matches the documented convention.

Traced path: anonymize_text → _finalize_presidio_anonymize_numbered_tokens → request_data['metadata']['pii_tokens']. That map feeds _unmask_pii_text for non-streaming, streaming SSE, Anthropic and Responses replies.

Boundary cases checked:

  • Empty and inverted spans are dropped.
  • Equal-start runs work in both analyzer orders.
  • A contained higher-scored fragment does not relabel its container.
  • Partial overlap masks the union.
  • A same value across parts reuses its token.
  • A different value across parts gets a spare number above all used numbers.

The spare-number invariant (no token number exceeds the map size) holds by induction, and fuzzing confirmed it. anonymize_text is synchronous between the shared-map read and write, so concurrent part masking cannot interleave inside the allocation.

  • Passed · Unit tests: test_presidio.py (optional): .venv/bin/python -m pytest -q -p no:warnings tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py: 174 passed in 6.52s. The new parametrized tests assert the full masked text, token map, counts and the unmask round-trip.
  • Passed · Integration: test_presidio_overlapping_spans.py (optional): Ran tests/integration/run.py extensions tests/integration/observability/test_presidio_overlapping_spans.py with INTEGRATION_WORKERS=2 against local Postgres 15 and Redis: 16 passed in 64s. Tests drive a real proxy process with wire-level analyzer, anonymizer and provider stubs. The analyzer stub replays spans the test labels as recorded from Presidio 2.2.364. Cases cover streaming and non-streaming, input and default scope, and separate messages vs. content parts.
  • Passed · Randomized round-trip fuzz (optional): Ad-hoc script /tmp/fuzz.py ran 30,000 trials. Each trial had 1–10 parts with random overlapping, empty and inverted spans over 3 entity types. It checked that no earlier pii_tokens entry was overwritten and that _unmask_pii_text restores every part exactly. Result: bad 0.

View review · Reviewed bb55d177d482

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@codspeed

codspeed Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

⚠️ 1 benchmark spent significant time in system calls

System calls cannot be consistently instrumented, so they are not included in the measure, which understates the real cost. Please switch to the Walltime instrument to accurately measure system calls.

Measurement and system calls

✅ 32 untouched benchmarks


Comparing litellm_presidio_overlapping_spans (bb55d17) with main (caad4d6)

Open in CodSpeed

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

@codecov

codecov Bot commented Oct 17, 2026

Copy link
Copy Markdown

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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

@veria-ai

veria-ai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No 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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

…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
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litereview code-review

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

✅ 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 BrickerP left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Solid fix for overlapping Presidio spans corrupting numbered PII tokens.

Verified on bb55d177:

  • _resolve_overlapping_spans collapses overlap runs; _collapse_run labels 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.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

litellm-stampbot Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

litellm-stampbot: risk low

Approved at bb55d17.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): low, probability of high 0.09 (high at or above 0.75)

  • risk: low (probability of high 0.09)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:low Small, isolated, low-risk change label Oct 17, 2026

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

Low risk by rule and by judgement at bb55d17

@yucheng-berri
yucheng-berri merged commit 223800f into main Oct 17, 2026
101 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:low Small, isolated, low-risk change

Projects

None yet

4 participants