From d1b8b032704916be2d20a72d12e6fa677712d768 Mon Sep 17 00:00:00 2001 From: WatchTree-19 Date: Tue, 10 Nov 2026 14:35:19 +0000 Subject: [PATCH 1/7] FEAT: exhaustive tool matching, so ToolsCalled can say "and nothing else" ToolsCalled is a subset match, so a run that calls the required tools plus others satisfies it. Add exhaustive=True for an exact match: the named tools ran and no other tool did. With no tools it asks that no tool ran at all. One observed execution of an unnamed tool disproves the match, even from partial evidence; confirming it needs complete, fully correlated evidence. OtelToolCallScorer now downgrades only verdicts that rest on absence when a request carries no trace link, which leaves subset behaviour unchanged. MessageToolCallScorer can refute an exhaustive match from a stored execution but never confirm one. The flag is left out of serialization while false, so stored subset conditions keep their form and expectation fingerprint (pinned in a test). --- doc/code/scoring/5_tool_call_scorer.ipynb | 25 ++++ doc/code/scoring/5_tool_call_scorer.py | 20 ++++ pyrit/models/score/condition.py | 21 +++- .../true_false/message_tool_call_scorer.py | 43 ++++++- .../score/true_false/otel_tool_call_scorer.py | 74 +++++++++--- tests/unit/models/test_condition.py | 42 +++++++ .../score/test_message_tool_call_scorer.py | 58 +++++++++ .../unit/score/test_message_trace_scoring.py | 46 ++++++++ .../unit/score/test_otel_tool_call_scorer.py | 111 ++++++++++++++++++ 9 files changed, 419 insertions(+), 21 deletions(-) diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 012ea178ae..071a3b19f9 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -428,6 +428,31 @@ "`OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is\n", "also available." ] + }, + { + "cell_type": "markdown", + "id": "15", + "metadata": {}, + "source": [ + "## Require that nothing else ran\n", + "\n", + "`ToolsCalled` is a subset match: a run that calls the required tools and three\n", + "others satisfies it. Set `exhaustive=True` to ask for an exact match instead, so\n", + "the required tools ran and no other tool did. With no tools, an exhaustive\n", + "condition asks that no tool ran at all, which suits confirmation gates.\n", + "\n", + "The two halves need different evidence. One observed execution of an unnamed\n", + "tool disproves the match, even from partial evidence. Confirming it needs\n", + "complete evidence, because only that rules out every other tool. So\n", + "`OtelToolCallScorer` returns true only for complete, fully correlated traces,\n", + "and `MessageToolCallScorer` returns false for a stored execution of an unnamed\n", + "tool and is otherwise undetermined. Use `OtelToolCallScorer` when an exhaustive\n", + "check needs to be able to pass.\n", + "\n", + "```python\n", + "ToolsCalled(tools=(ToolCallRequirement(name=\"read_file\"),), exhaustive=True)\n", + "```" + ] } ], "metadata": { diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index 298ab51dc3..03751f5d4c 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -299,3 +299,23 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: # records these pieces when it runs `custom_functions`. Combine it with # `OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is # also available. + +# %% [markdown] +# ## Require that nothing else ran +# +# `ToolsCalled` is a subset match: a run that calls the required tools and three +# others satisfies it. Set `exhaustive=True` to ask for an exact match instead, so +# the required tools ran and no other tool did. With no tools, an exhaustive +# condition asks that no tool ran at all, which suits confirmation gates. +# +# The two halves need different evidence. One observed execution of an unnamed +# tool disproves the match, even from partial evidence. Confirming it needs +# complete evidence, because only that rules out every other tool. So +# `OtelToolCallScorer` returns true only for complete, fully correlated traces, +# and `MessageToolCallScorer` returns false for a stored execution of an unnamed +# tool and is otherwise undetermined. Use `OtelToolCallScorer` when an exhaustive +# check needs to be able to pass. +# +# ```python +# ToolsCalled(tools=(ToolCallRequirement(name="read_file"),), exhaustive=True) +# ``` diff --git a/pyrit/models/score/condition.py b/pyrit/models/score/condition.py index af92d35f7c..64f5129d44 100644 --- a/pyrit/models/score/condition.py +++ b/pyrit/models/score/condition.py @@ -175,24 +175,35 @@ class ToolCallRequirement(BaseModel): class ToolsCalled(Condition): - """Require every named tool to have an execution attempt, regardless of success.""" + """ + Require every named tool to have an execution attempt, regardless of success. + + By default this is a subset match: other tools may also have run. ``exhaustive`` asks for + an exact match instead, so the named tools ran and no other tool did. An exhaustive + condition with no tools asks that no tool ran at all. + + An exhaustive match can be disproved by one observed execution of an unnamed tool, but + confirming it needs evidence complete enough to rule out every other tool. + """ condition_type: Literal["tools_called"] = "tools_called" tools: tuple[ToolCallRequirement, ...] + #: Left out of serialization while false, so subset conditions keep their stored form and fingerprint. + exhaustive: bool = Field(default=False, strict=True, exclude_if=lambda value: value is False) @model_validator(mode="after") def _validate_tools(self) -> ToolsCalled: """ - Require a nonempty set of distinct exact names. + Require distinct exact names, and at least one unless the match is exhaustive. Returns: ToolsCalled: The validated condition. Raises: - ValueError: If there are no tools or an exact name repeats. + ValueError: If a subset match names no tools or an exact name repeats. """ - if not self.tools: - raise ValueError("ToolsCalled requires at least one tool.") + if not self.tools and not self.exhaustive: + raise ValueError("ToolsCalled requires at least one tool unless exhaustive is set.") names = [tool.name for tool in self.tools] if len(set(names)) != len(names): raise ValueError("ToolsCalled requires each tool name once.") diff --git a/pyrit/score/true_false/message_tool_call_scorer.py b/pyrit/score/true_false/message_tool_call_scorer.py index 8a5e3e5f51..1d3da61142 100644 --- a/pyrit/score/true_false/message_tool_call_scorer.py +++ b/pyrit/score/true_false/message_tool_call_scorer.py @@ -111,8 +111,13 @@ class MessageToolCallScorer(TrueFalseScorer): Score tool invocations recorded as function_call and function_call_output message pieces. This scorer needs no trace pipeline. Stored messages are partial evidence, so it reports true - when every required tool ran and undetermined otherwise; it never reports false. Compose it - with ``OtelToolCallScorer`` under an OR aggregator when trace evidence is also available. + when every required tool ran and undetermined otherwise; absence never makes it report false. + Compose it with ``OtelToolCallScorer`` under an OR aggregator when trace evidence is also + available. + + An exhaustive condition reverses which verdict the stored messages can support: a stored + execution of a tool the condition does not name disproves it, but stored messages can never + rule out other tools, so it is otherwise undetermined and never true. """ SUPPORTED_SCORABLE_TYPES = (MessageScorable,) @@ -134,6 +139,8 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin missing = [tool.name for tool in condition.tools if tool.name not in executed] piece_id = self._piece_id_from_scorable(scorable) names = ", ".join(tool.name for tool in condition.tools) + if condition.exhaustive: + return [self._score_exhaustive(condition=condition, executed=executed, scorable=scorable)] if missing: return [ self._build_undetermined_score( @@ -156,3 +163,35 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin message_piece_id=piece_id, ) ] + + def _score_exhaustive(self, *, condition: ToolsCalled, executed: set[str], scorable: MessageScorable) -> Score: + """ + Disprove an exact match from a stored execution of an unnamed tool, or leave it open. + + Returns: + Score: False when an unnamed tool ran, otherwise undetermined. + """ + piece_id = self._piece_id_from_scorable(scorable) + description = "Tool invocation; successful completion is not required." + extra = sorted(executed - {tool.name for tool in condition.tools}) + if extra: + return Score( + score_value="false", + score_type="true_false", + score_rationale=( + "Stored function call outputs show execution of tools outside the required set: " + f"{', '.join(extra)}." + ), + score_value_description=description, + scorer_class_identifier=self.get_identifier(), + scorable=scorable, + message_piece_id=piece_id, + ) + names = ", ".join(tool.name for tool in condition.tools) + expected = f"exactly the required tools ({names}) ran" if names else "no tool ran" + return self._build_undetermined_score( + rationale=f"Stored messages cannot establish that {expected}. {_INCOMPLETE_EVIDENCE_REASON}", + description=description, + scorable=scorable, + message_piece_id=piece_id, + ) diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 72d2556eb3..b32f8f4fb1 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -39,14 +39,63 @@ def match_tools_called( Match execution names without I/O, preserving unknown absence. Returns: - bool | None: True for observed calls, false for complete absence, otherwise None. + bool | None: True for observed calls, false for complete absence, otherwise None. An + exhaustive condition is also false when a tool it does not name was observed, and + true only when complete evidence rules out every other tool. + """ + return _match_tools_called(condition=condition, payload=payload, acquisition=acquisition)[0] + + +def _match_tools_called( + *, condition: ToolsCalled, payload: ToolEventsObservationPayload, acquisition: Acquisition +) -> tuple[bool | None, bool]: + """ + Match execution names and report whether the verdict rests on the absence of other calls. + + A verdict that rests on absence is only as good as the evidence is complete, so a caller + that knows of uncorrelated requests must not keep it. A verdict from an observed call holds. + + Returns: + tuple[bool | None, bool]: The verdict, and whether it depends on complete evidence. """ if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): - return None + return None, False observed = {event.name for event in payload.events} - if all(tool.name in observed for tool in condition.tools): - return True - return False if acquisition is Acquisition.COMPLETE and payload.coverage.complete else None + required = {tool.name for tool in condition.tools} + if condition.exhaustive and not observed <= required: + return False, False + complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete + if required <= observed: + if not condition.exhaustive: + return True, False + return (True, True) if complete else (None, False) + return (False, True) if complete else (None, False) + + +def _rationale(*, condition: ToolsCalled, payload: ToolEventsObservationPayload, value: bool | None) -> str: + """ + Explain a tool-call verdict in terms of the evidence that decided it. + + Returns: + str: The rationale. + """ + names = ", ".join(tool.name for tool in condition.tools) + if not condition.exhaustive: + if value is True: + return f"Observed execution of all required tools: {names}." + if value is False: + return f"Complete trace evidence does not contain all required tools: {names}." + return f"Trace evidence cannot establish invocation of all required tools: {names}." + required = {tool.name for tool in condition.tools} + extra = sorted({event.name for event in payload.events} - required) + expected = f"exactly the required tools: {names}" if names else "no tool execution" + if value is True: + return f"Complete trace evidence shows {expected}." + if value is False and extra: + return f"Observed execution of tools outside the required set: {', '.join(extra)}." + if value is False: + return f"Complete trace evidence does not contain all required tools: {names}." + return f"Trace evidence cannot establish {expected}." class OtelToolCallScorer(TrueFalseScorer): @@ -89,10 +138,14 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin raise ValueError("Trace source returned incompatible evidence or scope.") _collect_observation(observation) scores = self._score_observation(observation=observation, evidence=observation.payload, expectation=expectation) + condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalled) + _, rests_on_absence = _match_tools_called( + condition=condition, payload=observation.payload, acquisition=observation.acquisition + ) for score in scores: score.scorable = scorable score.message_piece_id = self._piece_id_from_scorable(scorable) - if not correlation_complete and not score.is_undetermined and score.get_value() is False: + if not correlation_complete and rests_on_absence and not score.is_undetermined: score.set_value(None) score.score_rationale = f"{score.score_rationale} {_UNLINKED_REQUESTS_REASON}" return scores @@ -108,14 +161,7 @@ def _score_observation( raise NonReplayableObservationError("Tool-call scoring requires a stored tool-event observation.") condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalled) value = match_tools_called(condition=condition, payload=evidence, acquisition=observation.acquisition) - names = ", ".join(tool.name for tool in condition.tools) - rationale = ( - f"Observed execution of all required tools: {names}." - if value is True - else f"Complete trace evidence does not contain all required tools: {names}." - if value is False - else f"Trace evidence cannot establish invocation of all required tools: {names}." - ) + rationale = _rationale(condition=condition, payload=evidence, value=value) return [ Score( score_value=None if value is None else str(value).lower(), diff --git a/tests/unit/models/test_condition.py b/tests/unit/models/test_condition.py index e4683dbf91..fb226b3062 100644 --- a/tests/unit/models/test_condition.py +++ b/tests/unit/models/test_condition.py @@ -145,6 +145,48 @@ def test_tools_called_requires_nonempty_unique_names(names: list[str]) -> None: ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names)) +def test_subset_tools_called_keeps_its_stored_form_and_fingerprint() -> None: + expectation = ScoringExpectation( + objective="x", conditions=(ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)), MatchesObjective()) + ) + + assert expectation.conditions[0].model_dump(mode="json") == { + "condition_type": "tools_called", + "tools": [{"name": "lookup"}], + } + # Computed on main before ``exhaustive`` existed: stored subset expectations must still match. + assert scoring_expectation_fingerprint(expectation) == ( + "09c38ed6d8ab39e973e8ffa1c30690079eaee0acd4df463665eaf3f62d8d482c" + ) + + +@pytest.mark.parametrize("names", [(), ("lookup",), ("lookup", "send")]) +def test_exhaustive_tools_called_round_trips(names: tuple[str, ...]) -> None: + condition = ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names), exhaustive=True) + expectation = ScoringExpectation(conditions=(condition,)) + + assert condition.model_dump(mode="json")["exhaustive"] is True + assert Condition.model_validate(condition.model_dump(mode="json")) == condition + assert ScoringExpectation.model_validate_persisted(expectation.model_dump(mode="json")) == expectation + assert scoring_expectation_fingerprint(expectation) != scoring_expectation_fingerprint( + ScoringExpectation(conditions=(condition.model_copy(update={"exhaustive": False}),)) + ) + + +@pytest.mark.parametrize("value", [1, "true", "yes", None]) +def test_exhaustive_flag_is_strict(value: object) -> None: + with pytest.raises(ValidationError): + ToolsCalled.model_validate({"tools": [{"name": "lookup"}], "exhaustive": value}) + + +def test_explicit_false_exhaustive_flag_loads_as_a_subset_match() -> None: + condition = Condition.model_validate( + {"condition_type": "tools_called", "tools": [{"name": "lookup"}], "exhaustive": False} + ) + + assert condition == ToolsCalled(tools=(ToolCallRequirement(name="lookup"),)) + + @pytest.mark.parametrize("field", ["arguments", "count", "order", "success"]) def test_tool_call_requirement_rejects_unsupported_matching_fields(field: str) -> None: with pytest.raises(ValidationError, match="Extra inputs"): diff --git a/tests/unit/score/test_message_tool_call_scorer.py b/tests/unit/score/test_message_tool_call_scorer.py index 4986c75635..ccffccd288 100644 --- a/tests/unit/score/test_message_tool_call_scorer.py +++ b/tests/unit/score/test_message_tool_call_scorer.py @@ -441,3 +441,61 @@ async def lookup_async(args: dict) -> dict: "missing_function": "lookup", "available_functions": [], } + + +async def _score_exhaustive(message: Message, *names: str): + expectation = ScoringExpectation( + conditions=(ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names), exhaustive=True),) + ) + scores = await MessageToolCallScorer().score_async( + scorable=MessageScorable.from_message(message), expectation=expectation + ) + assert len(scores) == 1 + return scores[0] + + +async def test_exhaustive_stored_execution_of_an_unnamed_tool_is_false_async(sqlite_instance: SQLiteMemory) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_responses_call("call_1", "lookup")) + await conversation.output_async("call_1") + await conversation.call_async(_responses_call("call_2", "delete")) + await conversation.output_async("call_2") + reply = await conversation.reply_async() + + score = await _score_exhaustive(reply, "lookup") + + assert score.status == ScoreStatus.COMPLETE + assert score.get_value() is False + assert "outside the required set: delete" in score.score_rationale + + +@pytest.mark.parametrize("names", [("lookup",), ()]) +async def test_exhaustive_match_is_never_true_from_stored_messages_async( + sqlite_instance: SQLiteMemory, names: tuple[str, ...] +) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + if names: + await conversation.call_async(_responses_call("call_1", "lookup")) + await conversation.output_async("call_1") + reply = await conversation.reply_async() + + score = await _score_exhaustive(reply, *names) + + assert score.status == ScoreStatus.UNDETERMINED + assert score.score_value is None + + +async def test_exhaustive_ignores_unnamed_calls_that_did_not_run_async(sqlite_instance: SQLiteMemory) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_responses_call("call_1", "delete")) + await conversation.output_async( + "call_1", {"error": "function_not_found", "missing_function": "delete", "available_functions": []} + ) + await conversation.call_async(_responses_call("call_2", "send")) + await conversation.add_async("simulated_assistant", "function_call", _responses_call("call_3", "wipe")) + await conversation.output_async("call_3") + reply = await conversation.reply_async() + + score = await _score_exhaustive(reply) + + assert score.status == ScoreStatus.UNDETERMINED diff --git a/tests/unit/score/test_message_trace_scoring.py b/tests/unit/score/test_message_trace_scoring.py index 0047b1305b..f817aa8641 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 datetime import UTC, datetime from unittest.mock import AsyncMock, patch import httpx @@ -32,6 +33,7 @@ ToolCallRequirement, ToolsCalled, TraceScorable, + TraceSpan, ) from pyrit.prompt_normalizer import PromptNormalizer from pyrit.prompt_target import HTTPTarget, TargetCapabilities, TargetConfiguration, TargetTraceConfig @@ -504,3 +506,47 @@ async def test_multipart_request_deduplicates_trace_scope(sqlite_instance: SQLit TraceScorable(trace_ids=("1" * 32,)), True, ) + + +@pytest.mark.parametrize( + ("names", "expected"), + [ + # "Nothing else ran" rests on absence, so an unlinked request leaves it open. + (("lookup",), None), + # An observed call outside the required set disproves the match whatever else ran. + (("lookup", "delete"), False), + ], +) +async def test_unlinked_request_blocks_only_absence_based_exhaustive_verdicts_async( + sqlite_instance: SQLiteMemory, names: tuple[str, ...], expected: bool | None +) -> None: + conversation = str(uuid.uuid4()) + (await _store_async(memory=sqlite_instance, conversation=conversation)) + (await _store_async(memory=sqlite_instance, conversation=conversation, role="assistant")) + (await _store_async(memory=sqlite_instance, conversation=conversation, trace_id="1" * 32)) + response = await _store_async(memory=sqlite_instance, conversation=conversation, role="assistant") + client = InMemoryTraceClient() + now = datetime.now(tz=UTC) + for index, name in enumerate(names): + client.add_span( + TraceSpan( + trace_id="1" * 32, + span_id=f"{index + 1:016x}", + start_time=now, + end_time=now, + attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name}, + ) + ) + client.mark_complete(trace_ids=("1" * 32,)) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + expectation = ScoringExpectation( + conditions=(ToolsCalled(tools=(ToolCallRequirement(name="lookup"),), exhaustive=True),) + ) + + score = (await scorer.score_async(scorable=MessageScorable.from_message(response), expectation=expectation))[0] + + if expected is None: + assert score.is_undetermined + assert "no trace link" in score.score_rationale + else: + assert score.get_value() is expected diff --git a/tests/unit/score/test_otel_tool_call_scorer.py b/tests/unit/score/test_otel_tool_call_scorer.py index 86d53b37af..1c626ae6aa 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -25,6 +25,8 @@ Score, ScoringExpectation, ToolCallRequirement, + ToolEventsObservationPayload, + ToolExecution, ToolsCalled, TraceCoverage, TraceQuery, @@ -42,6 +44,7 @@ OtelTraceSource, TraceAcquisitionError, ) +from pyrit.score.true_false.otel_tool_call_scorer import match_tools_called pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -553,3 +556,111 @@ async def test_tool_observation_and_score_roll_back_together_async(sqlite_instan assert sqlite_instance._query_entries(ScoreEntry) == [] assert (await sqlite_instance.get_observations_async(observation_ids=[observation.id])) == [] + + +def _exhaustive(*names: str) -> ScoringExpectation: + return ScoringExpectation( + conditions=(ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names), exhaustive=True),) + ) + + +def _tool_payload(*names: str, complete: bool) -> ToolEventsObservationPayload: + now = datetime.now(tz=UTC) + events = tuple( + ToolExecution(name=name, trace_id="1" * 32, span_id=f"{index + 1:016x}", start_time=now, end_time=now) + for index, name in enumerate(names) + ) + return ToolEventsObservationPayload( + scope=TraceScorable(trace_ids=("1" * 32,)), + events=events, + coverage=TraceCoverage(complete=complete, reasons=() if complete else ("source_coverage_incomplete",)), + ) + + +@pytest.mark.parametrize( + ("required", "observed", "complete", "expected"), + [ + (("lookup",), ("lookup",), True, True), + (("lookup",), ("lookup",), False, None), + (("lookup",), ("lookup", "delete"), False, False), + (("lookup",), ("lookup", "delete"), True, False), + (("lookup",), ("delete",), False, False), + (("lookup",), (), True, False), + (("lookup",), (), False, None), + (("lookup", "send"), ("send", "lookup"), True, True), + ((), (), True, True), + ((), (), False, None), + ((), ("delete",), False, False), + ], +) +def test_exhaustive_match_needs_complete_evidence_to_confirm_but_one_extra_call_to_refute( + required: tuple[str, ...], observed: tuple[str, ...], complete: bool, expected: bool | None +) -> None: + condition = _exhaustive(*required).conditions[0] + acquisition = Acquisition.COMPLETE if complete else Acquisition.PARTIAL + payload = _tool_payload(*observed, complete=complete) + + assert match_tools_called(condition=condition, payload=payload, acquisition=acquisition) is expected + + +@pytest.mark.parametrize("acquisition", [Acquisition.ERROR, Acquisition.UNAVAILABLE]) +def test_exhaustive_match_is_undetermined_without_evidence(acquisition: Acquisition) -> None: + condition = _exhaustive("lookup").conditions[0] + payload = _tool_payload(complete=False) + + assert match_tools_called(condition=condition, payload=payload, acquisition=acquisition) is None + + +def test_subset_match_still_ignores_other_tools() -> None: + condition = _expectation("lookup").conditions[0] + payload = _tool_payload("lookup", "delete", complete=True) + + assert match_tools_called(condition=condition, payload=payload, acquisition=Acquisition.COMPLETE) is True + + +@pytest.mark.parametrize( + ("names", "complete", "expected", "rationale"), + [ + (("lookup",), True, True, "exactly the required tools: lookup"), + (("lookup", "delete"), False, False, "outside the required set: delete"), + (("lookup",), False, None, "cannot establish exactly the required tools"), + ], +) +async def test_exhaustive_scoring_and_offline_replay_async( + sqlite_instance: SQLiteMemory, + names: tuple[str, ...], + complete: bool, + expected: bool | None, + rationale: str, +) -> None: + client = InMemoryTraceClient() + for index, name in enumerate(names): + client.add_span(_span(name=name, span_id=f"{index + 1:016x}")) + scope = TraceScorable(trace_ids=("1" * 32,)) + if complete: + client.mark_complete(trace_ids=scope.trace_ids) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + + score = (await scorer.score_async(scorable=scope, expectation=_exhaustive("lookup")))[0] + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + client.close() + replay = (await scorer.score_observation_async(observation=observation, expectation=_exhaustive("lookup")))[0] + + for result in (score, replay): + assert rationale in result.score_rationale + if expected is None: + assert result.is_undetermined + else: + assert result.get_value() is expected + + +async def test_exhaustive_condition_with_no_tools_confirms_that_nothing_ran_async() -> None: + client = InMemoryTraceClient() + scope = TraceScorable(trace_ids=("1" * 32,)) + client.mark_complete(trace_ids=scope.trace_ids) + scorer = OtelToolCallScorer(source=OtelTraceSource(trace_client=client)) + + score = (await scorer.score_async(scorable=scope, expectation=_exhaustive()))[0] + + assert score.get_value() is True + assert "no tool execution" in score.score_rationale From 00feb233e5827d78b11bc9dcfc7f9baf92c46b5c Mon Sep 17 00:00:00 2001 From: WatchTree-19 Date: Wed, 11 Nov 2026 13:39:35 +0000 Subject: [PATCH 2/7] TEST: Name the exhaustive scoring helper with the async suffix Follow the repository convention for async helpers: add the _async suffix and the Score return annotation. --- tests/unit/score/test_message_tool_call_scorer.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/unit/score/test_message_tool_call_scorer.py b/tests/unit/score/test_message_tool_call_scorer.py index ccffccd288..b0179f5304 100644 --- a/tests/unit/score/test_message_tool_call_scorer.py +++ b/tests/unit/score/test_message_tool_call_scorer.py @@ -17,6 +17,7 @@ Message, MessagePiece, MessageScorable, + Score, ScoreStatus, ScoringExpectation, ToolCallRequirement, @@ -443,7 +444,7 @@ async def lookup_async(args: dict) -> dict: } -async def _score_exhaustive(message: Message, *names: str): +async def _score_exhaustive_async(message: Message, *names: str) -> Score: expectation = ScoringExpectation( conditions=(ToolsCalled(tools=tuple(ToolCallRequirement(name=name) for name in names), exhaustive=True),) ) @@ -462,7 +463,7 @@ async def test_exhaustive_stored_execution_of_an_unnamed_tool_is_false_async(sql await conversation.output_async("call_2") reply = await conversation.reply_async() - score = await _score_exhaustive(reply, "lookup") + score = await _score_exhaustive_async(reply, "lookup") assert score.status == ScoreStatus.COMPLETE assert score.get_value() is False @@ -479,7 +480,7 @@ async def test_exhaustive_match_is_never_true_from_stored_messages_async( await conversation.output_async("call_1") reply = await conversation.reply_async() - score = await _score_exhaustive(reply, *names) + score = await _score_exhaustive_async(reply, *names) assert score.status == ScoreStatus.UNDETERMINED assert score.score_value is None @@ -496,6 +497,6 @@ async def test_exhaustive_ignores_unnamed_calls_that_did_not_run_async(sqlite_in await conversation.output_async("call_3") reply = await conversation.reply_async() - score = await _score_exhaustive(reply) + score = await _score_exhaustive_async(reply) assert score.status == ScoreStatus.UNDETERMINED From 95f060c4def0ec9e7beaafa7f5443aac85a13ef1 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Thu, 12 Nov 2026 21:15:37 -0800 Subject: [PATCH 3/7] Clarify subset-only tool scorer verdict guarantee Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/scoring/5_tool_call_scorer.ipynb | 4 ++-- doc/code/scoring/5_tool_call_scorer.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 071a3b19f9..e8294a3665 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -422,8 +422,8 @@ "not count either.\n", "\n", "Stored messages are partial evidence. Hosted tools, several response section\n", - "types, and targets that execute tools themselves leave no output pieces, so the\n", - "scorer returns true or undetermined and never false. `OpenAIResponseTarget`\n", + "types, and targets that execute tools themselves leave no output pieces. For\n", + "subset conditions, the scorer returns true or undetermined and never false. `OpenAIResponseTarget`\n", "records these pieces when it runs `custom_functions`. Combine it with\n", "`OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is\n", "also available." diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index 03751f5d4c..6d0ce5558f 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -294,8 +294,8 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: # not count either. # # Stored messages are partial evidence. Hosted tools, several response section -# types, and targets that execute tools themselves leave no output pieces, so the -# scorer returns true or undetermined and never false. `OpenAIResponseTarget` +# types, and targets that execute tools themselves leave no output pieces. For +# subset conditions, the scorer returns true or undetermined and never false. `OpenAIResponseTarget` # records these pieces when it runs `custom_functions`. Combine it with # `OtelToolCallScorer` under `TrueFalseScoreAggregator.OR` when trace evidence is # also available. From d695654711c30876b003b7dfebe0ca425dfc505c Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Fri, 13 Nov 2026 23:58:39 -0800 Subject: [PATCH 4/7] Fix exhaustive tool matching for error acquisition Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pyrit/score/true_false/otel_tool_call_scorer.py | 4 ++-- tests/unit/score/test_otel_tool_call_scorer.py | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index b32f8f4fb1..00910ff356 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -58,12 +58,12 @@ def _match_tools_called( Returns: tuple[bool | None, bool]: The verdict, and whether it depends on complete evidence. """ - if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): - return None, False observed = {event.name for event in payload.events} required = {tool.name for tool in condition.tools} if condition.exhaustive and not observed <= required: return False, False + if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): + return None, False complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete if required <= observed: if not condition.exhaustive: diff --git a/tests/unit/score/test_otel_tool_call_scorer.py b/tests/unit/score/test_otel_tool_call_scorer.py index 1c626ae6aa..19629b01f5 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -611,6 +611,13 @@ def test_exhaustive_match_is_undetermined_without_evidence(acquisition: Acquisit assert match_tools_called(condition=condition, payload=payload, acquisition=acquisition) is None +def test_exhaustive_match_refutes_error_acquisition_with_an_observed_extra_tool() -> None: + condition = _exhaustive("lookup").conditions[0] + payload = _tool_payload("delete", complete=False) + + assert match_tools_called(condition=condition, payload=payload, acquisition=Acquisition.ERROR) is False + + def test_subset_match_still_ignores_other_tools() -> None: condition = _expectation("lookup").conditions[0] payload = _tool_payload("lookup", "delete", complete=True) From 2bfeb495c80abfa437301acc4da46eb65fa22285 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Sat, 14 Nov 2026 01:03:27 -0800 Subject: [PATCH 5/7] docs: clarify exhaustive trace errors Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- doc/code/scoring/5_tool_call_scorer.ipynb | 3 ++- doc/code/scoring/5_tool_call_scorer.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index e0da63b07d..43426c3b52 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -443,7 +443,8 @@ "condition asks that no tool ran at all, which suits confirmation gates.\n", "\n", "The two halves need different evidence. One observed execution of an unnamed\n", - "tool disproves the match, even from partial evidence. Confirming it needs\n", + "tool disproves the match, even when acquisition reports `Acquisition.PARTIAL`\n", + "or `Acquisition.ERROR`, provided the event was retained. Confirming it needs\n", "complete evidence, because only that rules out every other tool. So\n", "`OtelToolCallScorer` returns true only for complete, fully correlated traces,\n", "and `MessageToolCallScorer` returns false for a stored execution of an unnamed\n", diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index f68cc90291..6a475afc5b 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -310,7 +310,8 @@ async def local_agent_async(request: httpx.Request) -> httpx.Response: # condition asks that no tool ran at all, which suits confirmation gates. # # The two halves need different evidence. One observed execution of an unnamed -# tool disproves the match, even from partial evidence. Confirming it needs +# tool disproves the match, even when acquisition reports `Acquisition.PARTIAL` +# or `Acquisition.ERROR`, provided the event was retained. Confirming it needs # complete evidence, because only that rules out every other tool. So # `OtelToolCallScorer` returns true only for complete, fully correlated traces, # and `MessageToolCallScorer` returns false for a stored execution of an unnamed From 06d407306a7c138bab21a6201740cb231b32fedc Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Sat, 14 Nov 2026 01:16:55 -0800 Subject: [PATCH 6/7] style: format exhaustive tool matching Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- pyrit/score/true_false/otel_tool_call_scorer.py | 4 +--- tests/unit/score/test_message_tool_call_scorer.py | 8 ++------ 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index ea481344e7..197b7c7836 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -84,9 +84,7 @@ def _match_tools_called( for event in payload.events: # Trace events do not retain arguments, so they cannot confirm an argument requirement. calls.setdefault(event.name, []).append(None) - verdicts = [ - match_tool_requirement(requirement=tool, calls=calls.get(tool.name, [])) for tool in condition.tools - ] + verdicts = [match_tool_requirement(requirement=tool, calls=calls.get(tool.name, [])) for tool in condition.tools] complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete if all(verdict is True for verdict in verdicts): if not condition.exhaustive: diff --git a/tests/unit/score/test_message_tool_call_scorer.py b/tests/unit/score/test_message_tool_call_scorer.py index 927c711d18..c4c5314c2e 100644 --- a/tests/unit/score/test_message_tool_call_scorer.py +++ b/tests/unit/score/test_message_tool_call_scorer.py @@ -614,9 +614,7 @@ async def test_exhaustive_argument_match_stays_open_until_other_tool_evidence_as tools=( ToolCallRequirement( name="send_email", - arguments=( - ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")), - ), + arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")),), ), ), exhaustive=True, @@ -625,9 +623,7 @@ async def test_exhaustive_argument_match_stays_open_until_other_tool_evidence_as ) score = ( - await MessageToolCallScorer().score_async( - scorable=MessageScorable.from_message(reply), expectation=expectation - ) + await MessageToolCallScorer().score_async(scorable=MessageScorable.from_message(reply), expectation=expectation) )[0] assert score.score_value == (None if expected is None else str(expected).lower()) From d87dc0eb1035be184fd17611b4428008b960ca94 Mon Sep 17 00:00:00 2001 From: WatchTree-19 <119982314+WatchTree-19@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:49:52 +0000 Subject: [PATCH 7/7] TEST: Cover the exhaustive rationale when a required tool is missing Drops the unreachable subset branch from _rationale, which is only called for exhaustive conditions, and builds the subset rationale only on the subset path. --- .../score/true_false/otel_tool_call_scorer.py | 27 +++++++------------ .../unit/score/test_otel_tool_call_scorer.py | 1 + 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 197b7c7836..c01a7c4a4c 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -101,12 +101,6 @@ def _rationale(*, condition: ToolsCalled, payload: ToolEventsObservationPayload, str: The rationale. """ names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools) - if not condition.exhaustive: - if value is True: - return f"Observed execution of all required tools: {names}." - if value is False: - return f"Complete trace evidence does not contain all required tools: {names}." - return f"Trace evidence cannot establish invocation of all required tools: {names}." required = {tool.name for tool in condition.tools} extra = sorted({event.name for event in payload.events} - required) expected = f"exactly the required tools: {names}" if names else "no tool execution" @@ -189,19 +183,18 @@ def _score_observation( "OtelToolCallScorer received a requirement with argument constraints, which trace evidence " "cannot confirm. Use MessageToolCallScorer to match arguments." ) - rationale = ( - f"Observed execution of all required tools: {names}." - if value is True - else f"Complete trace evidence does not contain all required tools: {names}." - if value is False - else f"Trace evidence cannot establish invocation of all required tools: {names}." - ) - if value is None and constrains_arguments: - rationale = f"{rationale} {_NO_TRACE_ARGUMENTS_REASON}" if condition.exhaustive: rationale = _rationale(condition=condition, payload=evidence, value=value) - if value is None and constrains_arguments: - rationale = f"{rationale} {_NO_TRACE_ARGUMENTS_REASON}" + else: + rationale = ( + f"Observed execution of all required tools: {names}." + if value is True + else f"Complete trace evidence does not contain all required tools: {names}." + if value is False + else f"Trace evidence cannot establish invocation of all required tools: {names}." + ) + if value is None and constrains_arguments: + rationale = f"{rationale} {_NO_TRACE_ARGUMENTS_REASON}" return [ Score( score_value=None if value is None else str(value).lower(), diff --git a/tests/unit/score/test_otel_tool_call_scorer.py b/tests/unit/score/test_otel_tool_call_scorer.py index 4670026a51..a4b3c0dbaa 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -750,6 +750,7 @@ def test_subset_match_still_ignores_other_tools() -> None: (("lookup",), True, True, "exactly the required tools: lookup"), (("lookup", "delete"), False, False, "outside the required set: delete"), (("lookup",), False, None, "cannot establish exactly the required tools"), + ((), True, False, "does not contain all required tools: lookup"), ], ) async def test_exhaustive_scoring_and_offline_replay_async(