diff --git a/doc/code/analytics/0_attack_results.md b/doc/code/analytics/0_attack_results.md index 37d879a91f..e9df9d06b1 100644 --- a/doc/code/analytics/0_attack_results.md +++ b/doc/code/analytics/0_attack_results.md @@ -212,10 +212,56 @@ identity, score type, or scoring expectation is absent, compatibility cannot be fully verified. Different matched seed groups may use different scoring contexts if each individual baseline/attack pair has the same expectation. Older runs without a saved run plan and separately executed runs are not -supported. The reported difference is descriptive and does not establish that +supported; to compare reruns, use `compute_outcome_repeatability` (below). The reported difference is descriptive and does not establish that the attack caused an outcome to change. No confidence interval is provided, because small and constant paired samples need careful uncertainty treatment. +### Compare reruns of the same scenario + +Targets and scorers are stochastic, so one run is one sample per objective: two +runs with the same success rate can still disagree on which objectives +succeeded. `compute_outcome_repeatability` compares two or more **separately +executed** runs of the same scenario configuration and reports, for each +objective planned in all of them, whether the attack always succeeded, always +failed, or changed between runs. + +```python +from pyrit.analytics import compute_outcome_repeatability + +# run_a, run_b and run_c are loaded ScenarioResults of the same configuration, +# each containing hydrated AttackResults. +report = compute_outcome_repeatability([run_a, run_b, run_c]) +counts = report.overall +print(counts.always_success, counts.always_failure, counts.mixed) +print(counts.agreement_rate, counts.run_success_rates, counts.rate_range) +print(counts.shared_units, counts.decided_units) +for technique, technique_counts in report.by_technique.items(): + print(technique, technique_counts.agreement_rate) +``` + +Units are matched across runs by their planned +`(atomic_group_id, seed_group_id)`, which are deterministic, and each run +contributes its latest top-level result per unit, selected as +`compute_scenario_statistics` does. `shared_units` counts units planned in every +run, and `decided_units` the shared units whose outcome is success or failure in +every run. `agreement_rate` is `(always_success + always_failure) / decided_units`. +`run_success_counts` and `run_success_rates` follow the order the runs were +passed in, and the rates use `decided_units` as their denominator, so +`rate_range` (highest rate minus lowest) compares the same objectives. When no +unit is decided in every run, `agreement_rate` and `rate_range` are `None` and +`run_success_rates` holds one `None` per run. + +Errored, undetermined and missing outcomes stay out of the denominator and are +counted instead: `error_units`, `undetermined_units` and `missing_units` count +shared units with that outcome in at least one run, so they may overlap. +`partially_planned_units` counts units planned in only some runs. `by_technique` +gives the same counts per technique label; the baseline is labelled `baseline`. + +Every run needs a valid saved run plan, and all runs must share one scenario +evaluation hash, the check resume uses to refuse a changed scenario, technique +or dataset selection, target, or scorer; otherwise `ValueError` is raised. The +counts describe agreement and do not include confidence intervals. + ### ASSERT policy metrics `compute_assert_policy_metrics_async(result)` reports **impermissible behavior diff --git a/pyrit/analytics/__init__.py b/pyrit/analytics/__init__.py index f8a6b61cb6..633d3a1313 100644 --- a/pyrit/analytics/__init__.py +++ b/pyrit/analytics/__init__.py @@ -12,6 +12,11 @@ from pyrit.analytics.assert_policy_metrics import NotAssertPolicyRunError, compute_assert_policy_metrics_async from pyrit.analytics.attack_result_analytics import AttackResultAnalytics from pyrit.analytics.conversation_analytics import ConversationAnalytics + from pyrit.analytics.outcome_repeatability import ( + OutcomeRepeatability, + OutcomeRepeatabilityCounts, + compute_outcome_repeatability, + ) from pyrit.analytics.outcome_statistics import combine_outcome_statistics, compute_outcome_statistics from pyrit.analytics.paired_outcome_statistics import ( PairedOutcomeChildConversation, @@ -45,6 +50,7 @@ "combine_outcome_statistics": "pyrit.analytics.outcome_statistics", "compute_assert_policy_metrics_async": "pyrit.analytics.assert_policy_metrics", "NotAssertPolicyRunError": "pyrit.analytics.assert_policy_metrics", + "compute_outcome_repeatability": "pyrit.analytics.outcome_repeatability", "compute_outcome_statistics": "pyrit.analytics.outcome_statistics", "compute_paired_outcome_statistics": "pyrit.analytics.paired_outcome_statistics", "get_paired_outcome_details": "pyrit.analytics.paired_outcome_statistics", @@ -53,6 +59,8 @@ "compute_technique_stats_async": "pyrit.analytics.technique_analysis", "count_execution_units": "pyrit.analytics.scenario_statistics", "ConversationAnalytics": "pyrit.analytics.conversation_analytics", + "OutcomeRepeatability": "pyrit.analytics.outcome_repeatability", + "OutcomeRepeatabilityCounts": "pyrit.analytics.outcome_repeatability", "PairedOutcomeStatistics": "pyrit.analytics.paired_outcome_statistics", "PairedOutcomeChildConversation": "pyrit.analytics.paired_outcome_statistics", "PairedOutcomeDetail": "pyrit.analytics.paired_outcome_statistics", diff --git a/pyrit/analytics/assert_policy_metrics.py b/pyrit/analytics/assert_policy_metrics.py index fad06dbf75..4661577f23 100644 --- a/pyrit/analytics/assert_policy_metrics.py +++ b/pyrit/analytics/assert_policy_metrics.py @@ -21,11 +21,7 @@ from dataclasses import dataclass, field from typing import TYPE_CHECKING -from pyrit.analytics.scenario_statistics import ( - ScenarioPlanLookup, - load_scenario_run_plan, - resolve_attack_result_attempt, -) +from pyrit.analytics.scenario_statistics import load_scenario_run_plan, select_effective_attack_results from pyrit.memory import CentralMemory from pyrit.models import ( AssertBinaryRate, @@ -33,7 +29,6 @@ AssertDimensionResult, AssertPolicyMetrics, AttackOutcome, - ScenarioExecutionUnit, ScenarioRunPlanGroupKind, ScoreStatus, ViolatesAssertPolicy, @@ -49,7 +44,6 @@ from collections.abc import Iterable, Sequence from datetime import datetime - from pyrit.analytics.scenario_statistics import ScenarioAttempt from pyrit.memory import MemoryInterface from pyrit.models import ( AssertNodeJudgment, @@ -232,34 +226,14 @@ def _select_effective_results(scenario_result: ScenarioResult) -> list[_Effectiv list[_EffectiveResult]: The effective results. """ plan = load_scenario_run_plan(scenario_result) - lookup = ScenarioPlanLookup.from_plan(plan=plan) groups = {group.id: group for group in plan.atomic_groups} if plan is not None else {} - planned = ( - { - ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed) - for group in plan.atomic_groups - for seed in group.seed_group_ids - } - if plan is not None - else None - ) - attempts: dict[ScenarioExecutionUnit, list[tuple[ScenarioAttempt, AttackResult]]] = {} - for name, results in scenario_result.attack_results.items(): - for result in results: - attempt = resolve_attack_result_attempt(atomic_attack_name=name, attack_result=result, plan_lookup=lookup) - if planned is None or attempt.unit in planned: - attempts.setdefault(attempt.unit, []).append((attempt, result)) - effective = [] - for unit, entries in attempts.items(): - completions = sorted( - (entry for entry in entries if entry[0].attempt_index is None), - key=lambda entry: (entry[0].timestamp, entry[0].attempt_id), + return [ + _EffectiveResult( + technique=_technique(attempt.atomic_attack_name, group=groups.get(unit.atomic_group_id)), + result=result, ) - if completions: - attempt, result = completions[-1] - technique = _technique(attempt.atomic_attack_name, group=groups.get(unit.atomic_group_id)) - effective.append(_EffectiveResult(technique=technique, result=result)) - return effective + for unit, (attempt, result) in select_effective_attack_results(scenario_result, plan=plan).items() + ] def _technique(atomic_attack_name: str, *, group: ScenarioRunPlanAtomicGroup | None) -> str: diff --git a/pyrit/analytics/outcome_repeatability.py b/pyrit/analytics/outcome_repeatability.py new file mode 100644 index 0000000000..193983721b --- /dev/null +++ b/pyrit/analytics/outcome_repeatability.py @@ -0,0 +1,169 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Outcome agreement across separately executed runs of the same scenario configuration. + +Ports the logic of ``compute_repeatability`` in ASSERT's ``assert_ai/analysis/stability.py`` +(https://github.com/responsibleai/ASSERT, MIT license). Unlike upstream, errored and +undetermined outcomes are counted and kept out of the agreement denominator, per-run rates +cover only the units decided in every run, and the runs must share one configuration. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pyrit.analytics.scenario_statistics import load_scenario_run_plan, select_effective_attack_results +from pyrit.models import AttackOutcome, ScenarioEvaluationIdentifier, ScenarioExecutionUnit + +if TYPE_CHECKING: + from collections.abc import Sequence + + from pyrit.models import ScenarioResult + +_DECIDED = (AttackOutcome.SUCCESS, AttackOutcome.FAILURE) + + +@dataclass(frozen=True, slots=True) +class OutcomeRepeatabilityCounts: + """ + Outcome agreement for one set of execution units across the compared runs. + + ``shared_units`` counts units planned in every run, and ``decided_units`` the shared units + whose latest top-level outcome is success or failure in every run. ``agreement_rate`` and + each run's success rate use ``decided_units`` as the denominator, so ``rate_range`` compares + the same objectives; they are None when no unit is decided. ``missing_units``, + ``error_units`` and ``undetermined_units`` count shared units with that outcome in at least + one run, so they may overlap. ``partially_planned_units`` counts units planned in some runs + only; they are not shared. + """ + + shared_units: int + decided_units: int + always_success: int + always_failure: int + mixed: int + agreement_rate: float | None + run_success_counts: tuple[int, ...] + run_success_rates: tuple[float | None, ...] + rate_range: float | None + missing_units: int + error_units: int + undetermined_units: int + partially_planned_units: int + + +@dataclass(frozen=True, slots=True) +class OutcomeRepeatability: + """ + Outcome agreement across runs, overall and per technique label. + + ``run_count`` is the number of compared runs; ``run_success_counts`` and + ``run_success_rates`` follow the order the runs were passed in. ``by_technique`` is keyed by + each planned group's technique label, which names the baseline ``baseline``. + """ + + run_count: int + overall: OutcomeRepeatabilityCounts + by_technique: dict[str, OutcomeRepeatabilityCounts] + + +def compute_outcome_repeatability(scenario_results: Sequence[ScenarioResult]) -> OutcomeRepeatability: + """ + Compare the outcomes of two or more separately executed runs of one scenario configuration. + + Units are matched across runs by their planned ``(atomic_group_id, seed_group_id)``, which + are deterministic, and each run contributes the latest top-level outcome per unit, selected + as ``compute_scenario_statistics`` does. A unit decided in every run counts as + ``always_success``, ``always_failure`` or ``mixed``. + + Args: + scenario_results (Sequence[ScenarioResult]): The runs to compare, each with its hydrated + attack results. + + Returns: + OutcomeRepeatability: Agreement counts and per-run rates, overall and per technique. + + Raises: + ValueError: If fewer than two runs are given, a run is given twice, a run has no valid + saved plan, or the runs do not share one scenario configuration. + """ + if len(scenario_results) < 2: + raise ValueError("Outcome repeatability needs at least two scenario runs.") + run_ids = [str(result.id) for result in scenario_results] + if len(set(run_ids)) != len(run_ids): + raise ValueError("Each scenario run can be compared only once.") + + plans = [] + for result in scenario_results: + plan = load_scenario_run_plan(result) + if plan is None: + raise ValueError(f"Scenario result {result.id} has no valid saved run plan to match units across runs.") + plans.append(plan) + eval_hashes = {ScenarioEvaluationIdentifier(result.scenario_identifier).eval_hash for result in scenario_results} + if len(eval_hashes) > 1: + raise ValueError( + "Outcome repeatability compares runs of the same scenario configuration, but these runs " + "differ in scenario, technique or dataset selection, target, or scorer." + ) + + planned_by_run: list[set[ScenarioExecutionUnit]] = [] + techniques: dict[ScenarioExecutionUnit, str] = {} + for plan in plans: + planned: set[ScenarioExecutionUnit] = set() + for group in plan.atomic_groups: + for seed in group.seed_group_ids: + unit = ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed) + planned.add(unit) + techniques.setdefault(unit, group.technique_label) + planned_by_run.append(planned) + outcomes_by_run = [ + {unit: result.outcome for unit, (_, result) in select_effective_attack_results(scenario, plan=plan).items()} + for scenario, plan in zip(scenario_results, plans, strict=True) + ] + + shared = set.intersection(*planned_by_run) + partially_planned = set.union(*planned_by_run) - shared + overall = _counts(units=shared, partially_planned=partially_planned, outcomes_by_run=outcomes_by_run) + by_technique = { + technique: _counts( + units={unit for unit in shared if techniques[unit] == technique}, + partially_planned={unit for unit in partially_planned if techniques[unit] == technique}, + outcomes_by_run=outcomes_by_run, + ) + for technique in sorted(set(techniques.values())) + } + return OutcomeRepeatability(run_count=len(scenario_results), overall=overall, by_technique=by_technique) + + +def _counts( + *, + units: set[ScenarioExecutionUnit], + partially_planned: set[ScenarioExecutionUnit], + outcomes_by_run: list[dict[ScenarioExecutionUnit, AttackOutcome]], +) -> OutcomeRepeatabilityCounts: + decided = [unit for unit in units if all(run.get(unit) in _DECIDED for run in outcomes_by_run)] + successes = [sum(run[unit] == AttackOutcome.SUCCESS for run in outcomes_by_run) for unit in decided] + always_success = sum(count == len(outcomes_by_run) for count in successes) + always_failure = sum(count == 0 for count in successes) + run_success_counts = tuple(sum(run[unit] == AttackOutcome.SUCCESS for unit in decided) for run in outcomes_by_run) + run_success_rates = tuple(count / len(decided) if decided else None for count in run_success_counts) + return OutcomeRepeatabilityCounts( + shared_units=len(units), + decided_units=len(decided), + always_success=always_success, + always_failure=always_failure, + mixed=len(decided) - always_success - always_failure, + agreement_rate=(always_success + always_failure) / len(decided) if decided else None, + run_success_counts=run_success_counts, + run_success_rates=run_success_rates, + rate_range=(max(run_success_counts) - min(run_success_counts)) / len(decided) if decided else None, + missing_units=sum(any(unit not in run for run in outcomes_by_run) for unit in units), + error_units=sum(any(run.get(unit) == AttackOutcome.ERROR for run in outcomes_by_run) for unit in units), + undetermined_units=sum( + any(run.get(unit) == AttackOutcome.UNDETERMINED for run in outcomes_by_run) for unit in units + ), + partially_planned_units=len(partially_planned), + ) diff --git a/pyrit/analytics/scenario_statistics.py b/pyrit/analytics/scenario_statistics.py index c87a20a225..532e9e4153 100644 --- a/pyrit/analytics/scenario_statistics.py +++ b/pyrit/analytics/scenario_statistics.py @@ -381,6 +381,53 @@ def select_execution_attack_result_ids( } +def select_effective_attack_results( + scenario_result: ScenarioResult, + *, + plan: ScenarioRunPlan | None, +) -> dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]]: + """ + Select the latest top-level attempt for each counted execution unit. + + Counted units are the planned units of ``plan``, or every resolved unit when ``plan`` is None, + matching ``compute_scenario_statistics``. Attempts are ordered by timestamp, then attempt ID. + A unit without a top-level completion has no entry. + + Args: + scenario_result (ScenarioResult): The scenario result with its hydrated attack results. + plan (ScenarioRunPlan | None): The run plan to resolve units against, or None for a legacy run. + + Returns: + dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]]: The selected attempt and + its attack result for each unit that has one. + """ + lookup = ScenarioPlanLookup.from_plan(plan=plan) + planned = ( + { + ScenarioExecutionUnit(atomic_group_id=group.id, seed_group_id=seed) + for group in plan.atomic_groups + for seed in group.seed_group_ids + } + if plan is not None + else None + ) + attempts: dict[ScenarioExecutionUnit, list[tuple[ScenarioAttempt, AttackResult]]] = {} + for name, results in scenario_result.attack_results.items(): + for result in results: + attempt = resolve_attack_result_attempt(atomic_attack_name=name, attack_result=result, plan_lookup=lookup) + if planned is None or attempt.unit in planned: + attempts.setdefault(attempt.unit, []).append((attempt, result)) + effective: dict[ScenarioExecutionUnit, tuple[ScenarioAttempt, AttackResult]] = {} + for unit, entries in attempts.items(): + completions = sorted( + (entry for entry in entries if entry[0].attempt_index is None), + key=lambda entry: (entry[0].timestamp, entry[0].attempt_id), + ) + if completions: + effective[unit] = completions[-1] + return effective + + def retry_pressure(*, attempts_per_unit: Iterable[int], persisted_retries: Iterable[int]) -> int: """ Combine per-attempt retries with re-attempts of the same execution unit. diff --git a/tests/unit/analytics/test_outcome_repeatability.py b/tests/unit/analytics/test_outcome_repeatability.py new file mode 100644 index 0000000000..633a6d9759 --- /dev/null +++ b/tests/unit/analytics/test_outcome_repeatability.py @@ -0,0 +1,232 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import uuid +from datetime import UTC, datetime, timedelta + +import pytest + +from pyrit.analytics import compute_outcome_repeatability +from pyrit.common.utils import to_sha256 +from pyrit.models import ( + SCENARIO_RUN_PLAN_METADATA_KEY, + AttackOutcome, + AttackResult, + ScenarioResult, + ScenarioRunPlan, + ScenarioRunPlanAtomicGroup, + ScenarioRunPlanGroupKind, + ScenarioRunPlanSeedGroup, +) +from unit.mocks import make_scenario_result + +_TIME = datetime(2026, 9, 1, tzinfo=UTC) + +S = AttackOutcome.SUCCESS +F = AttackOutcome.FAILURE +E = AttackOutcome.ERROR +U = AttackOutcome.UNDETERMINED + + +def _plan( + attack_ids: tuple[str, ...] = ("a", "b", "c", "d"), + baseline_ids: tuple[str, ...] = (), +) -> ScenarioRunPlan: + groups = [ + ScenarioRunPlanAtomicGroup( + id="attack", + atomic_attack_name="attack", + display_group="Attack", + technique_eval_hash="attack-eval", + technique_name="role_play", + kind=ScenarioRunPlanGroupKind.ATTACK, + seed_group_ids=list(attack_ids), + ) + ] + if baseline_ids: + groups.append( + ScenarioRunPlanAtomicGroup( + id="base", + atomic_attack_name="baseline", + display_group="Baseline", + technique_eval_hash="base-eval", + kind=ScenarioRunPlanGroupKind.BASELINE, + seed_group_ids=list(baseline_ids), + ) + ) + return ScenarioRunPlan( + atomic_groups=groups, + seed_groups=[ + ScenarioRunPlanSeedGroup(id=seed, objective=seed, objective_sha256=to_sha256(seed)) + for seed in sorted(set(attack_ids) | set(baseline_ids)) + ], + ) + + +def _result( + seed: str, + outcome: AttackOutcome, + *, + group: str = "attack", + seconds: int = 0, + attempt_index: int | None = None, +) -> AttackResult: + attribution: dict[str, object] = {"seed_group_id": seed, "parent_eval_hash": f"{group}-eval"} + if attempt_index is not None: + attribution["attempt_index"] = attempt_index + return AttackResult( + conversation_id=str(uuid.uuid4()), + attack_result_id=str(uuid.uuid4()), + objective=seed, + outcome=outcome, + timestamp=_TIME + timedelta(seconds=seconds), + attribution_data=attribution, + ) + + +def _run( + outcomes: dict[str, AttackOutcome], *, plan: ScenarioRunPlan | None = None, **identity: object +) -> ScenarioResult: + plan = plan or _plan() + return make_scenario_result( + attack_results={"attack": [_result(seed, outcome) for seed, outcome in outcomes.items()]}, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, + **identity, + ) + + +def test_counts_which_objectives_changed_even_when_run_rates_are_equal() -> None: + report = compute_outcome_repeatability( + [ + _run({"a": S, "b": F, "c": S, "d": F}), + _run({"a": S, "b": F, "c": F, "d": S}), + ] + ) + + counts = report.overall + assert report.run_count == 2 + assert (counts.shared_units, counts.decided_units) == (4, 4) + assert (counts.always_success, counts.always_failure, counts.mixed) == (1, 1, 2) + assert counts.agreement_rate == 0.5 + assert counts.run_success_counts == (2, 2) + assert counts.run_success_rates == (0.5, 0.5) + assert counts.rate_range == 0.0 + + +def test_compares_more_than_two_runs_in_the_order_given() -> None: + report = compute_outcome_repeatability( + [ + _run({"a": S, "b": S, "c": F, "d": F}), + _run({"a": S, "b": S, "c": S, "d": F}), + _run({"a": S, "b": F, "c": F, "d": F}), + ] + ) + + counts = report.overall + assert report.run_count == 3 + assert (counts.always_success, counts.always_failure, counts.mixed) == (1, 1, 2) + assert counts.run_success_counts == (2, 3, 1) + assert counts.run_success_rates == (0.5, 0.75, 0.25) + assert counts.rate_range == 0.5 + + +def test_keeps_errors_undetermined_and_missing_out_of_the_denominator_and_counts_them() -> None: + report = compute_outcome_repeatability( + [ + _run({"a": S, "b": E, "c": U, "d": E}), + _run({"a": S, "b": F, "c": E}), + ] + ) + + counts = report.overall + assert (counts.shared_units, counts.decided_units) == (4, 1) + assert (counts.always_success, counts.always_failure, counts.mixed) == (1, 0, 0) + assert counts.agreement_rate == 1.0 + assert counts.run_success_rates == (1.0, 1.0) + # "c" is undetermined in one run and errored in the other; "d" errored and is missing. + assert (counts.missing_units, counts.error_units, counts.undetermined_units) == (1, 3, 1) + + +def test_reports_units_planned_in_only_some_runs_outside_the_shared_units() -> None: + report = compute_outcome_repeatability( + [ + _run({"a": S, "b": F}, plan=_plan(attack_ids=("a", "b"))), + _run({"a": S, "b": F, "c": S}, plan=_plan(attack_ids=("a", "b", "c"))), + ] + ) + + counts = report.overall + assert (counts.shared_units, counts.decided_units, counts.partially_planned_units) == (2, 2, 1) + assert counts.agreement_rate == 1.0 + + +def test_uses_the_latest_top_level_completion_once_per_unit() -> None: + first = _run({"a": S, "b": F, "c": S, "d": F}) + second = make_scenario_result( + attack_results={ + "attack": [ + _result("a", F, seconds=0), + _result("a", S, seconds=10), + _result("b", S, seconds=20, attempt_index=1), + _result("b", F, seconds=5), + _result("c", S), + _result("d", F), + ] + }, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: _plan().model_dump(mode="json")}, + ) + + counts = compute_outcome_repeatability([first, second]).overall + + assert (counts.decided_units, counts.always_success, counts.always_failure, counts.mixed) == (4, 2, 2, 0) + + +def test_gives_the_same_counts_per_technique_label() -> None: + plan = _plan(attack_ids=("a", "b"), baseline_ids=("a", "b")) + + def run(attack: tuple[AttackOutcome, AttackOutcome], baseline: tuple[AttackOutcome, AttackOutcome]): + return make_scenario_result( + attack_results={ + "attack": [_result("a", attack[0]), _result("b", attack[1])], + "baseline": [_result("a", baseline[0], group="base"), _result("b", baseline[1], group="base")], + }, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, + ) + + report = compute_outcome_repeatability([run((S, S), (F, F)), run((S, F), (F, F))]) + + assert set(report.by_technique) == {"baseline", "role_play"} + assert (report.by_technique["role_play"].always_success, report.by_technique["role_play"].mixed) == (1, 1) + assert report.by_technique["baseline"].always_failure == 2 + assert report.overall.decided_units == 4 + + +def test_reports_no_rates_when_no_unit_is_decided_in_every_run() -> None: + counts = compute_outcome_repeatability([_run({"a": E}), _run({"a": S})]).overall + + assert counts.decided_units == 0 + assert counts.agreement_rate is None + assert counts.run_success_rates == (None, None) + assert counts.rate_range is None + + +def test_requires_at_least_two_runs() -> None: + with pytest.raises(ValueError, match="at least two"): + compute_outcome_repeatability([_run({"a": S})]) + + +def test_rejects_the_same_run_twice() -> None: + run = _run({"a": S}) + with pytest.raises(ValueError, match="only once"): + compute_outcome_repeatability([run, run]) + + +def test_rejects_a_run_without_a_saved_plan() -> None: + legacy = make_scenario_result(attack_results={"attack": [_result("a", S)]}) + with pytest.raises(ValueError, match="no valid saved run plan"): + compute_outcome_repeatability([_run({"a": S}), legacy]) + + +def test_rejects_runs_of_different_configurations() -> None: + with pytest.raises(ValueError, match="same scenario configuration"): + compute_outcome_repeatability([_run({"a": S}), _run({"a": S}, datasets=["other_dataset"])])