diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 8d49757378..7c514bb327 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -642,11 +642,25 @@ "```\n", "\n", "`MessageToolCallScorer` reads the arguments from the stored `function_call`\n", - "piece of each execution. Trace events do not retain arguments, so\n", + "piece of each execution. `OtelTraceSource` keeps no arguments by default, so\n", "`OtelToolCallScorer` cannot confirm an argument requirement and leaves it\n", "undetermined. Complete trace evidence with no execution of the tool still makes\n", "it false, because no call means no matching call.\n", "\n", + "To match arguments from traces, name the arguments the source may keep:\n", + "\n", + "```python\n", + "OtelTraceSource(trace_client=client, kept_arguments=(\"to\",))\n", + "```\n", + "\n", + "The source reads each span's `gen_ai.tool.call.arguments` attribute, keeps the\n", + "named top-level arguments, and redacts the rest before the evidence is stored.\n", + "A redacted argument is unknown, not absent: a requirement on it can neither\n", + "confirm nor refute a call, so the score stays undetermined even when the trace\n", + "evidence is complete, and the rationale names the arguments the source did not\n", + "keep. A kept argument that the call lacks, or whose value does not match, still\n", + "refutes the call.\n", + "\n", "## Let a scenario choose the tool-call scorer\n", "\n", "A scenario that takes a `CompatibleScorers` pool, such as `RapidResponse`, picks a scorer for\n", diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index b829dc266b..d6df0606cb 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -467,11 +467,25 @@ def trace_backend(request: httpx.Request) -> httpx.Response: # ``` # # `MessageToolCallScorer` reads the arguments from the stored `function_call` -# piece of each execution. Trace events do not retain arguments, so +# piece of each execution. `OtelTraceSource` keeps no arguments by default, so # `OtelToolCallScorer` cannot confirm an argument requirement and leaves it # undetermined. Complete trace evidence with no execution of the tool still makes # it false, because no call means no matching call. # +# To match arguments from traces, name the arguments the source may keep: +# +# ```python +# OtelTraceSource(trace_client=client, kept_arguments=("to",)) +# ``` +# +# The source reads each span's `gen_ai.tool.call.arguments` attribute, keeps the +# named top-level arguments, and redacts the rest before the evidence is stored. +# A redacted argument is unknown, not absent: a requirement on it can neither +# confirm nor refute a call, so the score stays undetermined even when the trace +# evidence is complete, and the rationale names the arguments the source did not +# keep. A kept argument that the call lacks, or whose value does not match, still +# refutes the call. +# # ## Let a scenario choose the tool-call scorer # # A scenario that takes a `CompatibleScorers` pool, such as `RapidResponse`, picks a scorer for diff --git a/pyrit/models/score/observation.py b/pyrit/models/score/observation.py index 2cf9d473ac..0308ac68b3 100644 --- a/pyrit/models/score/observation.py +++ b/pyrit/models/score/observation.py @@ -307,7 +307,12 @@ def _validate_references(self) -> ConversationObservationPayload: class ToolEventsObservationPayload(BaseModel): - """An immutable allowlisted tool snapshot, with arguments and results not retained.""" + """ + An immutable allowlisted tool snapshot, with raw arguments and results not retained. + + ``kept_arguments`` names the arguments the source kept at write time. Every other argument + was redacted, so a matcher treats it as unknown, never as absent. + """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -317,6 +322,8 @@ class ToolEventsObservationPayload(BaseModel): events: tuple[ToolExecution, ...] = () coverage: TraceCoverage = Field(default_factory=TraceCoverage) arguments_retained: Literal[False] = False + #: Left out of serialization while empty, so name-only snapshots keep their stored form. + kept_arguments: tuple[str, ...] = Field(default=(), exclude_if=lambda value: not value) @field_validator("arguments_retained", mode="before") @classmethod @@ -331,7 +338,7 @@ def _validate_arguments_retained(cls, value: object) -> Literal[False]: ValueError: If the marker is not exactly false. """ if value is not False: - raise ValueError("Tool payload arguments_retained must be false; arguments are not captured.") + raise ValueError("Tool payload arguments_retained must be false; raw arguments are not captured.") return False @field_validator("schema_version", mode="before") @@ -359,7 +366,7 @@ def _validate_scope_and_events(self) -> ToolEventsObservationPayload: ToolEventsObservationPayload: The validated snapshot. Raises: - ValueError: If identities, scope, or completeness are inconsistent. + ValueError: If identities, scope, completeness, or kept arguments are inconsistent. """ identities = [(event.trace_id, event.span_id) for event in self.events] if len(set(identities)) != len(identities): @@ -368,6 +375,11 @@ def _validate_scope_and_events(self) -> ToolEventsObservationPayload: raise ValueError("Tool events must belong to the declared trace scope.") if self.coverage.complete and any(event.end_time is None for event in self.events): raise ValueError("Complete coverage cannot contain unfinished tool events.") + if any(not name for name in self.kept_arguments) or len(set(self.kept_arguments)) != len(self.kept_arguments): + raise ValueError("Kept tool arguments must be distinct, nonempty names.") + kept = set(self.kept_arguments) + if any(event.arguments is not None and (not kept or not set(event.arguments) <= kept) for event in self.events): + raise ValueError("Tool events can only retain the arguments the payload declares kept.") return self diff --git a/pyrit/models/score/trace.py b/pyrit/models/score/trace.py index 815cd5fa53..003f7c56de 100644 --- a/pyrit/models/score/trace.py +++ b/pyrit/models/score/trace.py @@ -140,12 +140,19 @@ def _validate_availability(self) -> TraceQueryResult: class ToolExecution(_TraceInterval): - """Safe immutable name-only execution evidence; arguments and results are not retained.""" + """ + Safe immutable execution evidence; results and raw arguments are not retained. + + ``arguments`` holds only the arguments a source was configured to keep, redacting the rest + at write time. It is None when the source kept no arguments or could not read them. + """ name: ToolName parent_span_id: SpanId | None = None call_id: str | None = Field(default=None, min_length=1) status: TraceSpanStatus = TraceSpanStatus.UNSET + #: Left out of serialization while None, so name-only evidence keeps its stored form. + arguments: dict[str, JsonValue] | None = Field(default=None, exclude_if=lambda value: value is None) class ExecutionStepKind(str, Enum): diff --git a/pyrit/score/observation/otel_trace_source.py b/pyrit/score/observation/otel_trace_source.py index 62af17b243..e907574132 100644 --- a/pyrit/score/observation/otel_trace_source.py +++ b/pyrit/score/observation/otel_trace_source.py @@ -6,6 +6,7 @@ from __future__ import annotations import asyncio +import json import logging import math from typing import TYPE_CHECKING @@ -24,33 +25,103 @@ if TYPE_CHECKING: from collections.abc import Sequence + from pydantic import JsonValue + from pyrit.models import TraceQueryResult, TraceScorable, TraceSpan from pyrit.score.observation.trace_client import TraceClient logger = logging.getLogger(__name__) +#: The GenAI semantic-convention attribute that carries a tool call's arguments. +_ARGUMENTS_ATTRIBUTE = "gen_ai.tool.call.arguments" + + +def _has_non_finite_number(value: JsonValue) -> bool: + """ + Find a NaN or infinite number anywhere in a JSON value. + + Returns: + bool: Whether the value holds a number that is not finite. + """ + if isinstance(value, float): + return not math.isfinite(value) + if isinstance(value, dict): + return any(_has_non_finite_number(item) for item in value.values()) + if isinstance(value, list): + return any(_has_non_finite_number(item) for item in value) + return False + + +def _keep_arguments(value: JsonValue | None, *, kept: tuple[str, ...]) -> dict[str, JsonValue] | None: + """ + Keep only the named top-level arguments of one call, redacting the rest. + + A number that is not finite is not JSON, whether it arrives as a ``NaN`` or ``Infinity`` + constant, as a literal too large to represent, or inside an already-parsed object. + + Returns: + dict[str, JsonValue] | None: The kept arguments the call has, or None if its arguments + are missing, are not a JSON object, or hold a number that is not finite. + """ + if isinstance(value, str): + try: + value = json.loads(value) + except ValueError: + return None + if not isinstance(value, dict) or _has_non_finite_number(value): + return None + return {name: value[name] for name in kept if name in value} + class OtelTraceSource: - """Normalize explicit GenAI/OpenInference execution spans into safe evidence.""" + """ + Normalize explicit GenAI/OpenInference execution spans into safe evidence. + + Tool arguments are redacted at write time. By default none are kept. ``kept_arguments`` opts in + to keeping the named top-level arguments from the span's ``gen_ai.tool.call.arguments`` + attribute; every other argument, and the raw attribute, is discarded before the evidence is + stored. Spans that do not carry that attribute keep no arguments. + """ - def __init__(self, *, trace_client: TraceClient, max_spans: int = 10000, timeout_seconds: float = 30) -> None: + def __init__( + self, + *, + trace_client: TraceClient, + max_spans: int = 10000, + timeout_seconds: float = 30, + kept_arguments: Sequence[str] = (), + ) -> None: """ Initialize bounded acquisition through a caller-owned client. Raises: - ValueError: If the retrieval limit or timeout is not positive and finite. + ValueError: If the retrieval limit or timeout is not positive and finite, or the kept + argument names are not distinct and nonempty. """ if max_spans < 1 or not math.isfinite(timeout_seconds) or timeout_seconds <= 0: raise ValueError("max_spans and timeout_seconds must be positive.") + if ( + isinstance(kept_arguments, str) + or not all(isinstance(name, str) and name for name in kept_arguments) + or len(set(kept_arguments)) != len(kept_arguments) + ): + raise ValueError("kept_arguments must be a sequence of distinct, nonempty argument names.") self._client = trace_client self._max_spans = max_spans self._timeout_seconds = timeout_seconds + self._kept_arguments = tuple(kept_arguments) def get_identifier(self) -> ComponentIdentifier: """Return parser version and source identity without serializing the client.""" return ComponentIdentifier.of( self, - params={"normalization_version": 1, "max_spans": self._max_spans, "timeout_seconds": self._timeout_seconds}, + params={ + "normalization_version": 1, + "max_spans": self._max_spans, + "timeout_seconds": self._timeout_seconds, + # Omitted while empty, so a source that keeps no arguments keeps its identity. + "kept_arguments": list(self._kept_arguments) or None, + }, children={"trace_client": self._client.get_identifier()}, ) @@ -75,7 +146,7 @@ async def acquire_async(self, *, scorable: TraceScorable) -> Observation: ) spans, reasons = _scoped_spans(result=result, scope=scorable, max_spans=self._max_spans) - events, normalization_reasons = self._normalize(spans=spans) + events, normalization_reasons = self._normalize(spans=spans, kept=self._kept_arguments) reasons.extend(normalization_reasons) acquisition = Acquisition.PARTIAL if reasons else Acquisition.COMPLETE return self._observation( @@ -101,11 +172,12 @@ def _observation( scope=scorable, events=events, coverage=TraceCoverage(complete=acquisition is Acquisition.COMPLETE, reasons=reasons), + kept_arguments=self._kept_arguments, ), ) @staticmethod - def _normalize(*, spans: Sequence[TraceSpan]) -> tuple[tuple[ToolExecution, ...], list[str]]: + def _normalize(*, spans: Sequence[TraceSpan], kept: tuple[str, ...]) -> tuple[tuple[ToolExecution, ...], list[str]]: events: list[ToolExecution] = [] reasons: list[str] = [] for span in spans: @@ -130,6 +202,7 @@ def _normalize(*, spans: Sequence[TraceSpan]) -> tuple[tuple[ToolExecution, ...] start_time=span.start_time, end_time=span.end_time, status=span.status, + arguments=_keep_arguments(span.attributes.get(_ARGUMENTS_ATTRIBUTE), kept=kept) if kept else None, ) ) events.sort(key=lambda event: (event.start_time, event.trace_id, event.span_id)) diff --git a/pyrit/score/tool_argument_matching.py b/pyrit/score/tool_argument_matching.py index 4c221e7857..c0af110b1c 100644 --- a/pyrit/score/tool_argument_matching.py +++ b/pyrit/score/tool_argument_matching.py @@ -11,7 +11,7 @@ from pyrit.score.text_matching import match_text if TYPE_CHECKING: - from collections.abc import Mapping, Sequence + from collections.abc import Collection, Mapping, Sequence from pydantic import JsonValue @@ -42,7 +42,12 @@ def describe_tool_requirement(requirement: ToolCallRequirement) -> str: return f"{requirement.name}({', '.join(argument.name for argument in requirement.arguments)})" -def match_tool_arguments(*, requirement: ToolCallRequirement, arguments: Mapping[str, JsonValue] | None) -> bool | None: +def match_tool_arguments( + *, + requirement: ToolCallRequirement, + arguments: Mapping[str, JsonValue] | None, + kept: Collection[str] | None = None, +) -> bool | None: """ Decide whether one call's arguments satisfy every argument requirement. @@ -50,6 +55,11 @@ def match_tool_arguments(*, requirement: ToolCallRequirement, arguments: Mapping retained cannot show a match, so they leave the call undetermined. A missing argument, or one that does not match, decides the call. + ``kept`` names the arguments the evidence kept when the rest were redacted at write time; + None means every argument was retained. A redacted argument is unknown, not absent: a + constraint on it can neither match nor fail, so the call is undetermined unless another, + kept argument refutes it. + Returns: bool | None: True when every constraint matches, false when one fails, otherwise None. """ @@ -57,28 +67,35 @@ def match_tool_arguments(*, requirement: ToolCallRequirement, arguments: Mapping return True if arguments is None: return None + verdict: bool | None = True for constraint in requirement.arguments: - if constraint.name not in arguments: - return False - if not match_text(matcher=constraint.matcher, text=_argument_text(arguments[constraint.name])): + if kept is not None and constraint.name not in kept: + verdict = None + elif constraint.name not in arguments or not match_text( + matcher=constraint.matcher, text=_argument_text(arguments[constraint.name]) + ): return False - return True + return verdict def match_tool_requirement( - *, requirement: ToolCallRequirement, calls: Sequence[Mapping[str, JsonValue] | None] + *, + requirement: ToolCallRequirement, + calls: Sequence[Mapping[str, JsonValue] | None], + kept: Collection[str] | None = None, ) -> bool | None: """ Combine the calls of one tool into a verdict for its requirement. One matching call satisfies the requirement. It is refuted only when every call is refuted, including when there are none; any undetermined call leaves it undetermined. The caller - decides whether its evidence is complete enough to keep a refutation. + decides whether its evidence is complete enough to keep a refutation. ``kept`` is as for + ``match_tool_arguments``. Returns: bool | None: True when some call matches, false when every call is refuted, otherwise None. """ - verdicts = [match_tool_arguments(requirement=requirement, arguments=arguments) for arguments in calls] + verdicts = [match_tool_arguments(requirement=requirement, arguments=arguments, kept=kept) for arguments in calls] if True in verdicts: return True return None if None in verdicts else False diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 84b474371f..72acdd5208 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -61,6 +61,8 @@ def match_tools_called( A requirement with argument constraints needs an execution whose retained arguments match. Its absence can still be refuted from complete evidence, because no call means no matching call. + An argument the source did not keep was redacted at write time: a constraint on it can neither + confirm a call nor refute one, so a negative that would rest on it is undetermined. Returns: bool | None: True for observed calls, false for complete absence, otherwise None. An @@ -90,9 +92,11 @@ def _match_tools_called( 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] + calls.setdefault(event.name, []).append(event.arguments) + verdicts = [ + match_tool_requirement(requirement=tool, calls=calls.get(tool.name, []), kept=payload.kept_arguments) + 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: @@ -332,12 +336,24 @@ def _score_observation( condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalled) value = match_tools_called(condition=condition, payload=evidence, acquisition=observation.acquisition) names = ", ".join(describe_tool_requirement(tool) for tool in condition.tools) - constrains_arguments = any(tool.arguments for tool in condition.tools) - if constrains_arguments: + redacted = sorted( + { + argument.name + for tool in condition.tools + for argument in tool.arguments + if argument.name not in evidence.kept_arguments + } + ) + if redacted and not evidence.kept_arguments: logger.warning( "OtelToolCallScorer received a requirement with argument constraints, which trace evidence " "cannot confirm. Use MessageToolCallScorer to match arguments." ) + elif redacted: + logger.warning( + "OtelToolCallScorer received argument constraints on arguments its trace source does not keep: %s.", + ", ".join(redacted), + ) if condition.exhaustive: rationale = _rationale(condition=condition, payload=evidence, value=value) else: @@ -348,8 +364,10 @@ def _score_observation( if value is False else f"Trace evidence cannot establish invocation of all required tools: {names}." ) - if value is None and constrains_arguments: + if value is None and redacted and not evidence.kept_arguments: rationale = f"{rationale} {_NO_TRACE_ARGUMENTS_REASON}" + elif value is None and redacted: + rationale = f"{rationale} The trace source did not keep these arguments: {', '.join(redacted)}." return [ Score( score_value=None if value is None else str(value).lower(), diff --git a/tests/unit/models/test_tool_observation.py b/tests/unit/models/test_tool_observation.py index 1eb561c12e..95dbd6dc8e 100644 --- a/tests/unit/models/test_tool_observation.py +++ b/tests/unit/models/test_tool_observation.py @@ -91,6 +91,63 @@ def test_tool_payload_rejects_argument_capture_and_coercion(arguments_retained: ToolEventsObservationPayload.model_validate({"scope": SCOPE, "arguments_retained": arguments_retained}) +def _kept_event(arguments: dict[str, object] | None, *, span_id: str = "2" * 16) -> ToolExecution: + return ToolExecution.model_validate( + { + "name": "send_email", + "trace_id": TRACE_ID, + "span_id": span_id, + "start_time": START_TIME, + "arguments": arguments, + } + ) + + +def test_tool_payload_round_trips_kept_arguments() -> None: + payload = ToolEventsObservationPayload( + scope=SCOPE, + events=( + _kept_event({"to": "a@example.com"}), + _kept_event({}, span_id="3" * 16), + _kept_event(None, span_id="4" * 16), + ), + kept_arguments=("to", "subject"), + ) + observation = _observation(payload=payload, acquisition=Acquisition.PARTIAL) + + assert Observation.model_validate_json(observation.model_dump_json()) == observation + assert payload.model_dump(mode="json")["kept_arguments"] == ["to", "subject"] + assert payload.arguments_retained is False + + +def test_tool_payload_without_kept_arguments_keeps_its_stored_form() -> None: + payload = ToolEventsObservationPayload(scope=SCOPE, events=(_event(),)) + + assert "kept_arguments" not in payload.model_dump(mode="json") + assert "arguments" not in payload.model_dump(mode="json")["events"][0] + assert ( + ToolEventsObservationPayload.model_validate({**payload.model_dump(mode="json"), "kept_arguments": []}) + == payload + ) + + +@pytest.mark.parametrize( + ("kept_arguments", "arguments"), + [((), {"to": "a@example.com"}), (("to",), {"to": "a@example.com", "body": "secret"}), ((), {})], +) +def test_tool_payload_rejects_arguments_it_does_not_declare_kept( + kept_arguments: tuple[str, ...], arguments: dict[str, object] +) -> None: + with pytest.raises(ValidationError, match="declares kept"): + ToolEventsObservationPayload(scope=SCOPE, events=(_kept_event(arguments),), kept_arguments=kept_arguments) + + +@pytest.mark.parametrize("kept_arguments", [("",), ("to", "to")]) +def test_tool_payload_rejects_blank_or_repeated_kept_arguments(kept_arguments: tuple[str, ...]) -> None: + with pytest.raises(ValidationError, match="distinct, nonempty"): + ToolEventsObservationPayload(scope=SCOPE, kept_arguments=kept_arguments) + + def test_unavailable_observation_preserves_requested_scope() -> None: observation = _observation(payload=ToolEventsObservationPayload(scope=SCOPE), acquisition=Acquisition.UNAVAILABLE) assert Observation.model_validate_json(observation.model_dump_json()) == observation diff --git a/tests/unit/models/test_trace.py b/tests/unit/models/test_trace.py index 9bec6f3875..9b7c12e625 100644 --- a/tests/unit/models/test_trace.py +++ b/tests/unit/models/test_trace.py @@ -147,6 +147,22 @@ def test_tool_execution_preserves_attempt_status(status: TraceSpanStatus) -> Non } +def test_tool_execution_round_trips_kept_arguments() -> None: + event = ToolExecution.model_validate( + {**_model_data(ToolExecution), "arguments": {"to": "a@example.com", "recipient": {"cc": [1, None]}}} + ) + + assert ToolExecution.model_validate_json(event.model_dump_json()) == event + assert event.model_dump(mode="json")["arguments"] == {"to": "a@example.com", "recipient": {"cc": [1, None]}} + assert "arguments" not in ToolExecution.model_validate(_model_data(ToolExecution)).model_dump(mode="json") + + +@pytest.mark.parametrize("arguments", ["{}", ["to"], {"to": object()}]) +def test_tool_execution_rejects_unstructured_arguments(arguments: object) -> None: + with pytest.raises(ValidationError): + ToolExecution.model_validate({**_model_data(ToolExecution), "arguments": arguments}) + + @pytest.mark.parametrize("model_type", [TraceSpan, ToolExecution]) def test_execution_rejects_unknown_status(model_type: type[BaseModel]) -> None: with pytest.raises(ValidationError): diff --git a/tests/unit/score/test_otel_tool_call_scorer.py b/tests/unit/score/test_otel_tool_call_scorer.py index 763831af13..f1224005f0 100644 --- a/tests/unit/score/test_otel_tool_call_scorer.py +++ b/tests/unit/score/test_otel_tool_call_scorer.py @@ -293,6 +293,144 @@ async def test_absent_name_only_tool_refutes_alongside_an_undetermined_argument_ assert (await scorer.score_async(scorable=scope, expectation=_argument_expectation()))[0].is_undetermined +def _kept_argument_scorer(*arguments: JsonValue, kept: tuple[str, ...] = ("to",)) -> OtelToolCallScorer: + client = InMemoryTraceClient() + for index, value in enumerate(arguments): + span = _span(name="send_email", span_id=f"{index + 2:016x}") + if value is not None: + span.attributes["gen_ai.tool.call.arguments"] = value + client.add_span(span) + client.mark_complete(trace_ids=("1" * 32,)) + return OtelToolCallScorer(source=OtelTraceSource(trace_client=client, kept_arguments=kept)) + + +def _send_email_expectation(**matchers: str) -> ScoringExpectation: + arguments = tuple( + ToolArgumentRequirement(name=name, matcher=Equals(value=value)) for name, value in matchers.items() + ) + return ScoringExpectation( + conditions=(ToolsCalled(tools=(ToolCallRequirement(name="send_email", arguments=arguments),)),) + ) + + +async def test_source_keeps_only_the_named_arguments_async(sqlite_instance: SQLiteMemory) -> None: + scorer = _kept_argument_scorer( + '{"to": "a@example.com", "body": "private-body"}', '{"body": "private-other"}', kept=("to", "cc") + ) + + score = ( + await scorer.score_async( + scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=_send_email_expectation(to="a@example.com") + ) + )[0] + + assert score.get_value() is True + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.payload.kept_arguments == ("to", "cc") + assert [event.arguments for event in observation.payload.events] == [{"to": "a@example.com"}, {}] + assert "private-" not in observation.model_dump_json() + assert "gen_ai.tool.call.arguments" not in observation.model_dump_json() + + +@pytest.mark.parametrize( + "arguments", + [ + None, + "not json", + '["a@example.com"]', + '"a@example.com"', + '{"to": NaN}', + '{"to": 1e400}', + '{"to": "a@example.com", "body": {"sizes": [1, -Infinity]}}', + {"to": float("inf")}, + {"to": "a@example.com", "body": {"sizes": [1, float("nan")]}}, + 3, + ], +) +async def test_unreadable_trace_arguments_are_not_retained_and_stay_undetermined_async( + sqlite_instance: SQLiteMemory, arguments: JsonValue +) -> None: + scorer = _kept_argument_scorer(arguments) + + score = ( + await scorer.score_async( + scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=_send_email_expectation(to="a@example.com") + ) + )[0] + + assert score.is_undetermined + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.acquisition is Acquisition.COMPLETE + assert observation.payload.events[0].arguments is None + + +@pytest.mark.parametrize( + ("arguments", "matchers", "expected"), + [ + ('{"to": "a@example.com"}', {"to": "a@example.com"}, True), + ({"to": "a@example.com"}, {"to": "a@example.com"}, True), + ('{"to": "b@example.com"}', {"to": "a@example.com"}, False), + ('{"subject": "hi"}', {"to": "a@example.com"}, False), + ('{"to": "b@example.com", "body": "invoice"}', {"to": "a@example.com", "body": "invoice"}, False), + ('{"to": "a@example.com", "body": "invoice"}', {"to": "a@example.com", "body": "invoice"}, None), + ('{"to": "a@example.com", "body": "invoice"}', {"body": "invoice"}, None), + ('{"to": "a@example.com", "body": "other"}', {"body": "invoice"}, None), + ], +) +async def test_complete_evidence_never_decides_a_redacted_argument_async( + sqlite_instance: SQLiteMemory, arguments: JsonValue, matchers: dict[str, str], expected: bool | None +) -> None: + scorer = _kept_argument_scorer(arguments) + expectation = _send_email_expectation(**matchers) + + score = (await scorer.score_async(scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=expectation))[0] + + assert score.score_value == (None if expected is None else str(expected).lower()) + assert ("did not keep these arguments: body" in score.score_rationale) is (expected is None) + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.acquisition is Acquisition.COMPLETE + replay = (await scorer.score_observation_async(observation=observation, expectation=expectation))[0] + assert replay.score_value == score.score_value + + +async def test_redaction_leaves_name_only_negatives_confident_async() -> None: + scorer = _kept_argument_scorer('{"to": "a@example.com", "body": "invoice"}') + expectation = ScoringExpectation( + conditions=( + ToolsCalled( + tools=( + ToolCallRequirement( + name="send_email", + arguments=(ToolArgumentRequirement(name="body", matcher=Equals(value="invoice")),), + ), + ToolCallRequirement(name="lookup"), + ) + ), + ) + ) + + score = (await scorer.score_async(scorable=TraceScorable(trace_ids=("1" * 32,)), expectation=expectation))[0] + + assert score.get_value() is False + + +def test_source_identity_records_kept_arguments_only_when_set() -> None: + client = InMemoryTraceClient(source_id="same") + default = OtelTraceSource(trace_client=client).get_identifier() + + assert set(default.params) == {"normalization_version", "max_spans", "timeout_seconds"} + kept = OtelTraceSource(trace_client=client, kept_arguments=("to",)).get_identifier() + assert kept.params["kept_arguments"] == ["to"] + assert kept.hash != default.hash + assert OtelTraceSource(trace_client=client, kept_arguments=()).get_identifier().hash == default.hash + + +@pytest.mark.parametrize("kept_arguments", ["to", ("",), ("to", "to"), (3,)]) +def test_source_rejects_invalid_kept_arguments(kept_arguments: object) -> None: + with pytest.raises(ValueError, match="kept_arguments"): + OtelTraceSource(trace_client=InMemoryTraceClient(), kept_arguments=kept_arguments) # type: ignore[arg-type] + + @pytest.mark.parametrize( "scorable", [ContentScorable(value="I called lookup")], diff --git a/tests/unit/score/test_tool_argument_matching.py b/tests/unit/score/test_tool_argument_matching.py index 24a05af07b..3113f74b4b 100644 --- a/tests/unit/score/test_tool_argument_matching.py +++ b/tests/unit/score/test_tool_argument_matching.py @@ -108,3 +108,48 @@ def test_requirement_description_names_constrained_arguments() -> None: describe_tool_requirement(_requirement(to=Equals(value="x"), body=Contains(value="y"))) == "send_email(to, body)" ) + + +@pytest.mark.parametrize( + ("arguments", "expected"), + [ + ({"to": "a@example.com"}, None), + ({"to": "b@example.com"}, False), + ({}, False), + ], +) +def test_a_redacted_argument_can_neither_confirm_nor_refute_a_call( + arguments: dict[str, JsonValue], expected: bool | None +) -> None: + requirement = _requirement(to=Equals(value="a@example.com"), body=Contains(value="invoice")) + + # ``body`` was redacted at write time: the verdict can rest only on the kept ``to``. + assert match_tool_arguments(requirement=requirement, arguments=arguments, kept=("to",)) is expected + + +def test_a_kept_argument_the_call_lacks_is_absent_not_redacted() -> None: + requirement = _requirement(to=Equals(value="a@example.com")) + + assert match_tool_arguments(requirement=requirement, arguments={}, kept=("to",)) is False + assert match_tool_arguments(requirement=requirement, arguments={}, kept=()) is None + assert match_tool_arguments(requirement=requirement, arguments={}) is False + + +def test_redaction_leaves_name_only_requirements_unaffected() -> None: + assert match_tool_arguments(requirement=ToolCallRequirement(name="send_email"), arguments=None, kept=()) is True + + +@pytest.mark.parametrize( + ("calls", "expected"), + [ + ([{"to": "b@example.com"}, {"to": "a@example.com"}], None), + ([{"to": "b@example.com"}, {}], False), + ([], False), + ], +) +def test_redaction_makes_a_negative_that_rests_on_it_undetermined( + calls: list[dict[str, JsonValue] | None], expected: bool | None +) -> None: + requirement = _requirement(to=Equals(value="a@example.com"), body=Contains(value="invoice")) + + assert match_tool_requirement(requirement=requirement, calls=calls, kept=("to",)) is expected