Skip to content

FEAT: Add optional Presidio-based PII entity scorer - #4573

Draft
Umesh Chounde (umeshchounde) wants to merge 14 commits into
microsoft:mainfrom
umeshchounde:feat/presidio-pii-scorer
Draft

Umesh Chounde (umeshchounde) wants to merge 14 commits into
microsoft:mainfrom
umeshchounde:feat/presidio-pii-scorer

Conversation

@umeshchounde

@umeshchounde Umesh Chounde (umeshchounde) commented Nov 23, 2026 •

Copy link
Copy Markdown

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

  • It's a MessageTrueFalseScorer in pyrit/score/true_false/ and implements _score_piece_with_expectation_async. The arguments are keyword-only: entities, score_threshold, language, analyzer, analyzer_identifier, score_aggregator and validator. An empty entities list is rejected, and so is any threshold that isn't a finite value in [0, 1].
  • Metadata stores entity types and counts, not matched values. For multi-piece messages the counts are summed and the types unioned across pieces. The verdict still comes from the configured aggregator.
  • pyrit[presidio] is a new optional extra and is also in all. Presidio is imported lazily, with an install hint. The extra adds spacy with the fairness_bias pin and, through presidio-analyzer, phonenumbers, tldextract and requests-file.
  • Engine creation and analysis run on one dedicated single-worker executor shared by all instances. Waiting calls don't occupy default-executor threads, which memory and storage also use, and calls run one at a time. A job keeps running after its caller is cancelled, so a cancelled call can't overlap the next one or build a second engine. The executor is module-level, so the shallow copies made by scorer scoping keep working. The cost is that Presidio work from all instances is serialized.
  • For an injected analyzer, the identifier includes a hash of its configuration, taken when the scorer is constructed. The hash covers each recognizer's 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 unless analyzer_identifier is given, and that argument also covers custom recognizer logic that to_dict() doesn't expose.
  • It's exported from pyrit.score and 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 existing CredentialLeakScorer and by the new scorer with an analyzer injected using en_core_web_sm:

CredentialLeakScorer()                                        value=False  rationale=''
PresidioPiiScorer(entities=["CREDIT_CARD", "EMAIL_ADDRESS"])  value=True   rationale='Detected: CREDIT_CARD, EMAIL_ADDRESS'
  metadata={'entity_types': 'CREDIT_CARD, EMAIL_ADDRESS', 'total_detections': 2, 'count_CREDIT_CARD': 1, 'count_EMAIL_ADDRESS': 1}

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.toml and uv.lock, so they're easy to drop or adjust.

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.
Copilot AI balanced review requested due to automatic review settings November 23, 2026 02:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 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 presidio extra, 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.
@umeshchounde

Copy link
Copy Markdown
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

No deployments
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.

FEAT: Optional Presidio-based PII entity scorer for leakage evaluation

2 participants