Skip to content

Commit 6c7903a

Browse files
authored
fix(pii): tokenize long unbroken runs in linear time so workers stop missing health pings (#10111)
* fix(pii): tokenize long unbroken runs in linear time so workers stop missing health pings spaCy's tokenizer strips a whitespace-free run one prefix or suffix at a time and re-searches the whole run for each, so a long run such as minified JSON costs quadratic time with the GIL held. A 100k-character NER window of minified JSON held it for seconds, the worker missed uvicorn's 5s health ping, and the supervisor killed it along with every request it was serving. Wrap each model's tokenizer so runs of 100+ non-space characters split in linear time into words and single symbols, leaving doc.text and all other tokenization unchanged. Add an e2e check that fails on the old tokenizer. * test(pii): check PII on both sides of the long run is masked in place
1 parent 00209a0 commit 6c7903a

2 files changed

Lines changed: 84 additions & 0 deletions

File tree

‎apps/pii/server.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,8 @@
5353
from presidio_anonymizer import AnonymizerEngine
5454
from presidio_anonymizer.entities import OperatorConfig
5555
from pydantic import BaseModel, model_validator
56+
from spacy.tokenizer import Tokenizer
57+
from spacy.tokens import Doc
5658

5759
# Languages served. Each needs its spaCy model installed in the image; the
5860
# es/it/pl/fi predefined recognizers (ES_NIF, IT_FISCAL_CODE, PL_PESEL, ...)
@@ -153,12 +155,61 @@ def _register_common_recognizers(analyzer: AnalyzerEngine) -> None:
153155
analyzer.registry.add_recognizer(recognizer_cls())
154156

155157

158+
# spaCy's tokenizer peels a whitespace-free run one prefix or suffix at a time and
159+
# searches the whole run again for each, so a long run such as minified JSON costs
160+
# time quadratic in its length (about 4.5s for a 100,000-character array of small
161+
# objects). That work holds the GIL throughout, so the worker misses uvicorn's 5s
162+
# health ping and is killed with every request it is serving. A run at least this
163+
# long is instead split in linear time into single symbols and words, keeping
164+
# word characters joined by `.`, `,` or `:` together as spaCy does (`1,2,3`,
165+
# `example.com`) so NER does not read each piece of a number as its own entity.
166+
# Shorter runs tokenize as before.
167+
TOKENIZER_RUN_CHARS = 100
168+
_LONG_RUN = regex_module.compile(rf"(?<!\S)\S{{{TOKENIZER_RUN_CHARS},}}")
169+
_RUN_PIECE = regex_module.compile(r"\w+(?:[.,:]\w+)*|\W")
170+
171+
172+
class LongRunTokenizer:
173+
"""spaCy tokenizer that splits runs of TOKENIZER_RUN_CHARS or more non-space
174+
characters in linear time and leaves the rest to spaCy's own tokenizer. The
175+
Doc's text is the input unchanged, because Presidio runs its pattern
176+
recognizers on `doc.text`."""
177+
178+
def __init__(self, tokenizer: Tokenizer) -> None:
179+
self.tokenizer = tokenizer
180+
181+
def __call__(self, text: str) -> Doc:
182+
if not _LONG_RUN.search(text):
183+
return self.tokenizer(text)
184+
words: list[str] = []
185+
spaces: list[bool] = []
186+
start = 0
187+
for run in _LONG_RUN.finditer(text):
188+
self._tokenize_into(text[start : run.start()], words, spaces)
189+
pieces = _RUN_PIECE.findall(run.group())
190+
words.extend(pieces)
191+
spaces.extend([False] * len(pieces))
192+
start = run.end()
193+
# spaCy attaches one following space to the token before it.
194+
if text.startswith(" ", start):
195+
spaces[-1] = True
196+
start += 1
197+
self._tokenize_into(text[start:], words, spaces)
198+
return Doc(self.tokenizer.vocab, words=words, spaces=spaces)
199+
200+
def _tokenize_into(self, text: str, words: list[str], spaces: list[bool]) -> None:
201+
for token in self.tokenizer(text):
202+
words.append(token.text)
203+
spaces.append(bool(token.whitespace_))
204+
205+
156206
def build_analyzer() -> AnalyzerEngine:
157207
nlp_engine = NlpEngineProvider(nlp_configuration=NLP_CONFIGURATION).create_engine()
158208
for nlp in getattr(nlp_engine, "nlp", {}).values():
159209
for pipe in NER_ONLY_DISABLE:
160210
if pipe in nlp.pipe_names:
161211
nlp.disable_pipe(pipe)
212+
nlp.tokenizer = LongRunTokenizer(nlp.tokenizer)
162213
analyzer = AnalyzerEngine(nlp_engine=nlp_engine, supported_languages=SUPPORTED_LANGUAGES)
163214
_register_common_recognizers(analyzer)
164215
return analyzer

‎apps/sim/scripts/test-pii-redaction-e2e.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@ import { getErrorMessage } from '@sim/utils/errors'
1515
* Checks, each recorded in the report:
1616
* - Presidio masks a text over spaCy's limit: a name straddling an NER window edge,
1717
* a name at the very end, and a custom pattern that spans whitespace.
18+
* - Presidio masks names and an email on both sides of a long unbroken run of
19+
* brackets in place, within seconds; spaCy's own tokenizer needs time quadratic
20+
* in such a run's length.
1821
* - A persisted log holding a 5M-character base64 PDF and a 3M-character text that
1922
* names a person at the end: the PDF becomes the binary marker without reaching
2023
* Presidio, the name is masked by real NER, and no request fails.
@@ -177,6 +180,36 @@ async function main(): Promise<void> {
177180
return { textChars: text.length }
178181
})
179182

183+
await check('Presidio masks PII around a long unbroken run within seconds', async () => {
184+
const run = `${'['.repeat(20_000)}${']'.repeat(20_000)}`
185+
const after = '   Write to ada@example.com today.\n'
186+
const text = `${NAME_SENTENCE} ${run}${after}${NAME_SENTENCE}`
187+
const response = await realFetch(new URL('/redact_batch', presidioUrl), {
188+
method: 'POST',
189+
headers: { 'content-type': 'application/json' },
190+
body: JSON.stringify({
191+
texts: [text],
192+
language: 'en',
193+
entities: ['PERSON', 'EMAIL_ADDRESS'],
194+
}),
195+
signal: AbortSignal.timeout(30_000),
196+
})
197+
const body = await response.text()
198+
assert.equal(
199+
response.status,
200+
200,
201+
`Presidio answered ${response.status}: ${body.slice(0, 200)}`
202+
)
203+
const [masked] = (JSON.parse(body) as { texts: string[] }).texts
204+
const maskedSentence = 'Please send questions to <PERSON> before Friday.'
205+
assert.equal(
206+
masked,
207+
`${maskedSentence} ${run}${after.replace('ada@example.com', '<EMAIL_ADDRESS>')}${maskedSentence}`,
208+
'PII around the run was not masked in place'
209+
)
210+
return { textChars: text.length }
211+
})
212+
180213
await check('A persisted log replaces the PDF and masks the long text', async () => {
181214
const since = maskRequests.length
182215
const result = await redactPIIFromExecution(

0 commit comments

Comments
 (0)