From b73b489375b9b7343c34bfb38a014e074c28e1c4 Mon Sep 17 00:00:00 2001 From: Behnam Ousat Date: Wed, 25 Nov 2026 11:37:41 -0800 Subject: [PATCH] FEAT: Store scenario planned units and link attempts to them for history Scenario history rebuilt each run's planned units from the run_plan JSON in ScenarioResultEntries.scenario_metadata and matched every attempt to them with nested OPENJSON/json_each on every read. On SQL Server this re-expanded the plan per attempt and exhausted the database. - Add ScenarioPlannedUnitEntries (one row per planned atomic group x seed group), written in the same transaction as the scenario result. - Add AttackResultEntries.planned_unit_id (FK, NO ACTION). AtomicAttack and the adversarial benchmark's cached copies set it at write time through AttackResultAttribution, using the deterministic ScenarioRunPlan.compute_planned_unit_id so resumed runs need no lookup. - Scenario history aggregates join the planned unit on its primary key instead of expanding the plan; runs without a plan keep the legacy path. The backend _get_scenario_plan_unit_subqueries hooks are removed. - Migration 54eb9489b8f0 creates the table, column and indexes on SQLite and SQL Server, backfills units from every stored run plan, and links existing attempts with the resolution history used (name + technique hash, then attributed seed group or a unique objective match). Unresolved attempts stay NULL; counts are logged. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- pyrit/analytics/scenario_statistics.py | 3 +- .../attack/core/attack_result_attribution.py | 5 + pyrit/executor/attack/core/attack_strategy.py | 1 + ...54eb9489b8f0_add_scenario_planned_units.py | 324 ++++++++++++++++++ pyrit/memory/azure_sql_memory.py | 93 +---- pyrit/memory/memory_interface.py | 206 +++-------- pyrit/memory/memory_models.py | 61 ++++ pyrit/memory/sqlite_memory.py | 64 ---- pyrit/models/results/attack_result.py | 2 + pyrit/models/scenario_progress.py | 28 +- pyrit/scenario/core/atomic_attack.py | 6 + .../scenarios/benchmark/adversarial.py | 9 + .../test_scenario_statistics_parity.py | 7 + .../backend/test_scenario_hierarchy_parity.py | 6 + .../attack/core/test_attack_strategy.py | 4 + .../test_interface_scenario_history.py | 52 ++- tests/unit/memory/test_azure_sql_memory.py | 28 +- .../test_finding_field_values_migration.py | 1 + .../test_scenario_planned_units_migration.py | 219 ++++++++++++ .../scenario/benchmark/test_adversarial.py | 11 + .../unit/scenario/core/test_atomic_attack.py | 26 ++ 21 files changed, 814 insertions(+), 342 deletions(-) create mode 100644 pyrit/memory/alembic/versions/54eb9489b8f0_add_scenario_planned_units.py create mode 100644 tests/unit/memory/test_scenario_planned_units_migration.py diff --git a/pyrit/analytics/scenario_statistics.py b/pyrit/analytics/scenario_statistics.py index 1e4c98986b..323b78ad70 100644 --- a/pyrit/analytics/scenario_statistics.py +++ b/pyrit/analytics/scenario_statistics.py @@ -221,7 +221,8 @@ def resolve_execution_unit( The atomic group is the planned group matching the atomic attack name and technique configuration, or a hash of both for attempts the plan does not describe. The seed group comes from, in order: the persisted attribution, an objective match in the planned group, the atomic identifier's seeds, and - finally a hash of the objective (legacy rows). The SQL history query follows the same order. + finally a hash of the objective (legacy rows). The SQL history query instead reads each attempt's + stored planned-unit link, which the migration that introduced it backfilled in the same order. Returns: ScenarioExecutionUnit: The resolved execution unit. diff --git a/pyrit/executor/attack/core/attack_result_attribution.py b/pyrit/executor/attack/core/attack_result_attribution.py index 26adf60238..5d4cdfe4f4 100644 --- a/pyrit/executor/attack/core/attack_result_attribution.py +++ b/pyrit/executor/attack/core/attack_result_attribution.py @@ -57,6 +57,10 @@ class AttackResultAttribution: children of an orchestration parent. Persisted into ``AttackResultEntry.attribution_data``. ``SequentialAttack`` sets it for each child attack it dispatches, e.g. ``2`` for the second child. + planned_unit_id (str | None): Optional ID of the parent's planned unit of work this + result executes. Persisted to ``AttackResultEntry.planned_unit_id`` (foreign key to + ``ScenarioPlannedUnitEntries.id``). ``Scenario`` sets it from + ``ScenarioRunPlan.compute_planned_unit_id``. """ parent_id: str @@ -64,6 +68,7 @@ class AttackResultAttribution: parent_eval_hash: str | None = None seed_group_id: str | None = None attempt_index: int | None = None + planned_unit_id: str | None = None async def enrich_attack_result_identifier_async( diff --git a/pyrit/executor/attack/core/attack_strategy.py b/pyrit/executor/attack/core/attack_strategy.py index cf951947cb..f34b55958e 100644 --- a/pyrit/executor/attack/core/attack_strategy.py +++ b/pyrit/executor/attack/core/attack_strategy.py @@ -579,6 +579,7 @@ def _apply_attribution( result.attribution_data = attribution_data return result.attribution_parent_id = attribution.parent_id + result.planned_unit_id = attribution.planned_unit_id attribution_data["parent_collection"] = attribution.parent_collection if attribution.parent_eval_hash is not None: attribution_data["parent_eval_hash"] = attribution.parent_eval_hash diff --git a/pyrit/memory/alembic/versions/54eb9489b8f0_add_scenario_planned_units.py b/pyrit/memory/alembic/versions/54eb9489b8f0_add_scenario_planned_units.py new file mode 100644 index 0000000000..b5dc53cadc --- /dev/null +++ b/pyrit/memory/alembic/versions/54eb9489b8f0_add_scenario_planned_units.py @@ -0,0 +1,324 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +Store each scenario run's planned units in a table and link attack results to the unit they execute. + +A planned unit is one atomic group of a run plan paired with one of its seed groups. Until now the units +existed only in ``ScenarioResultEntries.scenario_metadata.run_plan``, and scenario history expanded that +JSON and matched attempts to it on every read. This adds ``ScenarioPlannedUnitEntries`` and +``AttackResultEntries.planned_unit_id``, stores the units of every saved run plan, and links existing +attempts with the rules history used: the planned group with the attempt's atomic attack name and +technique hash (or the only group with that name when the attempt has no hash), then the attributed seed +group, or else the only seed group in that group with the attempt's objective. Attempts matching no unit +stay unlinked, as history already left them out of unit counts. + +Revision ID: 54eb9489b8f0 +Revises: d43b1bcf9c56 +Create Date: 2026-11-25 12:00:00.000000 +""" + +import json +import logging +import uuid +from collections import Counter +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Any + +import sqlalchemy as sa +from alembic import op + +from pyrit.memory.memory_models import CustomUUID + +# revision identifiers, used by Alembic. +revision: str = "54eb9489b8f0" +down_revision: str | None = "d43b1bcf9c56" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +logger = logging.getLogger(__name__) + +_UNITS = "ScenarioPlannedUnitEntries" +_ATTEMPTS = "AttackResultEntries" +_FOREIGN_KEY = "fk_attack_results_planned_unit" +_TRIGGER = "trg_delete_scenario_planned_units" +_ID_MAX_LENGTH = 64 +# Frozen copy of ScenarioRunPlan.PLANNED_UNIT_ID_NAMESPACE: resumed runs reference backfilled units by this ID. +_PLANNED_UNIT_ID_NAMESPACE = uuid.UUID("0321aa1d-fe5c-4c66-b8d4-e7a8352a88e4") + + +@dataclass(frozen=True) +class _PlannedUnit: + """One planned unit read from a stored run plan, with the fields attempts are matched on.""" + + unit_id: uuid.UUID + group_ordinal: int + atomic_group_id: str + atomic_attack_name: Any + technique_eval_hash: Any + seed_group_id: str + objective_sha256: Any + + +def upgrade() -> None: + """Create the planned-unit table and attempt link, then backfill both from the stored run plans.""" + op.create_table( + _UNITS, + sa.Column("id", CustomUUID(), nullable=False), + sa.Column("scenario_result_id", CustomUUID(), nullable=False), + sa.Column("atomic_group_id", sa.String(_ID_MAX_LENGTH), nullable=False), + sa.Column("seed_group_id", sa.String(_ID_MAX_LENGTH), nullable=False), + sa.ForeignKeyConstraint(["scenario_result_id"], ["ScenarioResultEntries.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index(f"ix_{_UNITS}_scenario_result_id", _UNITS, ["scenario_result_id"]) + if op.get_context().dialect.name == "sqlite": + # Avoid reflecting/rebuilding the existing generated analytics column. + op.execute( + sa.text( + f'ALTER TABLE "{_ATTEMPTS}" ADD COLUMN planned_unit_id CHAR(36) ' + f'CONSTRAINT "{_FOREIGN_KEY}" REFERENCES "{_UNITS}" (id)' + ) + ) + # SQLite runs with foreign keys disabled, so delete the units with their run explicitly. + op.execute( + f""" + CREATE TRIGGER "{_TRIGGER}" + AFTER DELETE ON "ScenarioResultEntries" + BEGIN + DELETE FROM "{_UNITS}" WHERE scenario_result_id = OLD.id; + END + """ + ) + else: + op.add_column(_ATTEMPTS, sa.Column("planned_unit_id", CustomUUID(), nullable=True)) + # NO ACTION: SQL Server rejects a second cascade path from ScenarioResultEntries to attempts. + op.create_foreign_key(_FOREIGN_KEY, _ATTEMPTS, _UNITS, ["planned_unit_id"], ["id"]) + op.create_index(f"ix_{_ATTEMPTS}_planned_unit_id", _ATTEMPTS, ["planned_unit_id"]) + if op.get_context().as_sql: + logger.warning("Skipping planned unit backfill: offline SQL generation cannot read existing run plans.") + return + counts = backfill_planned_units(bind=op.get_bind()) + logger.info( + "Planned unit backfill: stored %d planned unit(s) for %d run plan(s), skipping %d with invalid IDs; " + "linked %d attempt(s) and left %d unlinked.", + counts["units"], + counts["runs"], + counts["invalid_units"], + counts["linked"], + counts["unlinked"], + ) + + +def downgrade() -> None: + """Drop the attempt links and planned units; the run plans still hold the units for a later upgrade.""" + op.drop_index(f"ix_{_ATTEMPTS}_planned_unit_id", table_name=_ATTEMPTS) + if op.get_context().dialect.name == "sqlite": + op.execute(f'DROP TRIGGER "{_TRIGGER}"') + else: + op.drop_constraint(_FOREIGN_KEY, _ATTEMPTS, type_="foreignkey") + op.drop_column(_ATTEMPTS, "planned_unit_id") + op.drop_index(f"ix_{_UNITS}_scenario_result_id", table_name=_UNITS) + op.drop_table(_UNITS) + + +def backfill_planned_units(*, bind: sa.Connection) -> Counter[str]: + """ + Store the planned units of every saved run plan and link each run's unlinked attempts to them. + + Rerunning it is safe: stored units and linked attempts are kept. + + Args: + bind (sa.Connection): The connection to backfill through. + + Returns: + Counter[str]: Counts of ``runs``, ``units`` stored, ``invalid_units`` skipped, and attempts + ``linked`` and left ``unlinked``. + """ + scenarios = sa.table( + "ScenarioResultEntries", sa.column("id", CustomUUID()), sa.column("scenario_metadata", sa.JSON()) + ) + counts: Counter[str] = Counter() + for scenario_id in bind.execute(sa.select(scenarios.c.id)).scalars().all(): + metadata = bind.execute( + sa.select(scenarios.c.scenario_metadata).where(scenarios.c.id == scenario_id) + ).scalar_one_or_none() + units = _read_planned_units(scenario_id=scenario_id, metadata=metadata, counts=counts) + if units is None: + continue + counts["runs"] += 1 + _insert_units(bind=bind, scenario_id=scenario_id, units=units, counts=counts) + _link_attempts(bind=bind, scenario_id=scenario_id, units=units, counts=counts) + return counts + + +def _read_planned_units(*, scenario_id: uuid.UUID, metadata: Any, counts: Counter[str]) -> list[_PlannedUnit] | None: + """ + Read the planned units of one run's stored plan as leniently as history read the plan JSON. + + Returns: + list[_PlannedUnit] | None: The units in plan order, or None when the run stored no plan. + """ + if isinstance(metadata, str): + metadata = json.loads(metadata) + plan = metadata.get("run_plan") if isinstance(metadata, dict) else None + if not isinstance(plan, dict) or not isinstance(plan.get("atomic_groups"), list): + return None + groups = plan["atomic_groups"] + seeds = plan.get("seed_groups") + objectives = { + seed.get("id"): seed.get("objective_sha256") + for seed in (seeds if isinstance(seeds, list) else []) + if isinstance(seed, dict) + } + units: dict[uuid.UUID, _PlannedUnit] = {} + for ordinal, group in enumerate(groups): + if not isinstance(group, dict) or not isinstance(group.get("seed_group_ids"), list): + continue + for seed_group_id in group["seed_group_ids"]: + group_id = group.get("id") + if not _is_valid_id(group_id) or not _is_valid_id(seed_group_id): + counts["invalid_units"] += 1 + continue + unit_id = uuid.uuid5(_PLANNED_UNIT_ID_NAMESPACE, f"{scenario_id}:{group_id}:{seed_group_id}") + units.setdefault( + unit_id, + _PlannedUnit( + unit_id=unit_id, + group_ordinal=ordinal, + atomic_group_id=group_id, + atomic_attack_name=group.get("atomic_attack_name"), + technique_eval_hash=group.get("technique_eval_hash"), + seed_group_id=seed_group_id, + objective_sha256=objectives.get(seed_group_id), + ), + ) + return list(units.values()) + + +def _is_valid_id(value: Any) -> bool: + """ + Return whether a plan ID fits the planned-unit columns. + + Returns: + bool: True for a non-empty string of at most 64 characters. + """ + return isinstance(value, str) and 0 < len(value) <= _ID_MAX_LENGTH + + +def _insert_units( + *, bind: sa.Connection, scenario_id: uuid.UUID, units: list[_PlannedUnit], counts: Counter[str] +) -> None: + """Insert one run's planned units that are not stored yet.""" + table = sa.table( + _UNITS, + sa.column("id", CustomUUID()), + sa.column("scenario_result_id", CustomUUID()), + sa.column("atomic_group_id", sa.String()), + sa.column("seed_group_id", sa.String()), + ) + stored = set(bind.execute(sa.select(table.c.id).where(table.c.scenario_result_id == scenario_id)).scalars()) + rows = [ + { + "id": unit.unit_id, + "scenario_result_id": scenario_id, + "atomic_group_id": unit.atomic_group_id, + "seed_group_id": unit.seed_group_id, + } + for unit in units + if unit.unit_id not in stored + ] + if rows: + bind.execute(table.insert(), rows) + counts["units"] += len(rows) + + +def _link_attempts( + *, bind: sa.Connection, scenario_id: uuid.UUID, units: list[_PlannedUnit], counts: Counter[str] +) -> None: + """Link each of one run's unlinked attempts to the planned unit it resolves to.""" + attempts = sa.table( + _ATTEMPTS, + sa.column("id", CustomUUID()), + sa.column("attribution_parent_id", CustomUUID()), + sa.column("attribution_data", sa.JSON()), + sa.column("objective_sha256", sa.String()), + sa.column("planned_unit_id", CustomUUID()), + ) + rows = bind.execute( + sa.select(attempts.c.id, attempts.c.attribution_data, attempts.c.objective_sha256).where( + attempts.c.attribution_parent_id == scenario_id, attempts.c.planned_unit_id.is_(None) + ) + ).all() + groups_per_name = Counter(name for name, _ in {(unit.atomic_attack_name, unit.atomic_group_id) for unit in units}) + units_per_objective = Counter((unit.atomic_group_id, unit.objective_sha256) for unit in units) + links = [] + for attempt_id, attribution_data, objective_sha256 in rows: + unit_id = _resolve_unit( + attribution_data=attribution_data, + objective_sha256=objective_sha256, + units=units, + groups_per_name=groups_per_name, + units_per_objective=units_per_objective, + ) + if unit_id is None: + counts["unlinked"] += 1 + else: + links.append({"b_attempt_id": attempt_id, "b_unit_id": unit_id}) + if links: + bind.execute( + attempts.update() + .where(attempts.c.id == sa.bindparam("b_attempt_id", type_=CustomUUID())) + .values(planned_unit_id=sa.bindparam("b_unit_id", type_=CustomUUID())), + links, + ) + counts["linked"] += len(links) + + +def _resolve_unit( + *, + attribution_data: Any, + objective_sha256: Any, + units: list[_PlannedUnit], + groups_per_name: Counter[Any], + units_per_objective: Counter[tuple[str, Any]], +) -> uuid.UUID | None: + """ + Resolve one attempt to its planned unit with the rules scenario history used before this revision. + + An attributed seed group must match exactly; without one, the attempt's objective must identify a single + seed group of the matched atomic group. Atomic groups sharing a name and technique hash go to the first + planned one. + + Returns: + uuid.UUID | None: The planned unit, or None when no unit matches. + """ + if isinstance(attribution_data, str): + attribution_data = json.loads(attribution_data) + data = attribution_data if isinstance(attribution_data, dict) else {} + name = data.get("parent_collection") + name = "" if name is None else name + eval_hash = data.get("parent_eval_hash") + eval_hash = "" if eval_hash is None else eval_hash + seed_group_id = data.get("seed_group_id") or None + best: tuple[tuple[int, str], uuid.UUID] | None = None + for unit in units: + if unit.atomic_attack_name != name: + continue + if not ((eval_hash == "" and groups_per_name[name] == 1) or unit.technique_eval_hash == eval_hash): + continue + if seed_group_id is not None: + matches = unit.seed_group_id == seed_group_id + else: + matches = ( + objective_sha256 is not None + and unit.objective_sha256 == objective_sha256 + and units_per_objective[(unit.atomic_group_id, objective_sha256)] == 1 + ) + if not matches: + continue + rank = (unit.group_ordinal, unit.seed_group_id) + if best is None or rank < best[0]: + best = (rank, unit.unit_id) + return best[1] if best is not None else None diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 6a2e310749..37eb240cc1 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -5,18 +5,15 @@ import logging import os import struct -import uuid from collections.abc import Mapping, Sequence from contextlib import closing from datetime import UTC, datetime, timedelta from typing import TYPE_CHECKING, Any, Literal, cast from sqlalchemy import ( - Integer, String, Unicode, and_, - bindparam, create_engine, event, exists, @@ -41,7 +38,6 @@ from pyrit.memory.memory_interface import MemoryInterface from pyrit.memory.memory_models import ( AttackResultEntry, - CustomUUID, PromptMemoryEntry, ScenarioResultEntry, UTCDateTime, @@ -51,6 +47,8 @@ from pyrit.models import AttackResultRole, ConversationStats if TYPE_CHECKING: + import uuid + from azure.core.credentials import AccessToken from sqlalchemy.sql import SQLColumnExpression @@ -924,93 +922,6 @@ def _get_scenario_attempt_unit_expressions(self) -> tuple[Any, Any, Any, Any]: ) return atomic_name, technique_hash, attributed_seed_group_id, identifier_seed_key - def _get_scenario_plan_unit_subqueries(self, *, scenario_result_ids: Sequence[uuid.UUID]) -> tuple[Any, Any]: - """Return SQL Server run-plan expansions for planned units and planned seed groups.""" - scenario_ids = bindparam( - "history_plan_scenario_ids", - value=list(scenario_result_ids), - expanding=True, - type_=CustomUUID(), - ) - planned_units = ( - text( - """ - SELECT - [plan_scenario].[id] AS [scenario_result_id], - CAST([plan_group].[key] AS INT) AS [group_ordinal], - JSON_VALUE([plan_group_json].[value], '$.id') AS [atomic_group_id], - JSON_VALUE([plan_group_json].[value], '$.atomic_attack_name') AS [atomic_attack_name], - JSON_VALUE([plan_group_json].[value], '$.technique_eval_hash') AS [technique_eval_hash], - [plan_group_seed].[value] AS [seed_group_id] - FROM [ScenarioResultEntries] AS [plan_scenario] - CROSS APPLY OPENJSON( - COALESCE( - JSON_QUERY( - [plan_scenario].[scenario_metadata], - '$.run_plan.atomic_groups' - ), - N'[]' - ) - ) AS [plan_group] - CROSS APPLY ( - SELECT CASE - WHEN ISJSON([plan_group].[value]) = 1 THEN [plan_group].[value] - ELSE N'{}' - END AS [value] - ) AS [plan_group_json] - CROSS APPLY OPENJSON([plan_group_json].[value], '$.seed_group_ids') AS [plan_group_seed] - WHERE ISJSON([plan_scenario].[scenario_metadata]) = 1 - AND [plan_scenario].[id] IN :history_plan_scenario_ids - """ - ) - .bindparams(scenario_ids) - .columns( - scenario_result_id=CustomUUID(), - group_ordinal=Integer(), - atomic_group_id=Unicode(), - atomic_attack_name=Unicode(), - technique_eval_hash=Unicode(), - seed_group_id=Unicode(), - ) - .subquery("plan_units") - ) - plan_seeds = ( - text( - """ - SELECT - [plan_scenario].[id] AS [scenario_result_id], - JSON_VALUE([plan_seed_json].[value], '$.id') AS [seed_group_id], - JSON_VALUE([plan_seed_json].[value], '$.objective_sha256') AS [objective_sha256] - FROM [ScenarioResultEntries] AS [plan_scenario] - CROSS APPLY OPENJSON( - COALESCE( - JSON_QUERY( - [plan_scenario].[scenario_metadata], - '$.run_plan.seed_groups' - ), - N'[]' - ) - ) AS [plan_seed] - CROSS APPLY ( - SELECT CASE - WHEN ISJSON([plan_seed].[value]) = 1 THEN [plan_seed].[value] - ELSE N'{}' - END AS [value] - ) AS [plan_seed_json] - WHERE ISJSON([plan_scenario].[scenario_metadata]) = 1 - AND [plan_scenario].[id] IN :history_plan_scenario_ids - """ - ) - .bindparams(scenario_ids) - .columns( - scenario_result_id=CustomUUID(), - seed_group_id=Unicode(), - objective_sha256=Unicode(), - ) - .subquery("plan_seeds") - ) - return planned_units, plan_seeds - def _get_sync_session(self) -> Session: """ Provide a session for database operations. diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index 00199bad41..bf8cc42ec9 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -58,7 +58,7 @@ from pyrit.analytics import compute_outcome_statistics from pyrit.analytics.outcome_statistics import success_percentage -from pyrit.analytics.scenario_statistics import combine_execution_counts +from pyrit.analytics.scenario_statistics import combine_execution_counts, load_scenario_run_plan from pyrit.common import print_deprecation_message from pyrit.common.async_compatibility import legacy_sync_override, run_legacy_sync_async from pyrit.common.pagination import DecodedKeysetCursor @@ -117,6 +117,7 @@ PromptGenerationEntry, PromptMemoryEntry, ScenarioIdentifierEntry, + ScenarioPlannedUnitEntry, ScenarioPlanSeedGroupEntry, ScenarioResultEntry, ScorableContentEntry, @@ -3632,24 +3633,6 @@ def _get_scenario_attempt_unit_expressions(self) -> tuple[Any, Any, Any, Any]: "to support Scenario history queries." ) - def _get_scenario_plan_unit_subqueries(self, *, scenario_result_ids: Sequence[uuid.UUID]) -> tuple[Any, Any]: - """ - Return backend-specific run-plan expansions used to resolve attempts to planned units. - - The first subquery yields one row per planned ``(atomic group, seed group)`` pair with - columns ``scenario_result_id``, ``group_ordinal``, ``atomic_group_id``, - ``atomic_attack_name``, ``technique_eval_hash`` and ``seed_group_id``. The second yields - one row per planned seed group with columns ``scenario_result_id``, ``seed_group_id`` and - ``objective_sha256``. - - Raises: - NotImplementedError: If the memory backend does not support Scenario history queries. - """ - raise NotImplementedError( - f"{type(self).__name__} must implement _get_scenario_plan_unit_subqueries " - "to support Scenario history queries." - ) - def _execute_add_scores_to_memory( self, *, @@ -8367,7 +8350,7 @@ def _execute_add_scenario_results_to_memory( SQLAlchemyError: If a scenario result or identifier graph cannot be persisted. """ entries = [ScenarioResultEntry(entry=scenario_result) for scenario_result in scenario_results] - plan_entries = [ + plan_entries: list[Base] = [ ScenarioPlanSeedGroupEntry( scenario_result_id=result_id, dataset_name=dataset_name, position=position, seed_group=seed_group ) @@ -8376,6 +8359,12 @@ def _execute_add_scenario_results_to_memory( (name, group) for name, groups in population.items() for group in groups ) ] + for scenario_result in scenario_results: + run_plan = load_scenario_run_plan(scenario_result) + if run_plan is not None: + plan_entries.extend( + ScenarioPlannedUnitEntry.from_run_plan(scenario_result_id=scenario_result.id, run_plan=run_plan) + ) with closing(self._get_session()) as session: try: for scenario_result in scenario_results: @@ -8747,12 +8736,11 @@ def _execute_get_scenario_history_aggregates( Persisted attempts are grouped into logical work units before being counted, so retries and errored re-runs of the same objective collapse into a single unit. - For every scenario listed in ``plan_scenario_ids`` the persisted run plan resolves - those units: attempts are matched to their planned atomic group and seed group - (remapping objective-hash attribution onto the planned seed group ID), and attempts - that resolve to no planned unit are excluded from the counters. Scenarios outside - ``plan_scenario_ids`` keep the persisted attribution as the unit identity and count - every unit, which is the legacy behavior for runs without a usable plan. + For every scenario listed in ``plan_scenario_ids``, an attempt counts toward the planned + unit it is linked to (``AttackResultEntry.planned_unit_id``), and attempts linked to no + planned unit are excluded from the counters. Scenarios outside ``plan_scenario_ids`` keep + the persisted attribution as the unit identity and count every unit, which is the legacy + behavior for runs without a usable plan. Args: scenario_result_ids (Sequence[str]): Scenario run IDs to aggregate. @@ -8945,13 +8933,12 @@ def _build_scenario_history_ranked_units( select( AttackResultEntry.id.label("attempt_id"), AttackResultEntry.attribution_parent_id.label("scenario_result_id"), + AttackResultEntry.planned_unit_id.label("planned_unit_id"), atomic_name.label("atomic_attack_name"), technique_hash.label("technique_eval_hash"), - attributed_seed_group_id.label("attributed_seed_group_id"), func.coalesce( attributed_seed_group_id, identifier_seed_key, AttackResultEntry.objective_sha256, "" ).label("seed_group_id"), - AttackResultEntry.objective_sha256.label("objective_sha256"), AttackResultEntry.outcome.label("outcome"), AttackResultEntry.timestamp.label("timestamp"), case( @@ -9232,151 +9219,41 @@ def _build_scenario_history_unit_statement(self, *, attempts: Any, plan_entry_id """ Resolve every persisted attempt to the logical work unit whose counters it feeds. + An attempt linked to a planned unit counts toward that unit. In runs listed in ``plan_entry_ids``, + unlinked attempts are excluded from the unit counters but keep their own identity for the + producer counts, so configurations sharing a name stay apart. + Returns: Any: A statement selecting one row per attempt with its resolved unit identity. """ - # Without a matching planned group, a unit is its atomic attack name plus technique configuration, + # Without a planned unit, a unit is its atomic attack name plus technique configuration, # the same identity pyrit.analytics.scenario_statistics uses, so configurations sharing a name stay apart. unplanned_group_id = ( type_coerce(attempts.c.atomic_attack_name, Unicode) .concat(literal("\x1f", Unicode)) .concat(type_coerce(attempts.c.technique_eval_hash, Unicode)) ) - if not plan_entry_ids: - return select( - attempts.c.scenario_result_id, - attempts.c.attempt_id, - attempts.c.outcome, - attempts.c.timestamp, - attempts.c.total_retries, - attempts.c.has_retries, - attempts.c.result_role, - attempts.c.attempt_index, - attempts.c.has_child_links, - attempts.c.duplicates_child_error, - unplanned_group_id.label("unit_group_id"), - attempts.c.seed_group_id.label("unit_seed_id"), - literal(1).label("is_planned"), - ) - - planned_units, plan_seeds = self._get_scenario_plan_unit_subqueries(scenario_result_ids=plan_entry_ids) - # How many planned groups share each atomic attack name, so name-only matches can require a unique group. - groups_per_name = ( - select( - planned_units.c.scenario_result_id, - planned_units.c.atomic_attack_name, - func.count(func.distinct(planned_units.c.atomic_group_id)).label("group_count"), - ) - .group_by(planned_units.c.scenario_result_id, planned_units.c.atomic_attack_name) - .subquery("history_planned_groups_per_name") - ) - planned = ( - select( - planned_units.c.scenario_result_id, - planned_units.c.group_ordinal, - planned_units.c.atomic_group_id, - planned_units.c.atomic_attack_name, - planned_units.c.technique_eval_hash, - planned_units.c.seed_group_id, - plan_seeds.c.objective_sha256, - groups_per_name.c.group_count, - func.count() - .over( - partition_by=( - planned_units.c.scenario_result_id, - planned_units.c.atomic_group_id, - plan_seeds.c.objective_sha256, - ) - ) - .label("objective_match_count"), - ) - .select_from( - planned_units.outerjoin( - plan_seeds, - and_( - plan_seeds.c.scenario_result_id == planned_units.c.scenario_result_id, - plan_seeds.c.seed_group_id == planned_units.c.seed_group_id, - ), - ).join( - groups_per_name, - and_( - groups_per_name.c.scenario_result_id == planned_units.c.scenario_result_id, - groups_per_name.c.atomic_attack_name == planned_units.c.atomic_attack_name, - ), - ) - ) - .subquery("history_planned_units") - ) - # Without explicit seed attribution, an objective must identify exactly one planned seed group. - seed_matches_exactly = planned.c.seed_group_id == attempts.c.attributed_seed_group_id - match_condition = and_( - planned.c.scenario_result_id == attempts.c.scenario_result_id, - planned.c.atomic_attack_name == attempts.c.atomic_attack_name, - # Same rule as ScenarioPlanLookup.resolve_group: without a technique hash, the name must be unambiguous. - or_( - and_(attempts.c.technique_eval_hash == "", planned.c.group_count == 1), - planned.c.technique_eval_hash == attempts.c.technique_eval_hash, - ), - or_( - seed_matches_exactly, - and_( - attempts.c.attributed_seed_group_id.is_(None), - planned.c.objective_sha256 == attempts.c.objective_sha256, - planned.c.objective_match_count == 1, - ), - ), - ) - matched = ( - select( - attempts.c.scenario_result_id, - attempts.c.attempt_id, - attempts.c.outcome, - attempts.c.timestamp, - attempts.c.total_retries, - attempts.c.has_retries, - attempts.c.result_role, - attempts.c.attempt_index, - attempts.c.has_child_links, - attempts.c.duplicates_child_error, - attempts.c.atomic_attack_name, - unplanned_group_id.label("unplanned_group_id"), - attempts.c.seed_group_id, - planned.c.atomic_group_id, - planned.c.seed_group_id.label("planned_seed_group_id"), - func.row_number() - .over( - partition_by=attempts.c.attempt_id, - order_by=( - case((seed_matches_exactly, 0), else_=1), - planned.c.group_ordinal, - planned.c.seed_group_id, - ), - ) - .label("match_rank"), - ) - .select_from(attempts.outerjoin(planned, match_condition)) - .subquery("history_matched_attempts") - ) + planned_units = ScenarioPlannedUnitEntry.__table__.alias("history_planned_units") return select( - matched.c.scenario_result_id, - matched.c.attempt_id, - matched.c.outcome, - matched.c.timestamp, - matched.c.total_retries, - matched.c.has_retries, - matched.c.result_role, - matched.c.attempt_index, - matched.c.has_child_links, - matched.c.duplicates_child_error, - func.coalesce(matched.c.atomic_group_id, matched.c.unplanned_group_id).label("unit_group_id"), - func.coalesce(matched.c.planned_seed_group_id, matched.c.seed_group_id).label("unit_seed_id"), + attempts.c.scenario_result_id, + attempts.c.attempt_id, + attempts.c.outcome, + attempts.c.timestamp, + attempts.c.total_retries, + attempts.c.has_retries, + attempts.c.result_role, + attempts.c.attempt_index, + attempts.c.has_child_links, + attempts.c.duplicates_child_error, + func.coalesce(planned_units.c.atomic_group_id, unplanned_group_id).label("unit_group_id"), + func.coalesce(planned_units.c.seed_group_id, attempts.c.seed_group_id).label("unit_seed_id"), # Runs outside the plan-resolution set keep their raw identity and stay counted. case( - (matched.c.scenario_result_id.notin_(plan_entry_ids), 1), - (matched.c.planned_seed_group_id.is_(None), 0), + (attempts.c.scenario_result_id.notin_(plan_entry_ids), 1), + (planned_units.c.id.is_(None), 0), else_=1, ).label("is_planned"), - ).where(matched.c.match_rank == 1) + ).select_from(attempts.outerjoin(planned_units, planned_units.c.id == attempts.c.planned_unit_id)) @staticmethod def _parse_scenario_started_at(*, raw_value: Any) -> datetime | None: @@ -13693,12 +13570,11 @@ async def get_scenario_history_aggregates_async( Persisted attempts are grouped into logical work units before being counted, so retries and errored re-runs of the same objective collapse into a single unit. - For every scenario listed in ``plan_scenario_ids`` the persisted run plan resolves - those units: attempts are matched to their planned atomic group and seed group - (remapping objective-hash attribution onto the planned seed group ID), and attempts - that resolve to no planned unit are excluded from the counters. Scenarios outside - ``plan_scenario_ids`` keep the persisted attribution as the unit identity and count - every unit, which is the legacy behavior for runs without a usable plan. + For every scenario listed in ``plan_scenario_ids``, an attempt counts toward the planned + unit it is linked to (``AttackResultEntry.planned_unit_id``), and attempts linked to no + planned unit are excluded from the counters. Scenarios outside ``plan_scenario_ids`` keep + the persisted attribution as the unit identity and count every unit, which is the legacy + behavior for runs without a usable plan. Args: scenario_result_ids (Sequence[str]): Scenario run IDs to aggregate. diff --git a/pyrit/memory/memory_models.py b/pyrit/memory/memory_models.py index e984092d98..3af1f58b81 100644 --- a/pyrit/memory/memory_models.py +++ b/pyrit/memory/memory_models.py @@ -73,6 +73,7 @@ ScenarioEvaluationIdentifier, ScenarioIdentifier, ScenarioResult, + ScenarioRunPlan, ScenarioRunState, Score, ScorerEvaluationIdentifier, @@ -2358,6 +2359,14 @@ class AttackResultEntry(Base): CustomUUID, ForeignKey("ScenarioResultEntries.id", ondelete="SET NULL"), nullable=True, index=True ) attribution_data: Mapped[dict[str, Any] | None] = mapped_column(JSON, nullable=True) + # The planned unit this result executes, written by the orchestrator that ran it. NO ACTION, because + # SQL Server rejects a second cascade path from ScenarioResultEntries. + planned_unit_id: Mapped[uuid.UUID | None] = mapped_column( + CustomUUID, + ForeignKey("ScenarioPlannedUnitEntries.id", name="fk_attack_results_planned_unit"), + nullable=True, + index=True, + ) last_response: Mapped["PromptMemoryEntry | None"] = relationship( "PromptMemoryEntry", @@ -2448,6 +2457,7 @@ def __init__(self, *, entry: AttackResult) -> None: # an AttackResultAttribution is present on the AttackContext; otherwise None) self.attribution_parent_id = uuid.UUID(entry.attribution_parent_id) if entry.attribution_parent_id else None self.attribution_data = entry.attribution_data + self.planned_unit_id = uuid.UUID(entry.planned_unit_id) if entry.planned_unit_id else None @staticmethod def _prepare_atomic_attack_identifier( @@ -2608,6 +2618,7 @@ def get_attack_result(self) -> AttackResult: total_retries=self.total_retries or 0, attribution_parent_id=str(self.attribution_parent_id) if self.attribution_parent_id else None, attribution_data=self.attribution_data, + planned_unit_id=str(self.planned_unit_id) if self.planned_unit_id else None, ) @@ -2888,3 +2899,53 @@ def get_seed_group(self) -> AttackSeedGroup: seed = SeedSimulatedConversation.model_validate(seed) seeds.append(seed) return AttackSeedGroup.model_validate({**self.seed_group, "seeds": seeds}) + + +class ScenarioPlannedUnitEntry(Base): + """ + One unit of work a scenario run planned: an atomic group paired with one of its seed groups. + + Stored with the run's plan. Each attack result the run executes references its unit through + ``AttackResultEntry.planned_unit_id``. Rows are deleted with their scenario result. + """ + + __tablename__ = "ScenarioPlannedUnitEntries" + + #: ``ScenarioRunPlan.compute_planned_unit_id`` of the run, atomic group, and seed group. + id: Mapped[uuid.UUID] = mapped_column(CustomUUID, primary_key=True) + scenario_result_id: Mapped[uuid.UUID] = mapped_column( + CustomUUID, ForeignKey("ScenarioResultEntries.id", ondelete="CASCADE"), nullable=False, index=True + ) + atomic_group_id: Mapped[str] = mapped_column(String(64), nullable=False) + seed_group_id: Mapped[str] = mapped_column(String(64), nullable=False) + + @classmethod + def from_run_plan( + cls, *, scenario_result_id: uuid.UUID, run_plan: ScenarioRunPlan + ) -> list["ScenarioPlannedUnitEntry"]: + """ + Build one entry per planned unit of a run plan. + + Args: + scenario_result_id (uuid.UUID): The run that planned the units. + run_plan (ScenarioRunPlan): The run's plan. + + Returns: + list[ScenarioPlannedUnitEntry]: The planned units, in plan order. + """ + return [ + cls( + id=uuid.UUID( + ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=scenario_result_id, + atomic_group_id=group.id, + seed_group_id=seed_group_id, + ) + ), + scenario_result_id=scenario_result_id, + atomic_group_id=group.id, + seed_group_id=seed_group_id, + ) + for group in run_plan.atomic_groups + for seed_group_id in group.seed_group_ids + ] diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index ef5cf2e114..dd9634f394 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -932,67 +932,3 @@ def _get_scenario_attempt_unit_expressions(self) -> tuple[Any, Any, Any, Any]: .scalar_subquery() ) return atomic_name, technique_hash, attributed_seed_group_id, identifier_seed_key - - def _get_scenario_plan_unit_subqueries(self, *, scenario_result_ids: Sequence[uuid.UUID]) -> tuple[Any, Any]: - """Return SQLite run-plan expansions for planned units and planned seed groups.""" - atomic_groups = case( - ( - func.json_type( - ScenarioResultEntry.scenario_metadata, - "$.run_plan.atomic_groups", - ) - == "array", - func.json_extract( - ScenarioResultEntry.scenario_metadata, - "$.run_plan.atomic_groups", - ), - ), - else_="[]", - ) - groups = func.json_each( - atomic_groups, - ).table_valued("key", "value", "type", joins_implicitly=True) - group_json = case((groups.c.type == "object", groups.c.value), else_="{}") - group_seeds = func.json_each(group_json, "$.seed_group_ids").table_valued("value", joins_implicitly=True) - seed_groups = case( - ( - func.json_type( - ScenarioResultEntry.scenario_metadata, - "$.run_plan.seed_groups", - ) - == "array", - func.json_extract( - ScenarioResultEntry.scenario_metadata, - "$.run_plan.seed_groups", - ), - ), - else_="[]", - ) - seeds = func.json_each( - seed_groups, - ).table_valued("value", "type", joins_implicitly=True) - seed_json = case((seeds.c.type == "object", seeds.c.value), else_="{}") - planned_units = ( - select( - ScenarioResultEntry.id.label("scenario_result_id"), - groups.c.key.label("group_ordinal"), - func.json_extract(group_json, "$.id").label("atomic_group_id"), - func.json_extract(group_json, "$.atomic_attack_name").label("atomic_attack_name"), - func.json_extract(group_json, "$.technique_eval_hash").label("technique_eval_hash"), - group_seeds.c.value.label("seed_group_id"), - ) - .select_from(ScenarioResultEntry, groups, group_seeds) - .where(ScenarioResultEntry.id.in_(scenario_result_ids)) - .subquery("plan_units") - ) - plan_seeds = ( - select( - ScenarioResultEntry.id.label("scenario_result_id"), - func.json_extract(seed_json, "$.id").label("seed_group_id"), - func.json_extract(seed_json, "$.objective_sha256").label("objective_sha256"), - ) - .select_from(ScenarioResultEntry, seeds) - .where(ScenarioResultEntry.id.in_(scenario_result_ids)) - .subquery("plan_seeds") - ) - return planned_units, plan_seeds diff --git a/pyrit/models/results/attack_result.py b/pyrit/models/results/attack_result.py index 8ebce30bde..8ec7d9f91a 100644 --- a/pyrit/models/results/attack_result.py +++ b/pyrit/models/results/attack_result.py @@ -259,6 +259,8 @@ class AttackResult(StrategyResult, Generic[_ResponsePieceT, _ScoreT]): # record their role even without an orchestrator; the parent ID stays None. attribution_parent_id: str | None = None attribution_data: dict[str, Any] | None = None + # The parent's planned unit of work this result executes, when the parent stored a plan. + planned_unit_id: str | None = None @property def scoring_inputs(self) -> AttackScoringInputs | None: diff --git a/pyrit/models/scenario_progress.py b/pyrit/models/scenario_progress.py index 584a65045a..f62d627350 100644 --- a/pyrit/models/scenario_progress.py +++ b/pyrit/models/scenario_progress.py @@ -5,8 +5,8 @@ from datetime import datetime from enum import Enum -from typing import Any, Literal, Self -from uuid import UUID +from typing import Any, ClassVar, Literal, Self +from uuid import UUID, uuid5 from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, model_validator @@ -121,6 +121,9 @@ def technique_label(self) -> str: class ScenarioRunPlan(BaseModel): """Versioned normalized execution plan persisted in ScenarioResult metadata.""" + #: Namespace of planned-unit IDs. Stored attempts reference these IDs, so it never changes. + PLANNED_UNIT_ID_NAMESPACE: ClassVar[UUID] = UUID("0321aa1d-fe5c-4c66-b8d4-e7a8352a88e4") + version: Literal[1] = 1 scenario_registry_name: str | None = None atomic_groups: list[ScenarioRunPlanAtomicGroup] @@ -159,6 +162,27 @@ def _validate_normalized_plan(self) -> "ScenarioRunPlan": ) return self + @classmethod + def compute_planned_unit_id( + cls, *, scenario_result_id: str | UUID, atomic_group_id: str, seed_group_id: str + ) -> str: + """ + Compute the stored ID of one planned unit: a run's planned atomic group and seed group pair. + + The ID is deterministic, so the code running a unit references the row stored with the plan + without reading it back. + + Args: + scenario_result_id (str | UUID): The run that planned the unit. + atomic_group_id (str): The planned atomic group's ID. + seed_group_id (str): The planned seed group's ID. + + Returns: + str: The planned unit's UUID. + """ + run_id = UUID(str(scenario_result_id)) + return str(uuid5(cls.PLANNED_UNIT_ID_NAMESPACE, f"{run_id}:{atomic_group_id}:{seed_group_id}")) + class ScenarioProgressHeader(BaseModel): """Compact persisted run header returned by the progress endpoint.""" diff --git a/pyrit/scenario/core/atomic_attack.py b/pyrit/scenario/core/atomic_attack.py index 463c932de7..35ca1453f8 100644 --- a/pyrit/scenario/core/atomic_attack.py +++ b/pyrit/scenario/core/atomic_attack.py @@ -28,6 +28,7 @@ AttackResult, AttackSeedGroup, ObjectiveTargetEvaluationIdentifier, + ScenarioRunPlan, ScenarioRunPlanGroupKind, ScenarioRunPlanScorerBinding, config_hash, @@ -523,6 +524,11 @@ async def run_async( parent_collection=self.atomic_attack_name, parent_eval_hash=technique_eval_hash, seed_group_id=seed_group.logical_id, + planned_unit_id=ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=self._scenario_result_id, + atomic_group_id=self.logical_group_id, + seed_group_id=seed_group.logical_id, + ), ) for seed_group in self._seed_groups ] diff --git a/pyrit/scenario/scenarios/benchmark/adversarial.py b/pyrit/scenario/scenarios/benchmark/adversarial.py index 584938f37d..2d29efa888 100644 --- a/pyrit/scenario/scenarios/benchmark/adversarial.py +++ b/pyrit/scenario/scenarios/benchmark/adversarial.py @@ -24,6 +24,7 @@ ObjectiveTargetEvaluationIdentifier, Parameter, ScenarioDatasetSizeEstimate, + ScenarioRunPlan, ScenarioRunSizeComponent, ScenarioRunSizeEstimate, ScenarioRunSizeEstimateCondition, @@ -955,8 +956,15 @@ async def _persist_precomputed_cached_results_async(self) -> None: if attack is not None: attribution_data["parent_eval_hash"] = attack.technique_eval_hash cached_seed_group = cached_seed_groups.get(to_sha256(result.objective)) + planned_unit_id = None if cached_seed_group is not None: attribution_data["seed_group_id"] = cached_seed_group.logical_id + if attack is not None: + planned_unit_id = ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=self._scenario_result_id, + atomic_group_id=self._get_atomic_group_id(atomic_attack=attack), + seed_group_id=cached_seed_group.logical_id, + ) metadata = dict(result.metadata) metadata.setdefault("cached_from_attack_result_id", result.attack_result_id) copies.append( @@ -966,6 +974,7 @@ async def _persist_precomputed_cached_results_async(self) -> None: "attack_result_id": str(uuid.uuid4()), "attribution_parent_id": self._scenario_result_id, "attribution_data": attribution_data, + "planned_unit_id": planned_unit_id, "operation_id": self._operation_id, "operation": None, "labels": { diff --git a/tests/unit/analytics/test_scenario_statistics_parity.py b/tests/unit/analytics/test_scenario_statistics_parity.py index 663ee219e7..8ba25b2359 100644 --- a/tests/unit/analytics/test_scenario_statistics_parity.py +++ b/tests/unit/analytics/test_scenario_statistics_parity.py @@ -9,6 +9,7 @@ and the reports (JSON printer). """ +import importlib import json import uuid from dataclasses import dataclass, field @@ -47,6 +48,9 @@ from unit.mocks import make_scenario_result _T0 = datetime(2026, 9, 1, tzinfo=UTC) +_PLANNED_UNITS_MIGRATION = importlib.import_module( + "pyrit.memory.alembic.versions.54eb9489b8f0_add_scenario_planned_units" +) @dataclass(frozen=True) @@ -462,6 +466,9 @@ async def _persist(memory: MemoryInterface, history: _History) -> str: ) if attack_results: await memory.add_attack_results_to_memory_async(attack_results=attack_results) + # The rows carry attribution without planned-unit links, like attempts saved before the upgrade that added them. + with memory.engine.begin() as connection: + _PLANNED_UNITS_MIGRATION.backfill_planned_units(bind=connection) return str(scenario_result_id) diff --git a/tests/unit/backend/test_scenario_hierarchy_parity.py b/tests/unit/backend/test_scenario_hierarchy_parity.py index 8ce4735edc..2e1f4623de 100644 --- a/tests/unit/backend/test_scenario_hierarchy_parity.py +++ b/tests/unit/backend/test_scenario_hierarchy_parity.py @@ -2777,6 +2777,9 @@ async def test_501_units_with_tail_error_and_unmatched_tail_error_diagnostics_pa "seed_group_id": f"seed_{i}", "result_role": AttackResultRole.TARGET_FACING.value, }, + planned_unit_id=ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=scenario_id, atomic_group_id="group_1", seed_group_id=f"seed_{i}" + ), timestamp=base_time + timedelta(seconds=i), ) for i in range(500) @@ -2799,6 +2802,9 @@ async def test_501_units_with_tail_error_and_unmatched_tail_error_diagnostics_pa "seed_group_id": "seed_500", "result_role": AttackResultRole.TARGET_FACING.value, }, + planned_unit_id=ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=scenario_id, atomic_group_id="group_1", seed_group_id="seed_500" + ), timestamp=base_time + timedelta(seconds=500), ) all_results.append(tail_planned_result) diff --git a/tests/unit/executor/attack/core/test_attack_strategy.py b/tests/unit/executor/attack/core/test_attack_strategy.py index e5049ff0f0..5366a57c11 100644 --- a/tests/unit/executor/attack/core/test_attack_strategy.py +++ b/tests/unit/executor/attack/core/test_attack_strategy.py @@ -889,6 +889,7 @@ async def test_on_post_execute_stamps_scenario_attribution_when_present( parent_id="scenario-1", parent_collection="atomic_a", seed_group_id="seed-a", + planned_unit_id="00000000-0000-0000-0000-0000000000a1", ) event_data = StrategyEventData( @@ -901,6 +902,7 @@ async def test_on_post_execute_stamps_scenario_attribution_when_present( await handler.on_event_async(event_data) assert sample_attack_result.attribution_parent_id == "scenario-1" + assert sample_attack_result.planned_unit_id == "00000000-0000-0000-0000-0000000000a1" assert sample_attack_result.attribution_data == { "parent_collection": "atomic_a", "result_role": "target_facing", @@ -941,6 +943,7 @@ async def test_on_error_stamps_scenario_attribution_when_present(self, sample_at parent_id="scenario-err", parent_collection="atomic_err", seed_group_id="seed-error", + planned_unit_id="00000000-0000-0000-0000-0000000000e1", ) event_data = StrategyEventData( @@ -957,6 +960,7 @@ async def test_on_error_stamps_scenario_attribution_when_present(self, sample_at persisted = call.kwargs["attack_results"][0] assert persisted.outcome == AttackOutcome.ERROR assert persisted.attribution_parent_id == "scenario-err" + assert persisted.planned_unit_id == "00000000-0000-0000-0000-0000000000e1" assert persisted.attribution_data == { "parent_collection": "atomic_err", "result_role": "target_facing", diff --git a/tests/unit/memory/memory_interface/test_interface_scenario_history.py b/tests/unit/memory/memory_interface/test_interface_scenario_history.py index c1f9de5f7d..6ccd41c60f 100644 --- a/tests/unit/memory/memory_interface/test_interface_scenario_history.py +++ b/tests/unit/memory/memory_interface/test_interface_scenario_history.py @@ -19,7 +19,7 @@ from pyrit.common.utils import to_sha256 from pyrit.memory import AttackResultEntry, AzureSQLMemory, MemoryInterface, ScenarioHistoryKeysetCursor, SQLiteMemory from pyrit.memory._scenario_history import _ScenarioHistoryQueries -from pyrit.memory.memory_models import ConversationEntry, ScenarioResultEntry +from pyrit.memory.memory_models import ConversationEntry, ScenarioPlannedUnitEntry, ScenarioResultEntry from pyrit.models import ( SCENARIO_CONVERSATIONS_METADATA_KEY, SCENARIO_RUN_PLAN_METADATA_KEY, @@ -60,7 +60,6 @@ def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any ("_get_scenario_registry_name_condition", {"scenario_names": ["test.scenario"]}), ("_get_scenario_history_plan_expressions", {}), ("_get_scenario_attempt_unit_expressions", {}), - ("_get_scenario_plan_unit_subqueries", {"scenario_result_ids": [uuid.uuid4()]}), ], ) def test_scenario_history_dialect_hooks_are_optional_until_used( @@ -117,6 +116,13 @@ def _make_scenario( ) +def _planned_unit_id(scenario_result_id: uuid.UUID) -> str: + """The planned unit of ``_make_scenario``'s plan, as a scenario links its attempts to it.""" + return ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=scenario_result_id, atomic_group_id="group-1", seed_group_id="seed-1" + ) + + async def test_history_pages_descending_equal_timestamps_by_id(sqlite_instance: MemoryInterface) -> None: timestamp = datetime(2026, 8, 7, tzinfo=UTC) scenarios = [ @@ -695,6 +701,13 @@ async def test_history_filters_names_statuses_and_labels_without_hydration( ) with sqlite_instance._get_session() as session: session.add_all([ScenarioResultEntry(entry=result) for result in (included, excluded)]) + session.flush() + session.add_all( + ScenarioPlannedUnitEntry.from_run_plan( + scenario_result_id=included.id, + run_plan=ScenarioRunPlan.model_validate(included.metadata[SCENARIO_RUN_PLAN_METADATA_KEY]), + ) + ) session.commit() started_at = timestamp + timedelta(seconds=30) ( @@ -712,6 +725,7 @@ async def test_history_filters_names_statuses_and_labels_without_hydration( execution_time_ms=1, timestamp=timestamp, attribution_parent_id=str(included.id), + planned_unit_id=_planned_unit_id(included.id), attribution_data={ "parent_collection": "attack", "parent_eval_hash": "eval-1", @@ -730,6 +744,7 @@ async def test_history_filters_names_statuses_and_labels_without_hydration( timestamp=timestamp + timedelta(seconds=1), total_retries=2, attribution_parent_id=str(included.id), + planned_unit_id=_planned_unit_id(included.id), attribution_data={ "parent_collection": "attack", "parent_eval_hash": "eval-1", @@ -811,6 +826,7 @@ async def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: Me execution_time_ms=1, timestamp=timestamp, attribution_parent_id=str(scenario.id), + planned_unit_id=_planned_unit_id(scenario.id), attribution_data={ "parent_collection": "attack", "parent_eval_hash": "eval-1", @@ -825,6 +841,7 @@ async def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: Me execution_time_ms=1, timestamp=timestamp + timedelta(seconds=1), attribution_parent_id=str(scenario.id), + planned_unit_id=_planned_unit_id(scenario.id), attribution_data={ "parent_collection": "attack", "parent_eval_hash": "eval-1", @@ -845,10 +862,10 @@ async def test_history_aggregate_uses_latest_attempt_outcome(sqlite_instance: Me assert aggregate.latest_attempt_timestamp == timestamp + timedelta(seconds=1) -async def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( +async def test_history_aggregates_count_linked_attempts_and_ignore_unplanned_units( sqlite_instance: MemoryInterface, ) -> None: - """Plan-aware aggregation folds hash-attributed attempts into their planned unit.""" + """Plan-aware aggregation counts attempts through their stored planned-unit link.""" timestamp = datetime(2026, 8, 7, tzinfo=UTC) planned = make_scenario_result( id=uuid.UUID(int=20), @@ -901,6 +918,7 @@ async def test_history_aggregates_ignore_unplanned_units_and_remap_hash_seeds( timestamp=timestamp, attribution_parent_id=str(planned.id), attribution_data={"parent_collection": "attack", "parent_eval_hash": "eval-1"}, + planned_unit_id=_planned_unit_id(planned.id), ), AttackResult( attack_result_id=str(uuid.UUID(int=23)), @@ -1058,6 +1076,32 @@ async def test_history_aggregates_fill_zero_for_runs_without_attempts(sqlite_ins assert aggregates[scenario_result_id].latest_attempt_timestamp is None +async def test_adding_scenario_result_stores_planned_units_attempts_reference( + sqlite_instance: MemoryInterface, +) -> None: + scenario = _make_scenario( + result_id=uuid.UUID(int=60), + timestamp=datetime(2026, 8, 7, tzinfo=UTC), + name="PlannedUnitsScenario", + registry_name="registered.scenario", + state=ScenarioRunState.CREATED, + labels={}, + ) + + await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[scenario]) + + with sqlite_instance._get_session() as session: + units = session.execute( + select( + ScenarioPlannedUnitEntry.id, + ScenarioPlannedUnitEntry.scenario_result_id, + ScenarioPlannedUnitEntry.atomic_group_id, + ScenarioPlannedUnitEntry.seed_group_id, + ) + ).all() + assert units == [(uuid.UUID(_planned_unit_id(scenario.id)), scenario.id, "group-1", "seed-1")] + + @pytest.mark.filterwarnings("error:The params\\(\\) and unique_params\\(\\).*:sqlalchemy.exc.SADeprecationWarning") async def test_legacy_label_hook_is_constructible_and_composes_multi_value_semantics( sqlite_instance: MemoryInterface, diff --git a/tests/unit/memory/test_azure_sql_memory.py b/tests/unit/memory/test_azure_sql_memory.py index 6213abe189..c0577a46c0 100644 --- a/tests/unit/memory/test_azure_sql_memory.py +++ b/tests/unit/memory/test_azure_sql_memory.py @@ -808,21 +808,19 @@ def test_scenario_history_seed_projection_defaults_to_empty_json(memory_interfac assert "INCLUDE_NULL_VALUES" in str(seed_projection) -def test_scenario_plan_unit_subqueries_expand_plan_json_server_side(memory_interface: AzureSQLMemory) -> None: - """The SQL Server plan expansion uses CROSS APPLY OPENJSON and binds scenario IDs.""" - scenario_result_id = uuid.uuid4() - plan_units, plan_seeds = memory_interface._get_scenario_plan_unit_subqueries( - scenario_result_ids=[scenario_result_id] - ) - - statement = select(plan_units.c.atomic_group_id, plan_seeds.c.seed_group_id).join( - plan_seeds, plan_units.c.atomic_group_id == plan_seeds.c.seed_group_id - ) - compiled = statement.compile(dialect=mssql.dialect()) - - assert "CROSS APPLY OPENJSON" in str(compiled) - assert "JOIN LATERAL" not in str(compiled) - assert str(scenario_result_id) in str(compiled.params) +@pytest.mark.parametrize("build_statement", ["aggregate", "group_aggregate"]) +def test_scenario_history_aggregates_join_planned_units_without_reading_run_plans( + memory_interface: AzureSQLMemory, build_statement: str +) -> None: + """Plan runs resolve units through the planned-unit link, never by expanding run-plan JSON.""" + builder = getattr(memory_interface, f"_build_scenario_history_{build_statement}_statement") + statement = builder(entry_ids=[uuid.uuid4()], plan_entry_ids=[uuid.uuid4()]) + compiled = str(statement.compile(dialect=mssql.dialect())) + + assert "[ScenarioPlannedUnitEntries] AS history_planned_units ON history_planned_units.id = " in compiled + assert "history_attempts.planned_unit_id" in compiled + assert "scenario_metadata" not in compiled + assert "run_plan" not in compiled def test_scenario_history_attempt_ranking_uses_canonical_uuid_order( diff --git a/tests/unit/memory/test_finding_field_values_migration.py b/tests/unit/memory/test_finding_field_values_migration.py index c7f529380b..b9e2ceba41 100644 --- a/tests/unit/memory/test_finding_field_values_migration.py +++ b/tests/unit/memory/test_finding_field_values_migration.py @@ -130,6 +130,7 @@ def test_upgrade_moves_existing_findings_into_field_values() -> None: ) ] assert evidence_rows == [(B, ATTACK_ID)] + command.upgrade(config, "head") check_schema_migrations(engine=engine) finally: engine.dispose() diff --git a/tests/unit/memory/test_scenario_planned_units_migration.py b/tests/unit/memory/test_scenario_planned_units_migration.py new file mode 100644 index 0000000000..30b750093d --- /dev/null +++ b/tests/unit/memory/test_scenario_planned_units_migration.py @@ -0,0 +1,219 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +import importlib +import json +import logging +import uuid +from pathlib import Path + +import pytest +import sqlalchemy as sa +from alembic import command +from alembic.config import Config +from alembic.script import ScriptDirectory +from sqlalchemy.dialects import mssql +from sqlalchemy.schema import CreateIndex, CreateTable + +from pyrit.common.utils import to_sha256 +from pyrit.memory import AttackResultEntry +from pyrit.memory.memory_models import ScenarioPlannedUnitEntry +from pyrit.memory.migration import check_schema_migrations +from pyrit.models import ScenarioRunPlan + +REVISION = "54eb9489b8f0" +PREVIOUS = "d43b1bcf9c56" +ALEMBIC_DIRECTORY = Path(__file__).resolve().parents[3] / "pyrit" / "memory" / "alembic" +PLANNED_RUN = uuid.UUID(int=1) +LEGACY_RUN = uuid.UUID(int=2) +STAMP = "2026-11-20 12:00:00" +# Two configurations share the name "attack"; seeds s2 and s3 share objective "Y". +PLAN = { + "atomic_groups": [ + { + "id": "group-a", + "atomic_attack_name": "attack", + "technique_eval_hash": "eval-1", + "seed_group_ids": ["s1", "s2", "s3"], + }, + {"id": "group-b", "atomic_attack_name": "attack", "technique_eval_hash": "eval-2", "seed_group_ids": ["s1"]}, + {"id": "group-c", "atomic_attack_name": "other", "technique_eval_hash": "eval-3", "seed_group_ids": ["s1"]}, + ], + "seed_groups": [ + {"id": "s1", "objective_sha256": to_sha256("X")}, + {"id": "s2", "objective_sha256": to_sha256("Y")}, + {"id": "s3", "objective_sha256": to_sha256("Y")}, + ], +} +# Attempt ID -> (scenario run, attribution, objective, expected planned group and seed or None). +ATTEMPTS = { + "attributed": ( + PLANNED_RUN, + {"parent_collection": "attack", "parent_eval_hash": "eval-2", "seed_group_id": "s1"}, + "X", + ("group-b", "s1"), + ), + "objective_match": ( + PLANNED_RUN, + {"parent_collection": "attack", "parent_eval_hash": "eval-1"}, + "X", + ("group-a", "s1"), + ), + "unique_name_without_hash": ( + PLANNED_RUN, + {"parent_collection": "other", "seed_group_id": "s1"}, + "X", + ("group-c", "s1"), + ), + "ambiguous_objective": (PLANNED_RUN, {"parent_collection": "attack", "parent_eval_hash": "eval-1"}, "Y", None), + "ambiguous_name_without_hash": (PLANNED_RUN, {"parent_collection": "attack", "seed_group_id": "s1"}, "X", None), + "unplanned_seed": ( + PLANNED_RUN, + {"parent_collection": "attack", "parent_eval_hash": "eval-1", "seed_group_id": "s9"}, + "X", + None, + ), + "legacy_run": (LEGACY_RUN, {"parent_collection": "attack", "seed_group_id": "s1"}, "X", None), +} + + +def _config(connection: sa.Connection) -> Config: + config = Config() + config.set_main_option("script_location", str(ALEMBIC_DIRECTORY)) + config.attributes.update(connection=connection, version_table="pyrit_memory_alembic_version") + return config + + +def _attempt_id(name: str) -> str: + return str(uuid.uuid5(uuid.NAMESPACE_OID, name)) + + +def _insert_runs_and_attempts(connection: sa.Connection) -> None: + for run_id, metadata in ((PLANNED_RUN, {"run_plan": PLAN}), (LEGACY_RUN, {})): + connection.execute( + sa.text( + "INSERT INTO ScenarioResultEntries (id, scenario_name, scenario_version, pyrit_version, " + "scenario_identifier, objective_target_identifier, scenario_run_state, number_tries, " + "completion_time, timestamp, scenario_metadata) VALUES (:id, 'Scenario', 1, '1.3.0', '{}', '{}', " + "'COMPLETED', 1, :stamp, :stamp, :metadata)" + ), + {"id": str(run_id), "stamp": STAMP, "metadata": json.dumps(metadata)}, + ) + for name, (run_id, attribution, objective, _) in ATTEMPTS.items(): + connection.execute( + sa.text( + "INSERT INTO AttackResultEntries (id, conversation_id, objective, objective_sha256, executed_turns, " + "execution_time_ms, outcome, timestamp, attribution_parent_id, attribution_data) VALUES " + "(:id, :id, :objective, :objective_sha256, 1, 1, 'success', :stamp, :run_id, :attribution)" + ), + { + "id": _attempt_id(name), + "objective": objective, + "objective_sha256": to_sha256(objective), + "stamp": STAMP, + "run_id": str(run_id), + "attribution": json.dumps(attribution), + }, + ) + + +def test_planned_units_migration_is_single_successor_of_finding_field_values() -> None: + scripts = ScriptDirectory(str(ALEMBIC_DIRECTORY)) + assert len(scripts.get_heads()) == 1 + revision = scripts.get_revision(REVISION) + assert revision is not None + assert revision.down_revision == PREVIOUS + + +def test_upgrade_backfills_planned_units_and_links_resolvable_attempts(caplog: pytest.LogCaptureFixture) -> None: + engine = sa.create_engine("sqlite:///:memory:") + try: + with engine.begin() as connection: + config = _config(connection) + command.upgrade(config, PREVIOUS) + _insert_runs_and_attempts(connection) + with caplog.at_level(logging.INFO): + command.upgrade(config, REVISION) + + units = connection.execute( + sa.text("SELECT id, scenario_result_id, atomic_group_id, seed_group_id FROM ScenarioPlannedUnitEntries") + ).all() + links = dict(connection.execute(sa.text("SELECT id, planned_unit_id FROM AttackResultEntries")).all()) + + planned_units = {(group["id"], seed) for group in PLAN["atomic_groups"] for seed in group["seed_group_ids"]} + assert {(uuid.UUID(run_id), group, seed) for _, run_id, group, seed in units} == { + (PLANNED_RUN, group, seed) for group, seed in planned_units + } + # Units keep the IDs a resumed run computes for its attempts. + assert {uuid.UUID(unit_id) for unit_id, *_ in units} == { + uuid.UUID( + ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=PLANNED_RUN, atomic_group_id=g, seed_group_id=s + ) + ) + for g, s in planned_units + } + for name, (run_id, _, _, expected) in ATTEMPTS.items(): + expected_link = ( + ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=run_id, atomic_group_id=expected[0], seed_group_id=expected[1] + ) + if expected + else None + ) + assert links[_attempt_id(name)] == expected_link, name + assert "stored 5 planned unit(s) for 1 run plan(s)" in caplog.text + assert "linked 3 attempt(s) and left 3 unlinked" in caplog.text + finally: + engine.dispose() + + +def test_planned_units_migration_downgrades_and_upgrades_again() -> None: + engine = sa.create_engine("sqlite:///:memory:") + try: + with engine.begin() as connection: + config = _config(connection) + command.upgrade(config, PREVIOUS) + _insert_runs_and_attempts(connection) + command.upgrade(config, REVISION) + command.downgrade(config, PREVIOUS) + inspector = sa.inspect(connection) + assert "ScenarioPlannedUnitEntries" not in inspector.get_table_names() + assert "planned_unit_id" not in {column["name"] for column in inspector.get_columns("AttackResultEntries")} + command.upgrade(config, "head") + linked = connection.execute( + sa.text("SELECT COUNT(*) FROM AttackResultEntries WHERE planned_unit_id IS NOT NULL") + ).scalar() + assert linked == 3 + check_schema_migrations(engine=engine) + finally: + engine.dispose() + + +def test_backfill_keeps_stored_units_and_links() -> None: + migration = importlib.import_module(f"pyrit.memory.alembic.versions.{REVISION}_add_scenario_planned_units") + engine = sa.create_engine("sqlite:///:memory:") + try: + with engine.begin() as connection: + config = _config(connection) + command.upgrade(config, PREVIOUS) + _insert_runs_and_attempts(connection) + command.upgrade(config, REVISION) + + counts = migration.backfill_planned_units(bind=connection) + + assert (counts["units"], counts["linked"], counts["unlinked"]) == (0, 0, 3) + finally: + engine.dispose() + + +def test_planned_units_schema_compiles_for_sql_server() -> None: + dialect = mssql.dialect() + units = str(CreateTable(ScenarioPlannedUnitEntry.__table__).compile(dialect=dialect)) + assert "atomic_group_id VARCHAR(64) NOT NULL" in units + assert "seed_group_id VARCHAR(64) NOT NULL" in units + for index in ScenarioPlannedUnitEntry.__table__.indexes: + CreateIndex(index).compile(dialect=dialect) + attempts = str(CreateTable(AttackResultEntry.__table__).compile(dialect=dialect)) + link = next(line for line in attempts.splitlines() if "fk_attack_results_planned_unit" in line) + assert "ON DELETE" not in link diff --git a/tests/unit/scenario/benchmark/test_adversarial.py b/tests/unit/scenario/benchmark/test_adversarial.py index cf294af2e1..d8c2b66c39 100644 --- a/tests/unit/scenario/benchmark/test_adversarial.py +++ b/tests/unit/scenario/benchmark/test_adversarial.py @@ -67,6 +67,7 @@ Operation, ScenarioIdentifier, ScenarioResult, + ScenarioRunPlan, ScenarioRunPlanGroupKind, ScenarioRunSizeEstimateStatus, ScenarioRunState, @@ -2554,6 +2555,7 @@ async def test_cached_copies_count_as_planned_units_in_either_order(self, revers outcome=AttackOutcome.FAILURE, ) attributed.attribution_data = {**(attributed.attribution_data or {}), "seed_group_id": "stale-seed"} + attributed.planned_unit_id = str(uuid.uuid4()) cached = [attributed, legacy] if reverse else [legacy, attributed] bench = AdversarialBenchmark(objective_scorer=MagicMock(spec=TrueFalseScorer)) @@ -2573,6 +2575,15 @@ async def test_cached_copies_count_as_planned_units_in_either_order(self, revers "legacy cached": seed_groups["legacy cached"].logical_id, "attributed cached": seed_groups["attributed cached"].logical_id, } + # Copies link to this run's stored planned units, never the original run's. + assert {copy.objective: copy.planned_unit_id for copy in copies} == { + objective: ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id=bench._scenario_result_id, + atomic_group_id=plan.atomic_groups[0].id, + seed_group_id=seed_groups[objective].logical_id, + ) + for objective in ("legacy cached", "attributed cached") + } fresh = AttackResult( conversation_id=str(uuid.uuid4()), diff --git a/tests/unit/scenario/core/test_atomic_attack.py b/tests/unit/scenario/core/test_atomic_attack.py index 3820e5dd8f..47fc81147c 100644 --- a/tests/unit/scenario/core/test_atomic_attack.py +++ b/tests/unit/scenario/core/test_atomic_attack.py @@ -20,6 +20,7 @@ AttackSeedGroup, AttackTechniqueSeedGroup, ComponentIdentifier, + ScenarioRunPlan, ScoringExpectation, SeedGroup, SeedGroupRequirements, @@ -1164,6 +1165,31 @@ async def test_attribution_includes_technique_eval_hash( assert all(attribution.parent_eval_hash is not None for attribution in attributions) assert all(attribution.parent_eval_hash == atomic.technique_eval_hash for attribution in attributions) + async def test_attribution_links_each_seed_group_to_its_planned_unit( + self, mock_attack, sample_seed_groups, sample_attack_results + ): + """Each attempt references the planned unit the run stored for its atomic group and seed group.""" + atomic = AtomicAttack( + attack_technique=AttackTechnique(attack=mock_attack), + seed_groups=sample_seed_groups, + atomic_attack_name="MyAtomicAttack", + ) + atomic._scenario_result_id = "00000000-0000-0000-0000-000000000abc" + + with patch.object(AttackExecutor, "execute_attack_from_seed_groups_async", new_callable=AsyncMock) as mock_exec: + mock_exec.return_value = wrap_results(sample_attack_results) + await atomic.run_async() + + attributions = mock_exec.call_args.kwargs["attributions"] + assert [attribution.planned_unit_id for attribution in attributions] == [ + ScenarioRunPlan.compute_planned_unit_id( + scenario_result_id="00000000-0000-0000-0000-000000000abc", + atomic_group_id=atomic.logical_group_id, + seed_group_id=seed_group.logical_id, + ) + for seed_group in sample_seed_groups + ] + @pytest.mark.usefixtures("patch_central_database") class TestAtomicAttackTechniqueEvalHash: