From 826154b0bcabae35a7278bd42c870105bb7d8248 Mon Sep 17 00:00:00 2001 From: WatchTree-19 Date: Tue, 10 Nov 2026 14:35:24 +0000 Subject: [PATCH 1/4] FEAT: Score the relative order of tool calls from trace evidence Add a ToolsCalledInOrder condition and OtelToolCallOrderScorer, a separate leaf that reads the same trace source and stored tool events as OtelToolCallScorer. A tool counts as earlier only when one of its execution spans ended strictly before a span of the next listed tool started, beyond an optional clock_skew_tolerance. Overlapping, unfinished or near-simultaneous spans give no order, so they stay undetermined. An observed order stands on partial evidence; a negative needs complete coverage, and unlinked requests still turn a negative into undetermined. Stored observations replay offline against new orders. --- doc/code/framework.md | 4 +- doc/code/scoring/5_tool_call_scorer.ipynb | 110 ++++++- doc/code/scoring/5_tool_call_scorer.py | 76 ++++- pyrit/models/__init__.py | 2 + pyrit/models/score/__init__.py | 2 + pyrit/models/score/condition.py | 32 ++ pyrit/score/__init__.py | 3 +- .../score/true_false/otel_tool_call_scorer.py | 158 ++++++++- tests/unit/models/test_condition.py | 18 + .../score/test_otel_tool_call_order_scorer.py | 307 ++++++++++++++++++ 10 files changed, 700 insertions(+), 12 deletions(-) create mode 100644 tests/unit/score/test_otel_tool_call_order_scorer.py diff --git a/doc/code/framework.md b/doc/code/framework.md index 68e4d5aac4..6f6e9c34dc 100644 --- a/doc/code/framework.md +++ b/doc/code/framework.md @@ -299,7 +299,9 @@ If you are contributing to PyRIT, that work will most likely land in one of the - Trace sources acquire and normalize execution evidence for `TraceScorable` IDs through an injected `TraceClient`. `OtelToolCallScorer` matches tool names against the saved snapshot; incomplete absence is - undetermined, not false. For a `MessageScorable`, the scoring layer resolves + undetermined, not false. `OtelToolCallOrderScorer` matches their relative order + in the same snapshot; overlapping spans give no order. + For a `MessageScorable`, the scoring layer resolves outbound request trace links, regardless of chat role, through the scored response. Attacks pass message evidence and route expectations according to scorer support. - Surface sources read what a location holds for a `SurfaceScorable`, such as files under one diff --git a/doc/code/scoring/5_tool_call_scorer.ipynb b/doc/code/scoring/5_tool_call_scorer.ipynb index 012ea178ae..ef9f63f9d1 100644 --- a/doc/code/scoring/5_tool_call_scorer.ipynb +++ b/doc/code/scoring/5_tool_call_scorer.ipynb @@ -10,7 +10,8 @@ "`OtelToolCallScorer` answers \"Did these tools run?\" It matches exact,\n", "case-sensitive names in execution spans, not claims in a response or\n", "model-proposed calls. A failed execution attempt counts; the scorer does not\n", - "check tool success, arguments, order, or call count.\n", + "check tool success, arguments, or call count. `OtelToolCallOrderScorer`, shown\n", + "below, checks the order of tool calls from the same evidence.\n", "\n", "The example tool is named **`my_tool_call`**, implemented by the `my_tool_call()` function\n", "below. Its span records `\"gen_ai.tool.name\": \"my_tool_call\"`.\n", @@ -206,6 +207,101 @@ "cell_type": "markdown", "id": "8", "metadata": {}, + "source": [ + "## Check the order of tool calls\n", + "\n", + "`OtelToolCallOrderScorer` matches a `ToolsCalledInOrder` condition against the\n", + "same trace evidence. Each listed tool needs an execution span that ended before\n", + "a span of the next listed tool started. Other tools may run in between.\n", + "\n", + "Order comes from span timestamps. Overlapping or unfinished spans give no order,\n", + "so they produce an undetermined score rather than false. A negative still needs\n", + "complete capture. When spans come from different clocks, pass\n", + "`clock_skew_tolerance` to treat spans that are closer than that as unordered.\n", + "\n", + "This example records spans with explicit timestamps so the result does not depend\n", + "on clock resolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "read_file before send_email: True\n", + "send_email before read_file: False\n", + "Overlapping spans: undetermined\n" + ] + } + ], + "source": [ + "import time\n", + "\n", + "from pyrit.models import ToolsCalledInOrder\n", + "from pyrit.score import OtelToolCallOrderScorer\n", + "\n", + "client = InMemoryTraceClient()\n", + "provider = TracerProvider(sampler=ALWAYS_ON, span_limits=SpanLimits(max_span_attribute_length=SpanLimits.UNSET))\n", + "provider.add_span_processor(SimpleSpanProcessor(InMemoryTraceExporter(trace_client=client)))\n", + "tracer = provider.get_tracer(\"pyrit-tool-order-example\")\n", + "order_scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client))\n", + "\n", + "\n", + "def expects_order(*names: str) -> ScoringExpectation:\n", + " \"\"\"Build an ordering condition over exact tool names.\"\"\"\n", + " return ScoringExpectation(\n", + " conditions=(ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)),)\n", + " )\n", + "\n", + "\n", + "def record_agent_run(*spans: tuple[str, int, int]) -> TraceScorable:\n", + " \"\"\"Record one agent trace whose tool spans have explicit start and end offsets in milliseconds.\"\"\"\n", + " base = time.time_ns()\n", + " with tracer.start_as_current_span(\"agent\", context=Context()) as root:\n", + " for name, start_ms, end_ms in spans:\n", + " span = tracer.start_span(\n", + " name,\n", + " start_time=base + start_ms * 1_000_000,\n", + " attributes={\"gen_ai.operation.name\": \"execute_tool\", \"gen_ai.tool.name\": name},\n", + " )\n", + " span.end(end_time=base + end_ms * 1_000_000)\n", + " trace_id = f\"{root.get_span_context().trace_id:032x}\"\n", + " return TraceScorable(trace_ids=(trace_id,))\n", + "\n", + "\n", + "sequential = record_agent_run((\"read_file\", 0, 1), (\"send_email\", 2, 3))\n", + "concurrent = record_agent_run((\"read_file\", 0, 2), (\"send_email\", 1, 3))\n", + "assert await asyncio.to_thread(provider.force_flush) # type: ignore\n", + "client.mark_complete(trace_ids=(*sequential.trace_ids, *concurrent.trace_ids))\n", + "\n", + "in_order = (\n", + " await order_scorer.score_async(scorable=sequential, expectation=expects_order(\"read_file\", \"send_email\")) # type: ignore\n", + ")[0]\n", + "reversed_order = (\n", + " await order_scorer.score_async(scorable=sequential, expectation=expects_order(\"send_email\", \"read_file\")) # type: ignore\n", + ")[0]\n", + "overlapping = (\n", + " await order_scorer.score_async(scorable=concurrent, expectation=expects_order(\"read_file\", \"send_email\")) # type: ignore\n", + ")[0]\n", + "assert in_order.get_value() is True\n", + "assert reversed_order.get_value() is False\n", + "assert overlapping.status is ScoreStatus.UNDETERMINED\n", + "print(f\"read_file before send_email: {in_order.get_value()}\")\n", + "print(f\"send_email before read_file: {reversed_order.get_value()}\")\n", + "print(f\"Overlapping spans: {overlapping.status.value}\")\n", + "await asyncio.to_thread(provider.shutdown) # type: ignore\n", + "client.close()" + ] + }, + { + "cell_type": "markdown", + "id": "10", + "metadata": {}, "source": [ "## Score a tool call through an attack\n", "\n", @@ -228,7 +324,7 @@ { "cell_type": "code", "execution_count": null, - "id": "9", + "id": "11", "metadata": {}, "outputs": [ { @@ -301,7 +397,7 @@ }, { "cell_type": "markdown", - "id": "10", + "id": "12", "metadata": {}, "source": [ "A composite receives the same message reference in each child. The message\n", @@ -313,7 +409,7 @@ { "cell_type": "code", "execution_count": null, - "id": "11", + "id": "13", "metadata": {}, "outputs": [ { @@ -353,7 +449,7 @@ }, { "cell_type": "markdown", - "id": "12", + "id": "14", "metadata": {}, "source": [ "## Configure tracing\n", @@ -382,7 +478,7 @@ }, { "cell_type": "markdown", - "id": "13", + "id": "15", "metadata": {}, "source": [ "## Use another trace source\n", @@ -404,7 +500,7 @@ }, { "cell_type": "markdown", - "id": "14", + "id": "16", "metadata": {}, "source": [ "## Score tool calls without traces\n", diff --git a/doc/code/scoring/5_tool_call_scorer.py b/doc/code/scoring/5_tool_call_scorer.py index 298ab51dc3..4085b2924c 100644 --- a/doc/code/scoring/5_tool_call_scorer.py +++ b/doc/code/scoring/5_tool_call_scorer.py @@ -14,7 +14,8 @@ # `OtelToolCallScorer` answers "Did these tools run?" It matches exact, # case-sensitive names in execution spans, not claims in a response or # model-proposed calls. A failed execution attempt counts; the scorer does not -# check tool success, arguments, order, or call count. +# check tool success, arguments, or call count. `OtelToolCallOrderScorer`, shown +# below, checks the order of tool calls from the same evidence. # # The example tool is named **`my_tool_call`**, implemented by the `my_tool_call()` function # below. Its span records `"gen_ai.tool.name": "my_tool_call"`. @@ -138,6 +139,79 @@ def my_tool_call() -> str: ].model_dump_json() == before_replay print(f"my_tool_call in saved evidence after capture is closed: {replayed.get_value()}") +# %% [markdown] +# ## Check the order of tool calls +# +# `OtelToolCallOrderScorer` matches a `ToolsCalledInOrder` condition against the +# same trace evidence. Each listed tool needs an execution span that ended before +# a span of the next listed tool started. Other tools may run in between. +# +# Order comes from span timestamps. Overlapping or unfinished spans give no order, +# so they produce an undetermined score rather than false. A negative still needs +# complete capture. When spans come from different clocks, pass +# `clock_skew_tolerance` to treat spans that are closer than that as unordered. +# +# This example records spans with explicit timestamps so the result does not depend +# on clock resolution. + +# %% +import time + +from pyrit.models import ToolsCalledInOrder +from pyrit.score import OtelToolCallOrderScorer + +client = InMemoryTraceClient() +provider = TracerProvider(sampler=ALWAYS_ON, span_limits=SpanLimits(max_span_attribute_length=SpanLimits.UNSET)) +provider.add_span_processor(SimpleSpanProcessor(InMemoryTraceExporter(trace_client=client))) +tracer = provider.get_tracer("pyrit-tool-order-example") +order_scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client)) + + +def expects_order(*names: str) -> ScoringExpectation: + """Build an ordering condition over exact tool names.""" + return ScoringExpectation( + conditions=(ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)),) + ) + + +def record_agent_run(*spans: tuple[str, int, int]) -> TraceScorable: + """Record one agent trace whose tool spans have explicit start and end offsets in milliseconds.""" + base = time.time_ns() + with tracer.start_as_current_span("agent", context=Context()) as root: + for name, start_ms, end_ms in spans: + span = tracer.start_span( + name, + start_time=base + start_ms * 1_000_000, + attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name}, + ) + span.end(end_time=base + end_ms * 1_000_000) + trace_id = f"{root.get_span_context().trace_id:032x}" + return TraceScorable(trace_ids=(trace_id,)) + + +sequential = record_agent_run(("read_file", 0, 1), ("send_email", 2, 3)) +concurrent = record_agent_run(("read_file", 0, 2), ("send_email", 1, 3)) +assert await asyncio.to_thread(provider.force_flush) # type: ignore +client.mark_complete(trace_ids=(*sequential.trace_ids, *concurrent.trace_ids)) + +in_order = ( + await order_scorer.score_async(scorable=sequential, expectation=expects_order("read_file", "send_email")) # type: ignore +)[0] +reversed_order = ( + await order_scorer.score_async(scorable=sequential, expectation=expects_order("send_email", "read_file")) # type: ignore +)[0] +overlapping = ( + await order_scorer.score_async(scorable=concurrent, expectation=expects_order("read_file", "send_email")) # type: ignore +)[0] +assert in_order.get_value() is True +assert reversed_order.get_value() is False +assert overlapping.status is ScoreStatus.UNDETERMINED +print(f"read_file before send_email: {in_order.get_value()}") +print(f"send_email before read_file: {reversed_order.get_value()}") +print(f"Overlapping spans: {overlapping.status.value}") +await asyncio.to_thread(provider.shutdown) # type: ignore +client.close() + # %% [markdown] # ## Score a tool call through an attack # diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index 31d258f386..b4767fb1b0 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -260,6 +260,7 @@ ToolEventsObservationPayload, ToolExecution, ToolsCalled, + ToolsCalledInOrder, TraceCoverage, TraceQuery, TraceQueryResult, @@ -523,6 +524,7 @@ "ToolEventsObservationPayload": "pyrit.models.score", "ToolExecution": "pyrit.models.score", "ToolsCalled": "pyrit.models.score", + "ToolsCalledInOrder": "pyrit.models.score", "TraceCoverage": "pyrit.models.score", "TraceQuery": "pyrit.models.score", "TraceQueryResult": "pyrit.models.score", diff --git a/pyrit/models/score/__init__.py b/pyrit/models/score/__init__.py index 44baf4d0e0..41645735d0 100644 --- a/pyrit/models/score/__init__.py +++ b/pyrit/models/score/__init__.py @@ -27,6 +27,7 @@ ProgramResult, ToolCallRequirement, ToolsCalled, + ToolsCalledInOrder, ) from pyrit.models.score.expectation import ( ScoringExpectation, @@ -115,6 +116,7 @@ "ToolEventsObservationPayload": "pyrit.models.score.observation", "ToolExecution": "pyrit.models.score.trace", "ToolsCalled": "pyrit.models.score.condition", + "ToolsCalledInOrder": "pyrit.models.score.condition", "TraceCoverage": "pyrit.models.score.trace", "TraceQuery": "pyrit.models.score.trace", "TraceQueryResult": "pyrit.models.score.trace", diff --git a/pyrit/models/score/condition.py b/pyrit/models/score/condition.py index af92d35f7c..db2bbdde9e 100644 --- a/pyrit/models/score/condition.py +++ b/pyrit/models/score/condition.py @@ -199,6 +199,38 @@ def _validate_tools(self) -> ToolsCalled: return self +class ToolsCalledInOrder(Condition): + """ + Require the named tools to have execution attempts in this relative order. + + Each listed tool needs an execution attempt that finished before an execution attempt of + the next listed tool started. Other tools, and further attempts of the listed tools, may run + in between. Success is not required. Overlapping or unfinished attempts do not establish an + order in either direction. + """ + + condition_type: Literal["tools_called_in_order"] = "tools_called_in_order" + tools: tuple[ToolCallRequirement, ...] + + @model_validator(mode="after") + def _validate_tools(self) -> ToolsCalledInOrder: + """ + Require at least two distinct exact names. + + Returns: + ToolsCalledInOrder: The validated condition. + + Raises: + ValueError: If fewer than two tools are named or an exact name repeats. + """ + if len(self.tools) < 2: + raise ValueError("ToolsCalledInOrder requires at least two tools; use ToolsCalled for one.") + names = [tool.name for tool in self.tools] + if len(set(names)) != len(names): + raise ValueError("ToolsCalledInOrder requires each tool name once.") + return self + + class OutputMatches(Condition): """The output satisfies the supplied text matcher.""" diff --git a/pyrit/score/__init__.py b/pyrit/score/__init__.py index 942ae22bd2..5fc5daa28e 100644 --- a/pyrit/score/__init__.py +++ b/pyrit/score/__init__.py @@ -110,7 +110,7 @@ MessageMultiLabelTrueFalseScorer, MultiLabelTrueFalseScorer, ) - from pyrit.score.true_false.otel_tool_call_scorer import OtelToolCallScorer + from pyrit.score.true_false.otel_tool_call_scorer import OtelToolCallOrderScorer, OtelToolCallScorer from pyrit.score.true_false.output_matches_scorer import OutputMatchesScorer from pyrit.score.true_false.program_execution_scorer import ProgramExecutionScorer from pyrit.score.true_false.prompt_shield_scorer import PromptShieldScorer @@ -230,6 +230,7 @@ "ObservationSource": "pyrit.score.observation.observation_source", "OtelTraceSource": "pyrit.score.observation.otel_trace_source", "OtelToolCallScorer": "pyrit.score.true_false.otel_tool_call_scorer", + "OtelToolCallOrderScorer": "pyrit.score.true_false.otel_tool_call_scorer", "TraceAcquisitionError": "pyrit.score.observation.trace_client", "TraceClient": "pyrit.score.observation.trace_client", "JsonSchemaResponseHandler": "pyrit.score.response_handler", diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 72d2556eb3..8a94fcb454 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -5,6 +5,8 @@ from __future__ import annotations +import math +from datetime import timedelta from typing import TYPE_CHECKING from pyrit.models import ( @@ -15,6 +17,7 @@ ScoreStatus, ToolEventsObservationPayload, ToolsCalled, + ToolsCalledInOrder, TraceScorable, ) from pyrit.score.observation.execution import NonReplayableObservationError, _collect_observation @@ -22,7 +25,9 @@ from pyrit.score.true_false.true_false_scorer import TrueFalseScorer if TYPE_CHECKING: - from pyrit.models import ComponentIdentifier, Scorable, ScoringExpectation + from collections.abc import Sequence + + from pyrit.models import ComponentIdentifier, Scorable, ScoringExpectation, ToolExecution from pyrit.score.observation.execution import _ObservationEvidence from pyrit.score.observation.observation_source import ObservationSource @@ -49,6 +54,81 @@ def match_tools_called( return False if acquisition is Acquisition.COMPLETE and payload.coverage.complete else None +def _definitely_precedes(*, first: ToolExecution, second: ToolExecution, tolerance: timedelta) -> bool: + """ + Check whether ``first`` finished before ``second`` started, by more than the clock tolerance. + + Returns: + bool: True only for a finished attempt that ends strictly before the other starts. + """ + return first.end_time is not None and first.end_time + tolerance < second.start_time + + +def _ordered_chain_exists(*, runs: Sequence[Sequence[ToolExecution]], tolerance: timedelta, definite: bool) -> bool: + """ + Search for one attempt per tool that respects the required order. + + With ``definite``, every adjacent pair must be ordered beyond doubt. Otherwise a pair only + must not be ordered the wrong way beyond doubt, so overlapping attempts remain possible. + + Returns: + bool: Whether such a chain of attempts exists. + """ + previous: ToolExecution | None = None + for index, attempts in enumerate(runs): + if previous is None: + candidates = list(attempts) + elif definite: + candidates = [ + run for run in attempts if _definitely_precedes(first=previous, second=run, tolerance=tolerance) + ] + else: + candidates = [ + run for run in attempts if not _definitely_precedes(first=run, second=previous, tolerance=tolerance) + ] + if definite and index < len(runs) - 1: + # The next tool must start after this attempt ends, so the earliest finished end is best. + candidates = [run for run in candidates if run.end_time is not None] + if not candidates: + return False + previous = min(candidates, key=lambda run: run.end_time or run.start_time) + else: + # The next tool must not end before this attempt starts, so the earliest start is best. + if not candidates: + return False + previous = min(candidates, key=lambda run: run.start_time) + return True + + +def match_tools_called_in_order( + *, + condition: ToolsCalledInOrder, + payload: ToolEventsObservationPayload, + acquisition: Acquisition, + clock_skew_tolerance: timedelta = timedelta(0), +) -> bool | None: + """ + Match the relative order of execution attempts without I/O, preserving unknown order. + + An order is observed only when one attempt ends before the next tool's attempt starts, by + more than ``clock_skew_tolerance``. Overlapping, unfinished, or near-simultaneous attempts + establish no order. An observed order stands with partial evidence. A negative needs + complete evidence in which every candidate order is contradicted or a tool never ran. + + Returns: + bool | None: True for an observed order, false for a complete contradiction, otherwise None. + """ + if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): + return None + runs = [[event for event in payload.events if event.name == tool.name] for tool in condition.tools] + if _ordered_chain_exists(runs=runs, tolerance=clock_skew_tolerance, definite=True): + return True + if acquisition is not Acquisition.COMPLETE or not payload.coverage.complete: + return None + # A tool that never ran leaves no possible order, so complete evidence of its absence is false. + return None if _ordered_chain_exists(runs=runs, tolerance=clock_skew_tolerance, definite=False) else False + + class OtelToolCallScorer(TrueFalseScorer): """Score actual tool invocations, not requested calls or response claims.""" @@ -68,7 +148,7 @@ def _build_identifier(self) -> ComponentIdentifier: async def _score_scorable_async(self, *, scorable: Scorable, expectation: ScoringExpectation | None) -> list[Score]: if not isinstance(scorable, (MessageScorable, TraceScorable)): - raise TypeError("OtelToolCallScorer requires a MessageScorable or an explicit TraceScorable.") + raise TypeError(f"{type(self).__name__} requires a MessageScorable or an explicit TraceScorable.") scope, correlation_complete = ( await resolve_message_trace_scope_async(scorable=scorable, memory=self._memory) if isinstance(scorable, MessageScorable) @@ -129,3 +209,77 @@ def _score_observation( observation_ids=[observation.id], ) ] + + +class OtelToolCallOrderScorer(OtelToolCallScorer): + """ + Score the relative order of actual tool invocations from the same evidence as ``OtelToolCallScorer``. + + The order comes from span timestamps. ``clock_skew_tolerance`` widens the band in which two + attempts are treated as unordered, for traces whose spans come from different clocks. + """ + + CONDITION_TYPE = ToolsCalledInOrder + + def __init__( + self, *, source: ObservationSource[TraceScorable], clock_skew_tolerance: timedelta = timedelta(0) + ) -> None: + """ + Initialize with a caller-configured trace source and a clock tolerance. + + Raises: + ValueError: If the tolerance is negative or not finite. + """ + seconds = clock_skew_tolerance.total_seconds() + if seconds < 0 or not math.isfinite(seconds): + raise ValueError("clock_skew_tolerance must not be negative.") + self._clock_skew_tolerance = clock_skew_tolerance + super().__init__(source=source) + + def _build_identifier(self) -> ComponentIdentifier: + return self._create_identifier( + params={ + "matching_version": 1, + "message_scope_version": 2, + "clock_skew_tolerance_seconds": self._clock_skew_tolerance.total_seconds(), + }, + children={"source": self._source.get_identifier()}, + ) + + def _score_observation( + self, + *, + observation: Observation, + evidence: _ObservationEvidence, + expectation: ScoringExpectation | None, + ) -> list[Score]: + if not isinstance(evidence, ToolEventsObservationPayload): + raise NonReplayableObservationError("Tool-order scoring requires a stored tool-event observation.") + condition = self._get_required_condition(expectation=expectation, condition_type=ToolsCalledInOrder) + value = match_tools_called_in_order( + condition=condition, + payload=evidence, + acquisition=observation.acquisition, + clock_skew_tolerance=self._clock_skew_tolerance, + ) + names = " -> ".join(tool.name for tool in condition.tools) + rationale = ( + f"Observed execution of the required tools in order: {names}." + if value is True + else f"Complete trace evidence contradicts the required tool order: {names}." + if value is False + else f"Trace evidence cannot establish the required tool order: {names}." + ) + return [ + Score( + score_value=None if value is None else str(value).lower(), + status=ScoreStatus.UNDETERMINED if value is None else ScoreStatus.COMPLETE, + score_type="true_false", + score_rationale=rationale, + score_value_description="Tool invocation order; successful completion is not required.", + scorer_class_identifier=self.get_identifier(), + scorable=observation.scorable, + message_piece_id=self._piece_id_from_scorable(observation.scorable), + observation_ids=[observation.id], + ) + ] diff --git a/tests/unit/models/test_condition.py b/tests/unit/models/test_condition.py index e4683dbf91..49bcd39ac1 100644 --- a/tests/unit/models/test_condition.py +++ b/tests/unit/models/test_condition.py @@ -14,6 +14,7 @@ ToolCall, ToolCallRequirement, ToolsCalled, + ToolsCalledInOrder, scoring_expectation_fingerprint, ) from pyrit.models import ToolCall as MessageToolCall @@ -197,3 +198,20 @@ def test_diverges_from_repetition_registered_without_scorer_import() -> None: def test_diverges_from_repetition_requires_string_text(value: dict[str, object]) -> None: with pytest.raises(ValidationError): DivergesFromRepetition.model_validate(value) + + +def test_tools_called_in_order_round_trip_retains_order() -> None: + condition = ToolsCalledInOrder(tools=(ToolCallRequirement(name="send"), ToolCallRequirement(name="read"))) + expectation = ScoringExpectation(conditions=(condition,)) + + assert Condition.model_validate(condition.model_dump(mode="json")) == condition + assert ScoringExpectation.model_validate_persisted(expectation.model_dump(mode="json")) == expectation + assert [tool.name for tool in condition.tools] == ["send", "read"] + assert _CONDITION_TYPES["tools_called_in_order"] is ToolsCalledInOrder + assert condition != ToolsCalledInOrder(tools=tuple(reversed(condition.tools))) + + +@pytest.mark.parametrize("names", [[], ["lookup"], ["lookup", "send", "lookup"]]) +def test_tools_called_in_order_requires_two_unique_names(names: list[str]) -> None: + with pytest.raises(ValidationError, match="at least two tools|each tool name once"): + ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)) diff --git a/tests/unit/score/test_otel_tool_call_order_scorer.py b/tests/unit/score/test_otel_tool_call_order_scorer.py new file mode 100644 index 0000000000..4cbccf7f22 --- /dev/null +++ b/tests/unit/score/test_otel_tool_call_order_scorer.py @@ -0,0 +1,307 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import uuid +from datetime import UTC, datetime, timedelta +from unittest.mock import AsyncMock, patch + +import pytest + +from pyrit.memory import SQLiteMemory +from pyrit.models import ( + Acquisition, + Message, + MessagePiece, + MessageScorable, + RequestTraceContext, + ScoringExpectation, + ToolCallRequirement, + ToolEventsObservationPayload, + ToolExecution, + ToolsCalled, + ToolsCalledInOrder, + TraceCoverage, + TraceScorable, + TraceSpan, +) +from pyrit.score import ( + InMemoryTraceClient, + OtelToolCallOrderScorer, + OtelToolCallScorer, + OtelTraceSource, + TrueFalseCompositeScorer, + TrueFalseScoreAggregator, +) +from pyrit.score.true_false.otel_tool_call_scorer import match_tools_called_in_order + +pytestmark = pytest.mark.usefixtures("patch_central_database") + +_TRACE = "1" * 32 +_EPOCH = datetime(2026, 1, 1, tzinfo=UTC) + + +def _at(seconds: float) -> datetime: + return _EPOCH + timedelta(seconds=seconds) + + +def _execution(name: str, start: float, end: float | None, index: int) -> ToolExecution: + return ToolExecution( + name=name, + trace_id=_TRACE, + span_id=f"{index + 1:016x}", + start_time=_at(start), + end_time=None if end is None else _at(end), + ) + + +def _span(name: str, start: float, end: float | None, index: int) -> TraceSpan: + return TraceSpan( + trace_id=_TRACE, + span_id=f"{index + 1:016x}", + start_time=_at(start), + end_time=None if end is None else _at(end), + attributes={"gen_ai.operation.name": "execute_tool", "gen_ai.tool.name": name}, + ) + + +def _payload(*runs: tuple[str, float, float | None], complete: bool) -> ToolEventsObservationPayload: + return ToolEventsObservationPayload( + scope=TraceScorable(trace_ids=(_TRACE,)), + events=tuple(_execution(name, start, end, index) for index, (name, start, end) in enumerate(runs)), + coverage=TraceCoverage(complete=complete, reasons=() if complete else ("capture_not_complete",)), + ) + + +def _order(*names: str) -> ToolsCalledInOrder: + return ToolsCalledInOrder(tools=tuple(ToolCallRequirement(name=name) for name in names)) + + +def _expectation(*names: str) -> ScoringExpectation: + return ScoringExpectation(conditions=(_order(*names),)) + + +def _match(*runs: tuple[str, float, float | None], complete: bool, tolerance: float = 0) -> bool | None: + return match_tools_called_in_order( + condition=_order("read", "send"), + payload=_payload(*runs, complete=complete), + acquisition=Acquisition.COMPLETE if complete else Acquisition.PARTIAL, + clock_skew_tolerance=timedelta(seconds=tolerance), + ) + + +@pytest.mark.parametrize( + ("runs", "complete", "expected"), + [ + # Sequential in the required order: conclusive even with partial evidence. + ((("read", 0, 1), ("send", 2, 3)), True, True), + ((("read", 0, 1), ("send", 2, 3)), False, True), + # Sequential the other way round: false only with complete evidence. + ((("send", 0, 1), ("read", 2, 3)), True, False), + ((("send", 0, 1), ("read", 2, 3)), False, None), + # Concurrent attempts establish no order in either direction. + ((("read", 0, 2), ("send", 1, 3)), True, None), + ((("send", 0, 2), ("read", 1, 3)), True, None), + # Equal timestamps are not an order. + ((("read", 1, 1), ("send", 1, 1)), True, None), + ((("read", 0, 1), ("send", 1, 2)), True, None), + # A missing tool is false only with complete evidence. + ((("read", 0, 1),), True, False), + ((("read", 0, 1),), False, None), + ((), True, False), + # An unfinished attempt cannot precede anything. + ((("read", 0, None), ("send", 2, 3)), False, None), + ((("read", 0, None), ("read", 1, 2), ("send", 3, 4)), False, True), + # Other tools and repeated attempts may run in between. + ((("send", 0, 1), ("read", 2, 3), ("lookup", 4, 5), ("send", 6, 7)), True, True), + ((("send", 0, 1), ("send", 2, 3), ("read", 4, 5)), True, False), + ], +) +def test_order_is_matched_from_trusted_intervals_only( + runs: tuple[tuple[str, float, float | None], ...], complete: bool, expected: bool | None +) -> None: + assert _match(*runs, complete=complete) is expected + + +def test_chain_uses_the_earliest_finishing_attempt() -> None: + payload = _payload(("read", 0, 10), ("read", 1, 2), ("send", 3, 4), ("summarize", 11, 12), complete=True) + condition = _order("read", "send", "summarize") + + assert match_tools_called_in_order(condition=condition, payload=payload, acquisition=Acquisition.COMPLETE) is True + + +def test_possible_order_uses_the_earliest_starting_attempt() -> None: + # send(4-5) can only follow read(3-6) by overlap, so the order is unknown, not false. + payload = _payload(("read", 7, 8), ("read", 3, 6), ("send", 4, 5), complete=True) + + assert ( + match_tools_called_in_order(condition=_order("read", "send"), payload=payload, acquisition=Acquisition.COMPLETE) + is None + ) + + +@pytest.mark.parametrize( + ("runs", "tolerance", "expected"), + [ + ((("read", 0, 1), ("send", 1.5, 2)), 0, True), + ((("read", 0, 1), ("send", 1.5, 2)), 1, None), + ((("read", 0, 1), ("send", 2.5, 3)), 1, True), + ((("send", 0, 1), ("read", 1.5, 2)), 0, False), + ((("send", 0, 1), ("read", 1.5, 2)), 1, None), + ], +) +def test_clock_skew_tolerance_widens_the_unordered_band( + runs: tuple[tuple[str, float, float | None], ...], tolerance: float, expected: bool | None +) -> None: + assert _match(*runs, complete=True, tolerance=tolerance) is expected + + +@pytest.mark.parametrize("acquisition", [Acquisition.ERROR, Acquisition.UNAVAILABLE]) +def test_failed_or_unavailable_acquisition_is_never_a_verdict(acquisition: Acquisition) -> None: + payload = _payload(("read", 0, 1), ("send", 2, 3), complete=False) + + assert ( + match_tools_called_in_order(condition=_order("read", "send"), payload=payload, acquisition=acquisition) is None + ) + + +def test_scorer_identifier_records_tolerance_and_source() -> None: + source = OtelTraceSource(trace_client=InMemoryTraceClient()) + identifier = OtelToolCallOrderScorer(source=source).get_identifier() + skewed = OtelToolCallOrderScorer(source=source, clock_skew_tolerance=timedelta(milliseconds=5)).get_identifier() + + assert identifier.children["source"] == source.get_identifier() + assert identifier.params["clock_skew_tolerance_seconds"] == 0 + assert skewed.params["clock_skew_tolerance_seconds"] == 0.005 + assert len({identifier.hash, skewed.hash, OtelToolCallScorer(source=source).get_identifier().hash}) == 3 + + +@pytest.mark.parametrize("tolerance", [timedelta(seconds=-1), timedelta(microseconds=-1)]) +def test_negative_tolerance_is_rejected(tolerance: timedelta) -> None: + with pytest.raises(ValueError, match="must not be negative"): + OtelToolCallOrderScorer( + source=OtelTraceSource(trace_client=InMemoryTraceClient()), clock_skew_tolerance=tolerance + ) + + +def test_scorer_declares_only_the_order_condition() -> None: + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=InMemoryTraceClient())) + + assert scorer.get_condition_types() == frozenset({ToolsCalledInOrder}) + assert scorer.get_supported_scorable_types() == frozenset({MessageScorable, TraceScorable}) + + +async def test_order_verdict_and_offline_replay_async(sqlite_instance: SQLiteMemory) -> None: + client = InMemoryTraceClient() + client.add_span(_span("read", 0, 1, 0)) + client.add_span(_span("send", 2, 3, 1)) + scope = TraceScorable(trace_ids=(_TRACE,)) + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client)) + + pending = (await scorer.score_async(scorable=scope, expectation=_expectation("send", "read")))[0] + assert pending.is_undetermined + client.mark_complete(trace_ids=scope.trace_ids) + positive = (await scorer.score_async(scorable=scope, expectation=_expectation("read", "send")))[0] + negative = (await scorer.score_async(scorable=scope, expectation=_expectation("send", "read")))[0] + assert positive.get_value() is True + assert negative.get_value() is False + assert "read -> send" in positive.score_rationale + + observation = (await sqlite_instance.get_observations_async(observation_ids=negative.observation_ids))[0] + assert observation.acquisition is Acquisition.COMPLETE + client.close() + with patch.object(client, "get_spans_async", new_callable=AsyncMock) as query: + query.side_effect = AssertionError("Replay must not query a trace client.") + replay = ( + await scorer.score_observation_async(observation=observation, expectation=_expectation("read", "send")) + )[0] + query.assert_not_called() + assert replay.get_value() is True + assert replay.observation_ids == negative.observation_ids + + +async def test_concurrent_attempts_stay_undetermined_with_complete_capture_async() -> None: + client = InMemoryTraceClient() + client.add_span(_span("read", 0, 2, 0)) + client.add_span(_span("send", 1, 3, 1)) + client.mark_complete(trace_ids=(_TRACE,)) + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client)) + + score = ( + await scorer.score_async(scorable=TraceScorable(trace_ids=(_TRACE,)), expectation=_expectation("read", "send")) + )[0] + + assert score.is_undetermined + assert "cannot establish" in score.score_rationale + + +async def test_unlinked_request_prevents_a_false_order_async(sqlite_instance: SQLiteMemory) -> None: + conversation = str(uuid.uuid4()) + unlinked = MessagePiece(role="user", original_value="content", conversation_id=conversation) + linked = MessagePiece(role="user", original_value="content", conversation_id=conversation) + linked.prompt_metadata.update(RequestTraceContext(traceparent=f"00-{_TRACE}-{'2' * 16}-01").to_metadata()) + for piece in ( + unlinked, + MessagePiece(role="assistant", original_value="content", conversation_id=conversation), + linked, + ): + (await sqlite_instance.add_message_to_memory_async(request=piece.to_message())) + response: Message = MessagePiece( + role="assistant", original_value="content", conversation_id=conversation + ).to_message() + (await sqlite_instance.add_message_to_memory_async(request=response)) + client = InMemoryTraceClient() + client.add_span(_span("send", 0, 1, 0)) + client.add_span(_span("read", 2, 3, 1)) + client.mark_complete(trace_ids=(_TRACE,)) + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client)) + + score = ( + await scorer.score_async( + scorable=MessageScorable.from_message(response), expectation=_expectation("read", "send") + ) + )[0] + + assert score.is_undetermined + observation = (await sqlite_instance.get_observations_async(observation_ids=score.observation_ids))[0] + assert observation.acquisition is Acquisition.COMPLETE + + +async def test_composite_routes_presence_and_order_to_separate_leaves_async() -> None: + client = InMemoryTraceClient() + client.add_span(_span("send", 0, 1, 0)) + client.add_span(_span("read", 2, 3, 1)) + client.mark_complete(trace_ids=(_TRACE,)) + source = OtelTraceSource(trace_client=client) + composite = TrueFalseCompositeScorer( + aggregator=TrueFalseScoreAggregator.AND, + scorers=[OtelToolCallScorer(source=source), OtelToolCallOrderScorer(source=source)], + ) + presence = ToolsCalled(tools=(ToolCallRequirement(name="read"), ToolCallRequirement(name="send"))) + expectation = ScoringExpectation(conditions=(presence, _order("read", "send"))) + + score = (await composite.score_async(scorable=TraceScorable(trace_ids=(_TRACE,)), expectation=expectation))[0] + + assert composite.get_condition_types() == frozenset({ToolsCalled, ToolsCalledInOrder}) + assert score.get_value() is False + + +async def test_presence_condition_alone_is_rejected_async() -> None: + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=InMemoryTraceClient())) + presence = ScoringExpectation(conditions=(ToolsCalled(tools=(ToolCallRequirement(name="read"),)),)) + + with pytest.raises(ValueError): + await scorer.score_async(scorable=TraceScorable(trace_ids=(_TRACE,)), expectation=presence) + + +async def test_scorer_applies_its_clock_skew_tolerance_async() -> None: + client = InMemoryTraceClient() + client.add_span(_span("send", 0, 1, 0)) + client.add_span(_span("read", 1.5, 2, 1)) + client.mark_complete(trace_ids=(_TRACE,)) + source = OtelTraceSource(trace_client=client) + scope = TraceScorable(trace_ids=(_TRACE,)) + strict = OtelToolCallOrderScorer(source=source) + tolerant = OtelToolCallOrderScorer(source=source, clock_skew_tolerance=timedelta(seconds=1)) + + assert (await strict.score_async(scorable=scope, expectation=_expectation("read", "send")))[0].get_value() is False + assert (await tolerant.score_async(scorable=scope, expectation=_expectation("read", "send")))[0].is_undetermined From c6fbbcdcd8ef5f9ddc260d8b2bec0e1a1b8242a0 Mon Sep 17 00:00:00 2001 From: WatchTree-19 Date: Wed, 11 Nov 2026 13:35:00 +0000 Subject: [PATCH 2/4] FIX: Check a possible tool order against every earlier tool A possible order only compared each attempt with the one chosen just before it. Overlap is not transitive, so with read(5-6), lookup(0-10) and send(1-2) every adjacent pair overlaps while send ended before read started. The order read, lookup, send cannot have happened, yet complete evidence scored it undetermined instead of false. Track the latest start among the attempts chosen so far and rule out an attempt that ends before it, beyond the clock tolerance. The definite order is unchanged: it is transitive already. --- .../score/true_false/otel_tool_call_scorer.py | 15 ++++++++-- .../score/test_otel_tool_call_order_scorer.py | 30 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 8a94fcb454..1e07741788 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -26,6 +26,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from datetime import datetime from pyrit.models import ComponentIdentifier, Scorable, ScoringExpectation, ToolExecution from pyrit.score.observation.execution import _ObservationEvidence @@ -68,13 +69,18 @@ def _ordered_chain_exists(*, runs: Sequence[Sequence[ToolExecution]], tolerance: """ Search for one attempt per tool that respects the required order. - With ``definite``, every adjacent pair must be ordered beyond doubt. Otherwise a pair only - must not be ordered the wrong way beyond doubt, so overlapping attempts remain possible. + With ``definite``, every adjacent pair must be ordered beyond doubt, which orders the whole + chain. Otherwise no pair in the chain, adjacent or not, may be ordered the wrong way beyond + doubt, so overlapping attempts remain possible. Returns: bool: Whether such a chain of attempts exists. """ previous: ToolExecution | None = None + # The latest start among the attempts chosen so far. Overlap is not transitive: an attempt can + # overlap both its neighbours while the first ends before the last starts, so a later attempt + # is checked against every earlier tool, not only the one just before it. + latest_start: datetime | None = None for index, attempts in enumerate(runs): if previous is None: candidates = list(attempts) @@ -84,7 +90,9 @@ def _ordered_chain_exists(*, runs: Sequence[Sequence[ToolExecution]], tolerance: ] else: candidates = [ - run for run in attempts if not _definitely_precedes(first=run, second=previous, tolerance=tolerance) + run + for run in attempts + if latest_start is None or run.end_time is None or run.end_time + tolerance >= latest_start ] if definite and index < len(runs) - 1: # The next tool must start after this attempt ends, so the earliest finished end is best. @@ -97,6 +105,7 @@ def _ordered_chain_exists(*, runs: Sequence[Sequence[ToolExecution]], tolerance: if not candidates: return False previous = min(candidates, key=lambda run: run.start_time) + latest_start = previous.start_time if latest_start is None else max(latest_start, previous.start_time) return True diff --git a/tests/unit/score/test_otel_tool_call_order_scorer.py b/tests/unit/score/test_otel_tool_call_order_scorer.py index 4cbccf7f22..691fb07dfb 100644 --- a/tests/unit/score/test_otel_tool_call_order_scorer.py +++ b/tests/unit/score/test_otel_tool_call_order_scorer.py @@ -139,6 +139,36 @@ def test_possible_order_uses_the_earliest_starting_attempt() -> None: ) +@pytest.mark.parametrize( + ("runs", "tolerance", "expected"), + [ + # lookup overlaps both neighbours, but send ended before read started, so read, lookup, + # send cannot have happened in that order. + ((("read", 5, 6), ("lookup", 0, 10), ("send", 1, 2)), 0, False), + # Within the clock tolerance the same gap is no longer a contradiction. + ((("read", 5, 6), ("lookup", 0, 10), ("send", 1, 2)), 3, None), + # All three overlap one another, so the order stays unknown. + ((("read", 0, 3), ("lookup", 1, 10), ("send", 2, 4)), 0, None), + # A later attempt of send that does not end before read starts keeps the order possible. + ((("read", 5, 6), ("lookup", 0, 10), ("send", 1, 2), ("send", 4, 7)), 0, None), + ], +) +def test_possible_order_checks_every_earlier_tool_not_only_the_neighbour( + runs: tuple[tuple[str, float, float | None], ...], tolerance: float, expected: bool | None +) -> None: + payload = _payload(*runs, complete=True) + + assert ( + match_tools_called_in_order( + condition=_order("read", "lookup", "send"), + payload=payload, + acquisition=Acquisition.COMPLETE, + clock_skew_tolerance=timedelta(seconds=tolerance), + ) + is expected + ) + + @pytest.mark.parametrize( ("runs", "tolerance", "expected"), [ From 6f4d6a78d7379d2fc613bf913f460e20263b950d Mon Sep 17 00:00:00 2001 From: WatchTree-19 Date: Fri, 13 Nov 2026 13:12:32 +0000 Subject: [PATCH 3/4] FIX: Address review on tool order scoring - Share _MESSAGE_SCOPE_VERSION between the presence and order identifiers so the two cannot drift apart. - Move the shared trace-evidence pipeline into a private abstract base, making OtelToolCallScorer and OtelToolCallOrderScorer siblings, so an isinstance check on one never matches the other. - Say in the ToolsCalledInOrder docstring that an order returning to a tool is out of scope, and why. - Reject a negative clock_skew_tolerance in match_tools_called_in_order as well as in the constructor. --- pyrit/models/score/condition.py | 4 ++ .../score/true_false/otel_tool_call_scorer.py | 60 +++++++++++++++---- .../score/test_otel_tool_call_order_scorer.py | 26 ++++++++ 3 files changed, 77 insertions(+), 13 deletions(-) diff --git a/pyrit/models/score/condition.py b/pyrit/models/score/condition.py index db2bbdde9e..0414a4ce66 100644 --- a/pyrit/models/score/condition.py +++ b/pyrit/models/score/condition.py @@ -207,6 +207,10 @@ class ToolsCalledInOrder(Condition): the next listed tool started. Other tools, and further attempts of the listed tools, may run in between. Success is not required. Overlapping or unfinished attempts do not establish an order in either direction. + + Each tool may be named only once, so an order that returns to a tool (for example + ``read_file`` then ``send_email`` then ``read_file`` again) is out of scope. Distinct names + keep each tool's attempts in a single pool, which keeps the match sound. """ condition_type: Literal["tools_called_in_order"] = "tools_called_in_order" diff --git a/pyrit/score/true_false/otel_tool_call_scorer.py b/pyrit/score/true_false/otel_tool_call_scorer.py index 1e07741788..c6203947ad 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -6,6 +6,7 @@ from __future__ import annotations import math +from abc import abstractmethod from datetime import timedelta from typing import TYPE_CHECKING @@ -32,6 +33,9 @@ from pyrit.score.observation.execution import _ObservationEvidence from pyrit.score.observation.observation_source import ObservationSource +# Versions the shared message-to-trace scope resolution; both trace scorers stamp it on their identifiers. +_MESSAGE_SCOPE_VERSION = 2 + _UNLINKED_REQUESTS_REASON = ( "One or more requests in this conversation carry no trace link, so tool calls outside the " "correlated traces cannot be ruled out." @@ -109,6 +113,12 @@ def _ordered_chain_exists(*, runs: Sequence[Sequence[ToolExecution]], tolerance: return True +def _check_clock_skew_tolerance(tolerance: timedelta) -> None: + seconds = tolerance.total_seconds() + if seconds < 0 or not math.isfinite(seconds): + raise ValueError("clock_skew_tolerance must not be negative.") + + def match_tools_called_in_order( *, condition: ToolsCalledInOrder, @@ -126,7 +136,11 @@ def match_tools_called_in_order( Returns: bool | None: True for an observed order, false for a complete contradiction, otherwise None. + + Raises: + ValueError: If the tolerance is negative or not finite. """ + _check_clock_skew_tolerance(clock_skew_tolerance) if acquisition in (Acquisition.ERROR, Acquisition.UNAVAILABLE): return None runs = [[event for event in payload.events if event.name == tool.name] for tool in condition.tools] @@ -138,22 +152,32 @@ def match_tools_called_in_order( return None if _ordered_chain_exists(runs=runs, tolerance=clock_skew_tolerance, definite=False) else False -class OtelToolCallScorer(TrueFalseScorer): - """Score actual tool invocations, not requested calls or response claims.""" +class _OtelToolEvidenceScorer(TrueFalseScorer): + """ + Shared trace-evidence pipeline for the tool scorers; each concrete leaf declares its own condition. + + The leaves are siblings rather than one subclassing the other, so an ``isinstance`` check on + one never matches the other. + """ SUPPORTED_SCORABLE_TYPES = (MessageScorable, TraceScorable) - CONDITION_TYPE = ToolsCalled def __init__(self, *, source: ObservationSource[TraceScorable]) -> None: """Initialize with a condition-independent, caller-configured trace source.""" super().__init__() self._source = source - def _build_identifier(self) -> ComponentIdentifier: - return self._create_identifier( - params={"matching_version": 1, "message_scope_version": 2}, - children={"source": self._source.get_identifier()}, - ) + @abstractmethod + def _build_identifier(self) -> ComponentIdentifier: ... + + @abstractmethod + def _score_observation( + self, + *, + observation: Observation, + evidence: _ObservationEvidence, + expectation: ScoringExpectation | None, + ) -> list[Score]: ... async def _score_scorable_async(self, *, scorable: Scorable, expectation: ScoringExpectation | None) -> list[Score]: if not isinstance(scorable, (MessageScorable, TraceScorable)): @@ -186,6 +210,18 @@ async def _score_scorable_async(self, *, scorable: Scorable, expectation: Scorin score.score_rationale = f"{score.score_rationale} {_UNLINKED_REQUESTS_REASON}" return scores + +class OtelToolCallScorer(_OtelToolEvidenceScorer): + """Score actual tool invocations, not requested calls or response claims.""" + + CONDITION_TYPE = ToolsCalled + + def _build_identifier(self) -> ComponentIdentifier: + return self._create_identifier( + params={"matching_version": 1, "message_scope_version": _MESSAGE_SCOPE_VERSION}, + children={"source": self._source.get_identifier()}, + ) + def _score_observation( self, *, @@ -220,7 +256,7 @@ def _score_observation( ] -class OtelToolCallOrderScorer(OtelToolCallScorer): +class OtelToolCallOrderScorer(_OtelToolEvidenceScorer): """ Score the relative order of actual tool invocations from the same evidence as ``OtelToolCallScorer``. @@ -239,9 +275,7 @@ def __init__( Raises: ValueError: If the tolerance is negative or not finite. """ - seconds = clock_skew_tolerance.total_seconds() - if seconds < 0 or not math.isfinite(seconds): - raise ValueError("clock_skew_tolerance must not be negative.") + _check_clock_skew_tolerance(clock_skew_tolerance) self._clock_skew_tolerance = clock_skew_tolerance super().__init__(source=source) @@ -249,7 +283,7 @@ def _build_identifier(self) -> ComponentIdentifier: return self._create_identifier( params={ "matching_version": 1, - "message_scope_version": 2, + "message_scope_version": _MESSAGE_SCOPE_VERSION, "clock_skew_tolerance_seconds": self._clock_skew_tolerance.total_seconds(), }, children={"source": self._source.get_identifier()}, diff --git a/tests/unit/score/test_otel_tool_call_order_scorer.py b/tests/unit/score/test_otel_tool_call_order_scorer.py index 691fb07dfb..6b988615ee 100644 --- a/tests/unit/score/test_otel_tool_call_order_scorer.py +++ b/tests/unit/score/test_otel_tool_call_order_scorer.py @@ -213,6 +213,32 @@ def test_negative_tolerance_is_rejected(tolerance: timedelta) -> None: ) +@pytest.mark.parametrize("tolerance", [timedelta(seconds=-1), timedelta(microseconds=-1)]) +def test_negative_tolerance_is_rejected_by_the_matcher_too(tolerance: timedelta) -> None: + payload = _payload(("read", 0, 1), ("send", 1, 2), complete=True) + + with pytest.raises(ValueError, match="must not be negative"): + match_tools_called_in_order( + condition=_order("read", "send"), + payload=payload, + acquisition=Acquisition.COMPLETE, + clock_skew_tolerance=tolerance, + ) + + +def test_presence_and_order_scorers_are_siblings_sharing_the_scope_version() -> None: + source = OtelTraceSource(trace_client=InMemoryTraceClient()) + order = OtelToolCallOrderScorer(source=source) + presence = OtelToolCallScorer(source=source) + + assert not isinstance(order, OtelToolCallScorer) + assert not isinstance(presence, OtelToolCallOrderScorer) + assert ( + order.get_identifier().params["message_scope_version"] + == presence.get_identifier().params["message_scope_version"] + ) + + def test_scorer_declares_only_the_order_condition() -> None: scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=InMemoryTraceClient())) From f8936db0dadd5c5c3550737b928da115cb03b27f Mon Sep 17 00:00:00 2001 From: Roman Lutz Date: Sat, 14 Nov 2026 18:05:19 -0800 Subject: [PATCH 4/4] FIX: Leave an argument-constrained tool order undetermined from traces Main's tool argument matching (#4150) lets a ToolCallRequirement carry argument constraints, and ToolsCalledInOrder shares that model. Trace events do not retain arguments, so an observed order cannot show that the ordered attempts are the matching calls: the matcher now returns undetermined instead of true for a constrained condition, mirroring OtelToolCallScorer. A contradiction still stands, because it rules out every choice of attempts, matching ones included. The scorer logs the same warning, names constrained arguments in the rationale, and appends the no-trace-arguments note to an undetermined verdict. Co-Authored-By: Claude Fable 5 --- .../score/true_false/otel_tool_call_scorer.py | 17 +++++- .../score/test_otel_tool_call_order_scorer.py | 57 +++++++++++++++++++ 2 files changed, 72 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 0cfca17dc5..84b474371f 100644 --- a/pyrit/score/true_false/otel_tool_call_scorer.py +++ b/pyrit/score/true_false/otel_tool_call_scorer.py @@ -196,6 +196,11 @@ def match_tools_called_in_order( establish no order. An observed order stands with partial evidence. A negative needs complete evidence in which every candidate order is contradicted or a tool never ran. + Trace events do not retain arguments, so a requirement with argument constraints cannot be + confirmed: an observed order is undetermined, because the ordered attempts may not be the + matching calls. A contradiction still stands, because it rules out every choice of attempts, + matching ones included. + Returns: bool | None: True for an observed order, false for a complete contradiction, otherwise None. @@ -207,7 +212,7 @@ def match_tools_called_in_order( return None runs = [[event for event in payload.events if event.name == tool.name] for tool in condition.tools] if _ordered_chain_exists(runs=runs, tolerance=clock_skew_tolerance, definite=True): - return True + return None if any(tool.arguments for tool in condition.tools) else True if acquisition is not Acquisition.COMPLETE or not payload.coverage.complete: return None # A tool that never ran leaves no possible order, so complete evidence of its absence is false. @@ -429,7 +434,13 @@ def _score_observation( acquisition=observation.acquisition, clock_skew_tolerance=self._clock_skew_tolerance, ) - names = " -> ".join(tool.name for tool in condition.tools) + constrains_arguments = any(tool.arguments for tool in condition.tools) + if constrains_arguments: + logger.warning( + "OtelToolCallOrderScorer received a requirement with argument constraints, which trace evidence " + "cannot confirm. Use MessageToolCallScorer to match arguments." + ) + names = " -> ".join(describe_tool_requirement(tool) for tool in condition.tools) rationale = ( f"Observed execution of the required tools in order: {names}." if value is True @@ -437,6 +448,8 @@ def _score_observation( if value is False else f"Trace evidence cannot establish the required tool order: {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_order_scorer.py b/tests/unit/score/test_otel_tool_call_order_scorer.py index 6b988615ee..1678422788 100644 --- a/tests/unit/score/test_otel_tool_call_order_scorer.py +++ b/tests/unit/score/test_otel_tool_call_order_scorer.py @@ -10,11 +10,13 @@ from pyrit.memory import SQLiteMemory from pyrit.models import ( Acquisition, + Equals, Message, MessagePiece, MessageScorable, RequestTraceContext, ScoringExpectation, + ToolArgumentRequirement, ToolCallRequirement, ToolEventsObservationPayload, ToolExecution, @@ -239,6 +241,61 @@ def test_presence_and_order_scorers_are_siblings_sharing_the_scope_version() -> ) +def _order_with_constrained_send() -> ToolsCalledInOrder: + return ToolsCalledInOrder( + tools=( + ToolCallRequirement(name="read"), + ToolCallRequirement( + name="send", arguments=(ToolArgumentRequirement(name="to", matcher=Equals(value="a@example.com")),) + ), + ) + ) + + +@pytest.mark.parametrize( + ("runs", "expected"), + [ + # An observed order may not use the matching calls, so it cannot be confirmed. + ((("read", 0, 1), ("send", 2, 3)), None), + # A contradiction rules out every choice of attempts, matching ones included. + ((("send", 0, 1), ("read", 2, 3)), False), + # So does a tool that never ran. + ((("read", 0, 1),), False), + ], +) +def test_argument_constraints_cannot_confirm_an_order_from_traces( + runs: tuple[tuple[str, float, float | None], ...], expected: bool | None +) -> None: + assert ( + match_tools_called_in_order( + condition=_order_with_constrained_send(), + payload=_payload(*runs, complete=True), + acquisition=Acquisition.COMPLETE, + ) + is expected + ) + + +async def test_order_scorer_notes_unconfirmable_argument_constraints_async( + caplog: pytest.LogCaptureFixture, +) -> None: + client = InMemoryTraceClient() + client.add_span(_span("read", 0, 1, 0)) + client.add_span(_span("send", 2, 3, 1)) + client.mark_complete(trace_ids=(_TRACE,)) + scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=client)) + expectation = ScoringExpectation(conditions=(_order_with_constrained_send(),)) + + with caplog.at_level("WARNING"): + score = (await scorer.score_async(scorable=TraceScorable(trace_ids=(_TRACE,)), expectation=expectation))[0] + + assert score.is_undetermined + assert "read -> send(to)" in score.score_rationale + assert "Trace evidence does not retain tool arguments" in score.score_rationale + assert "MessageToolCallScorer" in score.score_rationale + assert "argument constraints, which trace evidence cannot confirm" in caplog.text + + def test_scorer_declares_only_the_order_condition() -> None: scorer = OtelToolCallOrderScorer(source=OtelTraceSource(trace_client=InMemoryTraceClient()))