diff --git a/doc/code/framework.md b/doc/code/framework.md index c430f71838..a1abfc8b1e 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -219,7 +219,8 @@ Core components are pluggable bricks. Each one can be swapped, combined, or repl **Responsibility**: Tell the attack what happened. Was this blocked? Was the objective achieved? Was this tool called? Was this file written? - Score the evidence a `Scorable` identifies (a message, a trace, a file location, or a program run) against an optional `ScoringExpectation`: the objective and its typed conditions. -- Build on a result family: `TrueFalseScorer`, `FloatScaleScorer`, or `MultiLabelTrueFalseScorer` for independent labeled verdicts, where `TrueFalseScoreSelector` picks the verdict an attack uses. `MessageScorer` adds message handling. Declare the evidence a scorer reads, such as roles and data types, instead of making callers filter it. +- Build on a result family: `TrueFalseScorer` or `FloatScaleScorer`. `MessageScorer` adds message handling. Declare the evidence a scorer reads, such as roles and data types, instead of making callers filter it. +- A `TrueFalseScorer` makes one decision. When a scorer produces several results, such as a classifier's harm categories, make it a `FloatScaleScorer` that returns one score per category, even if each is 0 or 1. `FloatScaleThresholdScorer` turns those scores into a decision. - Score what the target actually produced. Simulated and injected messages are excluded unless a scorer explicitly selects them. - Compose instead of special-casing. A condition-based leaf checks exactly one condition type, and a leaf configured through its constructor takes none. Composites and wrappers, such as `TrueFalseCompositeScorer` and `TrueFalseInverterScorer`, combine results and route conditions. Every condition must reach a leaf that supports it. - Acquire evidence through injected sources and clients (traces, file surfaces, program execution), and judge what they return. The caller owns the environment: isolation, workspaces, and sandboxes. diff --git a/doc/code/scoring/0_scoring.ipynb b/doc/code/scoring/0_scoring.ipynb index d72e988160..8ea505220f 100644 --- a/doc/code/scoring/0_scoring.ipynb +++ b/doc/code/scoring/0_scoring.ipynb @@ -113,6 +113,7 @@ " PackageHallucinationScorer true_false no Content, ContentEntry, Message MatchesObjective if configured no\n", " PathTraversalOutputScorer true_false no Content, ContentEntry, Message MatchesObjective if configured no\n", " PhysicsConsistencyScorer true_false no Content, ContentEntry, Message MatchesObjective if configured no\n", + " PresidioPiiScorer true_false no Content, ContentEntry, Message MatchesObjective if configured no\n", " ProgramExecutionScorer true_false no Content, ContentEntry, Message, ProgramExecution ProgramBehaves no\n", " PromptShieldScorer true_false no Content, ContentEntry, Message MatchesObjective if configured no\n", " QuestionAnswerScorer true_false no Content, ContentEntry, Message AnswerMatches no\n", @@ -143,7 +144,6 @@ " TrueFalseCompositeScorer true_false same as wrapped same as wrapped same as wrapped no\n", " TrueFalseFallbackScorer true_false same as wrapped same as wrapped same as wrapped if both scorers do\n", " TrueFalseInverterScorer true_false same as wrapped same as wrapped same as wrapped no\n", - " TrueFalseScoreSelector true_false same as wrapped same as wrapped same as wrapped no\n", " VideoTrueFalseScorer true_false same as wrapped Content, ContentEntry, Message same as wrapped no\n" ] } diff --git a/doc/code/scoring/1_true_false_scorers.ipynb b/doc/code/scoring/1_true_false_scorers.ipynb index 53fa8e5a00..f68b1a949b 100644 --- a/doc/code/scoring/1_true_false_scorers.ipynb +++ b/doc/code/scoring/1_true_false_scorers.ipynb @@ -1104,33 +1104,6 @@ "print(scores[0])\n", "```" ] - }, - { - "cell_type": "markdown", - "id": "31", - "metadata": {}, - "source": [ - "## Selecting one label from a multi-label scorer\n", - "\n", - "`MultiLabelTrueFalseScorer` reports independent verdicts. When an attack or evaluator\n", - "expects one true/false result, use `TrueFalseScoreSelector` to choose a category\n", - "instead of combining unrelated labels.\n", - "\n", - "Given a configured `multi_label_scorer` that declares `harmful_response`:\n", - "\n", - "```python\n", - "from pyrit.score import TrueFalseScoreSelector\n", - "\n", - "objective_scorer = TrueFalseScoreSelector(\n", - " scorer=multi_label_scorer,\n", - " label=\"harmful_response\",\n", - ")\n", - "```\n", - "\n", - "Use `objective_scorer` wherever a single `TrueFalseScorer` is expected. The label\n", - "must match one of the source scorer's `labels`; the other verdicts are retained\n", - "as intermediate scores." - ] } ], "metadata": { diff --git a/doc/code/scoring/1_true_false_scorers.py b/doc/code/scoring/1_true_false_scorers.py index d6833ec54d..16dcb75cb0 100644 --- a/doc/code/scoring/1_true_false_scorers.py +++ b/doc/code/scoring/1_true_false_scorers.py @@ -715,25 +715,3 @@ # scores = await video_and_audio_scorer.score_async(scorable=video) # print(scores[0]) # ``` - -# %% [markdown] -# ## Selecting one label from a multi-label scorer -# -# `MultiLabelTrueFalseScorer` reports independent verdicts. When an attack or evaluator -# expects one true/false result, use `TrueFalseScoreSelector` to choose a category -# instead of combining unrelated labels. -# -# Given a configured `multi_label_scorer` that declares `harmful_response`: -# -# ```python -# from pyrit.score import TrueFalseScoreSelector -# -# objective_scorer = TrueFalseScoreSelector( -# scorer=multi_label_scorer, -# label="harmful_response", -# ) -# ``` -# -# Use `objective_scorer` wherever a single `TrueFalseScorer` is expected. The label -# must match one of the source scorer's `labels`; the other verdicts are retained -# as intermediate scores. diff --git a/doc/code/scoring/multi_label_true_false.md b/doc/code/scoring/multi_label_true_false.md deleted file mode 100644 index 8616f025f2..0000000000 --- a/doc/code/scoring/multi_label_true_false.md +++ /dev/null @@ -1,113 +0,0 @@ -# Multiple labeled true/false verdicts - -Some classifiers return several independent answers from one inference. For example, -a response may refuse a harmful request without itself being harmful. Combining those -answers with OR would lose that distinction. - -`MessageMultiLabelTrueFalseScorer` preserves one `Score` for each declared label in -`score_category`. Each supported message piece produces a complete set of labeled -verdicts. The message pipeline aggregates pieces within each label, using -`TrueFalseScoreAggregator.OR` by default. Existing `MessageTrueFalseScorer` subclasses -continue to return one aggregate verdict. - -## Implementing a classifier - -Declare nonempty, case-insensitively unique labels and implement -`_score_piece_with_expectation_async`. Return a separate true/false `Score` with -`score_category=[label]` for every declared label. Return `[]` when the classifier -does not apply to the evidence. Missing, duplicate, or unknown labels are rejected -before any scores are persisted. - -The following synthetic example reads classifier output from JSON. With PyRIT -initialized, it can demonstrate the contract without calling a model: - -```python -import json - -from pyrit.models import ContentScorable, MessagePiece, Score, ScoringExpectation -from pyrit.score import ( - MessageMultiLabelTrueFalseScorer, - ScorerPromptValidator, - TrueFalseScoreSelector, -) - - -class ExampleClassifier(MessageMultiLabelTrueFalseScorer): - def __init__(self) -> None: - super().__init__( - labels=["harmful_request", "response_refusal", "harmful_response"], - validator=ScorerPromptValidator(supported_data_types=["text"]), - ) - self.calls = 0 - - async def _score_piece_with_expectation_async( - self, message_piece: MessagePiece, *, expectation: ScoringExpectation | None - ) -> list[Score]: - self.calls += 1 - verdicts = json.loads(message_piece.converted_value) - return [ - Score( - score_value=str(value).lower(), - score_type="true_false", - score_category=[label], - scorer_class_identifier=self.get_identifier(), - message_piece_id=message_piece.id, - scored_expectation=expectation, - ) - for label, value in verdicts.items() - ] - - -classifier = ExampleClassifier() -evidence = ContentScorable( - value=json.dumps( - { - "harmful_request": True, - "response_refusal": True, - "harmful_response": False, - } - ) -) -objective_scorer = TrueFalseScoreSelector(scorer=classifier, label="harmful_response") -scores = await objective_scorer.score_async(scorable=evidence) -print(classifier.calls, scores[0].get_value()) -# 1 False -``` - -A concrete target-backed scorer owns its `TargetJudge`, renders its own prompt, -captures evidence with `_capture_judgment_evidence`, and passes the full expectation -in `JudgmentRequest`. Its identifier must include the target and any additional -behavioral configuration. The family base does not accept a `chat_target` parameter. -`MultiLabelTrueFalseScorer` provides the same result contract for other evidence types. - -## Selecting, composing, and evaluating a verdict - -Use `TrueFalseScoreSelector` for an attack's objective/refusal scorer, boolean -composition, or objective evaluation. The selector chooses by label, not output order, -and its identity includes both the label and the source scorer. It preserves the -source's target discovery and blocked-judge policy. Float thresholding is for float -scores, not multi-label boolean results. - -One selector call returns one public projection and persists all labeled child -verdicts as intermediate scores. The projection has its own score ID and selector -identity. Default queries return public results. Query retained labels with -`include_intermediate=True`: - -```python -from pyrit.memory import CentralMemory - -memory = CentralMemory.get_memory_instance() -request_scores = await memory.get_scores_async( - score_category="harmful_request", - include_intermediate=True, -) -``` - -Calling the multi-label scorer directly returns and persists every label as a public -result. Reading saved scores does not perform another inference. Separate scoring or -selector calls can perform separate inferences; the selector does not cache them. - -Unsupported roles or modalities return `[]`. Unreadable or fully blocked evidence -produces an undetermined score for each label. When `raise_if_scorer_blocks=False`, -a blocked judge response does the same, preserving any retained error observation. -The existing three-valued AND/OR aggregation applies independently to each label. diff --git a/doc/myst.yml b/doc/myst.yml index fe02ee8804..0907178fcc 100644 --- a/doc/myst.yml +++ b/doc/myst.yml @@ -183,7 +183,6 @@ project: - file: code/scoring/6_file_write_scorer.ipynb - file: code/scoring/7_program_execution_scorer.ipynb - file: code/scoring/8_trace_evidence_scoring.ipynb - - file: code/scoring/multi_label_true_false.md - file: code/scoring/scorer_stability.md - file: code/memory/0_memory.md children: diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index e2e6e9bb7d..75f60fa04e 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -156,10 +156,6 @@ from pyrit.score.true_false.local_refusal_classifier_scorer import LocalRefusalClassifierScorer from pyrit.score.true_false.manual_scorer import ManualScorer from pyrit.score.true_false.message_tool_call_scorer import MessageToolCallScorer - from pyrit.score.true_false.multi_label_true_false_scorer import ( - MessageMultiLabelTrueFalseScorer, - MultiLabelTrueFalseScorer, - ) from pyrit.score.true_false.otel_tool_call_scorer import OtelToolCallOrderScorer, OtelToolCallScorer from pyrit.score.true_false.output_matches_scorer import OutputMatchesScorer from pyrit.score.true_false.physics_consistency_scorer import PhysicsConsistencyScorer @@ -220,7 +216,6 @@ from pyrit.score.true_false.true_false_fallback_scorer import TrueFalseFallbackScorer from pyrit.score.true_false.true_false_inverter_scorer import TrueFalseInverterScorer from pyrit.score.true_false.true_false_score_aggregator import TrueFalseAggregatorFunc, TrueFalseScoreAggregator - from pyrit.score.true_false.true_false_score_selector import TrueFalseScoreSelector from pyrit.score.true_false.true_false_scorer import MessageTrueFalseScorer, TrueFalseScorer from pyrit.score.true_false.video_true_false_scorer import VideoTrueFalseScorer from pyrit.score.true_false.wildguard_parser import WildGuardLabel, parse_wildguard_response @@ -272,9 +267,6 @@ "FloatScaleScorer": "pyrit.score.float_scale.float_scale_scorer", "MessageFloatScaleScorer": "pyrit.score.float_scale.float_scale_scorer", "MessageTrueFalseScorer": "pyrit.score.true_false.true_false_scorer", - "MultiLabelTrueFalseScorer": "pyrit.score.true_false.multi_label_true_false_scorer", - "MessageMultiLabelTrueFalseScorer": "pyrit.score.true_false.multi_label_true_false_scorer", - "TrueFalseScoreSelector": "pyrit.score.true_false.true_false_score_selector", "FloatScaleThresholdScorer": "pyrit.score.true_false.float_scale_threshold_scorer", "GarakExploitationDetector": "pyrit.score.true_false.garak_exploitation_scorer", "GarakExploitationScorer": "pyrit.score.true_false.garak_exploitation_scorer", diff --git a/pyrit/score/scorer_evaluation/scorer_evaluator.py b/pyrit/score/scorer_evaluation/scorer_evaluator.py index 6e60b9ac0c..202b05d96c 100644 --- a/pyrit/score/scorer_evaluation/scorer_evaluator.py +++ b/pyrit/score/scorer_evaluation/scorer_evaluator.py @@ -30,7 +30,6 @@ find_objective_metrics_by_eval_hash, replace_evaluation_results, ) -from pyrit.score.true_false.multi_label_true_false_scorer import MultiLabelTrueFalseScorer from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: @@ -146,12 +145,7 @@ def __init__(self, scorer: Scorer) -> None: Args: scorer (Scorer): The scorer to evaluate. - - Raises: - ValueError: If a multi-label scorer has no explicit single-label projection. """ - if isinstance(scorer, MultiLabelTrueFalseScorer): - raise ValueError("Select a label with TrueFalseScoreSelector before evaluating a multi-label scorer.") self.scorer = scorer @classmethod diff --git a/pyrit/score/scorer_evaluation/scorer_stability.py b/pyrit/score/scorer_evaluation/scorer_stability.py index c80a82859d..a9b0615570 100644 --- a/pyrit/score/scorer_evaluation/scorer_stability.py +++ b/pyrit/score/scorer_evaluation/scorer_stability.py @@ -560,7 +560,7 @@ def __init__(self, *, scorer: TrueFalseScorer, presentations: Sequence[ScorerPre Raises: ValueError: If there is no presentation, a name is repeated or is the reference's, a - scorer is not a single-verdict true/false scorer, two scorers share a configuration, + scorer is not a true/false scorer, two scorers share a configuration, or a presentation's judge model settings differ from the reference's. """ if not presentations: @@ -569,7 +569,6 @@ def __init__(self, *, scorer: TrueFalseScorer, presentations: Sequence[ScorerPre if _REFERENCE_PRESENTATION in names or len(set(names)) != len(names): raise ValueError(f"Presentation names must be unique and must not be '{_REFERENCE_PRESENTATION}'.") all_presentations = [ScorerPresentation(name=_REFERENCE_PRESENTATION, scorer=scorer), *presentations] - # The evaluator rejects a multi-label scorer that has no label selected. self._evaluators = { presentation.name: ObjectiveScorerEvaluator(presentation.scorer) for presentation in all_presentations } diff --git a/pyrit/score/true_false/float_scale_threshold_scorer.py b/pyrit/score/true_false/float_scale_threshold_scorer.py index c313194d35..345c33b620 100644 --- a/pyrit/score/true_false/float_scale_threshold_scorer.py +++ b/pyrit/score/true_false/float_scale_threshold_scorer.py @@ -24,7 +24,6 @@ from pyrit.score.observation.execution import _merge_observation_ids from pyrit.score.score_utils import ORIGINAL_FLOAT_VALUE_KEY from pyrit.score.scorer import Scorer, SnapshotParticipation, _set_snapshot_participation -from pyrit.score.true_false.multi_label_true_false_scorer import MultiLabelTrueFalseScorer from pyrit.score.true_false.true_false_scorer import TrueFalseScorer @@ -70,8 +69,6 @@ def __init__( Raises: ValueError: If the threshold is non-finite or not in (0, 1]. """ - if isinstance(scorer, MultiLabelTrueFalseScorer): - raise ValueError("Multi-label true/false verdicts require TrueFalseScoreSelector, not a float threshold.") self._scorer = scorer self._threshold = threshold self._float_scale_aggregator = float_scale_aggregator diff --git a/pyrit/score/true_false/multi_label_true_false_scorer.py b/pyrit/score/true_false/multi_label_true_false_scorer.py deleted file mode 100644 index d69b5e8a14..0000000000 --- a/pyrit/score/true_false/multi_label_true_false_scorer.py +++ /dev/null @@ -1,220 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -from __future__ import annotations - -from abc import abstractmethod -from typing import TYPE_CHECKING, Any -from uuid import uuid4 - -from pyrit.common import forward_init_parameters -from pyrit.common.task_utils import gather_with_cleanup_async -from pyrit.models import ComponentIdentifier, Message, Score, ScoreStatus, ScoringExpectation -from pyrit.score.message_scorer import MessageScorer -from pyrit.score.observation.execution import _merge_observation_ids -from pyrit.score.scorer import Scorer -from pyrit.score.true_false.true_false_score_aggregator import TrueFalseAggregatorFunc, TrueFalseScoreAggregator - -if TYPE_CHECKING: - from collections.abc import Sequence - - from pyrit.models import MessagePiece, Scorable, ScoreType - from pyrit.score.message_scorable_resolver import MessageScorableResolver - from pyrit.score.scorer_evaluation.scorer_metrics import ScorerMetrics - from pyrit.score.scorer_prompt_validator import ScorerPromptValidator - - -class MultiLabelTrueFalseScorer(Scorer): - """Result family with one independent true/false score per declared category.""" - - @forward_init_parameters - def __init__(self, *, labels: Sequence[str], **kwargs: Any) -> None: - """ - Declare the labels produced by every applicable scoring operation. - - Args: - labels (Sequence[str]): Nonempty category names, unique ignoring case. - **kwargs (Any): Constructor arguments forwarded to the remaining bases. - - Raises: - ValueError: If labels are empty, duplicated, or contain surrounding whitespace. - """ - if isinstance(labels, (str, bytes)) or not labels: - raise ValueError("labels must be a nonempty sequence of category names.") - for label in labels: - if not isinstance(label, str): # type: ignore[ty:redundant-condition-strict] - raise ValueError("Each label must be a string.") - if not label.strip() or label != label.strip(): - raise ValueError("Each label must be nonempty without surrounding whitespace.") - if len({label.lower() for label in labels}) != len(labels): - raise ValueError("labels must be unique ignoring case.") - self._labels = tuple(labels) - super().__init__(**kwargs) - - @property - def labels(self) -> tuple[str, ...]: - """The ordered, immutable category names returned by this scorer.""" - return self._labels - - @property - def scorer_type(self) -> ScoreType: - """The true/false value type shared by the independent verdicts.""" - return "true_false" - - def validate_return_scores(self, scores: list[Score]) -> None: - """ - Require one distinct true/false result for each declared label. - - Raises: - ValueError: If a nonempty result violates the declared output contract. - """ - if not scores: - return - categories = [score.score_category for score in scores] - if any(not category or len(category) != 1 for category in categories): - raise ValueError("Each multi-label verdict must have exactly one score_category.") - returned_labels = [category[0] for category in categories if category] - if len(returned_labels) != len(self.labels) or set(returned_labels) != set(self.labels): - raise ValueError("Multi-label scorers must return exactly one score for each declared label.") - if len({score.id for score in scores}) != len(scores): - raise ValueError("Each labeled verdict must have a distinct score ID.") - for score in scores: - if score.score_type != "true_false": - raise ValueError("Every labeled verdict must have score_type='true_false'.") - if not score.is_undetermined and str(score.score_value).lower() not in {"true", "false"}: - raise ValueError("A completed labeled verdict must have a true/false value.") - - def get_scorer_metrics(self) -> ScorerMetrics | None: - """Return no aggregate metrics; evaluate a label through ``TrueFalseScoreSelector``.""" - return None - - -class MessageMultiLabelTrueFalseScorer(MultiLabelTrueFalseScorer, MessageScorer): - """ - Score supported message pieces once and aggregate independently within each label. - - Concrete scorers implement ``_score_piece_with_expectation_async`` and return one - ``Score`` per label. Unsupported evidence returns no scores. Unreadable evidence, - fully blocked responses, and suppressed judge blocks yield an undetermined verdict - for every label. Concrete target-backed scorers own their ``TargetJudge``. - """ - - def __init__( - self, - *, - labels: Sequence[str], - validator: ScorerPromptValidator, - score_aggregator: TrueFalseAggregatorFunc = TrueFalseScoreAggregator.OR, - message_resolver: MessageScorableResolver | None = None, - ) -> None: - """ - Initialize the category-preserving message pipeline. - - Args: - labels (Sequence[str]): Category names returned by each applicable piece. - validator (ScorerPromptValidator): Message roles and data types to read. - score_aggregator (TrueFalseAggregatorFunc): Aggregation within each label; defaults to OR. - message_resolver (MessageScorableResolver | None): Optional evidence resolver. - """ - self._score_aggregator = score_aggregator - super().__init__(labels=labels, validator=validator, message_resolver=message_resolver) - - def _build_identifier(self) -> ComponentIdentifier: - """ - Identify the output labels and their aggregation policy. - - Returns: - ComponentIdentifier: The scorer's labels and aggregation configuration. - """ - return self._create_identifier( - params={"labels": list(self.labels)}, - score_aggregator=self._score_aggregator.__name__, # type: ignore[ty:missing-attribute] - ) - - @abstractmethod - async def _score_piece_with_expectation_async( - self, message_piece: MessagePiece, *, expectation: ScoringExpectation | None - ) -> list[Score]: - """Return one labeled score per declared category using the complete expectation.""" - ... - - async def _score_async( - self, message: Message, *, objective: str | None = None, expectation: ScoringExpectation | None = None - ) -> list[Score]: - """ - Validate each piece's complete output before aggregating within labels. - - Returns: - list[Score]: One aggregate per label, or no scores for non-applicable pieces. - """ - if expectation is None and objective is not None: - expectation = ScoringExpectation(objective=objective) - piece_scores = await gather_with_cleanup_async( - [ - self._score_piece_with_expectation_async(message_piece=piece, expectation=expectation) - for piece in self._get_supported_pieces(message) - ] - ) - by_label: dict[str, list[Score]] = {label: [] for label in self.labels} - for scores in piece_scores: - self.validate_return_scores(scores) - for score in scores: - assert score.score_category is not None - by_label[score.score_category[0]].append(score) - - results = [] - for label, scores in by_label.items(): - if not scores: - continue - result = self._score_aggregator(scores) - results.append( - Score( - score_value=None if result.value is None else str(result.value).lower(), - status=ScoreStatus.UNDETERMINED if result.value is None else ScoreStatus.COMPLETE, - score_type="true_false", - score_category=[label], - score_value_description=result.description, - score_rationale=result.rationale, - score_metadata=result.metadata, - scorer_class_identifier=self.get_identifier(), - message_piece_id=scores[0].message_piece_id, - scorable=scores[0].scorable, - observation_ids=_merge_observation_ids(scores=scores), - scored_expectation=expectation, - ) - ) - return results - - def _build_fallback_score(self, *, message: Message, objective: str | None) -> list[Score]: - """ - Preserve message applicability without inferring any label from a transport block. - - Returns: - list[Score]: An undetermined fallback to expand, or no applicable scores. - """ - scores = self._build_neutral_fallback_score(message=message, objective=objective, neutral_value="false") - for score in scores: - if not score.is_undetermined: - score.set_value(None) - score.score_value_description = "Blocked evidence; no labeled verdict was reachable." - score.score_rationale = "A transport block does not determine any of the declared labels." - return scores - - async def _finalize_message_scores_async( - self, - *, - message: Message, - scores: list[Score], - anchor: Scorable | None, - expectation: ScoringExpectation | None, - ) -> None: - """Expand the shared undetermined fallback and retain its evidence and expectation.""" - if len(scores) == 1 and scores[0].is_undetermined and not scores[0].score_category: - fallback = scores[0] - scores[:] = [ - fallback.model_copy(deep=True, update={"id": uuid4(), "score_category": [label]}) - for label in self.labels - ] - await super()._finalize_message_scores_async( - message=message, scores=scores, anchor=anchor, expectation=expectation - ) diff --git a/pyrit/score/true_false/true_false_score_selector.py b/pyrit/score/true_false/true_false_score_selector.py deleted file mode 100644 index 564d294c51..0000000000 --- a/pyrit/score/true_false/true_false_score_selector.py +++ /dev/null @@ -1,89 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -from __future__ import annotations - -import copy -from typing import TYPE_CHECKING, Self - -from pyrit.score.true_false.multi_label_true_false_scorer import MultiLabelTrueFalseScorer -from pyrit.score.true_false.true_false_scorer import TrueFalseScorer - -if TYPE_CHECKING: - from pyrit.models import ComponentIdentifier, Scorable, Score, ScoringExpectation - from pyrit.prompt_target import PromptTarget - from pyrit.score.scorer import Scorer - - -class TrueFalseScoreSelector(TrueFalseScorer): - """Project one named verdict while retaining the source's labels as intermediate scores.""" - - def __init__(self, *, scorer: MultiLabelTrueFalseScorer, label: str) -> None: - """ - Select the verdict used by a single-result consumer. - - Args: - scorer (MultiLabelTrueFalseScorer): The scorer producing independent labeled verdicts. - label (str): One of the scorer's declared labels. - - Raises: - ValueError: If the source is not a multi-label scorer or the label is undeclared. - """ - if not isinstance(scorer, MultiLabelTrueFalseScorer): - raise ValueError("TrueFalseScoreSelector requires a MultiLabelTrueFalseScorer.") - if label not in scorer.labels: - raise ValueError(f"Unknown label {label!r}; choose one of {scorer.labels!r}.") - self._scorer = scorer - self._label = label - super().__init__() - - def get_chat_target(self) -> PromptTarget | None: - """Return the child's target for batch and evaluation rate-limit validation.""" - return self._scorer.get_chat_target() - - def with_scorer_block_policy(self, *, raise_if_scorer_blocks: bool) -> Self: - """ - Apply blocked-judge policy to the child without mutating shared instances. - - Returns: - Scorer: This selector or a copy containing the scoped child. - """ - child = self._scorer.with_scorer_block_policy(raise_if_scorer_blocks=raise_if_scorer_blocks) - if child is self._scorer: - return self - scoped = copy.copy(self) - scoped._scorer = child - return scoped - - def _build_identifier(self) -> ComponentIdentifier: - """ - Include the selected label and complete source configuration in the identity. - - Returns: - ComponentIdentifier: The selected label and source configuration. - """ - return self._create_identifier(params={"label": self._label}, sub_scorers=[self._scorer.get_identifier()]) - - def _get_child_scorers(self) -> tuple[Scorer, ...]: - """ - Expose the source for evidence and expectation preflight. - - Returns: - tuple[Scorer, ...]: The multi-label child. - """ - return (self._scorer,) - - async def _score_scorable_async(self, *, scorable: Scorable, expectation: ScoringExpectation | None) -> list[Score]: - """ - Run the source once and copy its selected verdict into a distinct public result. - - Returns: - list[Score]: The selected projection, or no result for non-applicable evidence. - """ - scores = await self._scorer._score_nested_async( - scorable=scorable, expectation=self._scorer._select_expectation(expectation=expectation) - ) - if not scores: - return [] - selected = next(score for score in scores if score.score_category == [self._label]) - return [self._create_wrapper_score(selected)] diff --git a/tests/unit/score/test_multi_label_true_false_scorer.py b/tests/unit/score/test_multi_label_true_false_scorer.py deleted file mode 100644 index ec6c1e7d8e..0000000000 --- a/tests/unit/score/test_multi_label_true_false_scorer.py +++ /dev/null @@ -1,574 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -import json -from collections.abc import Sequence -from typing import Any, assert_type -from unittest.mock import AsyncMock, patch - -import pytest -from unit.mocks import MockPromptTarget, get_image_message_piece, store_message_async - -from pyrit.exceptions import ScorerLLMResponseBlockedException -from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack -from pyrit.memory import MemoryInterface -from pyrit.models import ( - AttackOutcome, - ComponentIdentifier, - Contains, - ContentScorable, - Message, - MessagePiece, - MessageScorable, - OutputMatches, - Score, - ScoreStatus, - ScoringExpectation, -) -from pyrit.prompt_target import PromptTarget -from pyrit.score import ( - FloatScaleThresholdScorer, - JsonSchemaResponseHandler, - MessageMultiLabelTrueFalseScorer, - MultiLabelTrueFalseScorer, - ObjectiveScorerEvaluator, - Scorer, - ScorerEvaluator, - ScorerPromptValidator, - SubStringScorer, - TrueFalseAggregatorFunc, - TrueFalseCompositeScorer, - TrueFalseInverterScorer, - TrueFalseScoreAggregator, - TrueFalseScoreSelector, -) -from pyrit.score.observation.target_judge import JudgmentRequest, TargetJudge - -pytestmark = pytest.mark.usefixtures("patch_central_database") - -LABELS = ("harmful_request", "response_refusal", "harmful_response") -VERDICTS = {"harmful_request": True, "response_refusal": True, "harmful_response": False} - - -class SyntheticMultiLabelScorer(MessageMultiLabelTrueFalseScorer): - """Read independently labeled verdicts supplied as JSON instead of calling a model.""" - - def __init__( - self, - *, - labels: Sequence[str] = LABELS, - score_aggregator: TrueFalseAggregatorFunc = TrueFalseScoreAggregator.OR, - ) -> None: - super().__init__( - labels=labels, - validator=ScorerPromptValidator(supported_data_types=["text"]), - score_aggregator=score_aggregator, - ) - self.calls: list[ScoringExpectation | None] = [] - - async def _score_piece_with_expectation_async( - self, message_piece: MessagePiece, *, expectation: ScoringExpectation | None - ) -> list[Score]: - self.calls.append(expectation) - verdicts = json.loads(message_piece.converted_value) - return [ - Score( - score_value=None if value is None else str(value).lower(), - status=ScoreStatus.UNDETERMINED if value is None else ScoreStatus.COMPLETE, - score_type="true_false", - score_category=[label], - score_rationale=f"Verdict for {label}", - score_metadata={"label": label}, - message_piece_id=message_piece.id, - scorer_class_identifier=self.get_identifier(), - scored_expectation=expectation, - ) - for label, value in verdicts.items() - ] - - -class SyntheticJudgeScorer(SyntheticMultiLabelScorer): - """Exercise the real judge, parsing, observation, and persistence contracts.""" - - CONDITION_TYPE = OutputMatches - - def __init__(self, *, chat_target: PromptTarget) -> None: - super().__init__() - self._prompt_target = chat_target - self._judge = TargetJudge(target=chat_target, requirements=type(self).TARGET_REQUIREMENTS) - - def _build_identifier(self) -> ComponentIdentifier: - return self._create_identifier( - params={"labels": list(self.labels)}, - score_aggregator=self._score_aggregator.__name__, - prompt_target=self._prompt_target.get_identifier(), - ) - - async def _score_piece_with_expectation_async( - self, message_piece: MessagePiece, *, expectation: ScoringExpectation | None - ) -> list[Score]: - self.calls.append(expectation) - unvalidated = await self._judge.judge_async( - request=self._capture_judgment_evidence( - JudgmentRequest( - expectation=expectation, - system_prompt=None, - value=message_piece.converted_value, - data_type="text", - scored_prompt_id=message_piece.id, - scorer_identifier=self.get_identifier(), - ) - ), - response_handler=JsonSchemaResponseHandler(), - ) - return [ - unvalidated.to_score(score_value=str(value).lower(), score_type="true_false").model_copy( - update={"score_category": [label]} - ) - for label, value in json.loads(unvalidated.raw_score_value).items() - ] - - -async def test_one_piece_preserves_three_independent_persisted_verdicts(sqlite_instance: MemoryInterface) -> None: - scorer = SyntheticMultiLabelScorer() - scores = await scorer.score_async(scorable=ContentScorable(value=json.dumps(VERDICTS))) - - assert len(scorer.calls) == 1 - assert [score.score_category for score in scores] == [[label] for label in LABELS] - assert [score.get_value() for score in scores] == [True, True, False] - assert len({score.id for score in scores}) == 3 - for score in scores: - saved = await sqlite_instance.get_scores_async(score_ids=[str(score.id)]) - assert saved[0] == score - assert saved[0].message_piece_id is None - assert Score.model_validate_json(score.model_dump_json()) == score - assert await sqlite_instance.get_scores_async(score_category=score.score_category[0]) == saved - - -@pytest.mark.parametrize( - ("aggregator", "expected"), - [(TrueFalseScoreAggregator.OR, [True, True, False]), (TrueFalseScoreAggregator.AND, [False, False, False])], -) -async def test_pieces_aggregate_only_within_each_label( - aggregator: TrueFalseAggregatorFunc, expected: list[bool], sqlite_instance: MemoryInterface -) -> None: - scorer = SyntheticMultiLabelScorer(score_aggregator=aggregator) - first = MessagePiece(role="assistant", original_value=json.dumps(VERDICTS)) - second = MessagePiece( - role="assistant", - original_value=json.dumps(dict.fromkeys(reversed(LABELS), False)), - conversation_id=first.conversation_id, - ) - message = await store_message_async(Message(message_pieces=[first, second])) - - scores = await scorer.score_async(scorable=MessageScorable.from_message(message)) - - assert len(scorer.calls) == 2 - assert [score.get_value() for score in scores] == expected - assert [score.score_category for score in scores] == [[label] for label in LABELS] - assert all(score.scorable == MessageScorable.from_message(message) for score in scores) - assert all(score.score_metadata == {"label": score.score_category[0]} for score in scores) - assert len(await sqlite_instance.get_scores_async(score_type="true_false")) == 3 - - -@pytest.mark.parametrize( - ("aggregator", "second", "expected"), - [ - (TrueFalseScoreAggregator.OR, False, None), - (TrueFalseScoreAggregator.OR, True, True), - (TrueFalseScoreAggregator.AND, True, None), - (TrueFalseScoreAggregator.AND, False, False), - ], -) -async def test_undetermined_verdicts_follow_the_existing_three_valued_aggregation( - aggregator: TrueFalseAggregatorFunc, second: bool, expected: bool | None -) -> None: - scorer = SyntheticMultiLabelScorer(score_aggregator=aggregator) - first = MessagePiece(role="assistant", original_value=json.dumps(dict.fromkeys(LABELS, None))) - message = await store_message_async( - Message( - message_pieces=[ - first, - MessagePiece( - role="assistant", - original_value=json.dumps(dict.fromkeys(LABELS, second)), - conversation_id=first.conversation_id, - ), - ] - ) - ) - scores = await scorer.score_async(scorable=MessageScorable.from_message(message)) - - assert all(score.is_undetermined == (expected is None) for score in scores) - if expected is not None: - assert [score.get_value() for score in scores] == [expected] * 3 - - -@pytest.mark.parametrize("labels", [[], "label", [1], [""], [" "], [" spaced"], ["a", "a"], ["A", "a"]]) -def test_invalid_label_declarations_are_rejected(labels: Any) -> None: - with pytest.raises(ValueError, match="label"): - SyntheticMultiLabelScorer(labels=labels) - - -def test_labels_are_snapshotted_and_part_of_the_behavioral_identity() -> None: - labels = ["first", "second"] - scorer = SyntheticMultiLabelScorer(labels=labels) - labels.append("third") - assert scorer.labels == ("first", "second") - assert scorer.scorer_type == "true_false" - assert isinstance(scorer, MultiLabelTrueFalseScorer) - assert scorer.get_scorer_metrics() is None - assert scorer.get_identifier() != SyntheticMultiLabelScorer(labels=["first"]).get_identifier() - assert ( - scorer.get_identifier() - != SyntheticMultiLabelScorer( - labels=["first", "second"], - score_aggregator=TrueFalseScoreAggregator.AND, - ).get_identifier() - ) - - -@pytest.mark.parametrize( - "invalid", ["missing", "unknown", "duplicate", "multiple_categories", "unlabeled", "float", "value", "id"] -) -async def test_invalid_piece_contracts_fail_before_any_scores_are_saved( - invalid: str, sqlite_instance: MemoryInterface -) -> None: - scorer = SyntheticMultiLabelScorer() - scores = [ - Score( - score_value="true", - score_type="true_false", - score_category=[label], - scorer_class_identifier=scorer.get_identifier(), - ) - for label in LABELS - ] - if invalid == "missing": - scores.pop() - elif invalid == "unknown": - scores[-1].score_category = ["unknown"] - elif invalid == "duplicate": - scores[-1].score_category = [LABELS[0]] - elif invalid == "multiple_categories": - scores[0].score_category = list(LABELS) - elif invalid == "unlabeled": - scores[0].score_category = [] - elif invalid == "float": - scores[0].score_type = "float_scale" - scores[0].score_value = "0.5" - elif invalid == "value": - scores[0] = scores[0].model_copy(update={"score_value": "invalid"}) - else: - scores[0].id = scores[1].id - - with patch.object(scorer, "_score_piece_with_expectation_async", new_callable=AsyncMock) as score_piece: - score_piece.return_value = scores - with pytest.raises(RuntimeError, match="scorer"): - await scorer.score_async(scorable=ContentScorable(value="evidence")) - assert await sqlite_instance.get_scores_async(score_type="true_false", include_intermediate=True) == [] - - -async def test_each_piece_must_return_the_complete_contract() -> None: - scorer = SyntheticMultiLabelScorer() - first = MessagePiece(role="assistant", original_value=json.dumps({LABELS[0]: True})) - message = await store_message_async( - Message( - message_pieces=[ - first, - MessagePiece( - role="assistant", - original_value=json.dumps(dict.fromkeys(LABELS[1:], False)), - conversation_id=first.conversation_id, - ), - ] - ) - ) - with pytest.raises(RuntimeError, match="each declared label"): - await scorer.score_async(scorable=MessageScorable.from_message(message)) - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_selector_returns_one_public_result_and_retains_all_children( - select_label: bool, sqlite_instance: MemoryInterface -) -> None: - source = SyntheticMultiLabelScorer() - scorer = TrueFalseScoreSelector(scorer=source, label="harmful_response") if select_label else source - scores = await scorer.score_async(scorable=ContentScorable(value=json.dumps(VERDICTS))) - assert len(source.calls) == 1 - assert [score.get_value() for score in scores] == ([False] if select_label else [True, True, False]) - saved = await sqlite_instance.get_scores_async(score_type="true_false") - all_saved = await sqlite_instance.get_scores_async(score_type="true_false", include_intermediate=True) - assert {score.id for score in saved} == {score.id for score in scores} - assert len(all_saved) == (4 if select_label else 3) - if select_label: - child = [score for score in all_saved if score.id not in {item.id for item in saved}] - assert {score.score_category[0] for score in child} == set(LABELS) - assert all(score.scorer_class_identifier == source.get_identifier() for score in child) - assert saved[0].scorer_class_identifier == scorer.get_identifier() - assert saved[0].id not in {score.id for score in child} - assert await sqlite_instance.get_scores_async(score_category=LABELS[0]) == [] - retained = await sqlite_instance.get_scores_async(score_category=LABELS[0], include_intermediate=True) - assert len(retained) == 1 - assert retained[0].get_value() is True - - -@pytest.mark.parametrize("label", ["harmful_request", "harmful_response"]) -async def test_selector_composes_with_boolean_wrappers(label: str) -> None: - source = SyntheticMultiLabelScorer() - selected = TrueFalseScoreSelector(scorer=source, label=label) - inverted = TrueFalseInverterScorer(scorer=selected) - scores = await inverted.score_async(scorable=ContentScorable(value=json.dumps(VERDICTS))) - assert scores[0].get_value() is not VERDICTS[label] - assert len(source.calls) == 1 - composite = TrueFalseCompositeScorer(aggregator=TrueFalseScoreAggregator.AND, scorers=[selected]) - assert (await composite.score_async(scorable=ContentScorable(value=json.dumps(VERDICTS))))[ - 0 - ].get_value() == VERDICTS[label] - - -@pytest.mark.parametrize("consumer", ["attack", "refusal", "inverter", "composite", "threshold", "evaluation"]) -def test_raw_multi_label_scores_require_explicit_selection(consumer: str) -> None: - source = SyntheticMultiLabelScorer() - with pytest.raises(ValueError): - if consumer == "attack": - AttackScoringConfig(objective_scorer=source) - elif consumer == "refusal": - AttackScoringConfig(refusal_scorer=source) - elif consumer == "inverter": - TrueFalseInverterScorer(scorer=source) - elif consumer == "composite": - TrueFalseCompositeScorer(aggregator=TrueFalseScoreAggregator.OR, scorers=[source]) - elif consumer == "threshold": - FloatScaleThresholdScorer(scorer=source, threshold=0.5) - else: - ScorerEvaluator.from_scorer(source) - - -def test_selector_identity_and_invalid_selection() -> None: - source = SyntheticMultiLabelScorer() - first = TrueFalseScoreSelector(scorer=source, label=LABELS[0]) - last = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) - assert first.get_identifier() != last.get_identifier() - assert isinstance(ScorerEvaluator.from_scorer(last), ObjectiveScorerEvaluator) - AttackScoringConfig(objective_scorer=last) - with pytest.raises(ValueError, match="Unknown label"): - TrueFalseScoreSelector(scorer=source, label="unknown") - with pytest.raises(ValueError, match="MultiLabelTrueFalseScorer"): - TrueFalseScoreSelector(scorer=SubStringScorer(substring="test"), label=LABELS[0]) - - -async def test_batch_scoring_keeps_expectations_and_categories_independent() -> None: - source = SyntheticMultiLabelScorer() - expectations = [ScoringExpectation(objective=f"objective {index}") for index in range(2)] - scores = await source.score_batch_async( - scorables=[ContentScorable(value=json.dumps(VERDICTS)) for _ in range(2)], - expectations=expectations, - batch_size=2, - ) - assert len(scores) == 6 - assert source.calls == expectations - assert [score.scored_expectation for score in scores] == [item for item in expectations for _ in LABELS] - - -async def test_selector_batching_discovers_the_child_target_rate_limit() -> None: - source = SyntheticJudgeScorer(chat_target=MockPromptTarget(rpm=60)) - selector = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) - assert selector.get_chat_target() is source.get_chat_target() - with pytest.raises(ValueError, match="Batch size"): - await selector.score_batch_async(scorables=[ContentScorable(value="test")], batch_size=2) - assert source.calls == [] - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_target_judge_retains_one_observation_and_full_expectation( - select_label: bool, sqlite_instance: MemoryInterface -) -> None: - target = MockPromptTarget() - source = SyntheticJudgeScorer(chat_target=target) - scorer: Scorer = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - expectation = ScoringExpectation(objective="context", conditions=(OutputMatches(matcher=Contains(value="test")),)) - message = await store_message_async(MessagePiece(role="assistant", original_value="test evidence").to_message()) - response = MessagePiece( - role="assistant", - original_value=json.dumps({"score_value": json.dumps(VERDICTS), "rationale": "classifier"}), - ).to_message() - - with patch.object(target, "_send_prompt_to_target_async", new_callable=AsyncMock) as send: - send.return_value = [response] - scores = await scorer.score_async(scorable=MessageScorable.from_message(message), expectation=expectation) - assert send.call_count == 1 - assert source.calls == [expectation] - all_scores = await sqlite_instance.get_scores_async(score_type="true_false", include_intermediate=True) - assert len(all_scores) == (4 if select_label else 3) - assert all(score.scored_expectation == expectation for score in all_scores) - observation_ids = {identifier for score in all_scores for identifier in score.observation_ids} - assert len(observation_ids) == 1 - observations = await sqlite_instance.get_observations_async(observation_ids=list(observation_ids)) - assert len(observations) == 1 - assert all(score.message_piece_id == message.message_pieces[0].id for score in all_scores) - assert [score.get_value() for score in scores] == ([False] if select_label else [True, True, False]) - - -@pytest.mark.parametrize("response_error", ["blocked", "processing"]) -@pytest.mark.parametrize("select_label", [False, True]) -async def test_unreadable_or_blocked_message_has_undetermined_labeled_verdicts( - response_error: str, select_label: bool -) -> None: - source = SyntheticMultiLabelScorer() - scorer = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - message = await store_message_async( - MessagePiece( - role="assistant", - original_value="", - response_error=response_error, - ).to_message() - ) - scores = await scorer.score_async(scorable=MessageScorable.from_message(message)) - assert source.calls == [] - assert len(scores) == (1 if select_label else 3) - assert all(score.is_undetermined for score in scores) - assert len({score.id for score in scores}) == len(scores) - assert [score.score_category for score in scores] == ( - [[LABELS[-1]]] if select_label else [[label] for label in LABELS] - ) - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_suppressed_judge_block_expands_and_propagates_policy(select_label: bool) -> None: - source = SyntheticMultiLabelScorer() - original = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - scorer = original.with_scorer_block_policy(raise_if_scorer_blocks=False) - assert scorer is not original - assert source.raise_if_scorer_blocks is True - scoped_source = scorer._scorer if select_label else scorer - with patch.object(scoped_source, "_score_piece_with_expectation_async", new_callable=AsyncMock) as score_piece: - score_piece.side_effect = ScorerLLMResponseBlockedException() - scores = await scorer.score_async(scorable=ContentScorable(value="evidence")) - assert len(scores) == (1 if select_label else 3) - assert all(score.is_undetermined for score in scores) - assert scorer.with_scorer_block_policy(raise_if_scorer_blocks=False) is scorer - - -async def test_unsupported_message_role_does_not_create_verdicts() -> None: - source = SyntheticMultiLabelScorer() - message = await store_message_async(MessagePiece(role="simulated_assistant", original_value="ignored").to_message()) - assert await source.score_async(scorable=MessageScorable.from_message(message)) == [] - assert source.calls == [] - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_non_applicable_piece_does_not_invent_missing_labels( - select_label: bool, sqlite_instance: MemoryInterface -) -> None: - source = SyntheticMultiLabelScorer() - scorer = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - with patch.object(source, "_score_piece_with_expectation_async", new_callable=AsyncMock) as score_piece: - score_piece.return_value = [] - assert await scorer.score_async(scorable=ContentScorable(value="evidence")) == [] - assert await sqlite_instance.get_scores_async(score_type="true_false", include_intermediate=True) == [] - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_unsupported_modality_does_not_create_verdicts(select_label: bool) -> None: - source = SyntheticMultiLabelScorer() - scorer = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - message = await store_message_async(get_image_message_piece().to_message()) - assert await scorer.score_async(scorable=MessageScorable.from_message(message)) == [] - assert source.calls == [] - - -@pytest.mark.parametrize("select_label", [False, True]) -async def test_real_judge_block_retains_its_observation_for_every_label( - select_label: bool, sqlite_instance: MemoryInterface -) -> None: - target = MockPromptTarget() - source = SyntheticJudgeScorer(chat_target=target) - root = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) if select_label else source - scorer = root.with_scorer_block_policy(raise_if_scorer_blocks=False) - expectation = ScoringExpectation(objective="context", conditions=(OutputMatches(matcher=Contains(value="test")),)) - message = await store_message_async(MessagePiece(role="assistant", original_value="test evidence").to_message()) - response = MessagePiece( - role="assistant", original_value="blocked", original_value_data_type="error", response_error="blocked" - ).to_message() - - with patch.object(target, "_send_prompt_to_target_async", new_callable=AsyncMock) as send: - send.return_value = [response] - scores = await scorer.score_async(scorable=MessageScorable.from_message(message), expectation=expectation) - assert send.call_count == 1 - assert all(score.is_undetermined for score in scores) - all_scores = await sqlite_instance.get_scores_async(score_type="true_false", include_intermediate=True) - assert len(all_scores) == (4 if select_label else 3) - assert len({score.id for score in all_scores}) == len(all_scores) - assert all(score.scored_expectation == expectation for score in all_scores) - observation_ids = {identifier for score in all_scores for identifier in score.observation_ids} - assert len(observation_ids) == 1 - observations = await sqlite_instance.get_observations_async(observation_ids=list(observation_ids)) - assert len(observations) == 1 - assert observations[0].metadata == {"reason": "scorer_response_blocked"} - - -async def test_default_judge_block_policy_still_raises() -> None: - source = SyntheticMultiLabelScorer() - with patch.object(source, "_score_piece_with_expectation_async", new_callable=AsyncMock) as score_piece: - score_piece.side_effect = ScorerLLMResponseBlockedException() - with pytest.raises(ScorerLLMResponseBlockedException): - await TrueFalseScoreSelector(scorer=source, label=LABELS[-1]).score_async( - scorable=ContentScorable(value="evidence") - ) - - -@pytest.mark.parametrize("label", ["harmful_request", "harmful_response"]) -async def test_evaluation_uses_the_selected_label(label: str) -> None: - source = SyntheticMultiLabelScorer() - selector = TrueFalseScoreSelector(scorer=source, label=label) - evaluator = ScorerEvaluator.from_scorer(selector) - message = await store_message_async( - MessagePiece(role="assistant", original_value=json.dumps(VERDICTS)).to_message() - ) - groups = await evaluator._score_responses_grouped_async( - responses=[message], - objectives=["context"], - max_concurrency=1, - ) - score = evaluator._select_evaluation_score(scores=groups[0], harm_category=None) - assert score is not None - assert score.get_value() is VERDICTS[label] - assert score.score_category == [label] - assert len(source.calls) == 1 - - -async def test_attack_outcome_uses_the_selected_label_instead_of_the_first_verdict() -> None: - target = MockPromptTarget() - source = SyntheticMultiLabelScorer() - source._validator = ScorerPromptValidator(supported_data_types=["text"], is_objective_required=True) - selector = TrueFalseScoreSelector(scorer=source, label=LABELS[-1]) - attack = PromptSendingAttack( - objective_target=target, - attack_scoring_config=AttackScoringConfig(objective_scorer=selector), - ) - response = MessagePiece(role="assistant", original_value=json.dumps(VERDICTS)).to_message() - with patch.object(target, "_send_prompt_to_target_async", new_callable=AsyncMock) as send: - send.return_value = [response] - result = await attack.execute_async(objective="test objective") - assert result.outcome == AttackOutcome.FAILURE - assert len(source.calls) == 1 - - -def test_selector_with_scorer_block_policy_returns_subclass(patch_central_database): - """Self-typed with_scorer_block_policy preserves the subclass (PyRIT #4504).""" - - class _SubSelector(TrueFalseScoreSelector): - pass - - source = SyntheticMultiLabelScorer() - selector = _SubSelector(scorer=source, label=LABELS[0]) - - scoped = selector.with_scorer_block_policy(raise_if_scorer_blocks=False) - assert_type(scoped, _SubSelector) - assert isinstance(scoped, _SubSelector) - assert scoped is not selector - assert scoped._scorer.raise_if_scorer_blocks is False - assert source.raise_if_scorer_blocks is True - - assert selector.with_scorer_block_policy(raise_if_scorer_blocks=True) is selector diff --git a/tests/unit/score/test_scorer_info.py b/tests/unit/score/test_scorer_info.py index 6a0043cff4..789d627210 100644 --- a/tests/unit/score/test_scorer_info.py +++ b/tests/unit/score/test_scorer_info.py @@ -40,7 +40,6 @@ "TrueFalseCompositeScorer", "TrueFalseFallbackScorer", "TrueFalseInverterScorer", - "TrueFalseScoreSelector", } diff --git a/tests/unit/score/test_scorer_stability.py b/tests/unit/score/test_scorer_stability.py index 503805c8fc..4fd9c29406 100644 --- a/tests/unit/score/test_scorer_stability.py +++ b/tests/unit/score/test_scorer_stability.py @@ -26,7 +26,6 @@ from pyrit.score import ( HarmHumanLabeledEntry, HumanLabeledDataset, - MessageMultiLabelTrueFalseScorer, MessageTrueFalseScorer, MetricsType, ObjectiveHumanLabeledEntry, @@ -685,10 +684,6 @@ def test_presentations_are_required(self) -> None: with pytest.raises(ValueError, match="At least one presentation is required"): ScorerStabilityEvaluator(scorer=SubStringScorer(substring="x"), presentations=[]) - def test_multi_label_scorer_needs_a_label_selected_first(self) -> None: - with pytest.raises(ValueError, match="Select a label with TrueFalseScoreSelector"): - _evaluator(other=MagicMock(spec=MessageMultiLabelTrueFalseScorer)) - @pytest.mark.parametrize("names", [["a", "a"], ["reference"]]) def test_names_must_be_unique_and_not_the_references(self, names: list[str]) -> None: with pytest.raises(ValueError, match="must be unique and must not be 'reference'"):