Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/frontend_tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
82 changes: 82 additions & 0 deletions doc/code/analytics/0_attack_results.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
31 changes: 31 additions & 0 deletions doc/gui/0_gui.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
1 change: 1 addition & 0 deletions frontend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```

Expand Down
157 changes: 157 additions & 0 deletions frontend/e2e/fixtures/paired_outcomes_backend.py
Original file line number Diff line number Diff line change
@@ -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()
67 changes: 67 additions & 0 deletions frontend/e2e/paired-outcomes.spec.ts
Original file line number Diff line number Diff line change
@@ -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')
})
1 change: 1 addition & 0 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
2 changes: 1 addition & 1 deletion frontend/playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading