Repository navigation
FEAT: Add optional Presidio-based PII entity scorer - #4573
Draft
Umesh Chounde (umeshchounde) wants to merge 14 commits into
Draft
Umesh Chounde (umeshchounde) wants to merge 14 commits into
Umesh Chounde (umeshchounde) wants to merge 14 commits into
Conversation
Presidio-backed PII entity detection scorer (MessageTrueFalseScorer). Returns True if any requested entity type is found above a configurable confidence threshold. Score metadata carries entity types and counts, never matched values. The analyzer is injectable for testing; unit tests use a mock so CI needs no spaCy model.
Register the scorer in pyrit/score/__init__.py lazy exports and add a short section to the true/false scorers documentation page.
Isolated commit: adds presidio-analyzer as an optional dependency under pyrit[presidio] and includes it in the all group. Keep this commit separate so it can be dropped until a maintainer agrees to the extra.
In-repo scorers implement _score_piece_with_expectation_async since microsoft#3312; the legacy _score_piece_async hook is only kept until 2.0. Also match the renamed ty rule used by the other true/false scorers.
…identity - Create the default AnalyzerEngine and run analyze() in worker threads behind locks, as LocalRefusalClassifierScorer does, and document the spaCy model the default engine loads. - Sort and de-duplicate entities, reject an empty list (Presidio would treat it as all entities) and out-of-range thresholds, and include an injected analyzer's class and recognizer names in the identifier. - Rename aggregator to score_aggregator to match the other scorers. - Tests: spec the analyzer mock, add a sqlite contract test, a test with real Presidio pattern recognizers (skipped without the extra), and concurrency and identifier tests; drop the mock-only lookalike test.
Use a test card number and an example.com address that Presidio detects, drop the coordinates claim, note the spaCy model download, and add the same section to the paired notebook.
presidio-analyzer depends on spaCy; skip 3.8.14-3.8.15, which lack cp314 wheels, as fairness_bias and all already do.
Contributor
There was a problem hiding this comment.
🟡 Changes recommended
Injected analyzers with different detection behavior can share a scorer hash, allowing cached verdicts from an incompatible configuration to be reused.
3 open issues
What changed in this PR
Adds an optional Presidio-based scorer to detect personally identifiable information by entity type when leaked values are not known in advance, extending PyRIT’s true/false scoring options without changing scenario defaults.
Changes:
- Adds configurable entity detection with metadata containing types and counts, not matched values.
- Introduces the
presidioextra, lazy exports, and background-thread analysis. - Adds scorer tests, import guards, and paired documentation examples.
| File | Description |
|---|---|
uv.lock |
Locks Presidio and its additional dependencies. |
tests/unit/score/test_presidio_pii_scorer.py |
Tests detection, validation, persistence, identifiers, and threading. |
tests/unit/cli/test_import_guards.py |
Checks discovery avoids loading Presidio or spaCy. |
pyrit/score/true_false/presidio_pii_scorer.py |
Implements the optional PII entity scorer. |
pyrit/score/__init__.py |
Exposes the scorer through lazy imports. |
pyproject.toml |
Adds Presidio to optional dependencies and all. |
doc/code/scoring/1_true_false_scorers.py |
Documents usage and first-use model downloads. |
doc/code/scoring/1_true_false_scorers.ipynb |
Adds the matching notebook documentation. |
Review effort: Balanced
…ulti-piece metadata - Identity: fingerprint an injected analyzer from each recognizer's to_dict() (patterns, deny lists, context), the NLP engine models and analyzer settings, so same-named recognizers with different behavior no longer share a hash; add an optional analyzer_identifier for custom recognizer logic. - Cancellation: load and analyze under one threading.Lock inside a sync helper run via asyncio.to_thread, so a cancelled caller's worker keeps the lock and a retry neither overlaps it nor builds a second engine. - Multi-piece: wrap the configured aggregator, keeping its name and verdict, so metadata sums entity counts and unions entity types across pieces. - Tests for each, including cancel-then-retry and multi-piece scoring.
Author
|
@microsoft-github-policy-service agree |
…identity - Run engine loading and analysis on one shared single-worker executor instead of a threading.Lock inside asyncio.to_thread. Waiting calls no longer occupy default-executor threads that memory, storage and converters rely on; calls still run one at a time and stay safe after cancellation. Module-level so shallow copies made by scorer scoping keep working. - Fingerprint the analyzer at construction and include NER model configuration and regex flags. Sort set-derived lists so the digest is stable across processes, and reject configurations with no stable JSON form unless analyzer_identifier is given. - Keep a custom aggregator's other metadata when summing entity counts. - Tests: use TEST_WATCHDOG_SECONDS and a submit signal instead of sleeps, and cover the dedicated worker, executor starvation, NER config, regex flags, list order, construction-time snapshot and unstable configs.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Description
This adds
PresidioPiiScorer, an optional true/false scorer that uses Presidio to flag PII entity types in responses when the leaked value isn't known in advance.Closes #4572
MessageTrueFalseScorerinpyrit/score/true_false/and implements_score_piece_with_expectation_async. The arguments are keyword-only:entities,score_threshold,language,analyzer,analyzer_identifier,score_aggregatorandvalidator. An emptyentitieslist is rejected, and so is any threshold that isn't a finite value in [0, 1].pyrit[presidio]is a new optional extra and is also inall. Presidio is imported lazily, with an install hint. The extra addsspacywith thefairness_biaspin and, throughpresidio-analyzer,phonenumbers,tldextractandrequests-file.to_dict()(patterns, deny lists, context) and regex flags, the NLP engine's models and NER configuration, and the analyzer settings. Set-derived lists are sorted, so the hash is the same in every process. A configuration with no stable JSON form is rejected unlessanalyzer_identifieris given, and that argument also covers custom recognizer logic thatto_dict()doesn't expose.pyrit.scoreand has an example on the true/false scorers page. Scorer discovery doesn't import Presidio or spaCy, and no scenario defaults change.The same synthetic response,
"Sure. The customer's card is 4111 1111 1111 1111 and their email is jane@example.com.", scored by the existingCredentialLeakScorerand by the new scorer with an analyzer injected usingen_core_web_sm:This is a draft until the questions in #4572 are answered: the extra, the name and location, and the integration. The dependency changes are in commits that only touch
pyproject.tomlanduv.lock, so they're easy to drop or adjust.