Skip to content

Commit 3cb353b

Browse files
committed
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.
1 parent ba233ec commit 3cb353b

2 files changed

Lines changed: 75 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: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ 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 a name beside a long unbroken run of brackets within seconds;
19+
* spaCy's own tokenizer needs time quadratic in such a run's length.
1820
* - A persisted log holding a 5M-character base64 PDF and a 3M-character text that
1921
* names a person at the end: the PDF becomes the binary marker without reaching
2022
* Presidio, the name is masked by real NER, and no request fails.
@@ -177,6 +179,28 @@ async function main(): Promise<void> {
177179
return { textChars: text.length }
178180
})
179181

182+
await check('Presidio masks a name beside a long unbroken run within seconds', async () => {
183+
const text = `${NAME_SENTENCE} ${'['.repeat(20_000)}${']'.repeat(20_000)}`
184+
const response = await realFetch(new URL('/redact_batch', presidioUrl), {
185+
method: 'POST',
186+
headers: { 'content-type': 'application/json' },
187+
body: JSON.stringify({ texts: [text], language: 'en', entities: ['PERSON'] }),
188+
signal: AbortSignal.timeout(30_000),
189+
})
190+
const body = await response.text()
191+
assert.equal(
192+
response.status,
193+
200,
194+
`Presidio answered ${response.status}: ${body.slice(0, 200)}`
195+
)
196+
const [masked] = (JSON.parse(body) as { texts: string[] }).texts
197+
assert(
198+
masked.startsWith('Please send questions to <PERSON> before Friday. ['),
199+
'The name beside the run was not masked'
200+
)
201+
return { textChars: text.length }
202+
})
203+
180204
await check('A persisted log replaces the PDF and masks the long text', async () => {
181205
const since = maskRequests.length
182206
const result = await redactPIIFromExecution(

0 commit comments

Comments
 (0)