diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 35441880bb..43426c3b52 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -423,8 +423,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." @@ -435,6 +435,26 @@ "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 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", + "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", + "```\n", + "\n", "## Require arguments\n", "\n", "A `ToolCallRequirement` can also constrain the arguments of the call. Each\n", diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index bb33c73554..6a475afc5b 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -295,13 +295,33 @@ 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. # %% [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 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 +# 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) +# ``` +# # ## Require arguments # # A `ToolCallRequirement` can also constrain the arguments of the call. Each diff --git a/pyrit/models/score/condition.py b/pyrit/models/score/condition.py index 932166bca0..d0a8bfe4c7 100644 --- a/pyrit/models/score/condition.py +++ b/pyrit/models/score/condition.py @@ -198,24 +198,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 cca0ac301c..02353c0a03 100644 --- a/pyrit/score/true_false/message_tool_call_scorer.py +++ b/pyrit/score/true_false/message_tool_call_scorer.py @@ -125,8 +125,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. A requirement with argument constraints needs one execution whose requested arguments, as stored in its function_call piece, satisfy every constraint. @@ -159,6 +164,8 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin ] piece_id = self._piece_id_from_scorable(scorable) names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools) + if condition.exhaustive: + return [self._score_exhaustive(condition=condition, executed=set(calls), scorable=scorable)] if unmet: # A tool that ran with other arguments did run, so say so rather than report no execution. not_run = [describe_tool_requirement(tool) for tool in unmet if tool.name not in calls] @@ -190,3 +197,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 43493e9ec2..c01a7c4a4c 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -55,19 +55,62 @@ def match_tools_called( Its absence can still be refuted from complete evidence, because no call means no matching call. 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. + """ + 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 + return None, False calls: dict[str, list[Mapping[str, JsonValue] | None]] = {} 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] - if all(verdict is True for verdict in verdicts): - return True complete = acquisition is Acquisition.COMPLETE and payload.coverage.complete - return False if complete and any(verdict is False for verdict in verdicts) else None + if all(verdict is True for verdict in verdicts): + if not condition.exhaustive: + return True, False + return (True, True) if complete else (None, False) + return (False, True) if complete and any(verdict is False for verdict in verdicts) 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(describe_tool_requirement(tool) for tool in condition.tools) + 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): @@ -110,10 +153,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 @@ -136,13 +183,16 @@ 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 condition.exhaustive: + rationale = _rationale(condition=condition, payload=evidence, value=value) + 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 [ diff --git a/tests/unit/models/test_condition.py b/tests/unit/models/test_condition.py index 3d66e32b17..368c947d34 100644 --- a/tests/unit/models/test_condition.py +++ b/tests/unit/models/test_condition.py @@ -148,6 +148,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", ["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 f45f5aacde..c4c5314c2e 100644 --- a/tests/unit/score/test_message_tool_call_scorer.py +++ b/tests/unit/score/test_message_tool_call_scorer.py @@ -18,6 +18,7 @@ Message, MessagePiece, MessageScorable, + Score, ScoreStatus, ScoringExpectation, ToolArgumentRequirement, @@ -552,3 +553,96 @@ async def lookup_async(args: dict) -> dict: "missing_function": "lookup", "available_functions": [], } + + +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),) + ) + 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_async(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_async(reply, *names) + + assert score.status == ScoreStatus.UNDETERMINED + assert score.score_value is None + + +@pytest.mark.parametrize(("extra_tool", "expected"), [(False, None), (True, False)]) +async def test_exhaustive_argument_match_stays_open_until_other_tool_evidence_async( + sqlite_instance: SQLiteMemory, extra_tool: bool, expected: bool | None +) -> None: + conversation = await _Conversation.create_async(memory=sqlite_instance) + await conversation.call_async(_send_email(_responses_call, "call_1", {"to": "a@example.com"})) + await conversation.output_async("call_1") + if extra_tool: + await conversation.call_async(_responses_call("call_2", "delete")) + await conversation.output_async("call_2") + reply = await conversation.reply_async() + expectation = ScoringExpectation( + conditions=( + ToolsCalled( + tools=( + ToolCallRequirement( + name="send_email", + arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")),), + ), + ), + exhaustive=True, + ), + ) + ) + + score = ( + 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()) + assert score.status == (ScoreStatus.UNDETERMINED if expected is None else ScoreStatus.COMPLETE) + if extra_tool: + assert "outside the required set: delete" in score.score_rationale + + +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_async(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 7538c6007e..a4b3c0dbaa 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -27,6 +27,8 @@ ScoringExpectation, ToolArgumentRequirement, ToolCallRequirement, + ToolEventsObservationPayload, + ToolExecution, ToolsCalled, TraceCoverage, TraceQuery, @@ -44,6 +46,7 @@ OtelTraceSource, TraceAcquisitionError, ) +from pyrit.score.true_false.otel_tool_call_scorer import match_tools_called pytestmark = pytest.mark.usefixtures("patch_central_database") @@ -645,3 +648,146 @@ 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_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 + + +@pytest.mark.parametrize( + ("observed", "complete", "acquisition", "expected"), + [ + (("send_email",), True, Acquisition.COMPLETE, None), + (("send_email",), False, Acquisition.PARTIAL, None), + (("send_email", "delete"), False, Acquisition.PARTIAL, False), + (("delete",), False, Acquisition.ERROR, False), + (("lookup",), True, Acquisition.COMPLETE, False), + ], +) +def test_exhaustive_argument_requirement_preserves_trace_limits_and_extra_tool_precedence( + observed: tuple[str, ...], complete: bool, acquisition: Acquisition, expected: bool | None +) -> None: + condition = ToolsCalled( + tools=( + ToolCallRequirement( + name="send_email", + arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")),), + ), + ), + exhaustive=True, + ) + payload = _tool_payload(*observed, complete=complete) + + assert match_tools_called(condition=condition, payload=payload, acquisition=acquisition) is expected + + +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"), + ((), True, False, "does not contain all required tools: lookup"), + ], +) +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