Repository navigation
Add preempt PII sanitizer - #10
Conversation
Co-authored-by: Cursor <cursoragent@cursor.com>
The sanitizer still needs the name-list helpers, so those stay. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Treat an empty integration-test selection as success so CI does not fail before those tests exist. Co-authored-by: Cursor <cursoragent@cursor.com>
They stay on feat/training, with the tests that import them. Co-authored-by: Cursor <cursoragent@cursor.com>
- Every encryptor now returns {original: fake} per text, so encrypt,
decrypt, and callers share one shape.
- Name FPE is split into small helpers; encrypt and decrypt mirror each other.
- Explicit arguments and type hints replace **kwargs; encrypt_names no
longer mutates its input.
- Drop the unused NameDataset load in __init__ (about 25s faster to build).
- m-LDP money decryption restores amounts as written ("1,250", not "1250").
- Remove AnonymizationResult, AnonymizationContext, and Replacement from
contracts; only the benchmark used them.
- Add round-trip tests for names, money, and ages.
Known matching issues are tracked in #11.
Co-authored-by: Cursor <cursoragent@cursor.com>
…tebook. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…odels. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Name FPE built its lists from the inputs, so every single-name call encrypted the same index and nearly every name became "Patrick Orhan". Names are now swapped word by word through a keyed permutation of fixed first- and last-name lists, reversible with the key alone. Unlisted words get a keyed-hash pick that avoids collisions within a text. Also fix make_names_dataset prepending every first name to last_names. Fixes #12 Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
…nd GLiNER recognizer. Co-authored-by: Cursor <cursoragent@cursor.com> # Conflicts: # pyproject.toml # uv.lock
…tays light. Co-authored-by: Cursor <cursoragent@cursor.com>
…lbert. Co-authored-by: Cursor <cursoragent@cursor.com>
…traints Co-authored-by: Cursor <cursoragent@cursor.com>
…nch removed - Sanitizer requires key and tweak; no default key. Add generate_key(). - Sanitizer accepts a Recognizer directly and wraps it in LegacyNERShim. - Re-export Sanitizer, generate_key, LegacyNERShim, and contracts from preempt. - Switch sanitizer name-list messages from print to logging. - Demo notebook reads PREEMPT_MODEL_PATH, PREEMPT_KEY, PREEMPT_TWEAK, uses model.onnx (full precision), and is re-executed with outputs. - Add .env.example, README configuration section, and RELEASE_NOTES.md. - Remove pii-bench/ from this branch; it lives on feat/pii-bench. - Move the local training JSON to training-data/ and gitignore it. - Add LESSONS.md entries for these decisions. Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
- filelock 4.0.5 -> 4.2.9, msgpack 1.2.2 -> 1.2.4, tornado 6.5.10 -> 6.6, certifi, setuptools, virtualenv. - Lift pycryptodome to 4.3.0 via override-dependencies, since pyfpe 0.10.3 pins 3.10.1 (PYSEC-2026-1811). Co-authored-by: Cursor <cursoragent@cursor.com>
amrit110
left a comment
There was a problem hiding this comment.
First-pass review by Claude. A human second pass will follow.
This covers only the top 3 issues from a review across security and privacy, correctness, and API and packaging. All three are privacy or data-integrity problems in the main sanitize and restore flow, and I'd fix them before an open-source release.
Each one was reproduced by running code at db38e23. The trained model wasn't available, so recognizers were stubbed, and the truncation repro used a real fast tokenizer. The existing 21 tests pass but don't cover these paths. The substring and replacement-chaining problems are already tracked in #11, so they aren't repeated here.
| encoded = self.tokenizer( | ||
| text, | ||
| return_offsets_mapping=True, | ||
| truncation=True, |
There was a problem hiding this comment.
PII past max_length is never scanned, and nothing reports it.
truncation=True with no overflow handling means only the first 512 tokens reach the model. Names and ages after that point stay in the "sanitized" text, and encrypt still returns an empty invalid list, so the caller can't tell. Only currency_spans sees the full text. Long prompts are normal input for a guardrail, and this isn't listed under Known limitations.
Repro, using a real fast tokenizer and a stub ONNX session that tags every name correctly:
text = "Alice " + "filler " * 600 + "Bob is here"
# model saw 512 tokens; detected ['Alice']
# sanitized text still contains "Bob"; invalid == []Suggested fix: run overlapping windows (return_overflowing_tokens=True with a stride) and merge the spans. If that has to wait, fail closed by raising or flagging the row when the input was truncated. GlinerRecognizer may have a similar limit; I didn't test it.
| for original, fake in fakes.items(): | ||
| if fake is None: | ||
| invalid.append(i) | ||
| break |
There was a problem hiding this comment.
One unencryptable value leaves the rest of the text unsanitized.
break stops replacing values for that text, and the partly sanitized string is still returned. The failing value and every value after it in the mapping go out in plaintext. invalid does flag the row, but the demo discards it (sanitized_sentences, _ = ...), and the returned text looks like normal output.
This is easy to hit with money. pyfpe raises ValueError when the right half of the digits is all zeros, which round amounts of 7+ digits trigger once the 6-digit prefix is added. Line 326 turns that into None:
"Fund of $1,000,000 and a fee of $5,000 for Maria."
# -> unchanged, invalid == [0] (also $2,000,000, $10,000,000, $150,000,000)
"A fee of $5,000 on a fund of $1,000,000, then $750 more."
# -> 'A fee of $2404604114 on a fund of $1,000,000, then $750 more.'
# $750 had a valid fake but was never appliedAges hit the same path: with "He is age fifty and she is age 30.", fifty maps to None and 30 is never replaced.
Suggested fix: use continue instead of break, and don't return the raw value: replace it with a placeholder or raise, so the default fails closed. Separately, moving the padding to the end of the digits should avoid the all-zero case, because the right half would then always contain non-zero digits. decrypt_money would need to strip it from the end too.
| """Fakes to undo in text ``i``: detected, or saved by ``encrypt``.""" | ||
| if extracted is None or use_cache: | ||
| return [fake for fake in dict.fromkeys(self.entity_mapping[i].values()) if fake is not None] | ||
| return extracted[i] |
There was a problem hiding this comment.
Default decrypt rewrites values that were never encrypted, and can crash the batch.
With use_cache=False (the default), targets come from re-running NER on the text, with no check that a detection is one of our surrogates. Anything detected that happens to be a listed name or a 6+ character amount goes through the inverse mapping. That covers names missed at encrypt time, and anything new in a model reply, which the release notes describe as the intended use ("put the originals back after the model call").
# "John Smith" missed at encrypt, detected at decrypt (the PR's John Doe case)
'Loic Black and John Smith went to the bank.'
# default: 'Ben Parker and Christophe Cox went to the bank.'
# use_cache=True: 'Ben Parker and John Smith went to the bank.'
# Amount added by the model reply
'... The median is about $123,456.' # -> '... about $0.'
'... costs about $500,000.' # -> ValueError, whole batch failsThe result is a real person's name silently swapped for another, or a wrong figure, with no signal to the caller. The ValueError comes from the same all-zero case as the encrypt comment, and it isn't caught on this path.
Suggested fix: when encrypt state exists for the text, only undo values in that mapping, and make key-only decryption an explicit mode. In key-only mode, catch FF3 errors per value so one amount can't fail the batch.
- Scan long text in overlapping windows in DistilBertRecognizer and GlinerRecognizer instead of truncating, and merge window spans. - Encrypt FPE money with a suffix instead of a prefix, so round amounts no longer make FF3 reject the value. - Replace a value that cannot be encrypted with [REDACTED] and keep replacing the other values in that text. - Make decrypt restore only surrogates saved by the last encrypt call. Add key_only=True for explicit key-only inversion; it skips amounts FF3 rejects instead of failing the batch. - Document the new behavior and limits in RELEASE_NOTES.md and LESSONS.md. - Add tests for windows, redaction, round amounts, and decrypt scope. Co-authored-by: Cursor <cursoragent@cursor.com>
Summary
Replace the template package with the
preemptlibrary: recognizers and a sanitizer for names, ages, and money amounts, prepared for an open-source release.Sanitizerrequires a caller-supplied key and tweak, because a published default would let anyone undo FPE names and amounts. Training, NER evaluation, and the end-to-end benchmark stay on their own branches and are not in this diff.Clickup Ticket(s): N/A
Type of Change
Changes Made
preempt: DistilBERT and GLiNER span recognition, BIO labels, and a sanitizer for names, ages, and moneykeyandtweakonSanitizerand addgenerate_key(). There is no default keyRecognizerdirectly.Sanitizerwraps it inLegacyNERShim. Re-export the public API frompreemptPREEMPT_MODEL_PATH,PREEMPT_KEY, andPREEMPT_TWEAK, and run it onmodel.onnxrather than the int8 graph.env.example, a README configuration section, andRELEASE_NOTES.mdtraining-data/so the local PII-masking download stays out ofsrc/preemptand out of the packagefeat/training, NER evaluation onfeat/ner-bench, and the privacy/utility benchmark onfeat/pii-bench. This branch does not containpii-bench/Testing
uv run pytest tests/)uv run mypy <src_dir>)uv run ruff check src_dir/)Manual testing details:
uv run pytest tests/(21 passed),uv run mypy src, anduv run ruff check src testspassed on the sanitizer and API changes.pii-benchtests passed before that directory was removed from this branch. The demo notebook was executed withuv run --env-file .envagainst the full-precision ONNX graph (model.onnx). Round trips succeeded for the detected names, ages, and amounts. "Ben Parker and John Doe" was detected asBen Parkeronly, so "John Doe" stayed in the sentence. FPE money dropped the thousands separator:$10,000came back as$10000.Screenshots/Recordings
N/A
Related Issues
Relates to #11
Deployment Notes
Callers must pass
keyandtweak.generate_key()returns a 256-bit key and a 64-bit tweak, as hex. Anyone with the pair can reverse FPE names and amounts. Ages, and money withuse_fpe=False, still need the sameSanitizerinstance to be restored. ONNX export keeps the git pin ofoptimum-onnx. Copy.env.exampleto.envbefore running the demo. The demo loadsmodel.onnxfromPREEMPT_MODEL_PATH.Checklist