Skip to content

Add preempt PII sanitizer - #10

Merged
rjavadi merged 36 commits into
mainfrom
feat/core-preempt-with-distilbert
Nov 12, 2026
Merged

rjavadi merged 36 commits into
mainfrom
feat/core-preempt-with-distilbert

Conversation

@rjavadi

@rjavadi rjavadi commented Oct 16, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Replace the template package with the preempt library: recognizers and a sanitizer for names, ages, and money amounts, prepared for an open-source release. Sanitizer requires 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

  • 🐛 Bug fix (non-breaking change that fixes an issue)
  • ✨ New feature (non-breaking change that adds functionality)
  • 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • 📝 Documentation update
  • 🔧 Refactoring (no functional changes)
  • ⚡ Performance improvement
  • 🧪 Test improvements
  • 🔒 Security fix

Changes Made

  • Replace the template package with preempt: DistilBERT and GLiNER span recognition, BIO labels, and a sanitizer for names, ages, and money
  • Require key and tweak on Sanitizer and add generate_key(). There is no default key
  • Accept a Recognizer directly. Sanitizer wraps it in LegacyNERShim. Re-export the public API from preempt
  • Map listed names through a keyed permutation of fixed name lists, so a surrogate depends only on the name and the key
  • Make PyTorch, GLiNER, and ONNX export optional. The default install runs an exported ONNX graph
  • Point the demo at PREEMPT_MODEL_PATH, PREEMPT_KEY, and PREEMPT_TWEAK, and run it on model.onnx rather than the int8 graph
  • Add .env.example, a README configuration section, and RELEASE_NOTES.md
  • Gitignore training-data/ so the local PII-masking download stays out of src/preempt and out of the package
  • Leave training on feat/training, NER evaluation on feat/ner-bench, and the privacy/utility benchmark on feat/pii-bench. This branch does not contain pii-bench/

Testing

  • Tests pass locally (uv run pytest tests/)
  • Type checking passes (uv run mypy <src_dir>)
  • Linting passes (uv run ruff check src_dir/)
  • Manual testing performed (describe below)

Manual testing details:

uv run pytest tests/ (21 passed), uv run mypy src, and uv run ruff check src tests passed on the sanitizer and API changes. pii-bench tests passed before that directory was removed from this branch. The demo notebook was executed with uv run --env-file .env against the full-precision ONNX graph (model.onnx). Round trips succeeded for the detected names, ages, and amounts. "Ben Parker and John Doe" was detected as Ben Parker only, so "John Doe" stayed in the sentence. FPE money dropped the thousands separator: $10,000 came back as $10000.

Screenshots/Recordings

N/A

Related Issues

Relates to #11

Deployment Notes

Callers must pass key and tweak. 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 with use_fpe=False, still need the same Sanitizer instance to be restored. ONNX export keeps the git pin of optimum-onnx. Copy .env.example to .env before running the demo. The demo loads model.onnx from PREEMPT_MODEL_PATH.

Checklist

  • Code follows the project's style guidelines
  • Self-review of code completed
  • Documentation updated (if applicable)
  • No sensitive information (API keys, credentials) exposed

rjavadi and others added 15 commits October 5, 2026 14:47
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>
@rjavadi
rjavadi requested a review from amrit110 October 16, 2026 22:13
rjavadi and others added 14 commits October 20, 2026 12:05
- 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>
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>
rjavadi and others added 3 commits November 3, 2026 16:39
…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>
@rjavadi rjavadi changed the title Add DistilBERT PII sanitizer Add preempt PII sanitizer Nov 6, 2026
rjavadi and others added 3 commits November 6, 2026 12:30
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 amrit110 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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.

Comment thread src/preempt/sanitizer.py Outdated
for original, fake in fakes.items():
if fake is None:
invalid.append(i)
break

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 applied

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

Comment thread src/preempt/sanitizer.py Outdated
"""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]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 fails

The 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>
@rjavadi
rjavadi merged commit 7709bbb into main Nov 12, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants