diff --git a/.github/workflows/frontend_tests.yml b/.github/workflows/frontend_tests.yml index df9b0e8e1f..c43910699f 100644 --- a/.github/workflows/frontend_tests.yml +++ b/.github/workflows/frontend_tests.yml @@ -82,6 +82,10 @@ jobs: config: playwright.analytics.config.ts shard: 1 total: 1 + - project: paired-outcomes + config: playwright.paired-outcomes.config.ts + shard: 1 + total: 1 outputs: expected-reports: ${{ strategy.job-total }} permissions: @@ -126,8 +130,8 @@ jobs: - name: Install Playwright browsers run: npx playwright install --with-deps chromium - - name: Build the isolated analytics frontend - if: matrix.project == 'analytics' + - name: Build the isolated fixture frontend + if: matrix.project == 'analytics' || matrix.project == 'paired-outcomes' run: npm run build - name: Run E2E shard (no credentials needed) diff --git a/doc/code/analytics/0_attack_results.md b/doc/code/analytics/0_attack_results.md index 17964b0d17..a98825aeed 100644 --- a/doc/code/analytics/0_attack_results.md +++ b/doc/code/analytics/0_attack_results.md @@ -125,6 +125,88 @@ separate: an error followed by a successful retry contributes one historical err but no latest-unit error. Never derive the decided denominator by subtracting historical errors from completed units. +### Compare matched baseline and attack outcomes + +For scenarios that saved a normalized run plan with explicit baseline and attack +groups, `compute_paired_outcome_statistics` shows what changed for the **same +logical seed groups**. Supply the two atomic-group IDs from +`scenario_result.metadata["run_plan"]["atomic_groups"]`; this deliberately +avoids guessing which baseline belongs to a particular attack configuration. + +```python +from pyrit.analytics import compute_paired_outcome_statistics +from pyrit.models import ScenarioRunPlan, ScenarioRunPlanGroupKind + +# scenario_result is an already loaded ScenarioResult containing hydrated AttackResults. +plan = ScenarioRunPlan.model_validate(scenario_result.metadata["run_plan"]) +baseline = next(group for group in plan.atomic_groups if group.kind == ScenarioRunPlanGroupKind.BASELINE) +attack = next(group for group in plan.atomic_groups if group.kind == ScenarioRunPlanGroupKind.ATTACK) +# If several groups share a kind, choose the intended pair explicitly. +report = compute_paired_outcome_statistics( + scenario_result, + baseline_group_id=baseline.id, + attack_group_id=attack.id, +) +print(report.failure_to_success, report.success_to_failure) +print(report.failure_to_failure, report.success_to_success) +print(report.baseline_success_rate, report.attack_success_rate, report.paired_difference) +print(report.decided_pairs, report.excluded_pairs) +``` + +The four transitions are **failure→success**, **success→failure**, +**failure→failure**, and **success→success**. The denominator for both rates +(`baseline_success_rate` and `attack_success_rate`) is `decided_pairs`: +seed-group IDs scheduled in **both** selected atomic groups whose latest +top-level baseline and attack outcomes are both success or failure. The +`paired_difference` is attack rate minus baseline rate over that same cohort, +in proportions (not percentage points); for example, `0.25` means 25 +percentage points. If there are no decided pairs, all three values are `None`. +Unlike a subtraction of two overall success rates, the transition counts show +which outcomes changed, even when the marginal rates are identical. +For example, with four decided pairs (one of each transition), both success +rates are `0.5` and the paired difference is `0.0`, but one previously failed +objective succeeds and one previously successful objective fails. + +The function selects the effective **latest top-level result** per +`(atomic_group_id, seed_group_id)`, ordering by timestamp then result ID as +`compute_scenario_statistics` does. Child results and superseded retries never +create extra pairs. `planned_pairs` covers the **intersection** of planned seed IDs; +`decided_pairs` is the decided shared subset, and +`excluded_pairs = planned_pairs - decided_pairs`. The +`unmatched_baseline_seeds` and `unmatched_attack_seeds` counts cover seed IDs +planned on one side only, and are not included in `excluded_pairs`. +For shared IDs, `missing_both`, `missing_baseline`, +and `missing_attack` count absent top-level completions (the latter two +are exclusive of `missing_both`). `baseline_errors`, `attack_errors`, +`baseline_undetermined`, and `attack_undetermined` count each side's latest +outcomes, including when the other side is absent or undecided. These reason +counts can overlap across sides, so do not sum them to reconstruct exclusions. +`unattributed_attempts` counts results recorded under the selected atomic +names that resolve to neither selected planned group. + +Comparisons require one valid saved plan, distinct explicitly marked baseline +and attack groups, and overlapping logical seed-group IDs (unless both +groups are empty). Ambiguous group configurations, duplicated result IDs, +conflicting seed attribution, malformed attempt metadata, or incompatible +scoring evidence raise `ValueError` rather than silently pairing observations. +When scores are available, the comparison checks scorer identities and score +types both within pairs and across the decided cohort. Within each pair, it +also checks complete scoring expectations, including their conditions and any +optional scoring context, which may legitimately differ from the attack objective. +For compound outcomes, these checks follow all explicitly linked descendants, +including nested compounds. Missing child results or cyclic links are rejected; +descendants still do not add pairs or change the rate denominator. +The groups belong to the **same** ScenarioResult and share its scenario-level +target and scorer identity. When a run uses different per-group scorers, +persisted per-result scorer identities can reveal incompatibility; if scorer +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 +the attack caused an outcome to change. No confidence interval is provided, +because small and constant paired samples need careful uncertainty treatment. + ### Scenario producer accounting Scenario counts also expose `producer_counts`, separating target-facing, diff --git a/doc/gui/0_gui.md b/doc/gui/0_gui.md index d7512b013a..4a8658af25 100644 --- a/doc/gui/0_gui.md +++ b/doc/gui/0_gui.md @@ -962,3 +962,34 @@ CoPyRIT monitors the backend connection and shows a status banner: - **Disconnected (red):** Unable to reach the backend. Check that the server is running. - **Degraded (yellow):** Connection is unstable. - **Reconnected (green):** Briefly shown after a successful reconnection, then auto-dismissed. + +## Paired baseline and attack outcomes + +Open a completed run from **Scanner History** and find **Paired outcomes**. +Choose the saved **Baseline group** and **Attack group**, then select +**Compare outcomes**. Groups are explicitly marked by the saved execution +plan; PyRIT does not guess a baseline from its name. If several configurations +have the same name, the options include their group IDs to distinguish them. + +The comparison shows all four baseline-to-attack transitions, both success +rates, and their difference in percentage points. Rates use the same decided +pairs. For example, four pairs with one of each transition give 50% success +on each side and a 0 pp difference, while still showing one failure becoming +a success and one success becoming a failure. + +**Decided pairs** shows the number with success or failure on both sides, +followed by the number planned on both sides. **Excluded pairs** counts the +remaining shared pairs. Missing outcomes, errors, and undetermined outcomes +are listed separately; reason counts can overlap. Seeds planned on only one +side are unmatched and are not included in the pair denominator. + +The panel uses the [paired analytics SDK](../code/analytics/0_attack_results.md) +and its latest top-level outcome rules. Children and superseded retries do +not add observations. Empty decided populations display **Unavailable** rates. +Legacy runs without a complete saved plan, runs without explicit group kinds, +and runs that have not completed cannot be compared. Incompatible groups +show the backend's explanation, and **Compare outcomes** can retry a failed +request. Changing a group clears the comparison. + +Missing persisted scoring metadata limits compatibility validation. These +observed differences do not establish causation. diff --git a/frontend/README.md b/frontend/README.md index 382dd3bae7..fc4769916b 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -249,6 +249,7 @@ npm run test:coverage # Run with coverage report (85%+ threshold) # End-to-End Tests (Playwright) npm run test:e2e # Run headless (default local setup uses dev.py) npm run test:e2e:headed # Run with visible browser windows (requires display) +npm run test:e2e:paired-outcomes # Real SQLite/API paired-outcome acceptance tests npm run test:e2e:ui # Interactive UI mode (requires display) ``` diff --git a/frontend/e2e/fixtures/paired_outcomes_backend.py b/frontend/e2e/fixtures/paired_outcomes_backend.py new file mode 100644 index 0000000000..31e68731a5 --- /dev/null +++ b/frontend/e2e/fixtures/paired_outcomes_backend.py @@ -0,0 +1,157 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Disposable saved Scenario runs for paired-outcome browser acceptance tests.""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta +from typing import TYPE_CHECKING +from unittest.mock import patch +from uuid import UUID, uuid4 + +from frontend.e2e.fixtures import analytics_backend + +if TYPE_CHECKING: + from pyrit.memory import SQLiteMemory + + +async def _seed_async(memory: SQLiteMemory) -> None: + from pyrit.common.utils import to_sha256 + from pyrit.models import ( + SCENARIO_RUN_PLAN_METADATA_KEY, + AtomicAttackIdentifier, + AttackIdentifier, + AttackOutcome, + AttackResult, + ScenarioIdentifier, + ScenarioResult, + ScenarioRunPlan, + ScenarioRunPlanAtomicGroup, + ScenarioRunPlanGroupKind, + ScenarioRunPlanSeedGroup, + ScenarioRunState, + TargetIdentifier, + ) + + memory.disable_embedding() + timestamp = datetime(2026, 10, 20, tzinfo=UTC) + shared = ["a", "b", "c", "d", "missing", "undetermined", "error", "child-only"] + target = TargetIdentifier(class_name="MockPromptTarget", class_module="paired_browser_fixture") + identifier = AtomicAttackIdentifier.build( + attack_identifier=AttackIdentifier( + class_name="PromptSendingAttack", + class_module="pyrit.executor.attack", + objective_target=target, + ) + ) + plan = ScenarioRunPlan( + atomic_groups=[ + ScenarioRunPlanAtomicGroup( + id=name, + atomic_attack_name=name, + display_group=name.title(), + technique_eval_hash=f"{name}-eval", + kind=kind, + seed_group_ids=shared + [extra], + ) + for name, kind, extra in [ + ("baseline", ScenarioRunPlanGroupKind.BASELINE, "base-only"), + ("attack", ScenarioRunPlanGroupKind.ATTACK, "attack-only"), + ] + ], + seed_groups=[ + ScenarioRunPlanSeedGroup(id=seed, objective=seed, objective_sha256=to_sha256(seed)) + for seed in shared + ["base-only", "attack-only"] + ], + ) + for index, state in enumerate([ScenarioRunState.COMPLETED, ScenarioRunState.COMPLETED, ScenarioRunState.FAILED]): + scenario_id = UUID(int=9100 + index) + rows: dict[str, list[AttackResult]] = {"baseline": [], "attack": []} + for name, outcomes in [ + ("baseline", [AttackOutcome.FAILURE, AttackOutcome.SUCCESS, AttackOutcome.FAILURE, AttackOutcome.SUCCESS]), + ("attack", [AttackOutcome.SUCCESS, AttackOutcome.FAILURE, AttackOutcome.FAILURE, AttackOutcome.SUCCESS]), + ]: + for seed, outcome in zip(shared[:4], outcomes, strict=True): + rows[name].append( + AttackResult( + attack_result_id=str(uuid4()), + conversation_id=str(uuid4()), + objective=seed, + outcome=outcome, + timestamp=timestamp, + atomic_attack_identifier=identifier, + attribution_parent_id=str(scenario_id), + attribution_data={ + "seed_group_id": seed, + "parent_eval_hash": f"{name}-eval", + "parent_collection": name, + }, + ) + ) + for seed, outcome in [ + ("undetermined", AttackOutcome.UNDETERMINED), + ("error", AttackOutcome.ERROR), + ("child-only", AttackOutcome.FAILURE), + ]: + for name in ["baseline", "attack"]: + rows[name].append( + AttackResult( + attack_result_id=str(uuid4()), + conversation_id=str(uuid4()), + objective=seed, + outcome=AttackOutcome.FAILURE if name == "baseline" else outcome, + timestamp=timestamp, + atomic_attack_identifier=identifier, + attribution_parent_id=str(scenario_id), + attribution_data={ + "seed_group_id": seed, + "parent_eval_hash": f"{name}-eval", + "parent_collection": name, + **({"attempt_index": 1} if seed == "child-only" and name == "attack" else {}), + }, + ) + ) + rows["attack"].append( + AttackResult( + attack_result_id=str(uuid4()), + conversation_id=str(uuid4()), + objective="a", + outcome=AttackOutcome.FAILURE, + timestamp=timestamp - timedelta(seconds=1), + atomic_attack_identifier=identifier, + attribution_parent_id=str(scenario_id), + attribution_data={ + "seed_group_id": "a", + "parent_eval_hash": "attack-eval", + "parent_collection": "attack", + }, + ) + ) + await memory.add_attack_results_to_memory_async( + attack_results=[row for group in rows.values() for row in group] + ) + await memory.add_scenario_results_to_memory_async( + scenario_results=[ + ScenarioResult( + id=scenario_id, + scenario_identifier=ScenarioIdentifier( + class_name="PairedBrowserScenario", + class_module="paired_browser_fixture", + version=1, + objective_target=target, + ), + scenario_description="Offline paired outcomes acceptance fixture.", + attack_results=rows, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")} if index != 1 else {}, + scenario_run_state=state, + creation_time=timestamp, + completion_time=timestamp + timedelta(minutes=1), + ) + ] + ) + + +if __name__ == "__main__": + with patch.object(analytics_backend, "_seed_async", _seed_async): + analytics_backend.main() diff --git a/frontend/e2e/paired-outcomes.spec.ts b/frontend/e2e/paired-outcomes.spec.ts new file mode 100644 index 0000000000..4170ae90f0 --- /dev/null +++ b/frontend/e2e/paired-outcomes.spec.ts @@ -0,0 +1,67 @@ +import { expect, test } from '@playwright/test' +import { scenarioRunRoutePath } from '../src/utils/routeParams' + +const run = scenarioRunRoutePath('00000000-0000-0000-0000-00000000238c') + +test('compares persisted outcomes through the real API, including retries and exclusions', async ({ page }) => { + const errors: string[] = [] + page.on('pageerror', (error) => errors.push(error.message)) + await page.goto(run) + const panel = page.getByRole('region', { name: 'Paired outcomes', exact: true }) + await expect(panel).toBeVisible() + await expect(panel.getByRole('button', { name: 'Compare outcomes' })).toBeDisabled() + await panel.getByLabel('Baseline group').selectOption('baseline') + await panel.getByLabel('Attack group').selectOption('attack') + const response = page.waitForResponse((response) => response.url().includes('/paired-outcomes?')) + await panel.getByRole('button', { name: 'Compare outcomes' }).click() + const result = await response + expect(result.status()).toBe(200) + expect(await result.json()).toMatchObject({ + planned_pairs: 8, decided_pairs: 4, excluded_pairs: 4, + failure_to_success: 1, success_to_failure: 1, failure_to_failure: 1, success_to_success: 1, + baseline_success_rate: 0.5, attack_success_rate: 0.5, paired_difference: 0, + missing_both: 1, missing_attack: 1, attack_errors: 1, attack_undetermined: 1, + unmatched_baseline_seeds: 1, unmatched_attack_seeds: 1, + }) + const comparison = panel.getByRole('region', { name: 'Paired comparison' }) + await expect(comparison.getByRole('group', { name: 'Decided pairs' })).toContainText('4 / 8') + await expect(comparison.getByRole('group', { name: 'Baseline success rate' })).toContainText('50.0%') + await expect(comparison.getByRole('group', { name: 'Paired difference' })).toContainText('0.0 pp') + for (const label of ['Failure → Success', 'Success → Failure', 'Failure → Failure', 'Success → Success']) { + await expect(comparison.getByRole('row', { name: `${label} 1` })).toBeVisible() + } + await panel.getByLabel('Attack group').selectOption('') + await expect(comparison).toHaveCount(0) + await expect(panel.getByRole('button', { name: 'Compare outcomes' })).toBeDisabled() + expect(errors).toEqual([]) +}) + +test('keeps comparisons usable at a narrow viewport and with keyboard controls', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 390, height: 844 }) + await page.goto(run) + const panel = page.getByRole('region', { name: 'Paired outcomes', exact: true }) + await panel.getByLabel('Baseline group').selectOption('baseline') + await panel.getByLabel('Attack group').selectOption('attack') + await panel.getByLabel('Baseline group').focus() + await page.keyboard.press('Tab') + await expect(panel.getByLabel('Attack group')).toBeFocused() + await page.keyboard.press('Tab') + const button = panel.getByRole('button', { name: 'Compare outcomes' }) + await expect(button).toBeFocused() + await page.keyboard.press('Enter') + await expect(panel.getByRole('region', { name: 'Paired comparison' })).toBeVisible() + const overflow = await panel.evaluate((element) => element.scrollWidth > element.clientWidth) + expect(overflow).toBe(false) + const size = await button.boundingBox() + expect(size?.height).toBeGreaterThanOrEqual(44) + await panel.getByRole('table', { name: 'Outcome transitions' }).scrollIntoViewIfNeeded() + await expect(panel.getByRole('row', { name: 'Failure → Success 1' })).toBeVisible() + await page.screenshot({ path: testInfo.outputPath('paired-outcomes-mobile.png') }) +}) + +test('explains why legacy or failed runs cannot be compared', async ({ page }) => { + await page.goto(scenarioRunRoutePath('00000000-0000-0000-0000-00000000238d')) + await expect(page.getByRole('region', { name: 'Paired outcomes', exact: true })).toContainText('saved execution plan') + await page.goto(scenarioRunRoutePath('00000000-0000-0000-0000-00000000238e')) + await expect(page.getByRole('region', { name: 'Paired outcomes', exact: true })).toContainText('Complete the run') +}) diff --git a/frontend/package.json b/frontend/package.json index 0d4448c1ba..91e4466b9b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -16,6 +16,7 @@ "test:watch": "jest --watch", "test:coverage": "jest --coverage", "test:e2e": "playwright test", + "test:e2e:paired-outcomes": "npm run build && playwright test --config playwright.paired-outcomes.config.ts", "test:e2e:analytics": "npm run build && playwright test --config playwright.analytics.config.ts", "test:e2e:seeded": "playwright test --project seeded", "test:e2e:live": "E2E_LIVE_MODE=true playwright test --project live", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index 3487c87b46..b19f1e8d21 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -23,7 +23,7 @@ const E2E_BACKEND_URL = `http://127.0.0.1:${E2E_BACKEND_PORT}`; export default defineConfig({ testDir: "./e2e", - testIgnore: "**/analytics.spec.ts", + testIgnore: ["**/analytics.spec.ts", "**/paired-outcomes.spec.ts"], fullyParallel: true, forbidOnly: !!process.env.CI, retries: process.env.CI ? 2 : 0, diff --git a/frontend/playwright.paired-outcomes.config.ts b/frontend/playwright.paired-outcomes.config.ts new file mode 100644 index 0000000000..445b680e03 --- /dev/null +++ b/frontend/playwright.paired-outcomes.config.ts @@ -0,0 +1,22 @@ +import process from 'node:process' +import { defineConfig } from '@playwright/test' +import analytics from './playwright.analytics.config' + +const port = Number(process.env.PYRIT_E2E_PAIRED_PORT ?? '18497') +if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid paired outcomes test port') +const url = `http://127.0.0.1:${port}` + +export default defineConfig({ + ...analytics, + testMatch: 'paired-outcomes.spec.ts', + use: { + ...analytics.use, + baseURL: url, + storageState: { cookies: [], origins: [{ origin: url, localStorage: [{ name: 'pyrit-tour-completed', value: 'true' }] }] }, + }, + projects: [{ name: 'paired-outcomes', use: { viewport: { width: 1440, height: 1050 } } }], + webServer: { + command: `cd .. && uv run --no-sync python -m frontend.e2e.fixtures.paired_outcomes_backend --port ${port}`, + env: { PYTHONIOENCODING: 'utf-8' }, url: `${url}/api/health`, reuseExistingServer: false, timeout: 120_000, + }, +}) diff --git a/frontend/src/components/Scenarios/PairedOutcomes.styles.ts b/frontend/src/components/Scenarios/PairedOutcomes.styles.ts new file mode 100644 index 0000000000..fca3f35478 --- /dev/null +++ b/frontend/src/components/Scenarios/PairedOutcomes.styles.ts @@ -0,0 +1,41 @@ +import { makeStyles, tokens } from '@fluentui/react-components' + +import { MINIMUM_TOUCH_TARGET_SIZE, NARROW_VIEWPORT_QUERY } from '@/styles/touchTargets' + +export const usePairedOutcomesStyles = makeStyles({ + root: { + display: 'flex', + flexDirection: 'column', + gap: tokens.spacingVerticalM, + padding: tokens.spacingHorizontalL, + border: `1px solid ${tokens.colorNeutralStroke2}`, + borderRadius: tokens.borderRadiusMedium, + backgroundColor: tokens.colorNeutralBackground1, + minWidth: 0, + }, + controls: { + display: 'flex', + flexWrap: 'wrap', + alignItems: 'end', + gap: tokens.spacingHorizontalM, + '& select, & button': { minHeight: MINIMUM_TOUCH_TARGET_SIZE }, + [NARROW_VIEWPORT_QUERY]: { flexDirection: 'column', alignItems: 'stretch' }, + }, + selector: { + flex: '1 1 16rem', + minWidth: 0, + '& select': { width: '100%', textOverflow: 'ellipsis' }, + [NARROW_VIEWPORT_QUERY]: { flexBasis: 'auto' }, + }, + report: { + display: 'flex', + flexDirection: 'column', + gap: tokens.spacingVerticalM, + minWidth: 0, + }, + metrics: { + display: 'grid', + gridTemplateColumns: 'repeat(auto-fit, minmax(9rem, 1fr))', + gap: tokens.spacingHorizontalL, + }, +}) diff --git a/frontend/src/components/Scenarios/PairedOutcomes.test.tsx b/frontend/src/components/Scenarios/PairedOutcomes.test.tsx new file mode 100644 index 0000000000..895e14580d --- /dev/null +++ b/frontend/src/components/Scenarios/PairedOutcomes.test.tsx @@ -0,0 +1,101 @@ +import { act, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { FluentProvider, webLightTheme } from '@fluentui/react-components' +import { scenariosApi } from '@/services/api' +import type { PairedOutcomeStatistics, ScenarioRunPlan } from '@/types' +import PairedOutcomes from './PairedOutcomes' + +jest.mock('@/services/api', () => ({ scenariosApi: { getPairedOutcomes: jest.fn() } })) +const request = scenariosApi.getPairedOutcomes as jest.Mock +const plan: ScenarioRunPlan = { + version: 1, seed_groups: [], atomic_groups: [ + { id: 'base', kind: 'baseline', atomic_attack_name: 'baseline', display_group: 'Baseline', technique_eval_hash: 'b', seed_group_ids: [], tags: [] }, + { id: 'attack', kind: 'attack', atomic_attack_name: 'attack', display_group: 'Attack', technique_eval_hash: 'a', seed_group_ids: [], tags: [] }, + { id: 'other', kind: 'attack', atomic_attack_name: 'other', display_group: 'Other attack', technique_eval_hash: 'c', seed_group_ids: [], tags: [] }, + ], +} +const report: PairedOutcomeStatistics = { + baseline_group_id: 'base', attack_group_id: 'attack', planned_pairs: 6, decided_pairs: 4, excluded_pairs: 2, + failure_to_success: 1, success_to_failure: 1, failure_to_failure: 1, success_to_success: 1, + baseline_success_rate: 0.5, attack_success_rate: 0.5, paired_difference: 0, + missing_baseline: 0, missing_attack: 1, missing_both: 0, + baseline_errors: 0, attack_errors: 1, baseline_undetermined: 0, attack_undetermined: 0, + unmatched_baseline_seeds: 1, unmatched_attack_seeds: 0, unattributed_attempts: 0, +} +function mount(props: Partial> = {}) { + return render() +} +async function compare() { + const user = userEvent.setup() + await user.selectOptions(screen.getByLabelText('Baseline group'), 'base') + await user.selectOptions(screen.getByLabelText('Attack group'), 'attack') + await user.click(screen.getByRole('button', { name: 'Compare outcomes' })) + return user +} +beforeEach(() => { request.mockReset(); request.mockResolvedValue(report) }) + +test('requires explicit groups and shows backend transitions, paired rates and exclusions', async () => { + mount() + expect(screen.getByRole('button', { name: 'Compare outcomes' })).toBeDisabled() + expect(request).not.toHaveBeenCalled() + await compare() + const results = await screen.findByRole('region', { name: 'Paired comparison' }) + expect(within(results).getByRole('group', { name: 'Baseline success rate' })).toHaveTextContent('50.0%') + expect(within(results).getByRole('group', { name: 'Paired difference' })).toHaveTextContent('0.0 pp') + expect(within(results).getByRole('group', { name: 'Decided pairs' })).toHaveTextContent('4 / 6') + for (const name of ['Failure → Success', 'Success → Failure', 'Failure → Failure', 'Success → Success']) { + expect(within(results).getByRole('row', { name: `${name} 1` })).toBeInTheDocument() + } + expect(within(results).getByRole('group', { name: 'Excluded pairs' })).toHaveTextContent('2') + expect(within(results).getByText(/not establish causation/)).toBeInTheDocument() + expect(request).toHaveBeenCalledWith('run', { baseline_group_id: 'base', attack_group_id: 'attack' }, expect.any(AbortSignal)) +}) +test('shows unavailable rates when there are no decided pairs', async () => { + request.mockResolvedValue({ ...report, decided_pairs: 0, excluded_pairs: 6, + baseline_success_rate: null, attack_success_rate: null, paired_difference: null }) + mount(); await compare() + const results = await screen.findByRole('region', { name: 'Paired comparison' }) + expect(within(results).getByRole('group', { name: 'Baseline success rate' })).toHaveTextContent('Unavailable') + expect(within(results).getByRole('group', { name: 'Paired difference' })).toHaveTextContent('Unavailable') +}) +test('suppresses late results when a changed selection cancels a request', async () => { + let resolve!: (value: PairedOutcomeStatistics) => void + request.mockReturnValue(new Promise((done) => { resolve = done })) + mount() + const user = await compare() + const signal = request.mock.calls[0][2] as AbortSignal + await user.selectOptions(screen.getByLabelText('Attack group'), 'other') + expect(signal.aborted).toBe(true) + await act(async () => { resolve(report) }) + expect(screen.queryByRole('region', { name: 'Paired comparison' })).not.toBeInTheDocument() +}) +test('recovers from API errors and clears old results on refresh failure', async () => { + request.mockRejectedValueOnce(new Error('Scoring expectations are incompatible.')) + mount() + const user = await compare() + expect(await screen.findByText(/Scoring expectations are incompatible/)).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: 'Compare outcomes' })) + await screen.findByRole('region', { name: 'Paired comparison' }) + request.mockRejectedValueOnce(new Error('Connection lost')) + await user.click(screen.getByRole('button', { name: 'Compare outcomes' })) + await screen.findByText(/Connection lost/) + expect(screen.queryByRole('region', { name: 'Paired comparison' })).not.toBeInTheDocument() +}) +test.each([ + { status: 'IN_PROGRESS' as const, plan, message: /Complete the run/ }, + { status: 'FAILED' as const, plan, message: /Complete the run/ }, + { status: 'COMPLETED' as const, plan: null, message: /saved execution plan/ }, + { status: 'COMPLETED' as const, plan: { ...plan, atomic_groups: plan.atomic_groups.slice(1) }, message: /baseline and an attack group/ }, +])('explains unavailable comparisons without requesting results: $status', ({ message, ...props }) => { + mount(props) + expect(screen.getByText(message)).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Compare outcomes' })).not.toBeInTheDocument() + expect(request).not.toHaveBeenCalled() +}) +test('cancels requests on unmount', async () => { + request.mockReturnValue(new Promise(() => {})) + const view = mount(); await compare() + const signal = request.mock.calls[0][2] as AbortSignal + view.unmount() + expect(signal.aborted).toBe(true) +}) diff --git a/frontend/src/components/Scenarios/PairedOutcomes.tsx b/frontend/src/components/Scenarios/PairedOutcomes.tsx new file mode 100644 index 0000000000..96236cfe48 --- /dev/null +++ b/frontend/src/components/Scenarios/PairedOutcomes.tsx @@ -0,0 +1,229 @@ +import { useEffect, useId, useState } from 'react' + +import { + Button, + Field, + MessageBar, + MessageBarBody, + Select, + Spinner, + Table, + TableBody, + TableCell, + TableHeader, + TableHeaderCell, + TableRow, + Text, +} from '@fluentui/react-components' + +import { scenariosApi } from '@/services/api' +import { toApiError } from '@/services/errors' +import type { PairedOutcomeStatistics, ScenarioRunPlan, ScenarioRunState } from '@/types' + +import { usePairedOutcomesStyles } from './PairedOutcomes.styles' + +interface PairedOutcomesProps { + readonly scenarioResultId: string + readonly status: ScenarioRunState + readonly plan: ScenarioRunPlan | null +} + +interface ComparisonProps { + readonly scenarioResultId: string + readonly baselineId: string + readonly attackId: string +} + +/** Explicitly select two planned groups; the backend owns all matching and counting. */ +export default function PairedOutcomes({ scenarioResultId, status, plan }: PairedOutcomesProps) { + const styles = usePairedOutcomesStyles() + const headingId = useId() + const [baselineId, setBaselineId] = useState('') + const [attackId, setAttackId] = useState('') + const [comparison, setComparison] = useState<{ + baselineId: string + attackId: string + version: number + } | null>(null) + const baselines = plan?.atomic_groups.filter((group) => group.kind === 'baseline') ?? [] + const attacks = plan?.atomic_groups.filter((group) => group.kind === 'attack') ?? [] + const unavailable = status !== 'COMPLETED' + ? 'Complete the run before comparing baseline and attack outcomes.' + : !plan + ? 'Paired outcomes require a saved execution plan.' + : baselines.length === 0 || attacks.length === 0 + ? 'This run needs an explicitly identified baseline and an attack group to compare outcomes.' + : null + const validSelection = baselines.some((group) => group.id === baselineId) + && attacks.some((group) => group.id === attackId) + + return ( +
+ Paired outcomes + {unavailable ? {unavailable} : ( + <> + Compare the same logical objectives before and after an attack. +
+ + + + + + + +
+ {validSelection && comparison && comparison.baselineId === baselineId && comparison.attackId === attackId && ( + + )} + + )} +
+ ) +} + +/** A new selection or refresh mounts a new request, clearing previous results immediately. */ +function Comparison({ scenarioResultId, baselineId, attackId }: ComparisonProps) { + const styles = usePairedOutcomesStyles() + const [state, setState] = useState< + { status: 'loading' } + | { status: 'error'; error: string } + | { status: 'ready'; report: PairedOutcomeStatistics } + >({ status: 'loading' }) + + useEffect(() => { + const controller = new AbortController() + void scenariosApi.getPairedOutcomes(scenarioResultId, { + baseline_group_id: baselineId, + attack_group_id: attackId, + }, controller.signal).then((report) => { + if (!controller.signal.aborted) setState({ status: 'ready', report }) + }).catch((error: unknown) => { + if (!controller.signal.aborted) setState({ status: 'error', error: toApiError(error).detail }) + }) + return () => controller.abort() + }, [scenarioResultId, baselineId, attackId]) + + if (state.status === 'loading') return + if (state.status === 'error') { + return {state.error} + } + + const report = state.report + const difference = report.paired_difference === null + ? 'Unavailable' + : `${report.paired_difference > 0 ? '+' : ''}${(report.paired_difference * 100).toFixed(1)} pp` + const transitions = [ + ['Failure → Success', report.failure_to_success], + ['Success → Failure', report.success_to_failure], + ['Failure → Failure', report.failure_to_failure], + ['Success → Success', report.success_to_success], + ] as const + const exclusions = [ + ['Missing baseline', report.missing_baseline], + ['Missing attack', report.missing_attack], + ['Both missing', report.missing_both], + ['Baseline errors', report.baseline_errors], + ['Attack errors', report.attack_errors], + ['Baseline undetermined', report.baseline_undetermined], + ['Attack undetermined', report.attack_undetermined], + ['Unmatched baseline seeds', report.unmatched_baseline_seeds], + ['Unmatched attack seeds', report.unmatched_attack_seeds], + ['Unattributed attempts', report.unattributed_attempts], + ] as const + + return ( +
+
+ + + + + +
+ Rates use the same decided pairs. Difference = attack − baseline, in percentage points (pp). + + + + Baseline → Attack + Pairs + + + + {transitions.map(([label, count]) => ( + + {label} + {count.toLocaleString()} + + ))} + +
+ Exclusion details +
+ {exclusions.map(([label, count]) => )} +
+ + Planned pairs share a logical seed ID. Unmatched seeds are separate. + Reasons can overlap; do not sum them to reconstruct exclusions. + + + Only the latest top-level outcome counts; child attempts and older retries do not add pairs. + Missing scoring metadata limits compatibility checks. These observed differences do not establish causation. + +
+ ) +} + +function rate(value: number | null): string { + return value === null ? 'Unavailable' : `${(value * 100).toFixed(1)}%` +} + +function Metric({ label, value }: { label: string; value: string }) { + return ( +
+ {label} + {value} +
+ ) +} diff --git a/frontend/src/components/Scenarios/ScenarioRunPage.test.tsx b/frontend/src/components/Scenarios/ScenarioRunPage.test.tsx index 724a616504..7d22ca4069 100644 --- a/frontend/src/components/Scenarios/ScenarioRunPage.test.tsx +++ b/frontend/src/components/Scenarios/ScenarioRunPage.test.tsx @@ -685,6 +685,7 @@ describe('ScenarioRunPage', () => { 'Run configuration', 'Scenario queue', 'Overall progress', + 'Paired outcomes', 'Atomic attack groups', 'Objective Scorer', 'Techniques', diff --git a/frontend/src/components/Scenarios/ScenarioRunPage.tsx b/frontend/src/components/Scenarios/ScenarioRunPage.tsx index dcd931e5c1..4376a5b301 100644 --- a/frontend/src/components/Scenarios/ScenarioRunPage.tsx +++ b/frontend/src/components/Scenarios/ScenarioRunPage.tsx @@ -73,6 +73,7 @@ import AttackExecutionTable from './AttackExecutionTable' import { ObjectiveDetailsDialog, TechniqueDetailsDialog } from './ScenarioRunDialogs' import { useScenarioRunPageStyles } from './ScenarioRunPage.styles' import ScenarioQueue from './ScenarioQueue' +import PairedOutcomes from './PairedOutcomes' const CLOCK_REFRESH_INTERVAL_MS = 1_000 const MAX_VISIBLE_ATTEMPTS_PER_GROUP = 100 @@ -542,6 +543,8 @@ function ScenarioRunPageContent({ scenarioResultId, attackResultId }: ScenarioRu + +
diff --git a/frontend/src/services/api.ts b/frontend/src/services/api.ts index 15d0dd665b..2bd21495cd 100644 --- a/frontend/src/services/api.ts +++ b/frontend/src/services/api.ts @@ -53,6 +53,7 @@ import type { ScenarioRunSummary, ScenarioRunListResponse, ScenarioRunProgress, + PairedOutcomeStatistics, ScenarioQueueSnapshot, ScenarioRunState, ConfigurationFileContent, @@ -682,6 +683,18 @@ export const scenariosApi = { return response.data }, + getPairedOutcomes: async ( + scenarioResultId: string, + params: { baseline_group_id: string; attack_group_id: string }, + signal?: AbortSignal, + ): Promise => { + const response = await apiClient.get( + `/scenarios/runs/${encodeURIComponent(scenarioResultId)}/paired-outcomes`, + { params, signal }, + ) + return response.data + }, + getQueue: async (signal?: AbortSignal): Promise => { const response = await apiClient.get('/scenarios/runs/queue', { signal }) return response.data diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index ce12c01063..2946cb8bf5 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1661,7 +1661,33 @@ export interface ScenarioRunPlanSeedPrompt { parameters: string[] } +export interface PairedOutcomeStatistics { + baseline_group_id: string + attack_group_id: string + planned_pairs: number + decided_pairs: number + excluded_pairs: number + failure_to_success: number + success_to_failure: number + failure_to_failure: number + success_to_success: number + baseline_success_rate: number | null + attack_success_rate: number | null + paired_difference: number | null + missing_baseline: number + missing_attack: number + missing_both: number + baseline_errors: number + attack_errors: number + baseline_undetermined: number + attack_undetermined: number + unmatched_baseline_seeds: number + unmatched_attack_seeds: number + unattributed_attempts: number +} + export interface ScenarioRunPlanAtomicGroup { + kind?: 'baseline' | 'attack' | 'adaptive' | 'unknown' | null id: string atomic_attack_name: string display_group: string diff --git a/pyrit/analytics/__init__.py b/pyrit/analytics/__init__.py index f5113c3f66..89a5ec08be 100644 --- a/pyrit/analytics/__init__.py +++ b/pyrit/analytics/__init__.py @@ -12,6 +12,7 @@ from pyrit.analytics.attack_result_analytics import AttackResultAnalytics from pyrit.analytics.conversation_analytics import ConversationAnalytics from pyrit.analytics.outcome_statistics import combine_outcome_statistics, compute_outcome_statistics + from pyrit.analytics.paired_outcome_statistics import PairedOutcomeStatistics, compute_paired_outcome_statistics from pyrit.analytics.result_analysis import ( AttackStats, analyze_results, @@ -33,11 +34,13 @@ "AttackStats": "pyrit.analytics.result_analysis", "combine_outcome_statistics": "pyrit.analytics.outcome_statistics", "compute_outcome_statistics": "pyrit.analytics.outcome_statistics", + "compute_paired_outcome_statistics": "pyrit.analytics.paired_outcome_statistics", "compute_producer_counts": "pyrit.analytics.scenario_statistics", "compute_scenario_statistics": "pyrit.analytics.scenario_statistics", "compute_technique_stats_async": "pyrit.analytics.technique_analysis", "count_execution_units": "pyrit.analytics.scenario_statistics", "ConversationAnalytics": "pyrit.analytics.conversation_analytics", + "PairedOutcomeStatistics": "pyrit.analytics.paired_outcome_statistics", "ExactTextMatching": "pyrit.analytics.text_matching", "get_cached_results_for_technique": "pyrit.analytics.result_analysis", "get_cached_results_for_technique_async": "pyrit.analytics.result_analysis", diff --git a/pyrit/analytics/paired_outcome_statistics.py b/pyrit/analytics/paired_outcome_statistics.py new file mode 100644 index 0000000000..4291259736 --- /dev/null +++ b/pyrit/analytics/paired_outcome_statistics.py @@ -0,0 +1,427 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""Paired, effective baseline and attack outcomes within one planned scenario run.""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import TYPE_CHECKING + +from pyrit.analytics.scenario_statistics import ( + ScenarioPlanLookup, + load_scenario_run_plan, + resolve_attack_result_attempt, +) +from pyrit.common.utils import to_sha256 +from pyrit.models import AttackOutcome, ScenarioExecutionUnit, ScenarioRunPlanGroupKind + +if TYPE_CHECKING: + from collections.abc import Iterator + + from pyrit.analytics.scenario_statistics import ScenarioAttempt + from pyrit.models import AttackResult, ScenarioResult, ScenarioRunPlan, ScenarioRunPlanAtomicGroup + from pyrit.models.score import ScoringExpectation + + +@dataclass(frozen=True, slots=True) +class PairedOutcomeStatistics: + """ + Transition counts and exclusions for one explicitly selected pair of planned groups. + + ``planned_pairs`` counts seed IDs planned in both groups. Only shared IDs + whose latest top-level outcomes are both decided enter ``decided_pairs``. + Unmatched seed IDs are reported separately. Error and undetermined counts + describe each side, so they may overlap. + """ + + baseline_group_id: str + attack_group_id: str + planned_pairs: int + decided_pairs: int + excluded_pairs: int + failure_to_success: int + success_to_failure: int + failure_to_failure: int + success_to_success: int + baseline_success_rate: float | None + attack_success_rate: float | None + paired_difference: float | None + missing_baseline: int + missing_attack: int + missing_both: int + baseline_errors: int + attack_errors: int + baseline_undetermined: int + attack_undetermined: int + unmatched_baseline_seeds: int + unmatched_attack_seeds: int + unattributed_attempts: int + + +@dataclass(frozen=True, slots=True) +class _ScoringEvidence: + """Available scoring metadata for a persisted outcome.""" + + scorer_identifier: object | None = None + score_type: str | None = None + expectation: ScoringExpectation | None = None + + +@dataclass(frozen=True, slots=True) +class _OutcomeEvidence: + """Available evidence from a completion and its recorded child attempts.""" + + scores: tuple[_ScoringEvidence, ...] + objective_targets: tuple[str, ...] + + +def _selected_groups( + *, scenario_result: ScenarioResult, baseline_group_id: str, attack_group_id: str +) -> tuple[ScenarioRunPlanAtomicGroup, ScenarioRunPlanAtomicGroup, ScenarioRunPlan, ScenarioPlanLookup]: + """ + Validate the saved run plan and unambiguously resolve selected groups. + + Returns: + tuple[ScenarioRunPlanAtomicGroup, ScenarioRunPlanAtomicGroup, ScenarioRunPlan, ScenarioPlanLookup]: + The selected baseline, attack, validated plan and lookup. + + Raises: + ValueError: If the plan or selected groups are invalid or ambiguous. + """ + plan = load_scenario_run_plan(scenario_result) + if plan is None: + raise ValueError("Paired outcomes require a valid saved scenario run plan.") + if baseline_group_id == attack_group_id: + raise ValueError("Baseline and attack groups must be distinct.") + + by_id = {group.id: group for group in plan.atomic_groups} + if baseline_group_id not in by_id or attack_group_id not in by_id: + raise ValueError("Both selected atomic group IDs must exist in the saved run plan.") + baseline, attack = by_id[baseline_group_id], by_id[attack_group_id] + if baseline.kind != ScenarioRunPlanGroupKind.BASELINE or attack.kind != ScenarioRunPlanGroupKind.ATTACK: + raise ValueError("Selected groups must have explicit baseline and attack run-plan kinds.") + + # The canonical resolver indexes by (atomic name, technique evaluation hash). + # It cannot distinguish two planned groups with the same indexing identity. + for group in (baseline, attack): + if ( + sum( + other.atomic_attack_name == group.atomic_attack_name + and other.technique_eval_hash == group.technique_eval_hash + for other in plan.atomic_groups + ) + != 1 + ): + raise ValueError("Selected atomic group has an ambiguous name/configuration identity.") + + return baseline, attack, plan, ScenarioPlanLookup.from_plan(plan=plan) + + +def _score_details(result: AttackResult) -> _ScoringEvidence | None: + """ + Extract available scorer identity, type, and scoring criteria. + + Returns: + _ScoringEvidence | None: Persisted scorer identity, score type and expectation, if scored. + """ + score = result.last_score + if score is None: + return None + return _ScoringEvidence( + scorer_identifier=score.scorer_class_identifier, + score_type=score.score_type, + expectation=score.scored_expectation, + ) + + +def _objective_target_hash(result: AttackResult) -> str | None: + """ + Read the full recorded target identity, including model and endpoint. + + Returns: + str | None: Target identity hash, if the result records an objective target. + """ + identifier = result.atomic_attack_identifier + if identifier is None: + return None + technique = identifier.get_child("attack_technique") + attack = technique.get_child("attack") if technique is not None else identifier.get_child("attack") + target = attack.get_child("objective_target") if attack is not None else None + return target.hash if target is not None else None + + +def _linked_outcome_results(result: AttackResult, *, attempts_by_id: dict[str, AttackResult]) -> Iterator[AttackResult]: + """ + Traverse explicitly linked descendants without recursion or duplicate evidence. + + Yields: + AttackResult: The completion and its linked descendants. + + Raises: + ValueError: If a linked child is unavailable or the links contain a cycle. + """ + pending = [(result, False)] + active: set[str] = set() + visited: set[str] = set() + while pending: + linked, finished = pending.pop() + result_id = linked.attack_result_id + if finished: + active.remove(result_id) + visited.add(result_id) + continue + if result_id in active: + raise ValueError("A selected compound outcome contains a cycle in its child attack results.") + if result_id in visited: + continue + active.add(result_id) + pending.append((linked, True)) + child_ids = getattr(linked, "child_attack_result_ids", linked.metadata.get("child_attack_result_ids", ())) + live_children = {child.attack_result_id: child for child in getattr(linked, "child_attack_results", ())} + for child_id in reversed(child_ids): + child = attempts_by_id.get(child_id) or live_children.get(child_id) + if child is None: + raise ValueError("A selected compound outcome references a missing child attack result.") + pending.append((child, False)) + yield linked + + +def _outcome_evidence(result: AttackResult, *, attempts_by_id: dict[str, AttackResult]) -> _OutcomeEvidence: + """ + Retain scorer and target evidence from a completion and its linked descendants. + + Unrelated children and superseded top-level retries cannot affect it. + + Returns: + _OutcomeEvidence: Available scoring and objective-target identities. + + Raises: + ValueError: If linked descendants are missing or contain a cycle. + """ + scores: list[_ScoringEvidence] = [] + objective_targets: list[str] = [] + for linked in _linked_outcome_results(result, attempts_by_id=attempts_by_id): + score = _score_details(linked) + if score is not None: + scores.append(score) + target = _objective_target_hash(linked) + if target is not None: + objective_targets.append(target) + return _OutcomeEvidence(scores=tuple(scores), objective_targets=tuple(objective_targets)) + + +def _check_pair_evidence(before: _OutcomeEvidence, after: _OutcomeEvidence) -> None: + """ + Reject known target and scoring incompatibilities within one seed pair. + + Raises: + ValueError: If recorded target or scoring evidence conflicts. + """ + targets = before.objective_targets + after.objective_targets + if targets and any(target != targets[0] for target in targets[1:]): + raise ValueError("Selected outcomes used different objective targets.") + + scores = before.scores + after.scores + for attribute, message in ( + ("scorer_identifier", "Selected outcomes were evaluated by different scorers."), + ("score_type", "Selected outcomes have incompatible score types."), + ("expectation", "Selected outcomes have incompatible scoring expectations."), + ): + values = [value for score in scores if (value := getattr(score, attribute)) is not None] + if values and any(value != values[0] for value in values[1:]): + raise ValueError(message) + + +def compute_paired_outcome_statistics( + scenario_result: ScenarioResult, + *, + baseline_group_id: str, + attack_group_id: str, +) -> PairedOutcomeStatistics: + """ + Compare one baseline and one attack group from the same planned scenario run. + + Match only identical logical seed IDs in the saved plan. The latest top-level + attempt (timestamp, then result ID) determines each execution unit's outcome; + child attempts and superseded retries do not become extra observations. + Only pairs with SUCCESS/FAILURE on both sides enter the success rates. + + Args: + scenario_result (ScenarioResult): Hydrated results with a saved normalized run plan. + baseline_group_id (str): ID of a planned BASELINE atomic group. + attack_group_id (str): ID of a planned ATTACK atomic group. + + Returns: + PairedOutcomeStatistics: Observed transitions, paired rates, and exclusions. + + Raises: + ValueError: If the run plan, selection, attribution, objectives, or available + scorer identities cannot support an unambiguous comparison. + """ + baseline, attack, plan, lookup = _selected_groups( + scenario_result=scenario_result, + baseline_group_id=baseline_group_id, + attack_group_id=attack_group_id, + ) + baseline_seeds, attack_seeds = set(baseline.seed_group_ids), set(attack.seed_group_ids) + shared = baseline_seeds & attack_seeds + if not shared and (baseline_seeds or attack_seeds): + raise ValueError("Selected groups have no shared logical seed-group IDs to compare.") + + # The plan validates unique seed IDs. The same run carries the scenario-level + # target/scorer identity; per-result identities add stronger checks. + objectives = {seed.id: seed.objective_sha256 for seed in plan.seed_groups} + relevant_names = {baseline.atomic_attack_name, attack.atomic_attack_name} + selected_ids = {baseline.id, attack.id} + attempts_by_unit: dict[ScenarioExecutionUnit, list[tuple[ScenarioAttempt, AttackResult]]] = {} + seen_ids: set[str] = set() + unattributed_attempts = 0 + for name, results in scenario_result.attack_results.items(): + if name not in relevant_names: + continue + same_name_groups = lookup.groups_by_name.get(name, ()) + for result in results: + if result.attribution_data is not None and not isinstance(result.attribution_data, dict): + raise ValueError("An attempt has invalid attribution metadata.") + attribution = result.attribution_data or {} + eval_hash = attribution.get("parent_eval_hash") + if isinstance(eval_hash, str): + known_group = lookup.groups_by_identity.get((name, eval_hash)) + if known_group is not None and known_group.id not in selected_ids: + unattributed_attempts += 1 + continue + recorded_name = attribution.get("parent_collection") + if recorded_name is not None and recorded_name != name: + raise ValueError("An attempt's parent_collection disagrees with its recorded atomic name.") + if not isinstance(result.outcome, AttackOutcome): + raise ValueError("An attempt has an invalid outcome.") + if ( + not isinstance(result.timestamp, datetime) + or result.timestamp.tzinfo is None + or result.timestamp.utcoffset() is None + ): + raise ValueError("An attempt has an invalid timestamp.") + if not isinstance(result.metadata, dict): + raise ValueError("An attempt has invalid result metadata.") + children = result.metadata.get("child_attack_result_ids", ()) + if not isinstance(children, (list, tuple)) or any(not isinstance(child, str) for child in children): + raise ValueError("An attempt has invalid child_attack_result_ids metadata.") + child_index = attribution.get("attempt_index") + if child_index is not None and ( + not isinstance(child_index, int) or isinstance(child_index, bool) or child_index < 1 + ): + raise ValueError("An attempt has an invalid attempt_index.") + if len(same_name_groups) > 1 and not attribution.get("parent_eval_hash"): + raise ValueError("Attempt attribution cannot distinguish multiple planned configurations.") + attempt = resolve_attack_result_attempt(atomic_attack_name=name, attack_result=result, plan_lookup=lookup) + if attempt.unit.atomic_group_id not in selected_ids: + unattributed_attempts += 1 + continue + group = baseline if attempt.unit.atomic_group_id == baseline.id else attack + if attempt.attempt_id in seen_ids: + raise ValueError("Duplicate attack result IDs cannot be interpreted as separate attempts.") + seen_ids.add(attempt.attempt_id) + if attempt.unit.seed_group_id not in group.seed_group_ids: + raise ValueError("An attempt refers to a seed group outside its planned atomic group.") + if to_sha256(result.objective) != objectives[attempt.unit.seed_group_id]: + raise ValueError("An attempt's objective disagrees with its planned logical seed group.") + attempts_by_unit.setdefault(attempt.unit, []).append((attempt, result)) + + effective: dict[ScenarioExecutionUnit, tuple[AttackOutcome, AttackResult, dict[str, AttackResult]]] = {} + for unit, attempts in attempts_by_unit.items(): + attempts.sort(key=lambda entry: (entry[0].timestamp, entry[0].attempt_id)) + top_level = [entry for entry in attempts if entry[0].attempt_index is None] + if top_level: + attempt, result = top_level[-1] + by_id = {candidate.attack_result_id: candidate for _, candidate in attempts} + effective[unit] = (attempt.outcome, result, by_id) + + transitions: dict[tuple[AttackOutcome, AttackOutcome], int] = { + (before, after): 0 + for before in (AttackOutcome.FAILURE, AttackOutcome.SUCCESS) + for after in (AttackOutcome.FAILURE, AttackOutcome.SUCCESS) + } + missing_baseline = missing_attack = missing_both = 0 + baseline_errors = attack_errors = baseline_undetermined = attack_undetermined = 0 + observed_scorer: object | None = None + observed_score_type: str | None = None + observed_target: str | None = None + + for seed_id in shared: + before = effective.get(ScenarioExecutionUnit(atomic_group_id=baseline.id, seed_group_id=seed_id)) + after = effective.get(ScenarioExecutionUnit(atomic_group_id=attack.id, seed_group_id=seed_id)) + if before is None and after is None: + missing_both += 1 + elif before is None: + missing_baseline += 1 + elif after is None: + missing_attack += 1 + + if before is not None: + baseline_errors += before[0] == AttackOutcome.ERROR + baseline_undetermined += before[0] == AttackOutcome.UNDETERMINED + if after is not None: + attack_errors += after[0] == AttackOutcome.ERROR + attack_undetermined += after[0] == AttackOutcome.UNDETERMINED + + if before is None or after is None: + continue + before_score = _outcome_evidence(before[1], attempts_by_id=before[2]) + after_score = _outcome_evidence(after[1], attempts_by_id=after[2]) + _check_pair_evidence(before_score, after_score) + if (before[0], after[0]) in transitions: + for target in before_score.objective_targets + after_score.objective_targets: + if observed_target is not None and target != observed_target: + raise ValueError("Decided pairs contain incompatible objective targets.") + observed_target = target + for scoring_evidence in before_score.scores + after_score.scores: + scorer, score_type = scoring_evidence.scorer_identifier, scoring_evidence.score_type + if scorer is not None: + if observed_scorer is not None and scorer != observed_scorer: + raise ValueError("Decided pairs contain incompatible scorer identities.") + observed_scorer = scorer + if score_type is not None: + if observed_score_type is not None and score_type != observed_score_type: + raise ValueError("Decided pairs contain incompatible score types.") + observed_score_type = score_type + transitions[(before[0], after[0])] += 1 + + decided = sum(transitions.values()) + baseline_successes = ( + transitions[(AttackOutcome.SUCCESS, AttackOutcome.FAILURE)] + + transitions[(AttackOutcome.SUCCESS, AttackOutcome.SUCCESS)] + ) + attack_successes = ( + transitions[(AttackOutcome.FAILURE, AttackOutcome.SUCCESS)] + + transitions[(AttackOutcome.SUCCESS, AttackOutcome.SUCCESS)] + ) + baseline_rate = baseline_successes / decided if decided else None + attack_rate = attack_successes / decided if decided else None + return PairedOutcomeStatistics( + baseline_group_id=baseline.id, + attack_group_id=attack.id, + planned_pairs=len(shared), + decided_pairs=decided, + excluded_pairs=len(shared) - decided, + failure_to_success=transitions[(AttackOutcome.FAILURE, AttackOutcome.SUCCESS)], + success_to_failure=transitions[(AttackOutcome.SUCCESS, AttackOutcome.FAILURE)], + failure_to_failure=transitions[(AttackOutcome.FAILURE, AttackOutcome.FAILURE)], + success_to_success=transitions[(AttackOutcome.SUCCESS, AttackOutcome.SUCCESS)], + baseline_success_rate=baseline_rate, + attack_success_rate=attack_rate, + paired_difference=attack_rate - baseline_rate + if attack_rate is not None and baseline_rate is not None + else None, + missing_baseline=missing_baseline, + missing_attack=missing_attack, + missing_both=missing_both, + baseline_errors=baseline_errors, + attack_errors=attack_errors, + baseline_undetermined=baseline_undetermined, + attack_undetermined=attack_undetermined, + unmatched_baseline_seeds=len(baseline_seeds - attack_seeds), + unmatched_attack_seeds=len(attack_seeds - baseline_seeds), + unattributed_attempts=unattributed_attempts, + ) diff --git a/pyrit/backend/routes/scenarios.py b/pyrit/backend/routes/scenarios.py index 6ef2bdee5c..011a471514 100644 --- a/pyrit/backend/routes/scenarios.py +++ b/pyrit/backend/routes/scenarios.py @@ -15,7 +15,9 @@ import uuid from fastapi import APIRouter, HTTPException, Query, Request, status +from starlette.concurrency import run_in_threadpool +from pyrit.analytics import PairedOutcomeStatistics, compute_paired_outcome_statistics from pyrit.backend.models.common import MAX_ITEMS, CursorStr, IdentifierStr, LabelFilterStr, ProblemDetail from pyrit.backend.models.datasets import ScenarioDatasetLoadResponse from pyrit.backend.models.scenarios import ( @@ -437,3 +439,36 @@ async def get_scenario_run_results(scenario_result_id: IdentifierStr) -> Scenari detail=f"Scenario run '{scenario_result_id}' not found", ) return result + + +@router.get( + "/runs/{scenario_result_id}/paired-outcomes", + response_model=PairedOutcomeStatistics, + responses={ + 400: {"model": ProblemDetail, "description": "Selected groups cannot be compared"}, + 404: {"model": ProblemDetail, "description": "Run not found"}, + 409: {"model": ProblemDetail, "description": "Run not yet completed"}, + }, +) +async def get_paired_outcomes_async( + *, + scenario_result_id: IdentifierStr, + baseline_group_id: IdentifierStr = Query(..., description="Saved baseline atomic group ID"), + attack_group_id: IdentifierStr = Query(..., description="Saved attack atomic group ID"), +) -> PairedOutcomeStatistics: + """ + Compare explicitly selected groups using the SDK's effective outcome semantics. + + Returns: + PairedOutcomeStatistics: Transitions, paired rates, and exclusions for a completed run. + """ + result = await get_scenario_run_results(scenario_result_id=scenario_result_id) + try: + return await run_in_threadpool( + compute_paired_outcome_statistics, + result, + baseline_group_id=baseline_group_id, + attack_group_id=attack_group_id, + ) + except ValueError as exc: + raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from None diff --git a/tests/unit/analytics/test_paired_outcome_statistics.py b/tests/unit/analytics/test_paired_outcome_statistics.py new file mode 100644 index 0000000000..7809e50bf3 --- /dev/null +++ b/tests/unit/analytics/test_paired_outcome_statistics.py @@ -0,0 +1,902 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import uuid +from datetime import UTC, datetime, timedelta +from typing import ClassVar + +import pytest + +from pyrit.analytics.paired_outcome_statistics import compute_paired_outcome_statistics +from pyrit.common.utils import to_sha256 +from pyrit.executor.attack import PromptSendingAttack +from pyrit.executor.attack.compound import SequenceCompletionPolicy, SequentialAttackResult +from pyrit.models import ( + SCENARIO_RUN_PLAN_METADATA_KEY, + AtomicAttackIdentifier, + AttackIdentifier, + AttackOutcome, + AttackResult, + AttackSeedGroup, + ComponentIdentifier, + ScenarioRunPlan, + ScenarioRunPlanAtomicGroup, + ScenarioRunPlanGroupKind, + ScenarioRunPlanSeedGroup, + Score, + SeedObjective, + TargetIdentifier, +) +from pyrit.models.score import MatchesObjective, ScoringExpectation +from pyrit.scenario import DatasetConfiguration +from pyrit.scenario.core import AtomicAttack, BaselineAttackPolicy, Scenario, ScenarioTechnique +from pyrit.scenario.core.attack_technique import AttackTechnique +from pyrit.scenario.core.matrix_atomic_attack_builder import build_baseline_atomic_attack +from pyrit.score import SubStringScorer +from unit.mocks import MockPromptTarget, make_scenario_result + +_TIME = datetime(2026, 9, 1, tzinfo=UTC) + + +def _plan( + baseline_ids: tuple[str, ...] = ("a", "b", "c", "d"), + attack_ids: tuple[str, ...] = ("a", "b", "c", "d"), +) -> ScenarioRunPlan: + return ScenarioRunPlan( + atomic_groups=[ + ScenarioRunPlanAtomicGroup( + id="base", + atomic_attack_name="baseline", + display_group="Baseline", + technique_eval_hash="base-eval", + kind=ScenarioRunPlanGroupKind.BASELINE, + seed_group_ids=list(baseline_ids), + ), + ScenarioRunPlanAtomicGroup( + id="attack", + atomic_attack_name="attack", + display_group="Attack", + technique_eval_hash="attack-eval", + kind=ScenarioRunPlanGroupKind.ATTACK, + seed_group_ids=list(attack_ids), + ), + ], + seed_groups=[ + ScenarioRunPlanSeedGroup(id=seed, objective=seed, objective_sha256=to_sha256(seed)) + for seed in sorted(set(baseline_ids) | set(attack_ids)) + ], + ) + + +def _result( + seed: str, + outcome: AttackOutcome, + *, + seconds: int = 0, + group: str | None = None, + attempt_index: int | None = None, + result_id: str | None = None, + objective: str | None = None, +) -> AttackResult: + attribution = {"seed_group_id": seed} + if group is not None: + attribution["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=result_id or str(uuid.uuid4()), + objective=objective or seed, + outcome=outcome, + timestamp=_TIME + timedelta(seconds=seconds), + attribution_data=attribution, + ) + + +def _statistics(plan: ScenarioRunPlan, attack_results: dict[str, list[AttackResult]]): + scenario = make_scenario_result( + attack_results=attack_results, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, + ) + return compute_paired_outcome_statistics(scenario, baseline_group_id="base", attack_group_id="attack") + + +@pytest.mark.usefixtures("patch_central_database") +async def test_paired_outcomes_with_plan_built_by_real_scenario() -> None: + class PairTechnique(ScenarioTechnique): + ATTACK = ("attack", {"attack"}) + ALL = ("all", {"all"}) + + @classmethod + def get_aggregate_tags(cls) -> set[str]: + return {"all"} + + class PairScenario(Scenario): + BASELINE_ATTACK_POLICY: ClassVar[BaselineAttackPolicy] = BaselineAttackPolicy.Forbidden + + def __init__(self, *, atomic_attacks: list[AtomicAttack]) -> None: + super().__init__( + technique_class=PairTechnique, + default_dataset_config=DatasetConfiguration(), + objective_scorer=SubStringScorer(substring="success"), + version=1, + ) + self._paired_attacks = atomic_attacks + + async def _resolve_seed_groups_by_dataset_async(self, *, apply_sampling: bool = True): + return {} + + async def _build_atomic_attacks_async(self, *, context): + return self._paired_attacks + + target = MockPromptTarget() + scorer = SubStringScorer(substring="success") + seeds = [AttackSeedGroup(seeds=[SeedObjective(value="a")])] + baseline = build_baseline_atomic_attack(objective_target=target, objective_scorer=scorer, seed_groups=seeds) + attack = AtomicAttack( + atomic_attack_name="paired-attack", + technique_name="attack", + attack_technique=AttackTechnique(attack=PromptSendingAttack(objective_target=target)), + seed_groups=seeds, + ) + scenario = PairScenario(atomic_attacks=[baseline, attack]) + scenario.set_params_from_args(args={"objective_target": target}) + await scenario.initialize_async() + plan = scenario._build_run_plan() + baseline_group = next(group for group in plan.atomic_groups if group.kind == ScenarioRunPlanGroupKind.BASELINE) + attack_group = next(group for group in plan.atomic_groups if group.kind == ScenarioRunPlanGroupKind.ATTACK) + assert baseline_group.seed_group_ids == attack_group.seed_group_ids + + saved = make_scenario_result( + attack_results={ + baseline_group.atomic_attack_name: [_result("a", AttackOutcome.FAILURE)], + attack_group.atomic_attack_name: [_result("a", AttackOutcome.SUCCESS)], + }, + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, + ) + for name, group in ( + (baseline_group.atomic_attack_name, baseline_group), + (attack_group.atomic_attack_name, attack_group), + ): + result = saved.attack_results[name][0] + result.attribution_data = { + "parent_eval_hash": group.technique_eval_hash, + "seed_group_id": group.seed_group_ids[0], + } + stats = compute_paired_outcome_statistics( + saved, baseline_group_id=baseline_group.id, attack_group_id=attack_group.id + ) + assert (stats.planned_pairs, stats.decided_pairs, stats.failure_to_success) == (1, 1, 1) + + +def test_paired_outcomes_show_transitions_even_when_marginal_rates_are_equal() -> None: + plan = _plan() + result = _statistics( + plan, + { + "baseline": [ + _result("a", AttackOutcome.SUCCESS), + _result("b", AttackOutcome.SUCCESS), + _result("c", AttackOutcome.FAILURE), + _result("d", AttackOutcome.FAILURE), + ], + "attack": [ + _result("a", AttackOutcome.SUCCESS), + _result("b", AttackOutcome.FAILURE), + _result("c", AttackOutcome.SUCCESS), + _result("d", AttackOutcome.FAILURE), + ], + }, + ) + + assert (result.failure_to_success, result.success_to_failure) == (1, 1) + assert (result.failure_to_failure, result.success_to_success) == (1, 1) + assert (result.planned_pairs, result.decided_pairs, result.excluded_pairs) == (4, 4, 0) + assert result.baseline_success_rate == result.attack_success_rate == 0.5 + assert result.paired_difference == 0.0 + + +def test_paired_outcomes_use_latest_top_level_completion_once() -> None: + plan = _plan(("a",), ("a",)) + stats = _statistics( + plan, + { + "baseline": [_result("a", AttackOutcome.FAILURE)], + "attack": [ + _result("a", AttackOutcome.FAILURE, seconds=-3), + _result("a", AttackOutcome.ERROR, seconds=-2), + _result("a", AttackOutcome.SUCCESS, seconds=0), + _result("a", AttackOutcome.FAILURE, seconds=2, attempt_index=1), + ], + }, + ) + + assert stats.failure_to_success == 1 + assert stats.decided_pairs == 1 + assert stats.attack_errors == 0 + assert stats.paired_difference == 1.0 + + +def test_paired_outcomes_account_for_exclusions_without_rate_denominator_drift() -> None: + stats = _statistics( + _plan(("a", "b", "c", "d"), ("a", "b", "c", "e")), + { + "baseline": [ + _result("a", AttackOutcome.ERROR), + _result("b", AttackOutcome.UNDETERMINED), + _result("c", AttackOutcome.FAILURE), + ], + "attack": [ + _result("a", AttackOutcome.SUCCESS), + _result("b", AttackOutcome.ERROR), + _result("e", AttackOutcome.SUCCESS), + ], + }, + ) + + assert (stats.planned_pairs, stats.decided_pairs, stats.excluded_pairs) == (3, 0, 3) + assert (stats.unmatched_baseline_seeds, stats.unmatched_attack_seeds) == (1, 1) + assert (stats.missing_baseline, stats.missing_attack, stats.missing_both) == (0, 1, 0) + assert (stats.baseline_errors, stats.attack_errors) == (1, 1) + assert (stats.baseline_undetermined, stats.attack_undetermined) == (1, 0) + assert stats.baseline_success_rate is stats.attack_success_rate is stats.paired_difference is None + + +def test_paired_outcomes_account_for_both_missing_and_one_sided_missing() -> None: + stats = _statistics( + _plan(("a", "b", "c"), ("a", "b", "c")), + {"baseline": [_result("b", AttackOutcome.SUCCESS)], "attack": [_result("c", AttackOutcome.FAILURE)]}, + ) + + assert stats.missing_both == 1 + assert stats.missing_attack == 1 + assert stats.missing_baseline == 1 + assert stats.excluded_pairs == 3 + + +def test_paired_outcomes_report_unmatched_seeds_separately_from_pair_exclusions() -> None: + stats = _statistics( + _plan(("a", "b", "c", "d"), ("a", "b", "c")), + { + "baseline": [_result(seed, AttackOutcome.FAILURE) for seed in ("a", "b", "c", "d")], + "attack": [_result(seed, AttackOutcome.SUCCESS) for seed in ("a", "b", "c")], + }, + ) + + assert (stats.planned_pairs, stats.decided_pairs, stats.excluded_pairs) == (3, 3, 0) + assert (stats.unmatched_baseline_seeds, stats.unmatched_attack_seeds) == (1, 0) + assert stats.failure_to_success == 3 + + +def test_paired_outcomes_allow_empty_planned_groups() -> None: + stats = _statistics(_plan((), ()), {}) + assert stats.planned_pairs == stats.decided_pairs == stats.excluded_pairs == 0 + assert stats.paired_difference is None + assert stats.baseline_success_rate is None + + +def test_paired_outcomes_reject_disjoint_seed_groups() -> None: + with pytest.raises(ValueError, match="no shared logical seed-group"): + _statistics(_plan(("a",), ("b",)), {}) + + +def test_paired_outcomes_require_valid_plan_and_explicit_kinds() -> None: + scenario = make_scenario_result(attack_results={}) + with pytest.raises(ValueError, match="valid saved scenario run plan"): + compute_paired_outcome_statistics(scenario, baseline_group_id="base", attack_group_id="attack") + + plan = _plan(("a",), ("a",)) + plan.atomic_groups[0].kind = None + with pytest.raises(ValueError, match="explicit baseline and attack"): + _statistics(plan, {}) + + +def test_paired_outcomes_reject_ambiguous_group_configuration() -> None: + plan = _plan(("a",), ("a",)) + plan.atomic_groups.append( + ScenarioRunPlanAtomicGroup( + id="duplicate", + atomic_attack_name="baseline", + display_group="Other", + technique_eval_hash="base-eval", + kind=ScenarioRunPlanGroupKind.BASELINE, + seed_group_ids=["a"], + ) + ) + with pytest.raises(ValueError, match="ambiguous name/configuration"): + _statistics(plan, {}) + + +def test_paired_outcomes_reject_duplicate_results() -> None: + duplicate = _result("a", AttackOutcome.SUCCESS) + with pytest.raises(ValueError, match="Duplicate attack result IDs"): + _statistics(_plan(("a",), ("a",)), {"baseline": [duplicate, duplicate]}) + + +def test_paired_outcomes_reject_objective_drift_in_attributed_result() -> None: + with pytest.raises(ValueError, match="objective disagrees"): + _statistics( + _plan(("a",), ("a",)), + {"attack": [_result("a", AttackOutcome.SUCCESS, objective="a different objective")]}, + ) + + +def test_paired_outcomes_reject_ambiguous_attempt_attribution() -> None: + plan = _plan(("a",), ("a",)) + plan.atomic_groups.append( + ScenarioRunPlanAtomicGroup( + id="other", + atomic_attack_name="attack", + display_group="Another config", + technique_eval_hash="other-eval", + kind=ScenarioRunPlanGroupKind.ATTACK, + seed_group_ids=["a"], + ) + ) + with pytest.raises(ValueError, match="cannot distinguish multiple planned configurations"): + _statistics(plan, {"attack": [_result("a", AttackOutcome.SUCCESS)]}) + + +def _score(scorer: str, *, expectation: ScoringExpectation | None = None) -> Score: + return Score( + score_type="true_false", + score_value="true", + scorer_class_identifier=ComponentIdentifier(class_name=scorer, class_module="tests"), + scored_expectation=expectation, + ) + + +def _with_target(result: AttackResult, *, model_name: str, endpoint: str = "https://example.com") -> AttackResult: + result.atomic_attack_identifier = AtomicAttackIdentifier.build( + attack_identifier=AttackIdentifier( + class_name="PromptSendingAttack", + class_module="pyrit.executor.attack.single_turn.prompt_sending", + objective_target=TargetIdentifier( + class_name="MockPromptTarget", + class_module="tests", + model_name=model_name, + endpoint=endpoint, + ), + ) + ) + return result + + +@pytest.mark.parametrize( + ("baseline_model", "attack_model", "attack_endpoint"), + [("model-A", "model-B", "https://example.com"), ("model-A", "model-A", "https://other.example.com")], +) +def test_paired_outcomes_reject_different_recorded_objective_targets( + baseline_model: str, attack_model: str, attack_endpoint: str +) -> None: + baseline = _with_target(_result("a", AttackOutcome.FAILURE), model_name=baseline_model) + attack = _with_target(_result("a", AttackOutcome.SUCCESS), model_name=attack_model, endpoint=attack_endpoint) + + with pytest.raises(ValueError, match="different objective targets"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + +def test_paired_outcomes_reject_target_drift_across_decided_pairs() -> None: + baseline = [ + _with_target(_result(seed, AttackOutcome.FAILURE), model_name=model) + for seed, model in (("a", "model-A"), ("b", "model-B")) + ] + attack = [ + _with_target(_result(seed, AttackOutcome.SUCCESS), model_name=model) + for seed, model in (("a", "model-A"), ("b", "model-B")) + ] + + with pytest.raises(ValueError, match="incompatible objective targets"): + _statistics(_plan(("a", "b"), ("a", "b")), {"baseline": baseline, "attack": attack}) + + +def _compound_outcome( + *, scorer: str, expectation: ScoringExpectation | None = None +) -> tuple[SequentialAttackResult, AttackResult]: + child = _result("a", AttackOutcome.SUCCESS, group="attack", attempt_index=1) + child.automated_score = _score(scorer, expectation=expectation) + envelope = SequentialAttackResult.model_validate(_result("a", AttackOutcome.SUCCESS, group="attack").model_dump()) + envelope.completion_policy = SequenceCompletionPolicy.LAST_RESULT + envelope.metadata["completion_policy"] = SequenceCompletionPolicy.LAST_RESULT.value + envelope.metadata["child_attack_result_ids"] = [child.attack_result_id] + assert envelope.last_score is None + return envelope, child + + +def test_paired_outcomes_validate_compound_child_scorer_evidence() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("ScorerA") + envelope, child = _compound_outcome(scorer="ScorerB") + + with pytest.raises(ValueError, match="different scorers"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope, child]}) + + +def test_paired_outcomes_validate_live_compound_child_scorer_evidence() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("ScorerA") + envelope, child = _compound_outcome(scorer="ScorerB") + envelope.child_attack_results = [child] + + with pytest.raises(ValueError, match="different scorers"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope]}) + + +def _nested_compound_outcome() -> tuple[SequentialAttackResult, SequentialAttackResult, AttackResult]: + inner, leaf = _compound_outcome(scorer="SharedScorer", expectation=ScoringExpectation(objective="context")) + outer = inner.model_copy(deep=True) + outer.attack_result_id = str(uuid.uuid4()) + outer.metadata["child_attack_result_ids"] = [inner.attack_result_id] + outer.child_attack_results = [inner] + assert inner.attribution_data is not None + inner.attribution_data["attempt_index"] = 1 + inner.child_attack_results = [leaf] + return outer, inner, leaf + + +def _saved_compound_results(results: list[AttackResult]) -> list[AttackResult]: + return [ + AttackResult.model_validate({name: getattr(result, name) for name in AttackResult.model_fields}) + for result in results + ] + + +@pytest.mark.parametrize("live", [False, True]) +@pytest.mark.parametrize( + ("mismatch", "message"), + [ + ("scorer", "different scorers"), + ("target", "different objective targets"), + ("score_type", "incompatible score types"), + ("expectation", "incompatible scoring expectations"), + ], +) +def test_paired_outcomes_validate_nested_compound_evidence(live: bool, mismatch: str, message: str) -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + expectation = ScoringExpectation(objective="context") + baseline.automated_score = _score("SharedScorer", expectation=expectation) + outer, inner, leaf = _nested_compound_outcome() + if mismatch == "scorer": + leaf.automated_score = _score("OtherScorer", expectation=expectation) + elif mismatch == "target": + _with_target(baseline, model_name="model-A") + _with_target(leaf, model_name="model-B") + elif mismatch == "score_type": + leaf.automated_score = Score( + score_type="float_scale", + score_value="0.7", + scorer_class_identifier=baseline.automated_score.scorer_class_identifier, + scored_expectation=expectation, + ) + else: + leaf.automated_score = _score("SharedScorer", expectation=ScoringExpectation(objective="different context")) + results = [outer] if live else _saved_compound_results([outer, inner, leaf]) + + with pytest.raises(ValueError, match=message): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": results}) + + +@pytest.mark.parametrize("live", [False, True]) +@pytest.mark.parametrize("shared_leaf", [False, True]) +def test_paired_outcomes_count_compatible_nested_compound_once(live: bool, shared_leaf: bool) -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("SharedScorer", expectation=ScoringExpectation(objective="context")) + outer, inner, leaf = _nested_compound_outcome() + if shared_leaf: + outer.metadata["child_attack_result_ids"].append(leaf.attack_result_id) + outer.child_attack_results.append(leaf) + results = [outer] if live else _saved_compound_results([outer, inner, leaf]) + + stats = _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": results}) + + assert (stats.planned_pairs, stats.decided_pairs, stats.failure_to_success) == (1, 1, 1) + assert stats.paired_difference == 1.0 + + +@pytest.mark.parametrize("live", [False, True]) +def test_paired_outcomes_reject_missing_nested_compound_evidence(live: bool) -> None: + outer, inner, _ = _nested_compound_outcome() + inner.child_attack_results = [] + results = [outer] if live else _saved_compound_results([outer, inner]) + + with pytest.raises(ValueError, match="missing child attack result"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE, group="base")], "attack": results}, + ) + + +@pytest.mark.parametrize("live", [False, True]) +@pytest.mark.parametrize("self_reference", [False, True]) +def test_paired_outcomes_reject_compound_cycles(live: bool, self_reference: bool) -> None: + outer, inner, _ = _nested_compound_outcome() + linked = outer if self_reference else inner + linked.metadata["child_attack_result_ids"] = [outer.attack_result_id] + linked.child_attack_results = [outer] + results = [outer] if live else _saved_compound_results([outer, inner]) + + with pytest.raises(ValueError, match="cycle"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE, group="base")], "attack": results}, + ) + + +def test_paired_outcomes_handle_deep_saved_compounds_without_recursion_limit() -> None: + leaf = _result("a", AttackOutcome.SUCCESS, group="attack", attempt_index=1) + leaf.automated_score = _score("SharedScorer") + results = [leaf] + for _ in range(1500): + parent = _result("a", AttackOutcome.SUCCESS, group="attack", attempt_index=1) + parent.metadata["child_attack_result_ids"] = [results[-1].attack_result_id] + results.append(parent) + assert results[-1].attribution_data is not None + results[-1].attribution_data.pop("attempt_index") + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("SharedScorer") + + stats = _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": results}) + + assert (stats.decided_pairs, stats.failure_to_success) == (1, 1) + + +def test_paired_outcomes_reject_compound_child_target_mismatch() -> None: + baseline = _with_target(_result("a", AttackOutcome.FAILURE, group="base"), model_name="model-A") + envelope, child = _compound_outcome(scorer="SharedScorer") + _with_target(child, model_name="model-B") + + with pytest.raises(ValueError, match="different objective targets"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope, child]}) + + +def test_paired_outcomes_validate_compound_child_scoring_expectation() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("SharedScorer", expectation=ScoringExpectation(objective="first")) + envelope, child = _compound_outcome(scorer="SharedScorer", expectation=ScoringExpectation(objective="second")) + + with pytest.raises(ValueError, match="scoring expectations"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope, child]}) + + +def test_paired_outcomes_accept_matching_compound_child_scoring_evidence() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + baseline.automated_score = _score("SharedScorer") + envelope, child = _compound_outcome(scorer="SharedScorer") + unrelated = _result("a", AttackOutcome.FAILURE, group="attack", attempt_index=2) + unrelated.automated_score = _score("OtherScorer") + + stats = _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope, child, unrelated]}) + assert (stats.decided_pairs, stats.failure_to_success) == (1, 1) + + +def test_paired_outcomes_reject_unavailable_compound_child_evidence() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + envelope, _ = _compound_outcome(scorer="SharedScorer") + + with pytest.raises(ValueError, match="missing child attack result"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [envelope]}) + + +def test_paired_outcomes_exclude_unpaired_compound_without_child_evidence() -> None: + envelope, _ = _compound_outcome(scorer="SharedScorer") + stats = _statistics(_plan(("a",), ("a",)), {"attack": [envelope]}) + + assert (stats.decided_pairs, stats.missing_baseline, stats.excluded_pairs) == (0, 1, 1) + + +def test_paired_outcomes_reject_incompatible_persisted_scorers() -> None: + baseline = _result("a", AttackOutcome.SUCCESS, group="base") + attack = _result("a", AttackOutcome.SUCCESS, group="attack") + baseline.automated_score = _score("ScorerA") + attack.automated_score = _score("ScorerB") + + with pytest.raises(ValueError, match="different scorers"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + +def test_paired_outcomes_use_human_override_score_identity() -> None: + baseline = _result("a", AttackOutcome.FAILURE, group="base") + attack = _result("a", AttackOutcome.SUCCESS, group="attack") + baseline.automated_score = _score("ScorerA") + attack.automated_score = _score("OldScorer") + attack.human_score = _score("ScorerA") + stats = _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + assert stats.failure_to_success == 1 + + +def test_paired_outcomes_include_reused_persisted_completion() -> None: + # Reused completions can precede the live scenario and still carry valid + # plan attribution. Their timestamp must not prevent matching. + cached_baseline = _result("a", AttackOutcome.FAILURE, seconds=-3600, group="base") + cached_attack = _result("a", AttackOutcome.SUCCESS, seconds=-3600, group="attack") + stats = _statistics( + _plan(("a",), ("a",)), + {"baseline": [cached_baseline], "attack": [cached_attack]}, + ) + + assert (stats.planned_pairs, stats.decided_pairs, stats.failure_to_success) == (1, 1, 1) + + +def test_paired_outcomes_resolve_unique_seed_from_objective_without_explicit_attribution() -> None: + # Legacy records may omit the seed ID if the objective uniquely identifies a planned seed. + attack = _result("a", AttackOutcome.SUCCESS) + attack.attribution_data = None + + stats = _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": [attack]}, + ) + + assert stats.failure_to_success == stats.decided_pairs == 1 + assert stats.unattributed_attempts == 0 + + +def test_paired_outcomes_reject_ambiguous_objective_only_seed_attribution() -> None: + plan = _plan(("a", "b"), ("a", "b")) + # Distinct logical seeds are allowed to have the same objective. Without a + # persisted seed ID, an outcome cannot safely be assigned to either seed. + plan.seed_groups[1].objective = "a" + plan.seed_groups[1].objective_sha256 = to_sha256("a") + ambiguous = _result("a", AttackOutcome.SUCCESS, group="attack") + ambiguous.attribution_data = {"parent_eval_hash": "attack-eval"} + + with pytest.raises(ValueError, match="ambiguous|seed"): + _statistics(plan, {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": [ambiguous]}) + + +def test_paired_outcomes_do_not_count_other_configuration_with_same_atomic_name() -> None: + plan = _plan(("a",), ("a",)) + plan.atomic_groups.append( + ScenarioRunPlanAtomicGroup( + id="other", + atomic_attack_name="attack", + display_group="Other attack configuration", + technique_eval_hash="other-eval", + kind=ScenarioRunPlanGroupKind.ATTACK, + seed_group_ids=["a"], + ) + ) + unrelated = _result("a", AttackOutcome.FAILURE, seconds=10) + unrelated.attribution_data = {"seed_group_id": "a", "parent_eval_hash": "other-eval"} + + stats = _statistics( + plan, + { + "baseline": [_result("a", AttackOutcome.FAILURE, group="base")], + "attack": [_result("a", AttackOutcome.SUCCESS, group="attack"), unrelated], + }, + ) + + assert (stats.decided_pairs, stats.failure_to_success, stats.unattributed_attempts) == (1, 1, 1) + + +def test_paired_outcomes_ignore_malformed_records_from_known_unselected_configuration() -> None: + plan = _plan(("a",), ("a",)) + plan.atomic_groups.append( + ScenarioRunPlanAtomicGroup( + id="other", + atomic_attack_name="attack", + display_group="Other attack configuration", + technique_eval_hash="other-eval", + kind=ScenarioRunPlanGroupKind.ATTACK, + seed_group_ids=["a"], + ) + ) + unrelated = _result("a", AttackOutcome.FAILURE, group="other") + unrelated.timestamp = None # type: ignore[assignment] + unrelated.metadata["child_attack_result_ids"] = None + + stats = _statistics( + plan, + { + "baseline": [_result("a", AttackOutcome.FAILURE, group="base")], + "attack": [_result("a", AttackOutcome.SUCCESS, group="attack"), unrelated], + }, + ) + + assert (stats.decided_pairs, stats.failure_to_success, stats.unattributed_attempts) == (1, 1, 1) + + +def test_paired_outcomes_reject_conflicting_persisted_parent_collection() -> None: + mismatched = _result("a", AttackOutcome.SUCCESS, group="attack") + assert mismatched.attribution_data is not None + mismatched.attribution_data["parent_collection"] = "different_atomic_attack" + + with pytest.raises(ValueError, match="parent_collection|collection"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE, group="base")], "attack": [mismatched]}, + ) + + +def test_paired_outcomes_distinguish_selected_groups_sharing_an_atomic_name() -> None: + plan = _plan(("a",), ("a",)) + for group in plan.atomic_groups: + group.atomic_attack_name = "shared" + + stats = _statistics( + plan, + { + "shared": [ + _result("a", AttackOutcome.FAILURE, group="base"), + _result("a", AttackOutcome.SUCCESS, group="attack"), + ] + }, + ) + + assert (stats.decided_pairs, stats.failure_to_success, stats.unattributed_attempts) == (1, 1, 0) + + +def test_paired_outcomes_reject_duplicate_ids_across_selected_groups() -> None: + with pytest.raises(ValueError, match="Duplicate attack result IDs"): + _statistics( + _plan(("a",), ("a",)), + { + "baseline": [_result("a", AttackOutcome.FAILURE, result_id="reused-id")], + "attack": [_result("a", AttackOutcome.SUCCESS, result_id="reused-id")], + }, + ) + + +def test_paired_outcomes_reject_mixed_scorers_across_decided_pairs() -> None: + # Every pair is internally compatible, but the aggregated success rates + # silently combine evaluations from different scorer implementations. + baseline = [_result(seed, AttackOutcome.FAILURE) for seed in ("a", "b")] + attack = [_result(seed, AttackOutcome.SUCCESS) for seed in ("a", "b")] + for scorer, before, after in zip(("ScorerA", "ScorerB"), baseline, attack, strict=True): + before.automated_score = _score(scorer) + after.automated_score = _score(scorer) + + with pytest.raises(ValueError, match="scorer|incompatible"): + _statistics(_plan(("a", "b"), ("a", "b")), {"baseline": baseline, "attack": attack}) + + +def test_paired_outcomes_reject_different_score_types_from_same_scorer() -> None: + baseline = _result("a", AttackOutcome.FAILURE) + attack = _result("a", AttackOutcome.SUCCESS) + baseline.automated_score = _score("SharedScorer") + attack.automated_score = Score( + score_type="float_scale", + score_value="0.7", + scorer_class_identifier=ComponentIdentifier(class_name="SharedScorer", class_module="tests"), + ) + + with pytest.raises(ValueError, match="score|incompatible|type"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + +def test_paired_outcomes_reject_incompatible_scoring_objectives_within_pair() -> None: + baseline = _result("a", AttackOutcome.FAILURE) + attack = _result("a", AttackOutcome.SUCCESS) + baseline.automated_score = _score( + "SharedScorer", expectation=ScoringExpectation(objective="expected scoring context") + ) + attack.automated_score = Score( + score_type="true_false", + score_value="true", + scorer_class_identifier=ComponentIdentifier(class_name="SharedScorer", class_module="tests"), + objective="unrelated objective", + ) + + with pytest.raises(ValueError, match="scoring expectations"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + +def test_paired_outcomes_allow_matching_scoring_objective_distinct_from_attack_objective() -> None: + baseline = _result("a", AttackOutcome.FAILURE) + attack = _result("a", AttackOutcome.SUCCESS) + expectation = ScoringExpectation(objective="scoring context distinct from the attack objective") + baseline.automated_score = _score("SharedScorer", expectation=expectation) + attack.automated_score = _score("SharedScorer", expectation=expectation) + + stats = _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + assert stats.decided_pairs == stats.failure_to_success == 1 + + +def test_paired_outcomes_reject_different_scoring_criteria_within_pair() -> None: + baseline = _result("a", AttackOutcome.FAILURE) + attack = _result("a", AttackOutcome.SUCCESS) + baseline.automated_score = _score( + "SharedScorer", expectation=ScoringExpectation(objective="context", conditions=(MatchesObjective(),)) + ) + attack.automated_score = _score("SharedScorer", expectation=ScoringExpectation(objective="context", conditions=())) + + with pytest.raises(ValueError, match="scoring expectations"): + _statistics(_plan(("a",), ("a",)), {"baseline": [baseline], "attack": [attack]}) + + +def test_paired_outcomes_allow_distinct_scoring_contexts_across_matched_seeds() -> None: + baseline = [_result(seed, AttackOutcome.FAILURE) for seed in ("a", "b")] + attack = [_result(seed, AttackOutcome.SUCCESS) for seed in ("a", "b")] + for seed, before, after in zip(("a", "b"), baseline, attack, strict=True): + expectation = ScoringExpectation(objective=f"scoring context for {seed}") + before.automated_score = _score("SharedScorer", expectation=expectation) + after.automated_score = _score("SharedScorer", expectation=expectation) + + stats = _statistics(_plan(("a", "b"), ("a", "b")), {"baseline": baseline, "attack": attack}) + assert (stats.decided_pairs, stats.failure_to_success) == (2, 2) + + +@pytest.mark.parametrize("invalid_index", [0, -1, "1", True]) +def test_paired_outcomes_reject_invalid_child_attempt_index(invalid_index: object) -> None: + # Invalid but present child metadata must not silently promote a child to + # top-level status and let it supersede a completed parent result. + child = _result("a", AttackOutcome.FAILURE, seconds=10) + assert child.attribution_data is not None + child.attribution_data["attempt_index"] = invalid_index + + with pytest.raises(ValueError, match="attempt_index|malformed|invalid"): + _statistics( + _plan(("a",), ("a",)), + { + "baseline": [_result("a", AttackOutcome.FAILURE)], + "attack": [_result("a", AttackOutcome.SUCCESS), child], + }, + ) + + +def test_paired_outcomes_use_result_id_as_tie_breaker_independent_of_input_order() -> None: + # Two top-level completions can share a persisted timestamp. The higher + # result ID determines the winner regardless of result-list ordering. + older_id = _result("a", AttackOutcome.FAILURE, result_id="a-result") + newer_id = _result("a", AttackOutcome.SUCCESS, result_id="z-result") + + for results in ([newer_id, older_id], [older_id, newer_id]): + stats = _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": results}, + ) + assert (stats.decided_pairs, stats.failure_to_success, stats.paired_difference) == (1, 1, 1.0) + + +def test_paired_outcomes_exclude_pair_when_latest_top_level_retry_errors() -> None: + stats = _statistics( + _plan(("a",), ("a",)), + { + "baseline": [_result("a", AttackOutcome.FAILURE)], + "attack": [ + _result("a", AttackOutcome.SUCCESS, seconds=-1), + _result("a", AttackOutcome.ERROR, seconds=1), + ], + }, + ) + + assert (stats.decided_pairs, stats.excluded_pairs, stats.attack_errors) == (0, 1, 1) + assert stats.failure_to_success == 0 + assert stats.paired_difference is None + + +def test_paired_outcomes_reject_malformed_timestamp_in_candidate_completion() -> None: + result = _result("a", AttackOutcome.SUCCESS) + # Hydrated result models are mutable; a damaged persisted timestamp makes + # chronological latest-result selection unverifiable. + result.timestamp = None # type: ignore[assignment] + + with pytest.raises(ValueError, match="timestamp"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": [result]}, + ) + + +def test_paired_outcomes_reject_unrecognized_persisted_outcome() -> None: + result = _result("a", AttackOutcome.SUCCESS) + result.outcome = "not_a_valid_outcome" # type: ignore[assignment] + + with pytest.raises(ValueError, match="outcome"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": [result]}, + ) + + +def test_paired_outcomes_reject_malformed_child_result_ids() -> None: + result = _result("a", AttackOutcome.SUCCESS) + result.metadata["child_attack_result_ids"] = None + + with pytest.raises(ValueError, match="child_attack_result_ids|metadata|invalid"): + _statistics( + _plan(("a",), ("a",)), + {"baseline": [_result("a", AttackOutcome.FAILURE)], "attack": [result]}, + ) diff --git a/tests/unit/backend/test_paired_outcome_routes.py b/tests/unit/backend/test_paired_outcome_routes.py new file mode 100644 index 0000000000..1bb605147a --- /dev/null +++ b/tests/unit/backend/test_paired_outcome_routes.py @@ -0,0 +1,156 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +"""HTTP contract for paired analytics using real SDK computations.""" + +from datetime import UTC, datetime +from unittest.mock import AsyncMock, patch +from uuid import uuid4 + +import pytest +from fastapi.testclient import TestClient + +from pyrit.backend.main import app +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 + + +def _saved_result() -> ScenarioResult: + plan = ScenarioRunPlan( + atomic_groups=[ + ScenarioRunPlanAtomicGroup( + id=group, + atomic_attack_name=group, + display_group=group, + technique_eval_hash=group, + kind=kind, + seed_group_ids=["a", "b", "c", "d", "missing"], + ) + for group, kind in [ + ("baseline", ScenarioRunPlanGroupKind.BASELINE), + ("attack", ScenarioRunPlanGroupKind.ATTACK), + ] + ], + seed_groups=[ + ScenarioRunPlanSeedGroup(id=seed, objective=seed, objective_sha256=to_sha256(seed)) + for seed in ["a", "b", "c", "d", "missing"] + ], + ) + outcomes = { + "baseline": [AttackOutcome.FAILURE, AttackOutcome.SUCCESS, AttackOutcome.FAILURE, AttackOutcome.SUCCESS], + "attack": [AttackOutcome.SUCCESS, AttackOutcome.FAILURE, AttackOutcome.FAILURE, AttackOutcome.SUCCESS], + } + return make_scenario_result( + metadata={SCENARIO_RUN_PLAN_METADATA_KEY: plan.model_dump(mode="json")}, + attack_results={ + group: [ + AttackResult( + attack_result_id=str(uuid4()), + conversation_id=str(uuid4()), + objective=seed, + outcome=outcome, + timestamp=datetime(2026, 10, 20, tzinfo=UTC), + attribution_data={"seed_group_id": seed, "parent_eval_hash": group}, + ) + for seed, outcome in zip(["a", "b", "c", "d"], values, strict=True) + ] + for group, values in outcomes.items() + }, + ) + + +@pytest.fixture +def client(compatibility_headers: dict[str, str]) -> TestClient: + return TestClient(app, headers=compatibility_headers) + + +def test_paired_outcomes_reports_transitions_and_shared_denominator(client: TestClient) -> None: + with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as service: + service.return_value.get_run_results_async = AsyncMock(return_value=_saved_result()) + response = client.get( + "/api/scenarios/runs/saved/paired-outcomes", + params={ + "baseline_group_id": "baseline", + "attack_group_id": "attack", + }, + ) + assert response.status_code == 200 + assert response.json() == { + "baseline_group_id": "baseline", + "attack_group_id": "attack", + "planned_pairs": 5, + "decided_pairs": 4, + "excluded_pairs": 1, + "failure_to_success": 1, + "success_to_failure": 1, + "failure_to_failure": 1, + "success_to_success": 1, + "baseline_success_rate": 0.5, + "attack_success_rate": 0.5, + "paired_difference": 0.0, + "missing_baseline": 0, + "missing_attack": 0, + "missing_both": 1, + "baseline_errors": 0, + "attack_errors": 0, + "baseline_undetermined": 0, + "attack_undetermined": 0, + "unmatched_baseline_seeds": 0, + "unmatched_attack_seeds": 0, + "unattributed_attempts": 0, + } + + +@pytest.mark.parametrize( + ("saved", "error", "expected"), + [ + (None, None, 404), + (None, ValueError("Results are only available for completed runs."), 409), + (_saved_result(), None, 400), + ], +) +def test_paired_outcomes_returns_explicit_errors( + client: TestClient, saved: ScenarioResult | None, error: ValueError | None, expected: int +) -> None: + with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as service: + service.return_value.get_run_results_async = AsyncMock(return_value=saved, side_effect=error) + response = client.get( + "/api/scenarios/runs/saved/paired-outcomes", + params={ + "baseline_group_id": "baseline", + "attack_group_id": "unrelated", + }, + ) + assert response.status_code == expected + assert response.json()["detail"] + + +def test_paired_outcomes_requires_explicit_groups(client: TestClient) -> None: + response = client.get("/api/scenarios/runs/saved/paired-outcomes") + assert response.status_code == 422 + + +def test_paired_outcomes_rejects_legacy_plan(client: TestClient) -> None: + saved = _saved_result() + saved.metadata = {} + with patch("pyrit.backend.routes.scenarios.get_scenario_run_service") as service: + service.return_value.get_run_results_async = AsyncMock(return_value=saved) + response = client.get( + "/api/scenarios/runs/saved/paired-outcomes", + params={ + "baseline_group_id": "baseline", + "attack_group_id": "attack", + }, + ) + assert response.status_code == 400 + assert "saved scenario run plan" in response.json()["detail"]