Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
9e198b2
FIX: Do not score write-only target deliveries as attack responses
shashank03-dev Oct 31, 2026
cdec7e3
FIX: Mark write-only deliveries explicitly and keep side-effect scoring
shashank03-dev Nov 1, 2026
2b3a5eb
FIX: Score side-effect composites and keep TAP siblings on empty bran…
shashank03-dev Nov 1, 2026
06baa71
Merge branch 'main' into fix/write-only-target-false-success
shashank03-dev Nov 2, 2026
c989a03
Merge main into fix/write-only-target-false-success
romanlutz Nov 2, 2026
27deb6e
Merge main into fix/write-only-target-false-success
romanlutz Nov 3, 2026
4faa1e4
Merge main into fix/write-only-target-false-success
shashank03-dev Nov 15, 2026
7f2b8fe
FIX: Declare response support as a target capability
shashank03-dev Nov 15, 2026
4c6c094
Merge main into write-only target scoring fix
richlundeen Nov 16, 2026
dc85663
Clarify write-only target support in the target guide
richlundeen Nov 16, 2026
497e9da
Simplify write-only targets: ask the target, require responses by def…
richlundeen Nov 17, 2026
5a0a6f9
Merge commit '5325d9712245abdf77754c8b0acebf73e56d06a3' into HEAD
richlundeen Nov 17, 2026
66f4211
FIX: Preserve side-effect scoring for write-only manual sends
richlundeen Nov 17, 2026
b6cc963
FIX: Keep write-only score publication ordered by delivery
richlundeen Nov 17, 2026
4fb6406
FIX: Accept equal-timestamp write-only evaluations
richlundeen Nov 17, 2026
6901d8d
Exclude delivery's own multipart pieces from recency checks
richlundeen Nov 17, 2026
d33db7e
Merge main 44d031fc6 into fix/write-only-target-false-success
richlundeen Nov 17, 2026
61b7723
FIX: Compare stored anchor times for write-only score publication
richlundeen Nov 17, 2026
d15584e
TEST: Stop asserting score creation order for concurrent write-only s…
richlundeen Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 7 additions & 13 deletions doc/code/scoring/0_scoring.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -402,8 +402,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."
]
},
Expand All @@ -425,9 +425,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",
Expand All @@ -441,14 +441,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",
Expand Down
4 changes: 2 additions & 2 deletions doc/code/scoring/0_scoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,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
Expand Down
3 changes: 2 additions & 1 deletion doc/code/targets/0_prompt_targets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`. 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`.

Expand Down Expand Up @@ -283,6 +283,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` 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. |

Expand Down
68 changes: 60 additions & 8 deletions pyrit/backend/services/chat_scoring_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand All @@ -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(
Expand All @@ -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,
Expand Down Expand Up @@ -366,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,
Expand Down Expand Up @@ -557,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.

Expand All @@ -573,8 +604,28 @@ 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:
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()
if any(
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
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,
Expand All @@ -595,6 +646,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(
Expand Down
19 changes: 14 additions & 5 deletions pyrit/backend/services/message_send_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -791,15 +791,22 @@ 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
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 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(
Expand Down Expand Up @@ -849,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.
Expand All @@ -865,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:
Expand Down
4 changes: 4 additions & 0 deletions pyrit/executor/attack/compound/sequential_attack.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
AttackSeedGroup,
ScoringExpectation,
)
from pyrit.prompt_target import TargetRequirements

if TYPE_CHECKING:
from collections.abc import Mapping, Sequence
Expand Down Expand Up @@ -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

Expand Down
21 changes: 19 additions & 2 deletions pyrit/executor/attack/core/attack_scoring.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,37 @@ async def score_attack_response_async(
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 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``.
"""
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 objective_scorer.judges_side_effects():
objective_scorer = None
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(
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],
)
Loading