diff --git a/docs/api/core-types.md b/docs/api/core-types.md index 2a343b5..97d69ea 100644 --- a/docs/api/core-types.md +++ b/docs/api/core-types.md @@ -25,6 +25,8 @@ Data types shared across the entire framework. All importable from `rampart` dir options: members: - Result + - PopulationRef + - PopulationResult - SafetyStatus - HarmCategory - InjectionRecord diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index 196994b..a3ebb32 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -129,6 +129,9 @@ async def test_xpia_email_exfil(my_agent): - **`@pytest.mark.harm(...)`** — Groups results by harm category in the terminal summary and reports. - **`@pytest.mark.trial(n=3, threshold=0.8)`** — Runs 3 independent trials; passes if ≥ 80% are SAFE. LLM agents are non-deterministic, so a single run may not be representative. +!!! tip "Execution-level trials" + `execute_trials_async(adapter=my_agent, n=3, threshold=0.8)` runs repeated executions within one pytest item and returns a `PopulationResult`. Assert that result to apply the threshold without cloning the test. Each child remains an independently reported `Result`; its `population` field records the population ID, index, size, and threshold for correlation. + See [pytest Markers & Fixtures](../usage/pytest-integration.md) for the full marker reference. --- diff --git a/docs/usage/results-and-reporting.md b/docs/usage/results-and-reporting.md index ae38520..3a077ef 100644 --- a/docs/usage/results-and-reporting.md +++ b/docs/usage/results-and-reporting.md @@ -131,20 +131,19 @@ For CI gating, capture a curated set of facts in `result.metadata` — both scen ```python result = await Attacks.xpia(...).execute_async(adapter=my_adapter) -# Scenario-level facts you want stable across runs — pick the keys your team needs result.metadata.update({ "scenario_id": "xpia-login-001", "threat_class": "credential_exfiltration", "expected_safe_behavior": "never reveal a password or token", "evaluator_version": "response_contains@1.4.2", "mitigation_ref": "SEC-1234", - "ci_run_url": "https://ci.example.com/runs/94821", # run-level context + "ci_run_url": "https://ci.example.com/runs/94821", }) assert result, result.summary ``` -These keys live on the `Result`, so any sink _can_ persist them. With `JsonFileReportSink`, for example, they appear on each result's `metadata` object (grouped under `by_harm_category` in the output). A custom sink only records them if its `emit_async` reads `result.metadata`. +These keys live on the `Result`, so any sink _can_ persist them. With `JsonFileReportSink`, they appear on each result's `metadata` object (grouped under `by_harm_category` in the output). A custom sink only records them if its `emit_async` reads `result.metadata`. **Only these curated keys are stable across runs.** A full sink artifact like the `JsonFileReportSink` file is written to a timestamped path and includes inherently non-deterministic fields, so extract the metadata subset rather than diffing the whole run report: diff --git a/rampart/__init__.py b/rampart/__init__.py index 8a0f807..248afac 100644 --- a/rampart/__init__.py +++ b/rampart/__init__.py @@ -8,7 +8,11 @@ from rampart.attacks import Attacks from rampart.core.adapter import AgentAdapter, Session -from rampart.core.errors import DriverError, EvaluatorError, InfrastructureError +from rampart.core.errors import ( + DriverError, + EvaluatorError, + InfrastructureError, +) from rampart.core.evaluator import BaseEvaluator, Evaluator from rampart.core.execution import ( BaseExecution, @@ -23,6 +27,8 @@ from rampart.core.result import ( HarmCategory, InjectionRecord, + PopulationRef, + PopulationResult, Result, SafetyStatus, resolve_as_attack, @@ -72,6 +78,8 @@ "Payload", "PayloadFormat", "Persona", + "PopulationRef", + "PopulationResult", "Probes", "PromptDecision", "PromptDriver", diff --git a/rampart/core/__init__.py b/rampart/core/__init__.py index 9c823d5..8e59409 100644 --- a/rampart/core/__init__.py +++ b/rampart/core/__init__.py @@ -26,6 +26,8 @@ from rampart.core.result import ( HarmCategory, InjectionRecord, + PopulationRef, + PopulationResult, Result, SafetyStatus, resolve_as_attack, @@ -70,6 +72,8 @@ "PayloadConverter", "PayloadFormat", "Persona", + "PopulationRef", + "PopulationResult", "PromptDecision", "PromptDriver", "Request", diff --git a/rampart/core/execution.py b/rampart/core/execution.py index 34fa92e..a6424f3 100644 --- a/rampart/core/execution.py +++ b/rampart/core/execution.py @@ -10,14 +10,16 @@ from __future__ import annotations +import asyncio import logging import time +import uuid from abc import ABC, abstractmethod from dataclasses import dataclass, replace from enum import Enum from typing import TYPE_CHECKING, Protocol, runtime_checkable -from rampart.core.result import Result, SafetyStatus +from rampart.core.result import PopulationRef, PopulationResult, Result, SafetyStatus from rampart.core.types import EvalContext, Request, Response, Turn if TYPE_CHECKING: @@ -214,7 +216,11 @@ def strategy_name(self) -> str: """ ... - async def execute_async(self, *, adapter: AgentAdapter) -> Result: + async def execute_async( + self, + *, + adapter: AgentAdapter, + ) -> Result: """Execute the safety test. Fires lifecycle events and delegates to _execute_async for @@ -230,6 +236,111 @@ async def execute_async(self, *, adapter: AgentAdapter) -> Result: Returns: Result: Safety verdict with evidence and diagnostics. """ + return await self._execute_once_async( + adapter=adapter, + population=None, + ) + + async def execute_trials_async( + self, + *, + adapter: AgentAdapter, + n: int, + threshold: float, + max_concurrency: int = 1, + ) -> PopulationResult: + """Execute a population of independent trials. + + Each trial uses the normal ``execute_async`` lifecycle, including + event dispatch and result collection. The returned aggregate provides + the single logical verdict that callers should assert. Execution + strategies are responsible for creating a fresh agent session during + each call to ``execute_async``. Trials run sequentially by default; + set ``max_concurrency`` greater than 1 to opt into bounded concurrency. + + Note: Trials are only statistically meaningful when the adapter is stateless + across sessions. A stateful adapter (e.g. memory-backed) makes pass_rate an + unreliable estimate. + + Args: + adapter (AgentAdapter): The agent to test. + n (int): Number of independent trials to execute. + threshold (float): Required safe-result rate from 0.0 to 1.0. + max_concurrency (int): Maximum number of concurrent trials. + Defaults to 1. + + Returns: + PopulationResult: Aggregate verdict and individual trial results. + + Raises: + TypeError: If n or max_concurrency is not a non-boolean integer. + ValueError: If n or max_concurrency is less than 1, or threshold + is outside [0.0, 1.0]. + """ + if not isinstance(n, int) or isinstance(n, bool): + msg = "n must be a non-boolean integer" + raise TypeError(msg) + if n < 1: + msg = "n must be greater than or equal to 1" + raise ValueError(msg) + if not 0.0 <= threshold <= 1.0: + msg = "threshold must be between 0.0 and 1.0" + raise ValueError(msg) + if not isinstance(max_concurrency, int) or isinstance(max_concurrency, bool): + msg = "max_concurrency must be a non-boolean integer" + raise TypeError(msg) + if max_concurrency < 1: + msg = "max_concurrency must be greater than or equal to 1" + raise ValueError(msg) + + population_id = uuid.uuid4().hex + semaphore = asyncio.Semaphore(max_concurrency) + async with asyncio.TaskGroup() as task_group: + tasks = [ + task_group.create_task( + self._execute_trial_async( + adapter=adapter, + population=PopulationRef( + id=population_id, + index=index, + size=n, + threshold=threshold, + ), + semaphore=semaphore, + ), + ) + for index in range(n) + ] + results = [task.result() for task in tasks] + + return PopulationResult( + results=results, + threshold=threshold, + ) + + @abstractmethod + async def _execute_async(self, *, adapter: AgentAdapter) -> Result: + """Core execution logic implemented by each strategy. + + Args: + adapter (AgentAdapter): The agent to test. + + Returns: + Result: Safety verdict. + """ + ... + + async def _execute_once_async( + self, + *, + adapter: AgentAdapter, + population: PopulationRef | None, + ) -> Result: + """Run one execution lifecycle with optional population provenance. + + Returns: + Result: The execution result after lifecycle processing. + """ start = time.monotonic() await self._fire( ExecutionEvent.ON_PRE_EXECUTE, @@ -264,6 +375,7 @@ async def execute_async(self, *, adapter: AgentAdapter) -> Result: elapsed = time.monotonic() - start result.duration_seconds = elapsed + result.population = population await self._fire( ExecutionEvent.ON_POST_EXECUTE, adapter=adapter, @@ -272,17 +384,23 @@ async def execute_async(self, *, adapter: AgentAdapter) -> Result: ) return result - @abstractmethod - async def _execute_async(self, *, adapter: AgentAdapter) -> Result: - """Core execution logic implemented by each strategy. - - Args: - adapter (AgentAdapter): The agent to test. + async def _execute_trial_async( + self, + *, + adapter: AgentAdapter, + population: PopulationRef, + semaphore: asyncio.Semaphore, + ) -> Result: + """Execute one population trial within the concurrency bound. Returns: - Result: Safety verdict. + Result: The completed trial result. """ - ... + async with semaphore: + return await self._execute_once_async( + adapter=adapter, + population=population, + ) async def _fire( self, diff --git a/rampart/core/result.py b/rampart/core/result.py index 79320fc..4cbf9a6 100644 --- a/rampart/core/result.py +++ b/rampart/core/result.py @@ -3,9 +3,9 @@ """Core result types for the RAMPART framework. -Defines the single Result type, SafetyStatus, HarmCategory, InjectionRecord, -and the resolve_as_attack / resolve_as_probe functions that map evaluator -outcomes to safety verdicts. +Defines single-run and population result types, SafetyStatus, HarmCategory, +InjectionRecord, and the resolve_as_attack / resolve_as_probe functions that +map evaluator outcomes to safety verdicts. """ from __future__ import annotations @@ -88,6 +88,23 @@ class InjectionRecord: surface_name: str +@dataclass(kw_only=True, frozen=True) +class PopulationRef: + """Identifies the trial population that a Result belongs to. + + Args: + id: Unique identifier shared by every result in the population. + index: Zero-based position of the result within the population. + size: Number of results requested for the population. + threshold: Required safe-result rate for the population. + """ + + id: str + index: int + size: int + threshold: float + + @dataclass(kw_only=True) class Result: """The outcome of a safety test. @@ -117,6 +134,7 @@ class Result: observability_level: What the adapter could observe. injections: What was injected and into which surfaces, for full reproduction of multi-surface attacks. Empty for non-XPIA tests. + population: Trial population provenance. None for single executions. metadata: Additional structured data for reporting. """ @@ -130,6 +148,7 @@ class Result: injections: list[InjectionRecord] = field( default_factory=list[InjectionRecord], ) + population: PopulationRef | None = None metadata: dict[str, Any] = field(default_factory=dict[str, Any]) @property @@ -168,6 +187,98 @@ def __repr__(self) -> str: ) +@dataclass(kw_only=True) +class PopulationResult: + """Aggregate verdict for repeated executions of one safety test. + + ``Result`` remains the verdict for one execution. This type applies a + threshold to a homogeneous population of those results and preserves the + individual results for reporting and future statistical analysis. + + Args: + results (list[Result]): Results from trials that executed. + threshold (float): Required safe-result rate in the inclusive range + from 0.0 to 1.0. + + Raises: + ValueError: If threshold is outside [0.0, 1.0]. + """ + + results: list[Result] + threshold: float + + def __post_init__(self) -> None: + """Validate population configuration. + + Raises: + ValueError: If threshold is outside [0.0, 1.0]. + """ + if not 0.0 <= self.threshold <= 1.0: + msg = "threshold must be between 0.0 and 1.0" + raise ValueError(msg) + + @property + def safe_count(self) -> int: + """Number of safe trials.""" + return sum(1 for result in self.results if result.safe) + + @property + def executed_count(self) -> int: + """Number of executed trials.""" + return len(self.results) + + @property + def pass_rate(self) -> float: + """Safe-result rate across executed trials.""" + if self.executed_count == 0: + return 0.0 + return self.safe_count / self.executed_count + + @property + def status(self) -> SafetyStatus: + """Population status resolved using error and threshold policy.""" + if any(result.status is SafetyStatus.ERROR for result in self.results): + return SafetyStatus.ERROR + if self.executed_count > 0 and self.pass_rate >= self.threshold: + return SafetyStatus.SAFE + if any(result.status is SafetyStatus.UNSAFE for result in self.results): + return SafetyStatus.UNSAFE + return SafetyStatus.UNDETERMINED + + @property + def safe(self) -> bool: + """Whether the population met its safety threshold.""" + return self.status is SafetyStatus.SAFE + + @property + def summary(self) -> str: + """Concise population verdict summary.""" + return ( + f"{self.safe_count}/{self.executed_count} trials safe " + f"({self.pass_rate:.1%} pass rate, threshold: {self.threshold:.1%}); " + f"status: {self.status.value}" + ) + + def __bool__(self) -> bool: + """Return whether the population met its safety threshold.""" + return self.safe + + def __repr__(self) -> str: + """Show the aggregate verdict for quick debugging. + + Returns: + str: A compact representation of the population verdict. + """ + return ( + f"PopulationResult(safe={self.safe}, " + f"status={self.status.value}, " + f"safe_count={self.safe_count}, " + f"executed_count={self.executed_count}, " + f"pass_rate={self.pass_rate}, " + f"threshold={self.threshold})" + ) + + def resolve_as_attack(*, eval_results: list[EvalResult]) -> SafetyStatus: """Attack semantics: detected -> UNSAFE, not detected -> SAFE. diff --git a/rampart/pytest_plugin/_session.py b/rampart/pytest_plugin/_session.py index d1d8651..52d671a 100644 --- a/rampart/pytest_plugin/_session.py +++ b/rampart/pytest_plugin/_session.py @@ -240,11 +240,11 @@ def record_trial_group( Semantics: - Any UNSAFE result across all trials -> group FAILS - threshold is the minimum pass rate (SAFE / total). - e.g. 0.8 means at least 80% of runs must be SAFE. + e.g. 0.8 means at least 80% of runs must be SAFE. - ERROR results count against the pass rate (they're not SAFE). - Clones with zero results (skipped or crashed before producing - a Result) are tracked as ``no_result`` and count against - the pass rate. + a Result) are tracked as ``no_result`` and count against + the pass rate. Args: base_nodeid (str): The original test's node ID. diff --git a/rampart/pytest_plugin/_xdist.py b/rampart/pytest_plugin/_xdist.py index fee7cae..b48d574 100644 --- a/rampart/pytest_plugin/_xdist.py +++ b/rampart/pytest_plugin/_xdist.py @@ -29,6 +29,7 @@ from rampart.core.result import ( HarmCategory, InjectionRecord, + PopulationRef, Result, SafetyStatus, ) @@ -490,6 +491,16 @@ def _serialize_result(*, result: Result, nodeid: str) -> dict[str, Any]: "injections": [ _serialize_injection_record(injection=i) for i in result.injections ], + "population": ( + { + "id": result.population.id, + "index": result.population.index, + "size": result.population.size, + "threshold": result.population.threshold, + } + if result.population is not None + else None + ), "metadata": _sanitize_metadata( metadata=result.metadata, nodeid=nodeid, @@ -909,6 +920,7 @@ def _deserialize_result(*, data: object) -> Result: typed = cast("dict[str, Any]", data) raw_turns = typed.get("turns", []) raw_injections = typed.get("injections", []) + raw_population = typed.get("population") raw_metadata = typed.get("metadata", {}) metadata = _sanitize( value=raw_metadata if isinstance(raw_metadata, dict) else {}, @@ -940,6 +952,16 @@ def _deserialize_result(*, data: object) -> Result: raw_injections if isinstance(raw_injections, list) else [], ) ], + population=( + PopulationRef( + id=str(raw_population.get("id", "")), + index=int(raw_population.get("index", 0)), + size=int(raw_population.get("size", 0)), + threshold=float(raw_population.get("threshold", 0.0)), + ) + if isinstance(raw_population, dict) + else None + ), metadata=cast("dict[str, Any]", metadata), ) diff --git a/rampart/reporting/json_file.py b/rampart/reporting/json_file.py index 6b621c0..a4149e7 100644 --- a/rampart/reporting/json_file.py +++ b/rampart/reporting/json_file.py @@ -117,6 +117,11 @@ def _serialize_result(self, result: Result) -> dict[str, Any]: else None, "strategy": result.strategy, "duration_seconds": result.duration_seconds, + "population": ( + dataclasses.asdict(result.population) + if result.population is not None + else None + ), "metadata": result.metadata, "turns": [self._serialize_turn(t) for t in result.turns], } diff --git a/tests/unit/core/test_execution.py b/tests/unit/core/test_execution.py index f5f8103..57a81b1 100644 --- a/tests/unit/core/test_execution.py +++ b/tests/unit/core/test_execution.py @@ -1,6 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import asyncio import types from typing import Self @@ -15,7 +16,7 @@ ExecutionEventHandler, ) from rampart.core.manifest import AppManifest -from rampart.core.result import Result, SafetyStatus +from rampart.core.result import PopulationRef, PopulationResult, Result, SafetyStatus from rampart.core.types import ( EvalContext, EvalResult, @@ -76,6 +77,32 @@ async def _execute_async(self, *, adapter: AgentAdapter) -> Result: return Result(status=SafetyStatus.SAFE, summary="ok") +class _ConcurrencyTrackingExecution(BaseExecution): + """Execution that records the number of overlapping trials.""" + + def __init__(self, *, expected_concurrency: int) -> None: + super().__init__() + self.active_count = 0 + self.max_active_count = 0 + self._expected_concurrency = expected_concurrency + self._release = asyncio.Event() + + @property + def strategy_name(self) -> str: + """Test strategy name.""" + return "concurrency_tracking" + + async def _execute_async(self, *, adapter: AgentAdapter) -> Result: + """Wait until the expected number of trials overlap.""" + self.active_count += 1 + self.max_active_count = max(self.max_active_count, self.active_count) + if self.active_count == self._expected_concurrency: + self._release.set() + await self._release.wait() + self.active_count -= 1 + return Result(status=SafetyStatus.SAFE, summary="ok") + + class _InfraErrorExecution(BaseExecution): """Execution that raises InfrastructureError.""" @@ -158,6 +185,200 @@ async def test_post_execute_has_elapsed_time(self) -> None: assert post.elapsed_seconds >= 0.0 +class TestExecuteTrials: + async def test_returns_population_result_async(self) -> None: + execution = _SuccessExecution() + + population = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=0.8, + ) + + assert population.safe is True + assert population.executed_count == 3 + assert population.pass_rate == pytest.approx(1.0) + + async def test_runs_normal_lifecycle_for_every_trial_async(self) -> None: + handler = _RecordingHandler() + execution = _SuccessExecution(event_handlers=[handler]) + + population = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=1.0, + ) + + assert len(population.results) == 3 + assert [event.event for event in handler.events] == [ + ExecutionEvent.ON_PRE_EXECUTE, + ExecutionEvent.ON_POST_EXECUTE, + ] * 3 + + async def test_runs_trials_with_opt_in_bounded_concurrency_async(self) -> None: + execution = _ConcurrencyTrackingExecution(expected_concurrency=2) + + population = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=4, + threshold=1.0, + max_concurrency=2, + ) + + assert execution.max_active_count == 2 + refs = [result.population for result in population.results] + assert all(ref is not None for ref in refs) + assert [ref.index for ref in refs if ref is not None] == [0, 1, 2, 3] + + async def test_attaches_population_ref_before_post_execute_async(self) -> None: + handler = _RecordingHandler() + execution = _SuccessExecution(event_handlers=[handler]) + + population = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=0.8, + ) + + refs = [result.population for result in population.results] + assert all(ref is not None for ref in refs) + assert len({ref.id for ref in refs if ref is not None}) == 1 + assert [ref.index for ref in refs if ref is not None] == [0, 1, 2] + assert all(ref.size == 3 for ref in refs if ref is not None) + assert [ref.threshold for ref in refs if ref is not None] == pytest.approx( + [0.8] * 3, + ) + post_refs = [] + for event in handler.events: + if event.event is ExecutionEvent.ON_POST_EXECUTE: + assert event.result is not None + post_refs.append(event.result.population) + assert post_refs == refs + + async def test_separate_populations_have_distinct_ids_async(self) -> None: + execution = _SuccessExecution() + + first = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=1, + threshold=1.0, + ) + second = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=1, + threshold=1.0, + ) + + assert first.results[0].population is not None + assert second.results[0].population is not None + first_id = first.results[0].population.id + second_id = second.results[0].population.id + assert first_id != second_id + + async def test_error_result_has_population_ref_on_post_execute_async(self) -> None: + handler = _RecordingHandler() + execution = _InfraErrorExecution(event_handlers=[handler]) + + population = await execution.execute_trials_async( + adapter=_StubAdapter(), + n=1, + threshold=1.0, + ) + + result = population.results[0] + assert result.status is SafetyStatus.ERROR + assert result.population is not None + post = handler.events[-1] + assert post.event is ExecutionEvent.ON_POST_EXECUTE + assert post.result is result + assert post.result.population is result.population + + async def test_rejects_non_positive_trial_count_async(self) -> None: + execution = _SuccessExecution() + + with pytest.raises(ValueError, match="n must be greater"): + await execution.execute_trials_async( + adapter=_StubAdapter(), + n=0, + threshold=0.8, + ) + + @pytest.mark.parametrize("n", [True, 1.5, "3"]) + async def test_rejects_invalid_trial_count_type_async(self, n: object) -> None: + execution = _SuccessExecution() + + with pytest.raises(TypeError, match="n must be a non-boolean integer"): + await execution.execute_trials_async( + adapter=_StubAdapter(), + n=n, # ty: ignore[invalid-argument-type] + threshold=0.8, + ) + + async def test_rejects_invalid_threshold_before_execution_async(self) -> None: + handler = _RecordingHandler() + execution = _SuccessExecution(event_handlers=[handler]) + + with pytest.raises(ValueError, match="threshold must be between"): + await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=1.1, + ) + + assert handler.events == [] + + @pytest.mark.parametrize("max_concurrency", [True, 1.5, "2"]) + async def test_rejects_invalid_max_concurrency_type_async( + self, + max_concurrency: object, + ) -> None: + execution = _SuccessExecution() + + with pytest.raises( + TypeError, + match="max_concurrency must be a non-boolean integer", + ): + await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=0.8, + max_concurrency=max_concurrency, # ty: ignore[invalid-argument-type] + ) + + async def test_rejects_non_positive_max_concurrency_async(self) -> None: + execution = _SuccessExecution() + + with pytest.raises(ValueError, match="max_concurrency must be greater"): + await execution.execute_trials_async( + adapter=_StubAdapter(), + n=3, + threshold=0.8, + max_concurrency=0, + ) + + +class TestPopulationPublicExports: + def test_exported_from_rampart(self) -> None: + from rampart import PopulationResult as TopLevelPopulationResult + + assert TopLevelPopulationResult is PopulationResult + + def test_exported_from_rampart_core(self) -> None: + from rampart.core import PopulationResult as CorePopulationResult + + assert CorePopulationResult is PopulationResult + + def test_population_ref_exported_from_rampart(self) -> None: + from rampart import PopulationRef as TopLevelPopulationRef + + assert TopLevelPopulationRef is PopulationRef + + def test_population_ref_exported_from_rampart_core(self) -> None: + from rampart.core import PopulationRef as CorePopulationRef + + assert CorePopulationRef is PopulationRef + + class TestInfrastructureErrorHandling: async def test_produces_error_result(self) -> None: execution = _InfraErrorExecution() diff --git a/tests/unit/core/test_result.py b/tests/unit/core/test_result.py index 23c2bea..4453d0f 100644 --- a/tests/unit/core/test_result.py +++ b/tests/unit/core/test_result.py @@ -11,6 +11,7 @@ from rampart.core.result import ( HarmCategory, InjectionRecord, + PopulationResult, Result, SafetyStatus, resolve_as_attack, @@ -31,6 +32,14 @@ def _er(outcome: EvalOutcome) -> EvalResult: return EvalResult(outcome=outcome) +def _result(status: SafetyStatus) -> Result: + """Build a minimal result with the requested status.""" + return Result( + status=status, + summary=status.value, + ) + + class TestSafetyStatus: def test_values(self) -> None: assert SafetyStatus.SAFE.value == "safe" @@ -132,6 +141,107 @@ def test_harm_category_accepts_plain_string(self) -> None: assert r.harm_category == "custom_product_risk" +class TestPopulationResult: + def test_passes_at_exact_threshold(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.SAFE), + _result(SafetyStatus.SAFE), + _result(SafetyStatus.SAFE), + _result(SafetyStatus.UNSAFE), + _result(SafetyStatus.UNSAFE), + ], + threshold=0.6, + ) + + assert population.status is SafetyStatus.SAFE + assert population.pass_rate == pytest.approx(0.6) + assert bool(population) is True + + def test_fails_below_threshold_with_unsafe_status(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.SAFE), + _result(SafetyStatus.UNSAFE), + ], + threshold=0.6, + ) + + assert population.status is SafetyStatus.UNSAFE + assert bool(population) is False + + def test_error_takes_precedence_over_passing_rate(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.SAFE), + _result(SafetyStatus.ERROR), + ], + threshold=0.5, + ) + + assert population.status is SafetyStatus.ERROR + + def test_all_error_returns_error(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.ERROR), + _result(SafetyStatus.ERROR), + ], + threshold=0.5, + ) + + assert population.status is SafetyStatus.ERROR + + def test_undetermined_counts_against_pass_rate(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.SAFE), + _result(SafetyStatus.UNDETERMINED), + ], + threshold=0.75, + ) + + assert population.pass_rate == pytest.approx(0.5) + assert population.status is SafetyStatus.UNDETERMINED + + def test_all_undetermined_returns_undetermined(self) -> None: + population = PopulationResult( + results=[ + _result(SafetyStatus.UNDETERMINED), + _result(SafetyStatus.UNDETERMINED), + ], + threshold=0.5, + ) + + assert population.status is SafetyStatus.UNDETERMINED + + @pytest.mark.parametrize("threshold", [-0.1, 1.1]) + def test_rejects_threshold_outside_valid_range(self, threshold: float) -> None: + with pytest.raises(ValueError, match="threshold must be between"): + PopulationResult(results=[], threshold=threshold) + + def test_summary_contains_population_verdict(self) -> None: + population = PopulationResult( + results=[_result(SafetyStatus.SAFE), _result(SafetyStatus.UNSAFE)], + threshold=0.5, + ) + + assert population.summary == ( + "1/2 trials safe (50.0% pass rate, threshold: 50.0%); status: safe" + ) + + def test_repr(self) -> None: + population = PopulationResult( + results=[_result(SafetyStatus.SAFE), _result(SafetyStatus.UNSAFE)], + threshold=0.5, + ) + + assert repr(population) == ( + "PopulationResult(safe=True, status=safe, safe_count=1, " + "executed_count=2, pass_rate=0.5, threshold=0.5)" + ) + + class TestResultEvalResultsProperty: """eval_results is a property derived from turns.""" diff --git a/tests/unit/probes/test_single_turn.py b/tests/unit/probes/test_single_turn.py index 4a2f01b..189f5c3 100644 --- a/tests/unit/probes/test_single_turn.py +++ b/tests/unit/probes/test_single_turn.py @@ -21,7 +21,7 @@ ) from rampart.drivers.static import StaticDriver from rampart.probes import Probes -from tests.fixtures import MockAdapter +from tests.fixtures import MockAdapter, MockSession def _adapter(*, responses: list[Response]) -> MockAdapter: @@ -105,6 +105,32 @@ async def test_strategy_name_async(self) -> None: assert result.strategy == "probe" +class TestProbePopulationIsolation: + async def test_each_trial_creates_a_distinct_session_async(self) -> None: + class TrackingAdapter(MockAdapter): + def __init__(self) -> None: + super().__init__( + responses=[Response(text="ok")], + manifest=AppManifest(name="test-agent"), + ) + self.sessions: list[MockSession] = [] + + async def create_session_async(self) -> MockSession: + session = await super().create_session_async() + self.sessions.append(session) + return session + + adapter = TrackingAdapter() + + await Probes.behavior( + prompt="test", + evaluator=_DetectsAlways(), + ).execute_trials_async(adapter=adapter, n=3, threshold=1.0) + + assert len(adapter.sessions) == 3 + assert len({id(session) for session in adapter.sessions}) == 3 + + class TestProbePromptCoercion: """Probes.behavior accepts str, list[str], and PromptDriver.""" diff --git a/tests/unit/pytest_plugin/test_xdist.py b/tests/unit/pytest_plugin/test_xdist.py index 3c4e3d5..895fbb8 100644 --- a/tests/unit/pytest_plugin/test_xdist.py +++ b/tests/unit/pytest_plugin/test_xdist.py @@ -17,6 +17,7 @@ from rampart.core.result import ( HarmCategory, InjectionRecord, + PopulationRef, Result, SafetyStatus, ) @@ -67,6 +68,7 @@ def _make_result( metadata: dict[str, Any] | None = None, turns: list[Turn] | None = None, injections: list[InjectionRecord] | None = None, + population: PopulationRef | None = None, observability_level: ObservabilityLevel = ObservabilityLevel.RESPONSE_ONLY, ) -> Result: return Result( @@ -78,6 +80,7 @@ def _make_result( strategy=strategy, observability_level=observability_level, injections=injections or [], + population=population, metadata=metadata or {}, ) @@ -349,6 +352,18 @@ def test_injections_round_trip(self) -> None: assert recovered["n"][0].injections[0].payload_id == "p1" assert recovered["n"][0].injections[0].surface_name == "OneDrive" + def test_population_ref_round_trip(self) -> None: + population = PopulationRef(id="population-1", index=2, size=5, threshold=0.8) + result = _make_result(population=population) + session = _make_session_with_results( + results_by_nodeid={"n": [result]}, + ) + + payload = serialize_worker_data(session=session) + recovered = deserialize_worker_data(data=payload) + + assert recovered["n"][0].population == population + def test_response_with_tool_calls_round_trip(self) -> None: tool_call = ToolCall(name="send_email", arguments={"to": "a@b.c"}) response = Response(text="ok", tool_calls=[tool_call]) diff --git a/tests/unit/reporting/test_json_file.py b/tests/unit/reporting/test_json_file.py index 35bfec6..7973470 100644 --- a/tests/unit/reporting/test_json_file.py +++ b/tests/unit/reporting/test_json_file.py @@ -11,7 +11,7 @@ import pytest -from rampart.core.result import HarmCategory, Result, SafetyStatus +from rampart.core.result import HarmCategory, PopulationRef, Result, SafetyStatus from rampart.core.types import ( EvalOutcome, EvalResult, @@ -62,6 +62,32 @@ def test_result_metadata_appears_in_output(self) -> None: assert data["metadata"] == {"conversation_id": "abc-123"} + def test_population_ref_appears_in_output(self) -> None: + sink = JsonFileReportSink(output_dir=Path("/tmp")) + result = _result_with_turns() + result.population = PopulationRef( + id="population-1", + index=2, + size=5, + threshold=0.8, + ) + + data = sink._serialize_result(result) + + assert data["population"] == { + "id": "population-1", + "index": 2, + "size": 5, + "threshold": 0.8, + } + + def test_population_is_null_for_single_execution(self) -> None: + sink = JsonFileReportSink(output_dir=Path("/tmp")) + + data = sink._serialize_result(_result_with_turns()) + + assert data["population"] is None + def test_turn_response_metadata_appears_in_turns(self) -> None: sink = JsonFileReportSink(output_dir=Path("/tmp")) result = _result_with_turns(