Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

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

yucheng-berri223800f91637
diff --git a/litellm/proxy/guardrails/guardrail_hooks/presidio.py b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
index f21aabc7f33..cadc9ca689b 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@ -16,6 +16,7 @@ from collections.abc import AsyncGenerator, AsyncIterable, AsyncIterator, Awaita
from contextlib import asynccontextmanager
from dataclasses import dataclass
from datetime import datetime
+from itertools import accumulate, count, pairwise
from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, cast
import aiohttp
@@ -182,6 +183,59 @@ async def _coalesce_first_sse_frame(stream: AsyncIterator[object]) -> AsyncGener
yield chunk
+@dataclass(frozen=True, slots=True)
+class _Detection:
+ entity_type: str
+ start: int
+ end: int
+ score: float
+
+
+def _strictly_contains(outer: _Detection, inner: _Detection) -> bool:
+ return (
+ outer.start <= inner.start and inner.end <= outer.end and (outer.start, outer.end) != (inner.start, inner.end)
+ )
+
+
+def _collapse_run(run: Sequence[_Detection]) -> _Detection:
+ label: Final = max(
+ (detection for detection in run if not any(_strictly_contains(other, detection) for other in run)),
+ key=lambda detection: (detection.score, detection.end - detection.start, detection.entity_type),
+ )
+ return _Detection(label.entity_type, run[0].start, max(detection.end for detection in run), label.score)
+
+
+def _to_detection(item: PresidioAnalyzeResponseItem) -> _Detection:
+ return _Detection(
+ str(item.get("entity_type")),
+ int(item.get("start") or 0),
+ int(item.get("end") or 0),
+ float(item.get("score") or 0.0),
+ )
+
+
+def _resolve_overlapping_spans(analyze_results: Sequence[PresidioAnalyzeResponseItem]) -> tuple[_Detection, ...]:
+ """
+ Collapse each run of overlapping detections into one detection covering the whole run.
+
+ The run takes its entity type from its highest-scoring detection that no other
+ detection in the run strictly contains, the same containment rule Presidio's
+ anonymizer applies, so a phone number with a date-shaped fragment inside it stays
+ a PHONE_NUMBER. Runs come back sorted by start and never overlap.
+ """
+ detections: Final = sorted(
+ (detection for detection in map(_to_detection, analyze_results) if detection.start < detection.end),
+ key=lambda detection: detection.start,
+ )
+ run_ends: Final = tuple(accumulate((detection.end for detection in detections), max))
+ boundaries: Final = (
+ 0,
+ *(index for index in range(1, len(detections)) if detections[index].start >= run_ends[index - 1]),
+ len(detections),
+ )
+ return tuple(_collapse_run(detections[first:last]) for first, last in pairwise(boundaries) if first < last)
+
+
class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
user_api_key_cache = None
ad_hoc_recognizers: list[str] | None = None
@@ -822,31 +876,25 @@ class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
request_data["metadata"] = {}
if "pii_tokens" not in request_data["metadata"]:
request_data["metadata"]["pii_tokens"] = {}
- pii_tokens: Final = request_data["metadata"]["pii_tokens"]
-
- # Assign sequence numbers in forward (left-to-right) order so
- # that <PERSON_1> is the first entity in the text, etc.
- sorted_forward: Final = sorted(analyze_results, key=lambda x: x["start"])
- seq_map: Final = {}
- for idx, ar in enumerate(sorted_forward, start=1):
- seq_map[(ar["start"], ar["end"])] = idx
-
- # Apply replacements in reverse order by start position so
- # that replacing later spans first does not shift earlier
- # coordinates in the original text.
- for ar in reversed(sorted_forward):
- start = ar["start"]
- end = ar["end"]
- entity_type = ar["entity_type"]
- replacement = f"<{entity_type}>"
- seq = seq_map[(start, end)]
- if replacement.endswith(">"):
- replacement = f"{replacement[:-1]}_{seq}>"
- else:
- replacement = f"{replacement}_{seq}"
- pii_tokens[replacement] = text[start:end]
- new_text = new_text[:start] + replacement + new_text[end:]
- masked_entity_count[entity_type] = masked_entity_count.get(entity_type, 0) + 1
+ pii_tokens: Final = cast("dict[str, str]", request_data["metadata"]["pii_tokens"]) # cast-ok: this hook's map
+
+ runs: Final = _resolve_overlapping_spans(analyze_results)
+ # Every message and content part numbers its runs from 1 into this one map, so a
+ # token another part already holds for a different value takes a spare number.
+ # No token in the map is numbered above its size, so spares start above both.
+ spare_numbers: Final = count(max(len(pii_tokens), len(runs)) + 1)
+
+ for seq, run in reversed(tuple(enumerate(runs, start=1))):
+ original = text[run.start : run.end]
+ numbered = f"<{run.entity_type}_{seq}>"
+ replacement = (
+ numbered
+ if pii_tokens.get(numbered, original) == original
+ else f"<{run.entity_type}_{next(spare_numbers)}>"
+ )
+ pii_tokens[replacement] = original
+ new_text = new_text[: run.start] + replacement + new_text[run.end :]
+ masked_entity_count[run.entity_type] = masked_entity_count.get(run.entity_type, 0) + 1
return new_text
async def anonymize_text(
diff --git a/tests/integration/observability/test_presidio_overlapping_spans.py b/tests/integration/observability/test_presidio_overlapping_spans.py
new file mode 100644
index 00000000000..a2d92b15330
--- /dev/null
+++ b/tests/integration/observability/test_presidio_overlapping_spans.py
@@ -0,0 +1,251 @@
+import json
+import re
+from collections.abc import Iterator
+from contextlib import contextmanager
+from dataclasses import dataclass
+from itertools import chain
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final, Literal
+
+import pytest
+import yaml
+from integration._support.client import Gateway, gateway_from_environment
+from integration._support.process import owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+
+MODEL: Final = "gpt-6.1-sol"
+PHONE: Final = "4251234567"
+EMAIL: Final = "[email protected]"
+INTERNATIONAL_PHONE: Final = "+33 1 42 68 53 00"
+US_PHONE: Final = "+1 (206) 555-0199"
+SAME_SPAN: Final = f"Repeat exactly: my number is {PHONE}"
+NESTED: Final = f"contact {EMAIL} today"
+CONTAINED_FRAGMENT: Final = f"her phone is {INTERNATIONAL_PHONE}."
+SEPARATE_PARTS: Final = (f"My number is {PHONE}.", f"Also call {US_PHONE}.")
+# Spans, scores and anonymized texts recorded from presidio-analyzer and presidio-anonymizer 2.2.364 on 2026-10-16
+DETECTIONS: Final = MappingProxyType(
+ {
+ PHONE: (("PHONE_NUMBER", 0, 10, 0.75), ("US_BANK_NUMBER", 0, 10, 0.05), ("US_DRIVER_LICENSE", 0, 10, 0.01)),
+ EMAIL: (("EMAIL_ADDRESS", 0, 22, 1.0), ("URL", 0, 7, 0.5), ("URL", 11, 22, 0.5)),
+ "today": (("DATE_TIME", 0, 5, 0.85),),
+ INTERNATIONAL_PHONE: (("DATE_TIME", 12, 17, 0.85), ("PHONE_NUMBER", 0, 17, 0.75)),
+ US_PHONE: (("PHONE_NUMBER", 0, 17, 0.4),),
+ }
+)
+ANONYMIZED: Final = MappingProxyType(
+ {
+ SAME_SPAN: "Repeat exactly: my number is <PHONE_NUMBER>",
+ NESTED: "contact <EMAIL_ADDRESS> <DATE_TIME>",
+ CONTAINED_FRAGMENT: "her phone is <PHONE_NUMBER>.",
+ SEPARATE_PARTS[0]: "My number is <PHONE_NUMBER>.",
+ SEPARATE_PARTS[1]: "Also call <PHONE_NUMBER>.",
+ }
+)
+CASES: Final = (
+ pytest.param(SAME_SPAN, "Repeat exactly: my number is <PHONE_NUMBER_1>", id="same_span"),
+ pytest.param(NESTED, "contact <EMAIL_ADDRESS_1> <DATE_TIME_2>", id="nested"),
+ pytest.param(CONTAINED_FRAGMENT, "her phone is <PHONE_NUMBER_1>.", id="container_outranks_higher_scored_fragment"),
+)
+STREAM: Final = pytest.mark.parametrize("stream", [False, True], ids=["non_streaming", "streaming"])
+
+
+def _detections(text: str, value: str) -> Iterator[dict[str, str | int | float]]:
+ for match in re.finditer(rf"(?<!\w){re.escape(value)}(?!\w)", text):
+ for entity, start, end, score in DETECTIONS[value]:
+ yield {"entity_type": entity, "start": match.start() + start, "end": match.start() + end, "score": score}
+
+
+def _findings(text: str) -> list[dict[str, str | int | float]]:
+ findings: Final = chain.from_iterable(_detections(text, value) for value in DETECTIONS)
+ return sorted(findings, key=lambda item: -item["score"])
+
+
+def _spans(results: list[dict[str, str | int | float]]) -> list[tuple[str | int | float, ...]]:
+ return sorted(tuple(result[key] for key in ("entity_type", "start", "end", "score")) for result in results)
+
+
+def _analyze(request: Request) -> Reply:
+ assert request.target == "/analyze", request.target
+ return Reply(body=json.dumps(_findings(json.loads(request.body)["text"])).encode())
+
+
+def _anonymize(request: Request) -> Reply:
+ assert request.target == "/anonymize", request.target
+ body: Final = json.loads(request.body)
+ text: Final = body["text"]
+ if text not in ANONYMIZED:
+ return Reply(status=500, body=json.dumps({"error": f"no recorded anonymization for {text!r}"}).encode())
+ if _spans(body["analyzer_results"]) != _spans(_findings(text)):
+ return Reply(
+ status=500, body=json.dumps({"error": f"analyzer_results differ from the detections for {text!r}"}).encode()
+ )
+ return Reply(body=json.dumps({"text": ANONYMIZED[text], "items": []}).encode())
+
+
+def _texts(messages: list[dict]) -> tuple[str, ...]:
+ return tuple(
+ chain.from_iterable(
+ (message["content"],)
+ if isinstance(message["content"], str)
+ else (part["text"] for part in message["content"])
+ for message in messages
+ )
+ )
+
+
+def _chunk(text: str, finish: str | None) -> bytes:
+ delta: Final = {"role": "assistant", "content": text} if finish is None else {}
+ payload: Final = {
+ "id": "chatcmpl-echo",
+ "object": "chat.completion.chunk",
+ "created": 1,
+ "model": MODEL,
+ "choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
+ }
+ return b"data: " + json.dumps(payload).encode() + b"\n\n"
+
+
+def _echo(request: Request) -> Reply:
+ assert request.target == "/v1/chat/completions", request.target
+ body: Final = json.loads(request.body)
+ text: Final = " | ".join(_texts(body["messages"]))
+ if body.get("stream"):
+ pieces: Final = tuple(text[index : index + 6] for index in range(0, len(text), 6))
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(*(_chunk(piece, None) for piece in pieces), _chunk("", "stop"), b"data: [DONE]\n\n"),
+ )
+ reply: Final = {
+ "id": "chatcmpl-echo",
+ "object": "chat.completion",
+ "created": 1,
+ "model": MODEL,
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 9, "completion_tokens": 9, "total_tokens": 18},
+ }
+ return Reply(body=json.dumps(reply).encode())
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ proxy: Gateway
+ provider: Wire
+
+
+def _config(root: Path, provider: Wire, analyzer: Wire, anonymizer: Wire, scope: Literal["input"] | None) -> Path:
+ config: Final = yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text())
+ config["litellm_settings"]["cache"] = False
+ config["model_list"].append(
+ {
+ "model_name": MODEL,
+ "litellm_params": {"model": f"openai/{MODEL}", "api_base": provider.url + "/v1", "api_key": "synthetic"},
+ }
+ )
+ guardrail: Final = {
+ "guardrail": "presidio",
+ "mode": "pre_call",
+ "output_parse_pii": True,
+ "default_on": True,
+ "presidio_analyzer_api_base": analyzer.url + "/",
+ "presidio_anonymizer_api_base": anonymizer.url + "/",
+ }
+ scoped: Final = guardrail if scope is None else {**guardrail, "presidio_filter_scope": scope}
+ config["guardrails"] = [{"guardrail_name": "presidio-pii", "litellm_params": scoped}]
+ path: Final = root / "presidio-overlapping-spans.yaml"
+ path.write_text(yaml.safe_dump(config))
+ return path
+
+
+@contextmanager
+def _rig(root: Path, scope: Literal["input"] | None) -> Iterator[Rig]:
+ with (
+ gateway_from_environment() as gateway,
+ wire_server(_echo) as provider,
+ wire_server(_analyze) as analyzer,
+ wire_server(_anonymize) as anonymizer,
+ owned_proxy_process(
+ gateway, root, {}, config=_config(root, provider, analyzer, anonymizer, scope), workers=2
+ ) as owned,
+ ):
+ yield Rig(owned.gateway, provider)
+
+
[email protected](scope="module")
+def default_scope_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ with _rig(tmp_path_factory.mktemp("presidio-default-scope"), None) as rig:
+ yield rig
+
+
[email protected](scope="module")
+def input_scope_rig(tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ with _rig(tmp_path_factory.mktemp("presidio-input-scope"), "input") as rig:
+ yield rig
+
+
+def _send(rig: Rig, messages: list[dict], stream: bool) -> tuple[int, str]:
+ rig.provider.drain()
+ body: Final = {"model": MODEL, "messages": messages, "stream": stream}
+ headers: Final = {"Authorization": f"Bearer {rig.proxy.key}"}
+ if not stream:
+ response: Final = rig.proxy.client.post("/v1/chat/completions", json=body, headers=headers)
+ if response.status_code != 200:
+ return response.status_code, response.text
+ return response.status_code, response.json()["choices"][0]["message"]["content"]
+ with rig.proxy.client.stream("POST", "/v1/chat/completions", json=body, headers=headers) as streamed:
+ if streamed.status_code != 200:
+ return streamed.status_code, streamed.read().decode()
+ frames: Final = tuple(
+ json.loads(line.removeprefix("data: "))
+ for line in streamed.iter_lines()
+ if line.startswith("data: ") and line != "data: [DONE]"
+ )
+ return 200, "".join(frame["choices"][0]["delta"].get("content") or "" for frame in frames if frame["choices"])
+
+
+def _forwarded(rig: Rig) -> tuple[str, ...]:
+ received: Final = rig.provider.drain()
+ assert len(received) == 1, received
+ return _texts(json.loads(received[0].body)["messages"])
+
+
+@STREAM
[email protected](("text", "forwarded"), CASES)
+def test_overlapping_detections_reach_the_provider_as_one_token_and_come_back_unmasked(
+ input_scope_rig: Rig, text: str, forwarded: str, stream: bool
+) -> None:
+ status, replied = _send(input_scope_rig, [{"role": "user", "content": text}], stream)
+ assert status == 200, replied
+ assert _forwarded(input_scope_rig) == (forwarded,)
+ assert replied == text
+
+
+@STREAM
[email protected](("text", "forwarded"), CASES)
+def test_default_scope_masks_the_cleanly_restored_reply_like_presidio_masks_the_original(
+ default_scope_rig: Rig, text: str, forwarded: str, stream: bool
+) -> None:
+ status, replied = _send(default_scope_rig, [{"role": "user", "content": text}], stream)
+ assert status == 200, replied
+ assert _forwarded(default_scope_rig) == (forwarded,)
+ assert replied == ANONYMIZED[text]
+
+
+@STREAM
+ "messages",
+ [
+ pytest.param(
+ [{"role": "user", "content": [{"type": "text", "text": part} for part in SEPARATE_PARTS]}],
+ id="content_parts",
+ ),
+ pytest.param([{"role": "user", "content": part} for part in SEPARATE_PARTS], id="messages"),
+ ],
+)
+def test_one_type_in_separate_parts_gets_distinct_tokens_and_each_part_comes_back_as_itself(
+ input_scope_rig: Rig, messages: list[dict], stream: bool
+) -> None:
+ status, replied = _send(input_scope_rig, messages, stream)
+ assert status == 200, replied
+ assert _forwarded(input_scope_rig) == ("My number is <PHONE_NUMBER_1>.", "Also call <PHONE_NUMBER_2>.")
+ assert replied == " | ".join(SEPARATE_PARTS)
diff --git a/tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py b/tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py
index 7d0c81af4c2..bd1e9ae4068 100644
--- a/tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py
+++ b/tests/unit/proxy/guardrails/guardrail_hooks/test_presidio.py
@@ -3789,6 +3789,246 @@ async def test_output_parse_pii_numbered_tokens_across_chunks():
assert pii_tokens["<CREDIT_CARD_2>"] == CHUNK_MARKER_TWO
+ ("text", "analyze_results", "expected_text", "expected_tokens", "expected_counts"),
+ [
+ pytest.param(
+ "Repeat exactly: my number is 4251234567",
+ [
+ {"entity_type": "PHONE_NUMBER", "start": 29, "end": 39, "score": 0.75},
+ {"entity_type": "US_BANK_NUMBER", "start": 29, "end": 39, "score": 0.05},
+ {"entity_type": "US_DRIVER_LICENSE", "start": 29, "end": 39, "score": 0.01},
+ ],
+ "Repeat exactly: my number is <PHONE_NUMBER_1>",
+ {"<PHONE_NUMBER_1>": "4251234567"},
+ {"PHONE_NUMBER": 1},
+ id="same-span",
+ ),
+ pytest.param(
+ "contact [email protected] today",
+ [
+ {"entity_type": "EMAIL_ADDRESS", "start": 8, "end": 30, "score": 1.0},
+ {"entity_type": "DATE_TIME", "start": 31, "end": 36, "score": 0.85},
+ {"entity_type": "URL", "start": 8, "end": 15, "score": 0.5},
+ {"entity_type": "URL", "start": 19, "end": 30, "score": 0.5},
+ ],
+ "contact <EMAIL_ADDRESS_1> <DATE_TIME_2>",
+ {"<EMAIL_ADDRESS_1>": "[email protected]", "<DATE_TIME_2>": "today"},
+ {"EMAIL_ADDRESS": 1, "DATE_TIME": 1},
+ id="nested",
+ ),
+ pytest.param(
+ "her phone is +33 1 42 68 53 00.",
+ [
+ {"entity_type": "DATE_TIME", "start": 25, "end": 30, "score": 0.85},
+ {"entity_type": "PHONE_NUMBER", "start": 13, "end": 30, "score": 0.75},
+ ],
+ "her phone is <PHONE_NUMBER_1>.",
+ {"<PHONE_NUMBER_1>": "+33 1 42 68 53 00"},
+ {"PHONE_NUMBER": 1},
+ id="container-outranks-higher-scored-fragment",
+ ),
+ pytest.param(
+ "ids ab0123456789 and cd0123456789",
+ [
+ {"entity_type": "AAA", "start": 4, "end": 16, "score": 0.5},
+ {"entity_type": "BBB", "start": 21, "end": 29, "score": 0.5},
+ {"entity_type": "CCC", "start": 25, "end": 33, "score": 0.9},
+ ],
+ "ids <AAA_1> and <CCC_2>",
+ {"<AAA_1>": "ab0123456789", "<CCC_2>": "cd0123456789"},
+ {"AAA": 1, "CCC": 1},
+ id="partial-overlap-in-second-run",
+ ),
+ pytest.param(
+ "id ab0123456789",
+ [
+ {"entity_type": "AAA", "start": 3, "end": 15, "score": 0.5},
+ {"entity_type": "BBB", "start": 3, "end": 8, "score": 0.9},
+ ],
+ "id <AAA_1>",
+ {"<AAA_1>": "ab0123456789"},
+ {"AAA": 1},
+ id="container-sharing-start-outranks-fragment",
+ ),
+ pytest.param(
+ "id ab0123456789",
+ [
+ {"entity_type": "AAA", "start": 3, "end": 10, "score": 0.9},
+ {"entity_type": "BBB", "start": 7, "end": 15, "score": 0.5},
+ ],
+ "id <AAA_1>",
+ {"<AAA_1>": "ab0123456789"},
+ {"AAA": 1},
+ id="earlier-higher-scored-detection-labels-the-whole-run",
+ ),
+ pytest.param(
+ "id ab0123456789",
+ [
+ {"entity_type": "AAA", "start": 6, "end": 15, "score": 0.5},
+ {"entity_type": "BBB", "start": 3, "end": 8, "score": 0.5},
+ ],
+ "id <AAA_1>",
+ {"<AAA_1>": "ab0123456789"},
+ {"AAA": 1},
+ id="score-tie-goes-to-the-longer-detection",
+ ),
+ pytest.param(
+ "id ab0123456789",
+ [
+ {"entity_type": "AAA", "start": 3, "end": 9, "score": 0.5},
+ {"entity_type": "BBB", "start": 9, "end": 15, "score": 0.5},
+ ],
+ "id <AAA_1><BBB_2>",
+ {"<AAA_1>": "ab0123", "<BBB_2>": "456789"},
+ {"AAA": 1, "BBB": 1},
+ id="touching-detections-stay-separate",
+ ),
+ pytest.param(
+ "id ab0123456789",
+ [
+ {"entity_type": "AAA", "start": 3, "end": 15, "score": 0.5},
+ {"entity_type": "BBB", "start": 3, "end": 15, "score": 0.5},
+ ],
+ "id <BBB_1>",
+ {"<BBB_1>": "ab0123456789"},
+ {"BBB": 1},
+ id="identical-spans-with-equal-scores-label-the-same-in-any-order",
+ ),
+ pytest.param(
+ "My name is John Smith, phone +1 415 555 2671, please check the order.",
+ [
+ {"entity_type": "EMPTY", "start": 25, "end": 25, "score": 0.99},
+ {"entity_type": "INVERTED", "start": 40, "end": 30, "score": 0.99},
+ {"entity_type": "PERSON", "start": 11, "end": 21, "score": 0.9},
+ {"entity_type": "PHONE_NUMBER", "start": 29, "end": 44, "score": 0.85},
+ {"entity_type": "UK_NHS", "start": 32, "end": 44, "score": 0.6},
+ ],
+ "My name is <PERSON_1>, phone <PHONE_NUMBER_2>, please check the order.",
+ {"<PERSON_1>": "John Smith", "<PHONE_NUMBER_2>": "+1 415 555 2671"},
+ {"PERSON": 1, "PHONE_NUMBER": 1},
+ id="empty-and-inverted-spans-are-ignored",
+ ),
+ pytest.param(
+ "Code ABC-12345-XYZ is valid.",
+ [
+ {"entity_type": "GENERIC_ID", "start": 5, "end": 14, "score": 0.5},
+ {"entity_type": "SECRET_KEY", "start": 9, "end": 18, "score": 0.95},
+ ],
+ "Code <SECRET_KEY_1> is valid.",
+ {"<SECRET_KEY_1>": "ABC-12345-XYZ"},
+ {"SECRET_KEY": 1},
+ id="later-higher-scored-detection-labels-the-whole-run",
+ ),
+ ],
+)
[email protected]("order", ["analyzer", "reversed"])
+def test_numbered_tokens_collapse_overlapping_detections_into_one_token_per_run(
+ text: str,
+ analyze_results: list[PresidioAnalyzeResponseItem],
+ expected_text: str,
+ expected_tokens: dict[str, str],
+ expected_counts: dict[str, int],
+ order: Literal["analyzer", "reversed"],
+) -> None:
+ guardrail: Final = OPTIONAL_PresidioPIIMasking(mock_testing=True)
+ request_data: Final = {"metadata": {}}
+ masked_entity_count: Final = {}
+ ordered: Final = analyze_results if order == "analyzer" else analyze_results[::-1]
+
+ masked: Final = guardrail._finalize_presidio_anonymize_numbered_tokens(
+ text, ordered, request_data, masked_entity_count
+ )
+
+ assert masked == expected_text
+ assert request_data["metadata"]["pii_tokens"] == expected_tokens
+ assert masked_entity_count == expected_counts
+ assert OPTIONAL_PresidioPIIMasking._unmask_pii_text(masked, expected_tokens) == text
+
+
+ ("parts", "expected_masked", "expected_tokens"),
+ [
+ pytest.param(
+ (
+ (
+ "My number is 4251234567.",
+ [
+ {"entity_type": "PHONE_NUMBER", "start": 13, "end": 23, "score": 0.75},
+ {"entity_type": "US_BANK_NUMBER", "start": 13, "end": 23, "score": 0.05},
+ {"entity_type": "US_DRIVER_LICENSE", "start": 13, "end": 23, "score": 0.01},
+ ],
+ ),
+ (
+ "Also call +1 (206) 555-0199.",
+ [{"entity_type": "PHONE_NUMBER", "start": 10, "end": 27, "score": 0.4}],
+ ),
+ ),
+ ("My number is <PHONE_NUMBER_1>.", "Also call <PHONE_NUMBER_2>."),
+ {"<PHONE_NUMBER_1>": "4251234567", "<PHONE_NUMBER_2>": "+1 (206) 555-0199"},
+ id="overlapping-run-then-plain-detection",
+ ),
+ pytest.param(
+ (
+ ("Call John Smith.", [{"entity_type": "PERSON", "start": 5, "end": 15, "score": 0.85}]),
+ ("Again John Smith.", [{"entity_type": "PERSON", "start": 6, "end": 16, "score": 0.85}]),
+ ),
+ ("Call <PERSON_1>.", "Again <PERSON_1>."),
+ {"<PERSON_1>": "John Smith"},
+ id="same-value-keeps-its-token",
+ ),
+ pytest.param(
+ (
+ ("Call John Smith.", [{"entity_type": "PERSON", "start": 5, "end": 15, "score": 0.85}]),
+ (
+ "Ann Lee and Bob Ray.",
+ [
+ {"entity_type": "PERSON", "start": 0, "end": 7, "score": 0.85},
+ {"entity_type": "PERSON", "start": 12, "end": 19, "score": 0.85},
+ ],
+ ),
+ ),
+ ("Call <PERSON_1>.", "<PERSON_3> and <PERSON_2>."),
+ {"<PERSON_1>": "John Smith", "<PERSON_2>": "Bob Ray", "<PERSON_3>": "Ann Lee"},
+ id="bump-skips-every-claimed-number",
+ ),
+ pytest.param(
+ (
+ (
+ "Ann Lee and Bob Ray.",
+ [
+ {"entity_type": "PERSON", "start": 0, "end": 7, "score": 0.85},
+ {"entity_type": "PERSON", "start": 12, "end": 19, "score": 0.85},
+ ],
+ ),
+ ("Call John Smith.", [{"entity_type": "PERSON", "start": 5, "end": 15, "score": 0.85}]),
+ ),
+ ("<PERSON_1> and <PERSON_2>.", "Call <PERSON_3>."),
+ {"<PERSON_1>": "Ann Lee", "<PERSON_2>": "Bob Ray", "<PERSON_3>": "John Smith"},
+ id="spare-number-starts-above-every-earlier-part",
+ ),
+ ],
+)
+def test_numbered_tokens_stay_unique_across_parts_of_one_request(
+ parts: tuple[tuple[str, list[PresidioAnalyzeResponseItem]], ...],
+ expected_masked: tuple[str, ...],
+ expected_tokens: dict[str, str],
+) -> None:
+ guardrail: Final = OPTIONAL_PresidioPIIMasking(mock_testing=True)
+ request_data: Final = {"metadata": {}}
+
+ masked: Final = tuple(
+ guardrail._finalize_presidio_anonymize_numbered_tokens(text, results, request_data, {})
+ for text, results in parts
+ )
+
+ assert masked == expected_masked
+ assert request_data["metadata"]["pii_tokens"] == expected_tokens
+ assert OPTIONAL_PresidioPIIMasking._unmask_pii_text(" | ".join(masked), expected_tokens) == " | ".join(
+ text for text, _ in parts
+ )
+
+
@pytest.mark.asyncio
async def test_analyze_text_chunked_failure_stays_fail_closed():
"""If one chunk still fails, the chunked path raises exactly like a single