From bf9c457194684cc668db8f7028afb26df4aefe10 Mon Sep 17 00:00:00 2001 From: Garyouki Date: Sat, 3 Oct 2026 18:10:32 -0700 Subject: [PATCH] FIX: Include matcher configuration in substring scorer identity --- pyrit/analytics/text_matching.py | 23 +++++++- pyrit/score/true_false/substring_scorer.py | 2 + tests/unit/score/test_substring.py | 69 +++++++++++++++++++++- 3 files changed, 92 insertions(+), 2 deletions(-) diff --git a/pyrit/analytics/text_matching.py b/pyrit/analytics/text_matching.py index 9be1a36895..07cce77dad 100644 --- a/pyrit/analytics/text_matching.py +++ b/pyrit/analytics/text_matching.py @@ -9,7 +9,7 @@ """ import math -from typing import Protocol +from typing import Any, Protocol class TextMatching(Protocol): @@ -18,6 +18,9 @@ class TextMatching(Protocol): Classes implementing this protocol must provide an is_match method that checks if a target string matches text according to some strategy. + + Matchers may additionally expose ``get_identifier_params()`` with stable, + JSON-serializable behavioral parameters for use in scorer identifiers. """ def is_match(self, *, target: str, text: str) -> bool: @@ -52,6 +55,15 @@ def __init__(self, *, case_sensitive: bool = False, ignore_whitespace: bool = Tr self._case_sensitive = case_sensitive self._ignore_whitespace = ignore_whitespace + def get_identifier_params(self) -> dict[str, Any]: + """ + Return the configuration that determines matching behavior. + + Returns: + dict[str, Any]: Behavioral parameters for scorer identifiers. + """ + return {"case_sensitive": self._case_sensitive, "ignore_whitespace": self._ignore_whitespace} + def is_match(self, *, target: str, text: str) -> bool: """ Check if target string is present in text. @@ -103,6 +115,15 @@ def __init__(self, *, threshold: float = 0.5, n: int = 3, case_sensitive: bool = self._n = n self._case_sensitive = case_sensitive + def get_identifier_params(self) -> dict[str, Any]: + """ + Return the configuration that determines matching behavior. + + Returns: + dict[str, Any]: Behavioral parameters for scorer identifiers. + """ + return {"threshold": self._threshold, "n": self._n, "case_sensitive": self._case_sensitive} + def is_match(self, *, target: str, text: str) -> bool: """ Check if target approximately matches text using n-gram overlap. diff --git a/pyrit/score/true_false/substring_scorer.py b/pyrit/score/true_false/substring_scorer.py index 095e1a1c0e..ed93668dae 100644 --- a/pyrit/score/true_false/substring_scorer.py +++ b/pyrit/score/true_false/substring_scorer.py @@ -56,10 +56,12 @@ def _build_identifier(self) -> ComponentIdentifier: Returns: ComponentIdentifier: The identifier for this scorer. """ + get_matcher_params = getattr(self._text_matcher, "get_identifier_params", None) return self._create_identifier( params={ "substring": self._substring, "text_matcher": self._text_matcher.__class__.__name__, + "text_matcher_params": get_matcher_params() if callable(get_matcher_params) else None, }, score_aggregator=self._score_aggregator.__name__, # type: ignore[ty:unresolved-attribute] ) diff --git a/tests/unit/score/test_substring.py b/tests/unit/score/test_substring.py index e18984b23c..8c39f6f9c5 100644 --- a/tests/unit/score/test_substring.py +++ b/tests/unit/score/test_substring.py @@ -7,13 +7,80 @@ import pytest from unit.mocks import get_image_message_piece, store_message_async -from pyrit.analytics import ApproximateTextMatching, ExactTextMatching +from pyrit.analytics import ApproximateTextMatching, ExactTextMatching, TextMatching from pyrit.memory.central_memory import CentralMemory from pyrit.memory.memory_interface import MemoryInterface from pyrit.models import MatchesObjective, MessagePiece, ScoringExpectation from pyrit.score import ContentScorable, MessageScorable, Scorer, SubStringScorer +@pytest.mark.parametrize( + "first,second,substring,text", + [ + (ExactTextMatching(), ExactTextMatching(case_sensitive=True), "Hello", "hello"), + (ExactTextMatching(), ExactTextMatching(ignore_whitespace=False), " hello ", "hello"), + (ApproximateTextMatching(threshold=0.3), ApproximateTextMatching(threshold=0.5), "hello", "hallo"), + (ApproximateTextMatching(n=2), ApproximateTextMatching(n=3), "hello", "he lo"), + (ApproximateTextMatching(), ApproximateTextMatching(case_sensitive=True), "HELLO", "hello"), + ], +) +async def test_substring_identifier_distinguishes_matcher_behavior( + patch_central_database: MemoryInterface, first: TextMatching, second: TextMatching, substring: str, text: str +) -> None: + first_scorer = SubStringScorer(substring=substring, text_matcher=first) + second_scorer = SubStringScorer(substring=substring, text_matcher=second) + + first_scores = await first_scorer.score_text_async(text) + second_scores = await second_scorer.score_text_async(text) + + assert first_scores[0].get_value() is not second_scores[0].get_value() + assert first_scorer.get_identifier().hash != second_scorer.get_identifier().hash + assert first_scorer.get_identifier().eval_hash != second_scorer.get_identifier().eval_hash + + +@pytest.mark.parametrize("matcher_class", [ExactTextMatching, ApproximateTextMatching]) +def test_substring_identifier_stable_for_equivalent_matchers( + patch_central_database: MemoryInterface, matcher_class: type[ExactTextMatching] | type[ApproximateTextMatching] +) -> None: + first = SubStringScorer(substring="hello", text_matcher=matcher_class()) + second = SubStringScorer(substring="hello", text_matcher=matcher_class()) + + assert first.get_identifier().hash == second.get_identifier().hash + assert first.get_identifier().eval_hash == second.get_identifier().eval_hash + + +async def test_substring_accepts_custom_matcher_without_identifier_hook( + patch_central_database: MemoryInterface, +) -> None: + class CustomMatcher: + def is_match(self, *, target: str, text: str) -> bool: + return target == text + + scorer = SubStringScorer(substring="hello", text_matcher=CustomMatcher()) + scores = await scorer.score_text_async("hello") + + assert scores[0].get_value() is True + assert scorer.get_identifier().params["text_matcher"] == "CustomMatcher" + + +def test_substring_custom_matcher_can_supply_identifier_params(patch_central_database: MemoryInterface) -> None: + class CustomMatcher: + def __init__(self, *, case_sensitive: bool) -> None: + self.case_sensitive = case_sensitive + + def is_match(self, *, target: str, text: str) -> bool: + return target == text if self.case_sensitive else target.lower() == text.lower() + + def get_identifier_params(self) -> dict[str, bool]: + return {"case_sensitive": self.case_sensitive} + + first = SubStringScorer(substring="hello", text_matcher=CustomMatcher(case_sensitive=True)) + second = SubStringScorer(substring="hello", text_matcher=CustomMatcher(case_sensitive=False)) + + assert first.get_identifier().hash != second.get_identifier().hash + assert first.get_identifier().eval_hash != second.get_identifier().eval_hash + + @pytest.fixture def image_message_piece() -> MessagePiece: return get_image_message_piece()