From 6f5cebed67ec291729221040cfbd485ee3999cc7 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 14:27:10 -0800 Subject: [PATCH 1/5] FEAT: Explain how to recover when a resumed run's datasets changed Resuming a scenario after its dataset was deleted reported "no seeds found in memory. Call prepare_async() ...", which resume never does. After an edit or refresh it reported only "missing N planned seed group(s)". Resume now names the deleted datasets, or the resolved datasets whose content changed, and ends with the two recoveries: re-import the content the run used, or drop scenario_result_id to start a new run. Only a dataset that is actually absent is reported as deleted; other resolution errors propagate unchanged. Co-Authored-By: Claude Opus 5.5 --- pyrit/scenario/core/scenario.py | 73 ++++++++++++++++++++--- tests/unit/scenario/core/test_scenario.py | 27 ++++++++- 2 files changed, 91 insertions(+), 9 deletions(-) diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index dc07e50c6a..eaa2cb460e 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -83,6 +83,7 @@ from pyrit.scenario.core.atomic_attack import AtomicAttack from pyrit.scenario.core.dataset_configuration import ( DatasetAttackConfiguration, + DatasetConstraintError, DatasetSource, DatasetSourceKind, ) @@ -1479,11 +1480,14 @@ async def initialize_async(self) -> None: ``supported_parameters`` falls back to that input's default here. Raises: + DatasetConstraintError: If the configured datasets can't be resolved for a reason other + than a resumed run's dataset having been deleted. IncompatibleTechniqueError: If techniques were selected but none can run. ValueError: If ``objective_target`` is declared but not resolvable (neither supplied nor registered as a default), if a supplied target name is not registered in - ``TargetRegistry``, or if ``include_baseline=True`` is set for a scenario whose - ``BASELINE_ATTACK_POLICY`` is ``Forbidden``. + ``TargetRegistry``, if ``include_baseline=True`` is set for a scenario whose + ``BASELINE_ATTACK_POLICY`` is ``Forbidden``, or if a resumed run's datasets were + deleted or changed after the run was planned. """ if not self._params_resolved: self.set_params_from_args(args=self.params) @@ -1560,7 +1564,12 @@ async def initialize_async(self) -> None: is_resume = self._scenario_result_id is not None if not is_resume: await self._prepare_datasets_async() - seed_groups_by_dataset = await self._resolve_seed_groups_by_dataset_async(apply_sampling=not is_resume) + try: + seed_groups_by_dataset = await self._resolve_seed_groups_by_dataset_async(apply_sampling=not is_resume) + except DatasetConstraintError as error: + if is_resume: + await self._raise_if_datasets_deleted_async(cause=error) + raise if stored_plan is not None: planned_seed_ids = {group_id for group in stored_plan.atomic_groups for group_id in group.seed_group_ids} if seed_groups_by_dataset: @@ -1568,8 +1577,11 @@ async def initialize_async(self) -> None: missing_seed_ids = planned_seed_ids - resolved_seed_ids if missing_seed_ids: raise ValueError( - f"Scenario result id '{self._scenario_result_id}' cannot resume: " - f"missing {len(missing_seed_ids)} planned seed group(s) in the resolved datasets." + self._resume_error_message( + reason=f"missing {len(missing_seed_ids)} planned seed group(s) in the resolved " + f"datasets ({', '.join(repr(name) for name in seed_groups_by_dataset)}); " + "their content changed after the run was planned" + ) ) seed_groups_by_dataset = { name: [group for group in groups if group.logical_id in planned_seed_ids] @@ -1800,6 +1812,51 @@ def _get_stored_run_plan(*, stored_result: ScenarioResult) -> ScenarioRunPlan | return None return ScenarioRunPlan.model_validate(raw_plan) + def _resume_error_message(self, *, reason: str) -> str: + """ + Build the error for a resume refused because its planned seeds can't be found. + + Args: + reason (str): What is missing, without a trailing period. + + Returns: + str: The message, ending with the two ways to recover. + """ + return ( + f"Scenario result id '{self._scenario_result_id}' cannot resume: {reason}. " + "To resume, re-import the dataset content this run used; " + "otherwise drop scenario_result_id to start a new run." + ) + + async def _raise_if_datasets_deleted_async(self, *, cause: DatasetConstraintError) -> None: + """ + Explain a resume whose dataset resolution failed because a dataset was deleted. + + Only an absent population or required dataset is reported this way; any other resolution + error is left for the caller to re-raise unchanged. Names are compared case-insensitively, + so a backend with a case-insensitive collation never reports a present dataset as deleted. + + Args: + cause (DatasetConstraintError): The error raised while resolving the planned datasets. + + Raises: + ValueError: If any population or required dataset has no seeds in memory. + """ + configured = list(self._dataset_config.dataset_names) + if self._required_data is not None: + configured.extend(name for name in self._required_data.dataset_names if name not in configured) + if not configured: + return + stored = {name.casefold() for name in await self._memory.get_seed_dataset_names_async()} + missing = [name for name in configured if name.casefold() not in stored] + if missing: + raise ValueError( + self._resume_error_message( + reason=f"dataset(s) {', '.join(repr(name) for name in missing)} are no longer in memory; " + "they were deleted after the run was planned" + ) + ) from cause + def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: """ Validate and replay the exact logical units captured by a stored plan. @@ -1826,8 +1883,10 @@ def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: missing_seed_groups = set(planned_group.seed_group_ids) - current_seed_groups.keys() if missing_seed_groups: raise ValueError( - f"Scenario result id '{self._scenario_result_id}' cannot resume: atomic group " - f"'{planned_group.atomic_attack_name}' is missing {len(missing_seed_groups)} planned seed group(s)." + self._resume_error_message( + reason=f"atomic group '{planned_group.atomic_attack_name}' is missing " + f"{len(missing_seed_groups)} planned seed group(s)" + ) ) atomic_attack._seed_groups = [current_seed_groups[group_id] for group_id in planned_group.seed_group_ids] retained_attacks.append(atomic_attack) diff --git a/tests/unit/scenario/core/test_scenario.py b/tests/unit/scenario/core/test_scenario.py index aba6c4ddae..9ebdc8864d 100644 --- a/tests/unit/scenario/core/test_scenario.py +++ b/tests/unit/scenario/core/test_scenario.py @@ -58,7 +58,7 @@ ScenarioResult, TechniqueRequirements, ) -from pyrit.scenario.core import AtomicAttack, BaselineAttackPolicy, Scenario, ScenarioTechnique +from pyrit.scenario.core import AtomicAttack, BaselineAttackPolicy, DatasetConstraintError, Scenario, ScenarioTechnique from pyrit.scenario.core.matrix_atomic_attack_builder import build_baseline_atomic_attack, build_matrix_atomic_attacks from pyrit.scenario.core.scenario_context import ScenarioContext from pyrit.score import ( @@ -1953,13 +1953,36 @@ async def test_named_source_preparation_and_resume( await resumed.initialize_async() assert resumed._build_run_plan() == original_plan else: - with pytest.raises(ValueError): + expected_error = { + "missing-dataset": r"dataset\(s\) 'fixture' are no longer in memory; they were deleted", + "refreshed": r"missing 3 planned seed group\(s\) in the resolved datasets \('fixture'\); " + "their content changed", + }.get(resume_state) + with pytest.raises(ValueError, match=expected_error) as error: await resumed.initialize_async() + if expected_error: + assert str(error.value).endswith( + "To resume, re-import the dataset content this run used; " + "otherwise drop scenario_result_id to start a new run." + ) prepare.assert_not_awaited() provider.fetch_dataset_async.assert_not_awaited() lookup.assert_not_awaited() sample.assert_not_called() + async def test_resume_reports_only_absent_datasets_as_deleted(self) -> None: + scenario = self._StrategyScenario(name="Named sources", version=1, scenario_result_id=str(uuid.uuid4())) + scenario._dataset_config = DatasetAttackConfiguration(sources=[DatasetSource(name="Fixture")]) + cause = DatasetConstraintError("resolution failed") + with patch.object(scenario._memory, "get_seed_dataset_names_async", AsyncMock(return_value=["fixture"])): + await scenario._raise_if_datasets_deleted_async(cause=cause) + with ( + patch.object(scenario._memory, "get_seed_dataset_names_async", AsyncMock(return_value=["other"])), + pytest.raises(ValueError, match=r"dataset\(s\) 'Fixture' are no longer in memory") as error, + ): + await scenario._raise_if_datasets_deleted_async(cause=cause) + assert error.value.__cause__ is cause + async def test_resume_reconstructs_persisted_subset_without_resampling(self, mock_objective_target): config = self._make_config() From bd6e0514d7da013daecaedc9f2a75fe8da7126e3 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 19:03:06 -0800 Subject: [PATCH 2/5] FEAT: Resume scenario runs from their stored planned seed groups A new run now stores the population it was built from, in the same transaction as its ScenarioResult, in ScenarioPlanSeedGroupEntries. Resume rebuilds from those groups and never prepares, resolves, or resamples the population datasets, so editing, refreshing, or deleting a dataset no longer breaks resume. Scenarios that override seed resolution still run it on resume for the state it sets up, and discard its groups. This also keeps exactly the copies of duplicate groups the first run sampled (#4157), and removes the legacy replay: objective_hashes, _apply_persisted_objectives, and rebuilding plans for results without one. Runs created before this change can no longer be resumed. Co-Authored-By: Claude Opus 5.5 --- .../instructions/scenarios.instructions.md | 10 +- ...1e9a3b5f2_add_scenario_plan_seed_groups.py | 56 +++++ pyrit/memory/memory_interface.py | 81 +++++++- pyrit/memory/memory_models.py | 89 ++++++++ pyrit/scenario/core/scenario.py | 193 +++++++----------- tests/unit/backend/test_scenario_resume.py | 11 +- .../test_dataset_lifecycle_migration.py | 1 + tests/unit/memory/test_planned_seed_groups.py | 68 ++++++ ...est_scenario_plan_seed_groups_migration.py | 54 +++++ tests/unit/scenario/core/test_scenario.py | 141 +++++++++---- .../core/test_scenario_dataset_overrides.py | 4 +- .../unit/scenario/core/test_scenario_retry.py | 53 ----- .../scenario/garak/test_latent_injection.py | 7 +- .../scenarios/adaptive/test_text_adaptive.py | 20 +- .../scenarios/technique/test_execute.py | 5 +- 15 files changed, 549 insertions(+), 244 deletions(-) create mode 100644 pyrit/memory/alembic/versions/c7d1e9a3b5f2_add_scenario_plan_seed_groups.py create mode 100644 tests/unit/memory/test_planned_seed_groups.py create mode 100644 tests/unit/memory/test_scenario_plan_seed_groups_migration.py diff --git a/.github/instructions/scenarios.instructions.md b/.github/instructions/scenarios.instructions.md index 51e836112c..52ee60ef07 100644 --- a/.github/instructions/scenarios.instructions.md +++ b/.github/instructions/scenarios.instructions.md @@ -206,9 +206,11 @@ Options: The catalog reads options and defaults from registry metadata, never from an estimate. - Explicit `load_datasets_async()` remains missing-only, regardless of the scan's policy. It does not refresh or change that policy. -- Resume replays the saved launch request; the stored run plan fixes the selected seed groups, - so caps and fetch policies cannot change a resumed run. Dataset names are checked by the - stored scenario identity. Resume never prepares datasets. +- Resume replays the saved launch request and rebuilds the population stored with the run, so caps, + fetch policies, and later dataset edits, refreshes, or deletes cannot change a resumed run. + Dataset names are checked by the stored scenario identity. Resume never prepares datasets. + A scenario that overrides `_resolve_seed_groups_by_dataset_async` still runs it on resume + for the state it sets up, so the datasets it reads must still exist. - Keep custom shaping in `_build_attack_groups()` or `_build_groups_by_dataset_async()`. Reads use `_collect_seeds_for_dataset_async()` and must not fetch. - Build synthesized prompts from those filtered seeds, not a second unfiltered memory query. @@ -305,7 +307,7 @@ Scenario-specific scorers, selectors, and construction options stay on the scena On resume, `context.stored_run_plan` carries the original plan. Restore committed per-input technique choices from it instead of selecting again. The base restores -the planned source population before builders check compatibility. Saved adaptive +the stored planned population before builders check compatibility. Saved adaptive choices must identify the full technique, including its prompts, not only its inner attack. ### Zero-boilerplate matrix scenarios diff --git a/pyrit/memory/alembic/versions/c7d1e9a3b5f2_add_scenario_plan_seed_groups.py b/pyrit/memory/alembic/versions/c7d1e9a3b5f2_add_scenario_plan_seed_groups.py new file mode 100644 index 0000000000..e02543e549 --- /dev/null +++ b/pyrit/memory/alembic/versions/c7d1e9a3b5f2_add_scenario_plan_seed_groups.py @@ -0,0 +1,56 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +""" +add scenario plan seed groups. + +Revision ID: c7d1e9a3b5f2 +Revises: a3f7c9e2b641 +Create Date: 2026-11-16 15:30:00.000000 +""" + +from collections.abc import Sequence + +import sqlalchemy as sa +from alembic import op + +import pyrit.memory.memory_models + +# revision identifiers, used by Alembic. +revision: str = "c7d1e9a3b5f2" +down_revision: str | None = "a3f7c9e2b641" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + + +def upgrade() -> None: + """Store the seed groups each new scenario run planned, so resume doesn't read datasets.""" + op.create_table( + "ScenarioPlanSeedGroupEntries", + sa.Column("id", pyrit.memory.memory_models.CustomUUID(), nullable=False), + sa.Column("scenario_result_id", pyrit.memory.memory_models.CustomUUID(), nullable=False), + sa.Column("dataset_name", sa.Unicode(), nullable=False), + sa.Column("position", sa.INTEGER(), nullable=False), + sa.Column("seed_group", sa.JSON(), nullable=False), + sa.Column("has_media", sa.Boolean(), nullable=False), + sa.ForeignKeyConstraint(["scenario_result_id"], ["ScenarioResultEntries.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + op.create_index( + "ix_ScenarioPlanSeedGroupEntries_scenario_result_id_position", + "ScenarioPlanSeedGroupEntries", + ["scenario_result_id", "position"], + unique=False, + ) + op.create_index( + "ix_ScenarioPlanSeedGroupEntries_has_media", "ScenarioPlanSeedGroupEntries", ["has_media"], unique=False + ) + + +def downgrade() -> None: + """Drop stored plan seed groups; runs planned after the upgrade can no longer resume.""" + op.drop_index("ix_ScenarioPlanSeedGroupEntries_has_media", table_name="ScenarioPlanSeedGroupEntries") + op.drop_index( + "ix_ScenarioPlanSeedGroupEntries_scenario_result_id_position", table_name="ScenarioPlanSeedGroupEntries" + ) + op.drop_table("ScenarioPlanSeedGroupEntries") diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index 40404fac8e..670cf0e3a9 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -103,6 +103,7 @@ PromptConverterIdentifierEntry, PromptMemoryEntry, ScenarioIdentifierEntry, + ScenarioPlanSeedGroupEntry, ScenarioResultEntry, ScorableContentEntry, ScoreEntry, @@ -129,6 +130,7 @@ AttackResult, AttackResultRole, AttackResultSelection, + AttackSeedGroup, AttackTechniqueIdentifier, ComponentIdentifier, ContentEntryScorable, @@ -7678,17 +7680,33 @@ def _execute_get_unique_attack_attribution(self) -> dict[str, list[str]]: ] return {"operators": sorted(operators), "operations": sorted(operations)} - def _execute_add_scenario_results_to_memory(self, *, scenario_results: Sequence[ScenarioResult]) -> None: + def _execute_add_scenario_results_to_memory( + self, + *, + scenario_results: Sequence[ScenarioResult], + planned_seed_groups: Mapping[uuid.UUID, Mapping[str, Sequence[AttackSeedGroup]]] | None = None, + ) -> None: """ Insert a list of scenario results into the memory storage. Args: scenario_results: Sequence of ScenarioResult objects to store in the database. + planned_seed_groups: The population each result's run planned, keyed by result ID and + then by dataset name, stored in the same transaction. Raises: SQLAlchemyError: If a scenario result or identifier graph cannot be persisted. """ entries = [ScenarioResultEntry(entry=scenario_result) for scenario_result in scenario_results] + plan_entries = [ + ScenarioPlanSeedGroupEntry( + scenario_result_id=result_id, dataset_name=dataset_name, position=position, seed_group=seed_group + ) + for result_id, population in (planned_seed_groups or {}).items() + for position, (dataset_name, seed_group) in enumerate( + (name, group) for name, groups in population.items() for group in groups + ) + ] with closing(self._get_session()) as session: try: for scenario_result in scenario_results: @@ -7699,6 +7717,8 @@ def _execute_add_scenario_results_to_memory(self, *, scenario_results: Sequence[ for entry in entries: self._validate_activity_operation(session=session, entry=entry) session.add_all(entries) + session.flush() + session.add_all(plan_entries) self._recheck_activity_operations(session=session, entries=entries) session.commit() except SQLAlchemyError as error: @@ -7855,7 +7875,7 @@ def _execute_update_scenario_metadata( Replace the ``scenario_metadata`` JSON blob on an existing scenario result. Used by the scenario layer to persist first-run state (e.g. - ``objective_hashes``) that resume needs to replay. Performs a + an adaptive run's choices) that resume needs to replay. Performs a targeted UPDATE so it doesn't clobber other columns. Args: @@ -7925,6 +7945,24 @@ def _execute_increment_scenario_number_tries( session.commit() return new_tries + def _execute_get_planned_seed_groups(self, *, scenario_result_id: str) -> dict[str, list[AttackSeedGroup]]: + """ + Read a run's stored planned seed groups. + + Returns: + dict[str, list[AttackSeedGroup]]: The population by dataset name, in planned order. + """ + with closing(self._get_session()) as session: + entries = session.scalars( + select(ScenarioPlanSeedGroupEntry) + .where(ScenarioPlanSeedGroupEntry.scenario_result_id == uuid.UUID(scenario_result_id)) + .order_by(ScenarioPlanSeedGroupEntry.position) + ).all() + population: dict[str, list[AttackSeedGroup]] = {} + for entry in entries: + population.setdefault(entry.dataset_name, []).append(entry.get_seed_group()) + return population + def _execute_get_scenario_result_header(self, *, scenario_result_id: str) -> ScenarioResult | None: """Return one ScenarioResult header without hydrating linked attack results.""" with closing(self._get_session()) as session: @@ -12487,6 +12525,43 @@ async def add_scenario_results_to_memory_async(self, *, scenario_results: Sequen self._execute_add_scenario_results_to_memory, scenario_results=scenario_results ) + async def add_planned_scenario_result_async( + self, *, scenario_result: ScenarioResult, seed_groups_by_dataset: Mapping[str, Sequence[AttackSeedGroup]] + ) -> None: + """ + Insert a new scenario result together with the seed groups its run planned. + + Resume rebuilds the run from these groups, so later dataset changes don't affect it. + + Args: + scenario_result (ScenarioResult): The new scenario result. + seed_groups_by_dataset (Mapping[str, Sequence[AttackSeedGroup]]): The planned population, + by dataset name, in the order the run was built from. + + Raises: + SQLAlchemyError: If the result, its identifier graph, or its seed groups cannot be persisted. + """ + return await self._run_database_operation_async( + self._execute_add_scenario_results_to_memory, + scenario_results=[scenario_result], + planned_seed_groups={scenario_result.id: seed_groups_by_dataset}, + ) + + async def get_planned_seed_groups_async(self, *, scenario_result_id: str) -> dict[str, list[AttackSeedGroup]]: + """ + Return the seed groups a scenario run planned, as stored when the run was created. + + Args: + scenario_result_id (str): The scenario result ID. + + Returns: + dict[str, list[AttackSeedGroup]]: The planned population by dataset name, in planned + order. Empty when the run planned no groups or was created before they were stored. + """ + return await self._run_database_operation_async( + self._execute_get_planned_seed_groups, scenario_result_id=scenario_result_id + ) + def update_scenario_run_state( self, *, @@ -12685,7 +12760,7 @@ async def update_scenario_metadata_async(self, *, scenario_result_id: str, metad Replace the ``scenario_metadata`` JSON blob on an existing scenario result. Used by the scenario layer to persist first-run state (e.g. - ``objective_hashes``) that resume needs to replay. Performs a + an adaptive run's choices) that resume needs to replay. Performs a targeted UPDATE so it doesn't clobber other columns. Args: diff --git a/pyrit/memory/memory_models.py b/pyrit/memory/memory_models.py index fa409dc756..5f4a0f5d7a 100644 --- a/pyrit/memory/memory_models.py +++ b/pyrit/memory/memory_models.py @@ -42,12 +42,14 @@ from pyrit.memory.analytics_identity_v1 import ObjectiveTargetAnalyticsIdentityV1 from pyrit.memory.analytics_sql import ResolvedAttackIdentifierHash from pyrit.models import ( + MEDIA_PATH_DATA_TYPES, SEED_RESPONSE_JSON_SCHEMA_METADATA_KEY, AtomicAttackEvaluationIdentifier, AtomicAttackIdentifier, AttackIdentifier, AttackOutcome, AttackResult, + AttackSeedGroup, AttackTechniqueIdentifier, ChatMessageRole, ComponentIdentifier, @@ -2680,3 +2682,90 @@ def __str__(self) -> str: str: String representation of the scenario result entry """ return f"ScenarioResultEntry: {self.scenario_name} (version {self.scenario_version})" + + +_SIMULATED_CONVERSATION_PROMPT_FIELDS = ( + "adversarial_chat_system_prompt", + "simulated_target_system_prompt", + "next_message_system_prompt", +) + + +def planned_media_values(seed_group: dict[str, Any]) -> list[str]: + """ + Return the media paths a stored planned seed group references. + + Args: + seed_group (dict[str, Any]): A ``ScenarioPlanSeedGroupEntry.seed_group`` value. + + Returns: + list[str]: The media paths, in seed order. + """ + values: list[str] = [] + for seed in seed_group.get("seeds", []): + prompts = [seed] + if seed.get("seed_type") == "simulated_conversation": + prompts = [seed.get(field) for field in _SIMULATED_CONVERSATION_PROMPT_FIELDS] + values.extend( + prompt["value"] + for prompt in prompts + if isinstance(prompt, dict) and prompt.get("data_type") in MEDIA_PATH_DATA_TYPES + ) + return values + + +class ScenarioPlanSeedGroupEntry(Base): + """ + One seed group a scenario run planned, stored when the run is created. + + Resume rebuilds the run's population from these rows instead of reading its datasets, so + editing, refreshing, or deleting a dataset doesn't change what a run resumes on. Rows are + deleted with their scenario result. + """ + + __tablename__ = "ScenarioPlanSeedGroupEntries" + __table_args__ = ( + Index("ix_ScenarioPlanSeedGroupEntries_scenario_result_id_position", "scenario_result_id", "position"), + Index("ix_ScenarioPlanSeedGroupEntries_has_media", "has_media"), + ) + + 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 + ) + #: The population key the group was planned under, usually its dataset name. + dataset_name: Mapped[str] = mapped_column(Unicode, nullable=False) + #: The group's order in the planned population, across all datasets. + position: Mapped[int] = mapped_column(INTEGER, nullable=False) + #: The ``AttackSeedGroup`` as JSON. + seed_group: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False) + #: Whether ``seed_group`` references media files, so media cleanup reads only these rows. + has_media: Mapped[bool] = mapped_column(Boolean, nullable=False) + + def __init__( + self, *, scenario_result_id: uuid.UUID, dataset_name: str, position: int, seed_group: AttackSeedGroup + ) -> None: + """ + Store one planned seed group. + + Args: + scenario_result_id (uuid.UUID): The run that planned the group. + dataset_name (str): The population key the group was planned under. + position (int): The group's order in the planned population. + seed_group (AttackSeedGroup): The planned group. + """ + self.id = uuid.uuid4() + self.scenario_result_id = scenario_result_id + self.dataset_name = dataset_name + self.position = position + self.seed_group = seed_group.model_dump(mode="json") + self.has_media = bool(planned_media_values(self.seed_group)) + + def get_seed_group(self) -> AttackSeedGroup: + """ + Rebuild the planned seed group. + + Returns: + AttackSeedGroup: The group, equal to the one the run planned. + """ + return AttackSeedGroup.model_validate(self.seed_group) diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index eaa2cb460e..608b565f4c 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -118,6 +118,10 @@ logger = logging.getLogger(__name__) +#: Scenario result metadata key marking a run whose planned population is stored with it, so +#: resume can rebuild it. Runs created before planned seed groups were stored lack it. +_PLANNED_SEED_GROUPS_METADATA_KEY = "planned_seed_groups_stored" + #: Param names a scenario must not declare via ``supported_parameters()``. These #: collide with promoted identity fields on ``ScenarioIdentifier`` and would be @@ -1481,13 +1485,13 @@ async def initialize_async(self) -> None: Raises: DatasetConstraintError: If the configured datasets can't be resolved for a reason other - than a resumed run's dataset having been deleted. + than a dataset having been deleted after a resumed run was planned. IncompatibleTechniqueError: If techniques were selected but none can run. ValueError: If ``objective_target`` is declared but not resolvable (neither supplied nor registered as a default), if a supplied target name is not registered in ``TargetRegistry``, if ``include_baseline=True`` is set for a scenario whose - ``BASELINE_ATTACK_POLICY`` is ``Forbidden``, or if a resumed run's datasets were - deleted or changed after the run was planned. + ``BASELINE_ATTACK_POLICY`` is ``Forbidden``, or if a resumed run can't be rebuilt + (it was created by an older PyRIT, or a dataset its scenario reads was deleted). """ if not self._params_resolved: self.set_params_from_args(args=self.params) @@ -1559,43 +1563,25 @@ async def initialize_async(self) -> None: # ``self._include_baseline`` above, which the ScenarioContext carries as # ``include_baseline``. # - # Resolve without sampling on resume, then restore the planned population before - # builders check compatibility. Inputs outside the saved run must not affect resume. - is_resume = self._scenario_result_id is not None - if not is_resume: + # A new run resolves and samples its population, then stores it with the result. Resume + # rebuilds from that stored population and never reads the population datasets, so + # dataset edits, refreshes, and deletes after planning don't affect it. + if stored_result is not None: + seed_groups_by_dataset = await self._load_planned_population_async( + stored_result=stored_result, stored_plan=stored_plan + ) + else: await self._prepare_datasets_async() - try: - seed_groups_by_dataset = await self._resolve_seed_groups_by_dataset_async(apply_sampling=not is_resume) - except DatasetConstraintError as error: - if is_resume: - await self._raise_if_datasets_deleted_async(cause=error) - raise - if stored_plan is not None: - planned_seed_ids = {group_id for group in stored_plan.atomic_groups for group_id in group.seed_group_ids} - if seed_groups_by_dataset: - resolved_seed_ids = {group.logical_id for groups in seed_groups_by_dataset.values() for group in groups} - missing_seed_ids = planned_seed_ids - resolved_seed_ids - if missing_seed_ids: - raise ValueError( - self._resume_error_message( - reason=f"missing {len(missing_seed_ids)} planned seed group(s) in the resolved " - f"datasets ({', '.join(repr(name) for name in seed_groups_by_dataset)}); " - "their content changed after the run was planned" - ) + seed_groups_by_dataset = await self._resolve_seed_groups_by_dataset_async(apply_sampling=True) + if self._dataset_config.max_total != "all": + count = sum(len(groups) for groups in seed_groups_by_dataset.values()) + if count > self._dataset_config.max_total: + seed_groups_by_dataset = sample_with_coverage( + groups_by_dataset=seed_groups_by_dataset, + cap=self._dataset_config.max_total, + required_keys=self._get_required_objective_keys(), + key=lambda name, _: name, ) - seed_groups_by_dataset = { - name: [group for group in groups if group.logical_id in planned_seed_ids] - for name, groups in seed_groups_by_dataset.items() - } - if not is_resume and self._dataset_config.max_total != "all": - count = sum(len(groups) for groups in seed_groups_by_dataset.values()) - if count > self._dataset_config.max_total: - seed_groups_by_dataset = sample_with_coverage( - groups_by_dataset=seed_groups_by_dataset, - cap=self._dataset_config.max_total, - required_keys=self._get_required_objective_keys(), - key=lambda name, _: name, - ) # A fresh run's result id is chosen now, so attacks built below can already refer to the run. new_result_id = uuid.uuid4() context = self._build_scenario_context( @@ -1626,19 +1612,7 @@ async def initialize_async(self) -> None: stored_result=stored_result, current_identifier=scenario_identifier, ) - if stored_plan is not None: - self._apply_persisted_run_plan(stored_plan=stored_plan) - else: - self._apply_persisted_objectives(stored_result=stored_result) - reconstructed_plan = self._build_run_plan() - metadata = dict(stored_result.metadata) - metadata[SCENARIO_RUN_PLAN_METADATA_KEY] = reconstructed_plan.model_dump(mode="json", exclude_none=True) - ( - await self._memory.update_scenario_metadata_async( - scenario_result_id=self._scenario_result_id, - metadata=metadata, - ) - ) + self._apply_persisted_run_plan(stored_plan=cast("ScenarioRunPlan", stored_plan)) return # Valid resume - skip creating new scenario result # Build display group mapping from atomic attacks @@ -1664,7 +1638,9 @@ async def initialize_async(self) -> None: }, ) - (await self._memory.add_scenario_results_to_memory_async(scenario_results=[result])) + await self._memory.add_planned_scenario_result_async( + scenario_result=result, seed_groups_by_dataset=seed_groups_by_dataset + ) self._scenario_result_id = str(result.id) logger.info(f"Created new scenario result with ID: {self._scenario_result_id}") @@ -1672,29 +1648,14 @@ def _build_initial_scenario_metadata(self) -> dict[str, Any]: """ Build the metadata dict persisted with a freshly-created ``ScenarioResult``. - When a source or total limit is in effect, the dataset config draws an - unseeded ``random.sample`` and the chosen subset would silently change - on the next run (e.g. a resume). To make resume reliable, snapshot the - chosen objective hashes here so the next ``_setup_scenario_async`` can - replay them via ``keep_seed_groups_with_hashes``. - - The normalized run plan is always stored. When no sampling limits are set, - only the run plan is needed because the full dataset is deterministic. + The normalized run plan is always stored. The sampled population itself is stored + alongside the result (see ``add_planned_scenario_result_async``), so resume never + resamples. Returns: dict[str, Any]: Metadata payload for the new ScenarioResult. """ - metadata: dict[str, Any] = {} - if self._dataset_config.has_sampling_limits: - hashes: list[str] = [] - seen: set[str] = set() - for aa in self._atomic_attacks: - for sg in aa.seed_groups: - sha = to_sha256(sg.objective.value) - if sha not in seen: - seen.add(sha) - hashes.append(sha) - metadata["objective_hashes"] = hashes + metadata: dict[str, Any] = {_PLANNED_SEED_GROUPS_METADATA_KEY: True} metadata[SCENARIO_RUN_PLAN_METADATA_KEY] = self._build_run_plan().model_dump(mode="json", exclude_none=True) metadata["incompatible_technique_policy"] = self._incompatible_technique_policy.value adaptations = { @@ -1828,6 +1789,44 @@ def _resume_error_message(self, *, reason: str) -> str: "otherwise drop scenario_result_id to start a new run." ) + async def _load_planned_population_async( + self, *, stored_result: ScenarioResult, stored_plan: ScenarioRunPlan | None + ) -> dict[str, list[AttackSeedGroup]]: + """ + Rebuild a resumed run's population from the seed groups stored when it was created. + + Population datasets are never read, so they may have been edited, refreshed, or deleted. + A scenario that resolves its own seed groups still runs that resolution, without sampling, + for the state it sets up (such as scorers built from required datasets); its groups are + discarded. + + Args: + stored_result (ScenarioResult): The stored scenario result. + stored_plan (ScenarioRunPlan | None): The stored run plan, if any. + + Returns: + dict[str, list[AttackSeedGroup]]: The planned population, by dataset name. + + Raises: + ValueError: If the run stored no plan or planned seed groups, or a dataset the + scenario's own resolution reads was deleted. + DatasetConstraintError: If the scenario's own resolution fails for another reason. + """ + if stored_plan is None or stored_result.metadata.get(_PLANNED_SEED_GROUPS_METADATA_KEY) is not True: + raise ValueError( + f"Scenario result id '{self._scenario_result_id}' cannot resume: it was created by an older " + "PyRIT version that didn't store the seeds it planned. Drop scenario_result_id to start a new run." + ) + population = await self._memory.get_planned_seed_groups_async(scenario_result_id=str(stored_result.id)) + resolver = type(self)._resolve_seed_groups_by_dataset_async + if resolver.__qualname__ != Scenario._resolve_seed_groups_by_dataset_async.__qualname__: + try: + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + except DatasetConstraintError as error: + await self._raise_if_datasets_deleted_async(cause=error) + raise + return population + async def _raise_if_datasets_deleted_async(self, *, cause: DatasetConstraintError) -> None: """ Explain a resume whose dataset resolution failed because a dataset was deleted. @@ -1893,51 +1892,6 @@ def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: self._atomic_attacks = retained_attacks self._display_group_map = {group.atomic_attack_name: group.display_group for group in stored_plan.atomic_groups} - def _apply_persisted_objectives(self, *, stored_result: ScenarioResult) -> None: - """ - On resume, replay the originally-sampled objective subset. - - When the first run used ``max_dataset_size``, the chosen subset was - recorded in ``ScenarioResult.metadata["objective_hashes"]``. Resume resolves - the **full, deterministic** dataset (sampling is bypassed on the resume branch of - ``initialize_async``), so restricting each atomic attack's seed_groups to the - persisted set here reconstructs exactly the objectives the first run committed to. - Per-objective atomic attacks outside that subset are removed before scheduling. - If any persisted hash is no longer present in the dataset, refuse to resume — that - now signals the dataset itself genuinely changed, not a random resample drift. - - Args: - stored_result (ScenarioResult): The scenario result loaded from memory. - - Raises: - ValueError: If any persisted objective hash is missing from the - currently-resolved dataset. - """ - metadata = stored_result.metadata or {} - persisted = metadata.get("objective_hashes") - if not persisted: - return - - persisted_hashes: set[str] = set(persisted) - retained: set[str] = set() - retained_attacks: list[AtomicAttack] = [] - for aa in self._atomic_attacks: - retained |= aa.keep_seed_groups_with_hashes(hashes=persisted_hashes) - if aa.seed_groups: - retained_attacks.append(aa) - - missing = persisted_hashes - retained - if missing: - sample = sorted(missing)[:3] - raise ValueError( - f"Scenario result id '{self._scenario_result_id}' cannot resume: " - f"{len(missing)} persisted objective hash(es) are no longer present in the dataset " - f"(missing examples: {', '.join(h[:12] + '...' for h in sample)}). " - f"Either restore the missing objectives or drop scenario_result_id to start a new scenario." - ) - - self._atomic_attacks = retained_attacks - def _get_identity_params(self) -> dict[str, Any]: """ Return the scenario's own parameters recorded in its identity. @@ -2139,10 +2093,9 @@ async def _resolve_seed_groups_by_dataset_async( Args: apply_sampling (bool): When True (default), apply ``max_dataset_size`` sampling. - On resume the base passes False so the full, deterministic dataset is resolved - and the persisted objective subset is reconstructed exactly (see - ``_apply_persisted_objectives``) rather than intersected against a fresh, - divergent ``random.sample`` draw. + Resume rebuilds the population from the seed groups stored with the run, so + it calls an overriding implementation only for the state it sets up (such as + scorers built from required datasets), with False, and discards its groups. Returns: dict[str, list[AttackSeedGroup]]: Seed groups keyed by dataset name. diff --git a/tests/unit/backend/test_scenario_resume.py b/tests/unit/backend/test_scenario_resume.py index 72e1f19a54..1ed6efa7a3 100644 --- a/tests/unit/backend/test_scenario_resume.py +++ b/tests/unit/backend/test_scenario_resume.py @@ -43,6 +43,7 @@ SCENARIO_RUN_PLAN_METADATA_KEY, AtomicAttackIdentifier, AttackOutcome, + AttackSeedGroup, ComponentIdentifier, DatasetFetchPolicy, DatasetSourceInput, @@ -707,7 +708,7 @@ async def test_real_foundry_launch_keeps_heartbeat_alive_during_disk_reads_async reads = 0 original_load = yaml_seed_loader._read_yaml original_read = sqlite_instance.get_seeds_async - original_write = sqlite_instance.add_scenario_results_to_memory_async + original_write = sqlite_instance.add_planned_scenario_result_async class OfflineFoundry(RedTeamAgent): def __init__(self, *, scenario_result_id: str | None = None) -> None: @@ -743,9 +744,11 @@ async def read_seeds_async(**kwargs: Any) -> Sequence[Seed[Any]]: assert asyncio.get_running_loop() is loop return await original_read(**kwargs) - async def write_results_async(*, scenario_results: Sequence[ScenarioResult]) -> None: + async def write_results_async( + *, scenario_result: ScenarioResult, seed_groups_by_dataset: Mapping[str, Sequence[AttackSeedGroup]] + ) -> None: assert asyncio.get_running_loop() is loop - await original_write(scenario_results=scenario_results) + await original_write(scenario_result=scenario_result, seed_groups_by_dataset=seed_groups_by_dataset) async def send_async(*, normalized_conversation: list[Message]) -> list[Message]: assert asyncio.get_running_loop() is loop @@ -771,7 +774,7 @@ async def send_async(*, normalized_conversation: list[Message]) -> list[Message] patch.object(yaml_seed_loader, "_read_yaml", side_effect=load_template), patch.object(sqlite_instance, "get_seeds_async", side_effect=read_seeds_async) as read_seeds, patch.object( - sqlite_instance, "add_scenario_results_to_memory_async", side_effect=write_results_async + sqlite_instance, "add_planned_scenario_result_async", side_effect=write_results_async ) as write, patch.object(target, "_send_prompt_to_target_async", side_effect=send_async), ): diff --git a/tests/unit/memory/test_dataset_lifecycle_migration.py b/tests/unit/memory/test_dataset_lifecycle_migration.py index 71db23d3a8..f588ac85ab 100644 --- a/tests/unit/memory/test_dataset_lifecycle_migration.py +++ b/tests/unit/memory/test_dataset_lifecycle_migration.py @@ -47,6 +47,7 @@ def test_dataset_lifecycle_migration_and_guarded_downgrade() -> None: "DatasetLifecycleLock", "DatasetLifecycleEntries", "DatasetMediaEntries", + "ScenarioPlanSeedGroupEntries", } assert connection.scalar(sa.select(DatasetLifecycleLock.id)) == 1 command.downgrade(config, PREVIOUS) diff --git a/tests/unit/memory/test_planned_seed_groups.py b/tests/unit/memory/test_planned_seed_groups.py new file mode 100644 index 0000000000..c79d517b41 --- /dev/null +++ b/tests/unit/memory/test_planned_seed_groups.py @@ -0,0 +1,68 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pyrit.memory import MemoryInterface +from pyrit.memory.memory_models import ScenarioPlanSeedGroupEntry, planned_media_values +from pyrit.models import AttackSeedGroup, SeedObjective, SeedPrompt +from unit.mocks import get_mock_target_identifier, make_scenario_result + + +def _group(objective: str, *prompts: SeedPrompt) -> AttackSeedGroup: + return AttackSeedGroup( + seeds=[SeedObjective(value=objective, description="kept", authors=["a"], harm_categories=["x"]), *prompts] + ) + + +async def test_planned_seed_groups_round_trip_in_order_with_duplicates(sqlite_instance: MemoryInterface) -> None: + duplicate = _group("dup") + population = { + "a": [duplicate, duplicate.model_copy(deep=True), _group("a2", SeedPrompt(value="context", role="system"))], + "b": [_group("b1")], + } + result = make_scenario_result(objective_target_identifier=get_mock_target_identifier(), attack_results={}) + await sqlite_instance.add_planned_scenario_result_async(scenario_result=result, seed_groups_by_dataset=population) + + stored = await sqlite_instance.get_planned_seed_groups_async(scenario_result_id=str(result.id)) + + assert stored == population + assert list(stored) == ["a", "b"] + assert (await sqlite_instance.get_scenario_results_async(scenario_result_ids=[str(result.id)]))[0].id == result.id + + +async def test_planned_seed_groups_are_empty_for_a_result_without_them(sqlite_instance: MemoryInterface) -> None: + result = make_scenario_result(objective_target_identifier=get_mock_target_identifier(), attack_results={}) + await sqlite_instance.add_scenario_results_to_memory_async(scenario_results=[result]) + + assert await sqlite_instance.get_planned_seed_groups_async(scenario_result_id=str(result.id)) == {} + + +def test_planned_seed_group_entry_flags_media() -> None: + result_id = make_scenario_result(objective_target_identifier=get_mock_target_identifier(), attack_results={}).id + text = ScenarioPlanSeedGroupEntry( + scenario_result_id=result_id, dataset_name="a", position=0, seed_group=_group("t") + ) + image = ScenarioPlanSeedGroupEntry( + scenario_result_id=result_id, + dataset_name="a", + position=1, + seed_group=_group("i", SeedPrompt(value="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/media/cat.png", data_type="image_path")), + ) + + assert (text.has_media, image.has_media) == (False, True) + assert planned_media_values(image.seed_group) == ["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/media/cat.png"] + assert image.get_seed_group() == image.get_seed_group() + + +def test_planned_media_values_reads_simulated_conversation_prompts() -> None: + seed_group = { + "seeds": [ + { + "seed_type": "simulated_conversation", + "adversarial_chat_system_prompt": {"value": "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/media/a.png", "data_type": "image_path"}, + "simulated_target_system_prompt": {"value": "text", "data_type": "text"}, + "next_message_system_prompt": None, + } + ] + } + + assert planned_media_values(seed_group) == ["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/media/a.png"] diff --git a/tests/unit/memory/test_scenario_plan_seed_groups_migration.py b/tests/unit/memory/test_scenario_plan_seed_groups_migration.py new file mode 100644 index 0000000000..6dde59c04d --- /dev/null +++ b/tests/unit/memory/test_scenario_plan_seed_groups_migration.py @@ -0,0 +1,54 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from pathlib import Path + +import sqlalchemy as sa +from alembic import command +from alembic.config import Config +from sqlalchemy.dialects import mssql +from sqlalchemy.schema import CreateIndex, CreateTable + +from pyrit.memory.memory_models import ScenarioPlanSeedGroupEntry +from pyrit.memory.migration import check_schema_migrations + +REVISION = "c7d1e9a3b5f2" +PREVIOUS = "a3f7c9e2b641" +TABLE = "ScenarioPlanSeedGroupEntries" + + +def _config(connection: sa.Connection) -> Config: + config = Config() + config.set_main_option("script_location", str(Path(__file__).resolve().parents[3] / "pyrit" / "memory" / "alembic")) + config.attributes.update(connection=connection, version_table="pyrit_memory_alembic_version") + return config + + +def test_scenario_plan_seed_groups_migration_upgrades_and_downgrades() -> None: + engine = sa.create_engine("sqlite:///:memory:") + try: + with engine.begin() as connection: + config = _config(connection) + command.upgrade(config, PREVIOUS) + assert TABLE not in sa.inspect(connection).get_table_names() + command.upgrade(config, REVISION) + inspector = sa.inspect(connection) + assert {index["name"] for index in inspector.get_indexes(TABLE)} == { + "ix_ScenarioPlanSeedGroupEntries_scenario_result_id_position", + "ix_ScenarioPlanSeedGroupEntries_has_media", + } + assert [key["referred_table"] for key in inspector.get_foreign_keys(TABLE)] == ["ScenarioResultEntries"] + command.downgrade(config, PREVIOUS) + assert TABLE not in sa.inspect(connection).get_table_names() + command.upgrade(config, "head") + check_schema_migrations(engine=engine) + finally: + engine.dispose() + + +def test_scenario_plan_seed_groups_schema_compiles_for_sql_server() -> None: + dialect = mssql.dialect() + table = ScenarioPlanSeedGroupEntry.__table__ + assert "CREATE TABLE [ScenarioPlanSeedGroupEntries]" in str(CreateTable(table).compile(dialect=dialect)) + for index in table.indexes: + CreateIndex(index).compile(dialect=dialect) diff --git a/tests/unit/scenario/core/test_scenario.py b/tests/unit/scenario/core/test_scenario.py index 9ebdc8864d..1b72bee4b0 100644 --- a/tests/unit/scenario/core/test_scenario.py +++ b/tests/unit/scenario/core/test_scenario.py @@ -473,11 +473,64 @@ def test_subclass_implementing_build_atomic_attacks_async_is_concrete(): assert not ConcreteScenario.__abstractmethods__ +@pytest.mark.usefixtures("patch_central_database") +async def test_resume_keeps_the_sampled_copy_of_a_duplicate_group_async() -> None: + """Regression for #4157: a duplicate group the first run sampled only once still resumes.""" + + class MatrixScenario(ConcreteScenario): + BASELINE_ATTACK_POLICY = BaselineAttackPolicy.Enabled + _resolve_seed_groups_by_dataset_async = Scenario._resolve_seed_groups_by_dataset_async + + async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: + return build_matrix_atomic_attacks(context=context, objective_scorer=self._objective_scorer) + + target = MockPromptTarget() + duplicate = AttackSeedGroup(seeds=[SeedObjective(value="dup objective")]) + other = AttackSeedGroup(seeds=[SeedObjective(value="other objective")]) + config = DatasetAttackConfiguration(seed_groups=[duplicate, duplicate.model_copy(deep=True), other], max_total=2) + factory = AttackTechniqueFactory( + name="test", + attack_class=PromptSendingAttack, + requirements=TechniqueRequirements(seed_group=SeedGroupRequirements(objective_only=True)), + ) + + def make_scenario(*, scenario_result_id: str | None = None) -> MatrixScenario: + scenario = MatrixScenario( + version=1, objective_scorer=SubStringScorer(substring="default"), scenario_result_id=scenario_result_id + ) + scenario.set_params_from_args( + args={ + "objective_target": target, + "dataset_config": config, + "scenario_techniques": [scenario._technique_class("test")], + "incompatible_technique_policy": "raise", + } + ) + return scenario + + registry = AttackTechniqueRegistry.get_registry_singleton() + with patch.object(registry, "get_factories_or_raise", return_value={"test": factory}): + original = make_scenario() + with patch( + "pyrit.scenario.core.dataset_configuration.random.sample", + side_effect=lambda population, k: [population[0], population[-1]], + ): + await original.initialize_async() + resumed = make_scenario(scenario_result_id=original._scenario_result_id) + await resumed.initialize_async() + assert resumed._build_run_plan() == original._build_run_plan() + assert [attack.atomic_attack_name for attack in resumed._atomic_attacks] == [ + attack.atomic_attack_name for attack in original._atomic_attacks + ] + + @pytest.mark.usefixtures("patch_central_database") class TestScenarioCompatibilityPolicy: @pytest.mark.parametrize("change", ["none", "planned", "unsampled"]) @pytest.mark.parametrize("include_baseline", [False, True]) - async def test_strict_resume_checks_only_sampled_groups_async(self, *, change: str, include_baseline: bool) -> None: + async def test_resume_runs_the_stored_sample_despite_input_changes_async( + self, *, change: str, include_baseline: bool + ) -> None: class MatrixScenario(ConcreteScenario): BASELINE_ATTACK_POLICY = BaselineAttackPolicy.Enabled @@ -521,18 +574,16 @@ def make_scenario(*, scenario_result_id: str | None = None) -> MatrixScenario: await original.initialize_async() original_plan = original._build_run_plan() assert original_plan.atomic_groups[0].seed_group_ids == [selected.logical_id] + planned = selected.model_copy(deep=True) if change == "planned": selected.seeds.append(SeedPrompt(value="changed planned input")) elif change == "unsampled": unsampled.seeds.append(SeedPrompt(value="changed unsampled input", sequence=1)) resumed = make_scenario(scenario_result_id=original._scenario_result_id) - if change == "planned": - with pytest.raises(ValueError, match="cannot resume: missing 1 planned seed group"): - await resumed.initialize_async() - else: - await resumed.initialize_async() - assert resumed._build_run_plan() == original_plan - assert resumed._atomic_attacks[0].seed_groups == [selected] + # Resume rebuilds the stored population, so a later change to the inputs never reaches it. + await resumed.initialize_async() + assert resumed._build_run_plan() == original_plan + assert resumed._atomic_attacks[0].seed_groups == [planned] @pytest.mark.parametrize( ("class_default", "override", "expected"), @@ -1826,6 +1877,9 @@ class TestScenarioResumeDeterministicUnderMaxDatasetSize: """ class _StrategyScenario(ConcreteScenarioWithTrueFalseScorer): + # Use the base seed resolution, so resume rebuilds only from the stored population. + _resolve_seed_groups_by_dataset_async = Scenario._resolve_seed_groups_by_dataset_async + async def _build_atomic_attacks_async(self, *, context): from pyrit.scenario import AttackTechnique @@ -1949,27 +2003,39 @@ async def test_named_source_preparation_and_resume( "pyrit.scenario.core.dataset_configuration.random.sample", side_effect=AssertionError("No resampling") ) as sample, ): - if resume_state == "valid": + if resume_state in ("valid", "missing-dataset", "refreshed"): + # Resume rebuilds the stored population, so deleting or refreshing the dataset doesn't matter. await resumed.initialize_async() assert resumed._build_run_plan() == original_plan else: - expected_error = { - "missing-dataset": r"dataset\(s\) 'fixture' are no longer in memory; they were deleted", - "refreshed": r"missing 3 planned seed group\(s\) in the resolved datasets \('fixture'\); " - "their content changed", - }.get(resume_state) - with pytest.raises(ValueError, match=expected_error) as error: + with pytest.raises(ValueError): await resumed.initialize_async() - if expected_error: - assert str(error.value).endswith( - "To resume, re-import the dataset content this run used; " - "otherwise drop scenario_result_id to start a new run." - ) prepare.assert_not_awaited() provider.fetch_dataset_async.assert_not_awaited() lookup.assert_not_awaited() sample.assert_not_called() + async def test_overriding_resolution_still_reads_its_datasets_on_resume(self, mock_objective_target) -> None: + class _OverridingScenario(self._StrategyScenario): + async def _resolve_seed_groups_by_dataset_async(self, *, apply_sampling: bool = True): + return await self._dataset_config.get_attack_groups_by_dataset_async(apply_sampling=apply_sampling) + + memory = CentralMemory.get_memory_instance() + await memory.add_seeds_to_memory_async( + seeds=[SeedObjective(value=f"objective-{index}", dataset_name="owned") for index in range(2)], + added_by="test", + ) + config = DatasetAttackConfiguration(sources=[DatasetSource(name="owned")], fetch=DatasetFetchPolicy.NEVER) + original = _OverridingScenario(name="Overriding", version=1) + original.set_params_from_args(args={"objective_target": mock_objective_target, "dataset_config": config}) + await original.initialize_async() + await memory.remove_seeds_from_memory_async(dataset_name="owned") + resumed = _OverridingScenario(name="Overriding", version=1, scenario_result_id=original._scenario_result_id) + resumed.set_params_from_args(args={"objective_target": mock_objective_target, "dataset_config": config}) + with pytest.raises(ValueError, match=r"dataset\(s\) 'owned' are no longer in memory") as error: + await resumed.initialize_async() + assert isinstance(error.value.__cause__, DatasetConstraintError) + async def test_resume_reports_only_absent_datasets_as_deleted(self) -> None: scenario = self._StrategyScenario(name="Named sources", version=1, scenario_result_id=str(uuid.uuid4())) scenario._dataset_config = DatasetAttackConfiguration(sources=[DatasetSource(name="Fixture")]) @@ -2051,7 +2117,7 @@ def _sample_last_k(population, k): assert resumed_header is not None assert resumed_header.metadata[SCENARIO_RUN_PLAN_METADATA_KEY] == original_plan - async def test_resume_rejects_changed_companion_seed_with_same_objective(self, mock_objective_target): + async def test_resume_runs_planned_companion_seed_after_it_changes(self, mock_objective_target): objective = "unchanged objective" original_seed_group = AttackSeedGroup( seeds=[SeedObjective(value=objective), SeedPrompt(value="original context")] @@ -2090,13 +2156,11 @@ async def test_resume_rejects_changed_companion_seed_with_same_objective(self, m } ) - with pytest.raises( - ValueError, - match=r"cannot resume: missing 1 planned seed group", - ): - await resumed.initialize_async() + await resumed.initialize_async() + assert [attack.seed_groups for attack in resumed._atomic_attacks] == [[original_seed_group]] - async def test_resume_reconstructs_plan_for_legacy_resumable_run(self, mock_objective_target): + @pytest.mark.parametrize("removed", ["marker", "plan"]) + async def test_resume_refuses_run_without_stored_planned_seeds(self, mock_objective_target, removed: str): config = self._make_config() with patch( "pyrit.scenario.core.dataset_configuration.random.sample", @@ -2117,19 +2181,12 @@ async def test_resume_reconstructs_plan_for_legacy_resumable_run(self, mock_obje header = await scenario._memory.get_scenario_result_header_async(scenario_result_id=scenario_result_id) assert header is not None legacy_metadata = dict(header.metadata) - legacy_metadata.pop(SCENARIO_RUN_PLAN_METADATA_KEY) - ( - await scenario._memory.update_scenario_metadata_async( - scenario_result_id=scenario_result_id, - metadata=legacy_metadata, - ) + legacy_metadata.pop("planned_seed_groups_stored" if removed == "marker" else SCENARIO_RUN_PLAN_METADATA_KEY) + await scenario._memory.update_scenario_metadata_async( + scenario_result_id=scenario_result_id, metadata=legacy_metadata ) - resumed = self._StrategyScenario( - name="Legacy resume", - version=1, - scenario_result_id=scenario_result_id, - ) + resumed = self._StrategyScenario(name="Legacy resume", version=1, scenario_result_id=scenario_result_id) resumed.set_params_from_args( args={ "objective_target": mock_objective_target, @@ -2137,12 +2194,8 @@ async def test_resume_reconstructs_plan_for_legacy_resumable_run(self, mock_obje "dataset_config": self._make_config(), } ) - await resumed.initialize_async() - - reconstructed = await resumed._memory.get_scenario_result_header_async(scenario_result_id=scenario_result_id) - assert reconstructed is not None - assert SCENARIO_RUN_PLAN_METADATA_KEY in reconstructed.metadata - assert reconstructed.metadata["objective_hashes"] == legacy_metadata["objective_hashes"] + with pytest.raises(ValueError, match="created by an older PyRIT version"): + await resumed.initialize_async() async def test_resume_discards_per_objective_attacks_outside_persisted_subset(self, mock_objective_target): def _sample_first_k(population, k): diff --git a/tests/unit/scenario/core/test_scenario_dataset_overrides.py b/tests/unit/scenario/core/test_scenario_dataset_overrides.py index f054170548..932b3b3d47 100644 --- a/tests/unit/scenario/core/test_scenario_dataset_overrides.py +++ b/tests/unit/scenario/core/test_scenario_dataset_overrides.py @@ -149,7 +149,7 @@ async def test_resume_replays_saved_selection_without_preparation() -> None: selected = [group.logical_id for group in scenario._atomic_attacks[0].seed_groups] assert len(selected) == 4 - # Changed caps do not matter on resume: the stored run plan fixes the selected seed groups. + # Changed caps do not matter on resume: the stored population fixes the selected seed groups. resumed = _Scenario(scenario_result_id=scenario._scenario_result_id) resumed._default_dataset_config = resumed._default_dataset_config.with_overrides(max_total=1, max_per_dataset=1) resumed.set_params_from_args(args={"objective_target": target, "dataset_overrides": overrides}) @@ -165,7 +165,7 @@ async def test_resume_replays_saved_selection_without_preparation() -> None: "dataset_overrides": ScenarioDatasetRequest(sources=[DatasetSourceInput(name="a")]), } ) - with pytest.raises(ValueError, match="cannot resume: missing .* planned seed group"): + with pytest.raises(ValueError, match="does not match the current '_Scenario' configuration"): await diverged.initialize_async() diff --git a/tests/unit/scenario/core/test_scenario_retry.py b/tests/unit/scenario/core/test_scenario_retry.py index b33b41d964..2720f736ae 100644 --- a/tests/unit/scenario/core/test_scenario_retry.py +++ b/tests/unit/scenario/core/test_scenario_retry.py @@ -1089,56 +1089,3 @@ async def test_backward_compat_matches_name_only_when_eval_hash_missing(self): ] result = await scenario._get_completed_objective_hashes_by_attack_async() assert result == {("a", None): {to_sha256("old")}} - - -@pytest.mark.usefixtures("patch_central_database") -class TestApplyPersistedObjectives: - """Direct tests for ``Scenario._apply_persisted_objectives`` — the - resume-time replay that locks subsequent runs to the originally-sampled - objective subset.""" - - def _make_scenario_with_atomics(self, atomics): - scenario = ConcreteScenario(name="S", version=1, atomic_attacks_to_return=[]) - scenario._scenario_result_id = "scn-1" - scenario._atomic_attacks = atomics - return scenario - - def test_noop_when_metadata_has_no_persisted_hashes(self): - atomic = MagicMock(spec=AtomicAttack) - atomic.attack_technique.attack.IS_COMPOUND = False - atomic.group_kind = ScenarioRunPlanGroupKind.ATTACK - scenario = self._make_scenario_with_atomics([atomic]) - stored = MagicMock() - stored.metadata = {} - scenario._apply_persisted_objectives(stored_result=stored) - atomic.keep_seed_groups_with_hashes.assert_not_called() - - def test_replays_persisted_subset_across_atomics(self): - atomic_a = MagicMock(spec=AtomicAttack) - atomic_a.attack_technique.attack.IS_COMPOUND = False - atomic_a.group_kind = ScenarioRunPlanGroupKind.ATTACK - atomic_a.keep_seed_groups_with_hashes.return_value = {"h1", "h2"} - atomic_b = MagicMock(spec=AtomicAttack) - atomic_b.attack_technique.attack.IS_COMPOUND = False - atomic_b.group_kind = ScenarioRunPlanGroupKind.ATTACK - atomic_b.keep_seed_groups_with_hashes.return_value = {"h3"} - scenario = self._make_scenario_with_atomics([atomic_a, atomic_b]) - - stored = MagicMock() - stored.metadata = {"objective_hashes": ["h1", "h2", "h3"]} - scenario._apply_persisted_objectives(stored_result=stored) - - atomic_a.keep_seed_groups_with_hashes.assert_called_once_with(hashes={"h1", "h2", "h3"}) - atomic_b.keep_seed_groups_with_hashes.assert_called_once_with(hashes={"h1", "h2", "h3"}) - - def test_raises_when_persisted_hash_is_missing(self): - atomic = MagicMock(spec=AtomicAttack) - atomic.attack_technique.attack.IS_COMPOUND = False - atomic.group_kind = ScenarioRunPlanGroupKind.ATTACK - atomic.keep_seed_groups_with_hashes.return_value = {"h1"} # h2 missing - scenario = self._make_scenario_with_atomics([atomic]) - - stored = MagicMock() - stored.metadata = {"objective_hashes": ["h1", "h2"]} - with pytest.raises(ValueError, match="cannot resume"): - scenario._apply_persisted_objectives(stored_result=stored) diff --git a/tests/unit/scenario/garak/test_latent_injection.py b/tests/unit/scenario/garak/test_latent_injection.py index 9bc27a6c8b..70de6dd72e 100644 --- a/tests/unit/scenario/garak/test_latent_injection.py +++ b/tests/unit/scenario/garak/test_latent_injection.py @@ -532,13 +532,14 @@ async def test_changed_harm_scorer_refuses_resume_async(self) -> None: with pytest.raises(ValueError, match="matching configuration"): await _initialize_async(resumed, **args) - async def test_changed_case_refuses_resume_async(self, seeded_memory_async: MemoryInterface) -> None: + async def test_changed_case_resumes_the_planned_cases_async(self, seeded_memory_async: MemoryInterface) -> None: original = LatentInjection() args = { "dataset_config": _config(families=["whois"], max_dataset_size=2), "scenario_techniques": [LatentInjectionTechnique.Bare], } await _initialize_async(original, **args) + planned = [[group.logical_id for group in attack.seed_groups] for attack in original._atomic_attacks] sources = { name: list(await seeded_memory_async.get_seeds_async(dataset_name=name)) for name in LatentInjection.required_datasets() @@ -547,5 +548,5 @@ async def test_changed_case_refuses_resume_async(self, seeded_memory_async: Memo seed.value += " changed" resumed = LatentInjection(scenario_result_id=original._scenario_result_id) with _read_ingredients(sources): - with pytest.raises(ValueError, match="cannot resume"): - await _initialize_async(resumed, **args) + await _initialize_async(resumed, **args) + assert [[group.logical_id for group in attack.seed_groups] for attack in resumed._atomic_attacks] == planned diff --git a/tests/unit/scenario/scenarios/adaptive/test_text_adaptive.py b/tests/unit/scenario/scenarios/adaptive/test_text_adaptive.py index 62eb7e93d9..840b67dfa4 100644 --- a/tests/unit/scenario/scenarios/adaptive/test_text_adaptive.py +++ b/tests/unit/scenario/scenarios/adaptive/test_text_adaptive.py @@ -606,7 +606,8 @@ async def _initialize_async(scenario_result_id: str | None = None) -> TextAdapti len({ScenarioEvaluationIdentifier(result.scenario_identifier).eval_hash for result in stored_results}) == 1 ) assert mock_prepare.await_count == 2 - assert [call.kwargs["apply_sampling"] for call in mock_groups.await_args_list] == [True, False, True] + # Resume rebuilds the stored population and never resolves the datasets. + assert [call.kwargs["apply_sampling"] for call in mock_groups.await_args_list] == [True, True] async def test_atomic_names_contain_dataset_and_objective_hash(self, mock_objective_target, mock_objective_scorer): groups = { @@ -1098,12 +1099,13 @@ async def initialize_async( restored_selector.select_async.assert_not_awaited() assert [group.model_dump(mode="json") for group in groups] == snapshots if max_total == "all": - with pytest.raises(ValueError, match="planned seed-group occurrence.*missing"): - await initialize_async( - selector=restored_selector, - scenario_result_id=original._scenario_result_id, - sources=groups[:1], - ) + # Resume rebuilds the stored population, so a source losing an occurrence doesn't matter. + shrunk = await initialize_async( + selector=restored_selector, + scenario_result_id=original._scenario_result_id, + sources=groups[:1], + ) + assert shrunk._build_run_plan() == plan restored_selector.select_async.assert_not_awaited() @pytest.mark.parametrize("simulated", [False, True]) @@ -1432,7 +1434,9 @@ async def test_resume_rejects_missing_saved_choices_async( selector.select_async.reset_mock() selector.select_async.side_effect = AssertionError("Resume selected techniques again") - with pytest.raises(ValueError, match="no saved adaptive technique choices"): + # A result without a run plan predates stored planned seeds, so base resume refuses it first. + expected = "no saved adaptive technique choices" if missing_data == "choices" else "created by an older PyRIT" + with pytest.raises(ValueError, match=expected): await self._initialize_scenario_async( target=mock_objective_target, scorer=mock_objective_scorer, diff --git a/tests/unit/scenario/scenarios/technique/test_execute.py b/tests/unit/scenario/scenarios/technique/test_execute.py index 1c3e573866..0442302723 100644 --- a/tests/unit/scenario/scenarios/technique/test_execute.py +++ b/tests/unit/scenario/scenarios/technique/test_execute.py @@ -1160,7 +1160,7 @@ async def test_resume_same_inputs_and_reject_changed_objective_async( retries_on_objective_failure=retries, objective="Changed objective", ) - with pytest.raises(ValueError, match="cannot resume: missing 1 planned seed group"): + with pytest.raises(ValueError, match="does not match the current .Execute. configuration"): await changed.initialize_async() @pytest.mark.parametrize("change", ["append", "metadata"]) @@ -1184,8 +1184,7 @@ async def test_resume_rejects_changed_source_async(self, *, scorer: MagicMock, c await memory.update_prompt_metadata_by_conversation_id_async( conversation_id=history_id, prompt_metadata={"custom": "new metadata"} ) - expected_error = "cannot resume: missing 1 planned seed group" if change == "append" else "does not match" - with pytest.raises(ValueError, match=expected_error): + with pytest.raises(ValueError, match="does not match"): await resumed.initialize_async() def test_alias_and_dynamic_cache_reset(self) -> None: From b184270ce9ec6bc6eb055e4fabb86b1bc69741f2 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Mon, 16 Nov 2026 20:47:16 -0800 Subject: [PATCH 3/5] MAINT: Drop resume-only population matching now that runs store their seeds Resume now receives exactly the planned population, in order and with its duplicate copies, so AdaptiveScenario builds and names its atomics the same way a new run does and only reads its saved technique choices from the plan. This removes _restore_planned_populations and the separate resume branches for the baseline and per-dataset atomics. AtomicAttack.keep_seed_groups_with_hashes only served the removed objective_hashes replay, so it is deprecated for removal in 1.4.0. Co-Authored-By: Claude Opus 5.5 --- pyrit/scenario/core/atomic_attack.py | 12 +- .../scenarios/adaptive/adaptive_scenario.py | 121 ++++-------------- .../unit/scenario/core/test_atomic_attack.py | 9 +- 3 files changed, 41 insertions(+), 101 deletions(-) diff --git a/pyrit/scenario/core/atomic_attack.py b/pyrit/scenario/core/atomic_attack.py index 7926f58508..3731722fe3 100644 --- a/pyrit/scenario/core/atomic_attack.py +++ b/pyrit/scenario/core/atomic_attack.py @@ -18,6 +18,7 @@ import logging from typing import TYPE_CHECKING, Any +from pyrit.common import print_deprecation_message from pyrit.common.utils import to_sha256 from pyrit.executor.attack import AttackExecutor, AttackExecutorResult from pyrit.executor.attack.core.attack_result_attribution import AttackResultAttribution @@ -332,10 +333,8 @@ def keep_seed_groups_with_hashes(self, *, hashes: set[str]) -> set[str]: """ Keep only seed groups whose ``objective_sha256`` is in ``hashes``. - Inverse of ``drop_seed_groups_with_hashes``: used on resume to - replay the originally-sampled subset and ignore any seed groups that - were added since (or that landed in this run's fresh ``random.sample`` - draw and are no longer in the persisted set). + Deprecated: resume used this to replay the originally-sampled subset. A scenario run now + stores the seed groups it planned and resumes from them, so nothing needs to filter. Args: hashes (set[str]): SHA256 hashes of objective text for seed @@ -347,6 +346,11 @@ def keep_seed_groups_with_hashes(self, *, hashes: set[str]) -> set[str]: union these across atomic attacks to detect persisted hashes that no longer exist in the dataset. """ + print_deprecation_message( + old_item="AtomicAttack.keep_seed_groups_with_hashes", + new_item="the seed groups a scenario run stores for resume", + removed_in="1.4.0", + ) retained: set[str] = set() new_groups: list[AttackSeedGroup] = [] for sg in self._seed_groups: diff --git a/pyrit/scenario/scenarios/adaptive/adaptive_scenario.py b/pyrit/scenario/scenarios/adaptive/adaptive_scenario.py index e2692266ca..bc347294d1 100644 --- a/pyrit/scenario/scenarios/adaptive/adaptive_scenario.py +++ b/pyrit/scenario/scenarios/adaptive/adaptive_scenario.py @@ -19,7 +19,7 @@ import asyncio import logging from abc import abstractmethod -from collections import Counter, defaultdict, deque +from collections import Counter from typing import TYPE_CHECKING, Any, ClassVar, get_type_hints from pyrit.common.utils import to_sha256 @@ -32,7 +32,7 @@ ) from pyrit.scenario.core.atomic_attack import AtomicAttack from pyrit.scenario.core.attack_technique import AttackTechnique -from pyrit.scenario.core.matrix_atomic_attack_builder import build_baseline_atomic_attack, build_baseline_atomic_attacks +from pyrit.scenario.core.matrix_atomic_attack_builder import build_baseline_atomic_attacks from pyrit.scenario.core.scenario import Scenario from pyrit.scenario.core.technique_requirements import ( IncompatibleTechniqueError, @@ -44,8 +44,6 @@ from pyrit.scenario.scenarios.adaptive.selectors import EpsilonGreedyTechniqueSelector, TechniqueSelector if TYPE_CHECKING: - from collections.abc import Iterable, Sequence - from pyrit.models import AttackSeedGroup, ScenarioRunPlan, ScenarioRunPlanAtomicGroup from pyrit.scenario.core.attack_technique_factory import AttackTechniqueFactory from pyrit.scenario.core.dataset_configuration import DatasetAttackConfiguration @@ -224,36 +222,18 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list self._selected_seed_group_adaptations = [] self._selected_technique_hashes = {} + # Resume receives the stored planned population, so it builds and names atomics exactly + # as the original run did; only the technique choices come from the stored plan. atomic_attacks: list[AtomicAttack] = [] if context.include_baseline: - if context.stored_run_plan is None: - atomic_attacks.extend( - build_baseline_atomic_attacks( - objective_target=context.objective_target, - objective_scorer=self._objective_scorer, - seed_groups=list(context.seed_groups), - memory_labels=context.memory_labels, - ) + atomic_attacks.extend( + build_baseline_atomic_attacks( + objective_target=context.objective_target, + objective_scorer=self._objective_scorer, + seed_groups=list(context.seed_groups), + memory_labels=context.memory_labels, ) - else: - for planned, population in self._restore_planned_populations( - seed_groups=context.seed_groups, - planned_groups=( - group - for group in context.stored_run_plan.atomic_groups - if group.kind is ScenarioRunPlanGroupKind.BASELINE - ), - ): - atomic_attacks.append( - build_baseline_atomic_attack( - objective_target=context.objective_target, - objective_scorer=self._objective_scorer, - seed_groups=population, - memory_labels=context.memory_labels, - atomic_attack_name=planned.atomic_attack_name, - display_group=planned.display_group, - ) - ) + ) for dataset_name, seed_groups in context.seed_groups_by_dataset.items(): atomic_attacks.extend( await self._build_atomics_for_dataset_async( @@ -444,8 +424,9 @@ async def _build_atomics_for_dataset_async( dispatcher. Seed compatibility is reported once per technique/dataset combination. - Groups with no compatible technique are not scheduled. On resume, only - groups in the stored plan are rebuilt, using their saved choices. + Groups with no compatible technique are not scheduled. On resume the population is + the stored planned one, so atomics get their original names; only groups in the + stored plan are rebuilt, using their saved choices. Args: context (ScenarioContext): The resolved runtime inputs. @@ -459,34 +440,15 @@ async def _build_atomics_for_dataset_async( list[AtomicAttack]: One atomic per compatible seed group. Empty list when every seed group is incompatible with every technique. - - Raises: - ValueError: If a saved adaptive group does not contain exactly one source group. """ named_seed_groups: list[tuple[str, AttackSeedGroup]] = [] - if stored_groups is None: - objective_counts = Counter(group.objective.value for group in seed_groups) - occurrences: Counter[str] = Counter() - for group in seed_groups: - key = ( - group.logical_id - if objective_counts[group.objective.value] > 1 - else to_sha256(group.objective.value) - ) - occurrences[key] += 1 - suffix = f"__{occurrences[key]}" if occurrences[key] > 1 else "" - named_seed_groups.append((f"{self._atomic_attack_prefix()}_{dataset_name}::{key}{suffix}", group)) - else: - for planned, population in self._restore_planned_populations( - seed_groups=seed_groups, - planned_groups=(group for group in stored_groups.values() if group.display_group == dataset_name), - ): - if len(population) != 1: - raise ValueError( - f"Adaptive atomic group '{planned.atomic_attack_name}' must contain one seed group." - ) - named_seed_groups.append((planned.atomic_attack_name, population[0])) - seed_groups = [group for _, group in named_seed_groups] + objective_counts = Counter(group.objective.value for group in seed_groups) + occurrences: Counter[str] = Counter() + for group in seed_groups: + key = group.logical_id if objective_counts[group.objective.value] > 1 else to_sha256(group.objective.value) + occurrences[key] += 1 + suffix = f"__{occurrences[key]}" if occurrences[key] > 1 else "" + named_seed_groups.append((f"{self._atomic_attack_prefix()}_{dataset_name}::{key}{suffix}", group)) dispatcher = AdaptiveTechniqueDispatcher( objective_target=context.objective_target, @@ -523,10 +485,14 @@ async def _build_atomics_for_dataset_async( ] if not compatible: continue + selected_hashes = None + if stored_groups is not None: + # A group the original run didn't schedule stays unscheduled; the base's plan + # check reports any planned group that can't be rebuilt. + if atomic_attack_name not in stored_groups: + continue + selected_hashes = stored_groups[atomic_attack_name].selected_technique_eval_hashes - selected_hashes = ( - stored_groups[atomic_attack_name].selected_technique_eval_hashes if stored_groups is not None else None - ) attack = await dispatcher.build_attack_async( seed_group=seed_group, compatible=compatible, @@ -555,37 +521,6 @@ async def _build_atomics_for_dataset_async( return atomics - @staticmethod - def _restore_planned_populations( - *, - seed_groups: Sequence[AttackSeedGroup], - planned_groups: Iterable[ScenarioRunPlanAtomicGroup], - ) -> list[tuple[ScenarioRunPlanAtomicGroup, list[AttackSeedGroup]]]: - """ - Restore saved populations in plan order, consuming each source occurrence once. - - Returns: - list[tuple]: Planned atomic groups paired with their original population sizes. - - Raises: - ValueError: If the source cannot supply a planned seed-group occurrence. - """ - available: dict[str, deque[AttackSeedGroup]] = defaultdict(deque) - for seed_group in seed_groups: - available[seed_group.logical_id].append(seed_group) - populations = [] - for planned in planned_groups: - population = [] - for seed_group_id in planned.seed_group_ids: - if not available[seed_group_id]: - raise ValueError( - f"Cannot resume atomic group '{planned.atomic_attack_name}': " - f"planned seed-group occurrence '{seed_group_id}' is missing." - ) - population.append(available[seed_group_id].popleft()) - populations.append((planned, population)) - return populations - def _build_run_plan(self) -> ScenarioRunPlan: """ Include the ordered adaptive choices in each planned source group. diff --git a/tests/unit/scenario/core/test_atomic_attack.py b/tests/unit/scenario/core/test_atomic_attack.py index 1d832b482f..9fe7db8793 100644 --- a/tests/unit/scenario/core/test_atomic_attack.py +++ b/tests/unit/scenario/core/test_atomic_attack.py @@ -1011,8 +1011,7 @@ def test_filter_is_stable_across_resampling(self, mock_attack, sample_seed_group @pytest.mark.usefixtures("patch_central_database") class TestAtomicAttackRestrictSeedGroupsToHashes: - """Tests for ``keep_seed_groups_with_hashes`` — the keep-set inverse used - on resume to replay the originally-sampled subset.""" + """Tests for the deprecated ``keep_seed_groups_with_hashes`` keep-set filter.""" def test_keeps_only_listed_hashes(self, mock_attack, sample_seed_groups): from pyrit.common.utils import to_sha256 @@ -1023,7 +1022,8 @@ def test_keeps_only_listed_hashes(self, mock_attack, sample_seed_groups): atomic_attack_name="test", ) keep = {to_sha256("objective1"), to_sha256("objective3")} - retained = atomic.keep_seed_groups_with_hashes(hashes=keep) + with pytest.warns(DeprecationWarning, match="keep_seed_groups_with_hashes"): + retained = atomic.keep_seed_groups_with_hashes(hashes=keep) assert {sg.objective.value for sg in atomic.seed_groups} == {"objective1", "objective3"} assert retained == keep @@ -1037,7 +1037,8 @@ def test_retained_set_excludes_missing_hashes(self, mock_attack, sample_seed_gro atomic_attack_name="test", ) keep = {to_sha256("objective1"), to_sha256("not-in-dataset")} - retained = atomic.keep_seed_groups_with_hashes(hashes=keep) + with pytest.warns(DeprecationWarning, match="keep_seed_groups_with_hashes"): + retained = atomic.keep_seed_groups_with_hashes(hashes=keep) assert {sg.objective.value for sg in atomic.seed_groups} == {"objective1"} assert retained == {to_sha256("objective1")} From 985d8a6518e6e00ccc041f30210fe3a867f4d746 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Tue, 17 Nov 2026 09:23:52 -0800 Subject: [PATCH 4/5] FEAT: Keep dataset media that an incomplete scenario run planned Resume rebuilds a run from its stored planned seed groups, but dataset media cleanup didn't count those groups as references, so deleting a dataset could remove a file a paused run still needed. stored_media_keys now also reads media paths from planned seed groups of runs that haven't completed, using the has_media index. Planned seed group writes go through the same dataset reference guard as seeds and messages, so a new run can't plan media that is already queued for deletion. Co-Authored-By: Claude Opus 5.5 --- pyrit/memory/dataset_lifecycle.py | 19 ++++++++- pyrit/memory/memory_session.py | 8 ++-- tests/unit/memory/test_dataset_lifecycle.py | 45 ++++++++++++++++++++- 3 files changed, 67 insertions(+), 5 deletions(-) diff --git a/pyrit/memory/dataset_lifecycle.py b/pyrit/memory/dataset_lifecycle.py index 72309f04f1..cd0958bec6 100644 --- a/pyrit/memory/dataset_lifecycle.py +++ b/pyrit/memory/dataset_lifecycle.py @@ -24,10 +24,13 @@ DatasetLifecycleLock, DatasetMediaEntry, PromptMemoryEntry, + ScenarioPlanSeedGroupEntry, + ScenarioResultEntry, ScorableContentEntry, SeedEntry, + planned_media_values, ) -from pyrit.models import MEDIA_PATH_DATA_TYPES +from pyrit.models import MEDIA_PATH_DATA_TYPES, ScenarioRunState if TYPE_CHECKING: from collections.abc import Awaitable, Callable, Sequence @@ -129,6 +132,8 @@ def _entry_media_values(entry: object) -> list[str]: return [] if isinstance(entry, ScorableContentEntry): return [entry.value] if entry.data_type in MEDIA_PATH_DATA_TYPES else [] + if isinstance(entry, ScenarioPlanSeedGroupEntry): + return planned_media_values(entry.seed_group) if isinstance(entry, PromptMemoryEntry): return [ value @@ -206,6 +211,9 @@ def stored_media_keys(session: Session) -> set[str]: """ Read all live seed, original/converted message, and loose scorer-media references. + Media planned by a scenario run that hasn't completed counts too, so deleting a dataset + doesn't remove files a paused run still needs to resume. + Returns: set[str]: Canonical identities of the referenced media. """ @@ -226,6 +234,15 @@ def stored_media_keys(session: Session) -> set[str]: (PromptMemoryEntry.converted_value, PromptMemoryEntry.converted_value_data_type), ): values.extend(session.scalars(select(value_column).where(type_column.in_(MEDIA_PATH_DATA_TYPES))).all()) + for seed_group in session.scalars( + select(ScenarioPlanSeedGroupEntry.seed_group) + .join(ScenarioResultEntry, ScenarioResultEntry.id == ScenarioPlanSeedGroupEntry.scenario_result_id) + .where( + ScenarioPlanSeedGroupEntry.has_media, + ScenarioResultEntry.scenario_run_state != ScenarioRunState.COMPLETED.value, + ) + ): + values.extend(planned_media_values(seed_group)) return _media_keys(session, [value for value in values if value]) diff --git a/pyrit/memory/memory_session.py b/pyrit/memory/memory_session.py index caf8fbc439..2bb28eb583 100644 --- a/pyrit/memory/memory_session.py +++ b/pyrit/memory/memory_session.py @@ -16,6 +16,7 @@ ObservationEntry, ObservationMessagePieceEntry, PromptMemoryEntry, + ScenarioPlanSeedGroupEntry, ScorableContentEntry, ScoreEntry, ScoreObservationEntry, @@ -78,7 +79,7 @@ def flush(self, objects: Sequence[Any] | None = None) -> None: writes = [ entry for entry in self.new | self.dirty | self.deleted - if isinstance(entry, (SeedEntry, PromptMemoryEntry, ScorableContentEntry)) + if isinstance(entry, (SeedEntry, PromptMemoryEntry, ScorableContentEntry, ScenarioPlanSeedGroupEntry)) ] if writes: from pyrit.memory.dataset_lifecycle import ( @@ -87,8 +88,8 @@ def flush(self, objects: Sequence[Any] | None = None) -> None: validate_dataset_reference_writes, ) - # Only seeds and media-bearing rows can reference dataset assets. Text-only message - # writes skip the global lifecycle lock so concurrent conversations are not serialized. + # Only seeds and media-bearing rows, including planned seed groups, can reference dataset assets. + # Text-only message writes skip the global lifecycle lock so concurrent conversations are not serialized. references = [entry for entry in writes if entry_references_dataset_assets(entry)] if references: lock_dataset_lifecycle(self) @@ -194,6 +195,7 @@ def _guard_bulk_media_writes(state: ORMExecuteState) -> Any: SeedEntry.__tablename__, PromptMemoryEntry.__tablename__, ScorableContentEntry.__tablename__, + ScenarioPlanSeedGroupEntry.__tablename__, }: return state.invoke_statement() from pyrit.memory.dataset_lifecycle import ( diff --git a/tests/unit/memory/test_dataset_lifecycle.py b/tests/unit/memory/test_dataset_lifecycle.py index 8b361e5c86..42e321af65 100644 --- a/tests/unit/memory/test_dataset_lifecycle.py +++ b/tests/unit/memory/test_dataset_lifecycle.py @@ -23,10 +23,19 @@ from pyrit.memory.dataset_lifecycle import DatasetNameConflictError, entry_references_dataset_assets from pyrit.memory.dataset_mutation import DatasetVersionConflictError, dataset_version, editable_seed from pyrit.memory.memory_models import DatasetLifecycleEntry -from pyrit.models import MessagePiece, SeedPrompt, SeedRecord, SeedUnion +from pyrit.models import ( + AttackSeedGroup, + MessagePiece, + ScenarioRunState, + SeedObjective, + SeedPrompt, + SeedRecord, + SeedUnion, +) from pyrit.setup import SQLITE, initialize_pyrit_async from pyrit.setup.pyrit_initializer import PyRITInitializer from unit.async_utils import TEST_WATCHDOG_SECONDS +from unit.mocks import get_mock_target_identifier, make_scenario_result if TYPE_CHECKING: from sqlalchemy.sql.dml import Insert, Update @@ -704,3 +713,37 @@ async def test_text_message_writes_skip_the_lifecycle_lock_but_seeds_take_it( await session.flush() assert session.info.get("dataset_lifecycle_locked") await session.commit() + + +async def _plan_media_run_async(memory: SQLiteMemory, *, path: Path, state: ScenarioRunState) -> None: + group = AttackSeedGroup( + seeds=[SeedObjective(value="objective"), SeedPrompt(value=str(path), data_type="binary_path")] + ) + result = make_scenario_result( + objective_target_identifier=get_mock_target_identifier(), attack_results={}, scenario_run_state=state + ) + await memory.add_planned_scenario_result_async(scenario_result=result, seed_groups_by_dataset={"owned": [group]}) + + +@pytest.mark.parametrize(("state", "kept"), [(ScenarioRunState.FAILED, True), (ScenarioRunState.COMPLETED, False)]) +async def test_dataset_delete_keeps_media_an_incomplete_run_planned( + memories: tuple[SQLiteMemory, SQLiteMemory], state: ScenarioRunState, kept: bool +) -> None: + memory = memories[0] + path = await _create_media_dataset_async(memory) + await _plan_media_run_async(memory, path=path, state=state) + + deletion_id = await memory.delete_dataset_async(dataset_name="owned") + result = await memory.cleanup_dataset_media_async(operation_id=deletion_id) + + assert result["status"] == "completed" + assert path.exists() is kept + + +async def test_run_cannot_plan_media_queued_for_deletion(memories: tuple[SQLiteMemory, SQLiteMemory]) -> None: + memory = memories[0] + path = await _create_media_dataset_async(memory) + await memory.delete_dataset_async(dataset_name="owned") + + with pytest.raises(ValueError, match="reserved for dataset cleanup"): + await _plan_media_run_async(memory, path=path, state=ScenarioRunState.CREATED) From 408b4b89ba8fc105443ebf74f0dade23f506d7c5 Mon Sep 17 00:00:00 2001 From: Richard Lundeen Date: Tue, 17 Nov 2026 10:03:16 -0800 Subject: [PATCH 5/5] MAINT: Simplify scenario resume around stored planned seed groups Resume no longer re-runs a scenario's seed resolution for its side effects. Scenarios that keep state from resolution restore it in a new _restore_resume_state_async hook: LatentInjection rebuilds its scorer from the stored groups, PromptInject and ApiKey restore templates and excluded values saved in run metadata, and PackageHallucination and AssertPolicy still read their datasets. Scenarios that only reshape groups no longer read datasets on resume, so they resume after a dataset delete too. Resume now requires the rebuilt plan to equal the stored plan and names the atomic groups that differ, replacing the reorder-and-filter replay. Execute no longer records or checks a hash of its source conversation, since the stored group holds the history it planned. Co-Authored-By: Claude Opus 5.5 --- .../instructions/scenarios.instructions.md | 9 +- pyrit/scenario/core/scenario.py | 140 +++++++++--------- .../scenarios/foundry/assert_policy.py | 20 ++- pyrit/scenario/scenarios/garak/api_key.py | 41 ++++- .../scenarios/garak/latent_injection.py | 22 ++- .../scenarios/garak/package_hallucination.py | 8 + .../scenario/scenarios/garak/prompt_inject.py | 33 ++++- pyrit/scenario/scenarios/technique/execute.py | 24 --- .../unit/scenario/core/test_atomic_attack.py | 2 +- tests/unit/scenario/core/test_scenario.py | 42 +++--- tests/unit/scenario/garak/test_api_key.py | 18 +++ .../unit/scenario/garak/test_exploitation.py | 2 +- .../scenario/garak/test_latent_injection.py | 18 +++ .../unit/scenario/garak/test_prompt_inject.py | 20 ++- .../scenarios/technique/test_execute.py | 18 +-- 15 files changed, 275 insertions(+), 142 deletions(-) diff --git a/.github/instructions/scenarios.instructions.md b/.github/instructions/scenarios.instructions.md index 52ee60ef07..6acd447440 100644 --- a/.github/instructions/scenarios.instructions.md +++ b/.github/instructions/scenarios.instructions.md @@ -208,9 +208,12 @@ Options: It does not refresh or change that policy. - Resume replays the saved launch request and rebuilds the population stored with the run, so caps, fetch policies, and later dataset edits, refreshes, or deletes cannot change a resumed run. - Dataset names are checked by the stored scenario identity. Resume never prepares datasets. - A scenario that overrides `_resolve_seed_groups_by_dataset_async` still runs it on resume - for the state it sets up, so the datasets it reads must still exist. + Dataset names are checked by the stored scenario identity. Resume never prepares datasets or calls + `_resolve_seed_groups_by_dataset_async`. State that hook sets up for builders (such as a scorer) + must also be set up in `_restore_resume_state_async`: derive it from the stored population or save + it in the run's metadata, and read datasets only when neither works. +- The rebuilt plan must equal the stored plan exactly, or resume refuses and names the atomic groups + that differ. - Keep custom shaping in `_build_attack_groups()` or `_build_groups_by_dataset_async()`. Reads use `_collect_seeds_for_dataset_async()` and must not fetch. - Build synthesized prompts from those filtered seeds, not a second unfiltered memory query. diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index 608b565f4c..ac987c01d9 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -1612,7 +1612,7 @@ async def initialize_async(self) -> None: stored_result=stored_result, current_identifier=scenario_identifier, ) - self._apply_persisted_run_plan(stored_plan=cast("ScenarioRunPlan", stored_plan)) + self._require_rebuilt_plan_matches(stored_plan=cast("ScenarioRunPlan", stored_plan)) return # Valid resume - skip creating new scenario result # Build display group mapping from atomic attacks @@ -1773,32 +1773,14 @@ def _get_stored_run_plan(*, stored_result: ScenarioResult) -> ScenarioRunPlan | return None return ScenarioRunPlan.model_validate(raw_plan) - def _resume_error_message(self, *, reason: str) -> str: - """ - Build the error for a resume refused because its planned seeds can't be found. - - Args: - reason (str): What is missing, without a trailing period. - - Returns: - str: The message, ending with the two ways to recover. - """ - return ( - f"Scenario result id '{self._scenario_result_id}' cannot resume: {reason}. " - "To resume, re-import the dataset content this run used; " - "otherwise drop scenario_result_id to start a new run." - ) - async def _load_planned_population_async( self, *, stored_result: ScenarioResult, stored_plan: ScenarioRunPlan | None ) -> dict[str, list[AttackSeedGroup]]: """ Rebuild a resumed run's population from the seed groups stored when it was created. - Population datasets are never read, so they may have been edited, refreshed, or deleted. - A scenario that resolves its own seed groups still runs that resolution, without sampling, - for the state it sets up (such as scorers built from required datasets); its groups are - discarded. + Datasets are not read, so they may have been edited, refreshed, or deleted. A scenario + that keeps state built during seed resolution restores it in ``_restore_resume_state_async``. Args: stored_result (ScenarioResult): The stored scenario result. @@ -1809,8 +1791,8 @@ async def _load_planned_population_async( Raises: ValueError: If the run stored no plan or planned seed groups, or a dataset the - scenario's own resolution reads was deleted. - DatasetConstraintError: If the scenario's own resolution fails for another reason. + scenario's state restore reads was deleted. + DatasetConstraintError: If the scenario's state restore fails for another reason. """ if stored_plan is None or stored_result.metadata.get(_PLANNED_SEED_GROUPS_METADATA_KEY) is not True: raise ValueError( @@ -1818,15 +1800,29 @@ async def _load_planned_population_async( "PyRIT version that didn't store the seeds it planned. Drop scenario_result_id to start a new run." ) population = await self._memory.get_planned_seed_groups_async(scenario_result_id=str(stored_result.id)) - resolver = type(self)._resolve_seed_groups_by_dataset_async - if resolver.__qualname__ != Scenario._resolve_seed_groups_by_dataset_async.__qualname__: - try: - await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) - except DatasetConstraintError as error: - await self._raise_if_datasets_deleted_async(cause=error) - raise + try: + await self._restore_resume_state_async(stored_result=stored_result, seed_groups_by_dataset=population) + except DatasetConstraintError as error: + await self._raise_if_datasets_deleted_async(cause=error) + raise return population + async def _restore_resume_state_async( # noqa: B027 + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + """ + Restore state a new run builds in ``_resolve_seed_groups_by_dataset_async``, for a resume. + + Resume doesn't call seed resolution; it rebuilds from the stored population. A scenario + whose resolution also sets up state its builders need (such as a scorer derived from the + population) overrides this to set it up again, preferably from ``seed_groups_by_dataset`` + or from values the run saved in its metadata. The default does nothing. + + Args: + stored_result (ScenarioResult): The stored scenario result, including its metadata. + seed_groups_by_dataset (dict[str, list[AttackSeedGroup]]): The stored planned population. + """ + async def _raise_if_datasets_deleted_async(self, *, cause: DatasetConstraintError) -> None: """ Explain a resume whose dataset resolution failed because a dataset was deleted. @@ -1850,47 +1846,57 @@ async def _raise_if_datasets_deleted_async(self, *, cause: DatasetConstraintErro missing = [name for name in configured if name.casefold() not in stored] if missing: raise ValueError( - self._resume_error_message( - reason=f"dataset(s) {', '.join(repr(name) for name in missing)} are no longer in memory; " - "they were deleted after the run was planned" - ) + f"Scenario result id '{self._scenario_result_id}' cannot resume: dataset(s) " + f"{', '.join(repr(name) for name in missing)} are no longer in memory; they were deleted after " + "the run was planned. To resume, re-import the dataset content this run used; otherwise drop " + "scenario_result_id to start a new run." ) from cause - def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: + def _require_rebuilt_plan_matches(self, *, stored_plan: ScenarioRunPlan) -> None: """ - Validate and replay the exact logical units captured by a stored plan. + Refuse to resume unless the rebuilt atomic attacks match the stored plan exactly. + + Resume rebuilds from the stored population, so a difference means something other than + the datasets changed, such as the scenario's code, its techniques, or data it still reads. + + Args: + stored_plan (ScenarioRunPlan): The plan stored when the run was created. Raises: - ValueError: If a planned atomic or seed group cannot be reconstructed. - """ - current_by_id = { - self._get_atomic_group_id(atomic_attack=atomic_attack): atomic_attack - for atomic_attack in self._atomic_attacks - } - planned_ids = {group.id for group in stored_plan.atomic_groups} - missing_groups = planned_ids - current_by_id.keys() - if missing_groups: + ValueError: If the rebuilt plan differs, naming the atomic groups that differ. + """ + rebuilt = self._build_run_plan() + if rebuilt != stored_plan: + stored_groups = {group.id: group for group in stored_plan.atomic_groups} + rebuilt_groups = {group.id: group for group in rebuilt.atomic_groups} + differences = [ + f"{label}: {', '.join(sorted(names))}" + for label, names in ( + ( + "missing", + [stored_groups[key].atomic_attack_name for key in stored_groups.keys() - rebuilt_groups], + ), + ( + "added", + [rebuilt_groups[key].atomic_attack_name for key in rebuilt_groups.keys() - stored_groups], + ), + ( + "changed", + [ + group.atomic_attack_name + for key, group in stored_groups.items() + if key in rebuilt_groups and rebuilt_groups[key] != group + ], + ), + ) + if names + ] or ["its seed groups or scenario changed"] raise ValueError( - f"Scenario result id '{self._scenario_result_id}' cannot resume: " - f"{len(missing_groups)} planned atomic group(s) are no longer reconstructable." + f"Scenario result id '{self._scenario_result_id}' cannot resume: the rebuilt run doesn't match " + f"its stored plan ({'; '.join(differences)}). Restore the original scenario configuration, " + "or drop scenario_result_id to start a new run." ) - - retained_attacks: list[AtomicAttack] = [] - for planned_group in stored_plan.atomic_groups: - atomic_attack = current_by_id[planned_group.id] - current_seed_groups = {seed_group.logical_id: seed_group for seed_group in atomic_attack.seed_groups} - missing_seed_groups = set(planned_group.seed_group_ids) - current_seed_groups.keys() - if missing_seed_groups: - raise ValueError( - self._resume_error_message( - reason=f"atomic group '{planned_group.atomic_attack_name}' is missing " - f"{len(missing_seed_groups)} planned seed group(s)" - ) - ) - atomic_attack._seed_groups = [current_seed_groups[group_id] for group_id in planned_group.seed_group_ids] - retained_attacks.append(atomic_attack) - self._atomic_attacks = retained_attacks - self._display_group_map = {group.atomic_attack_name: group.display_group for group in stored_plan.atomic_groups} + self._display_group_map = {attack.atomic_attack_name: attack.display_group for attack in self._atomic_attacks} def _get_identity_params(self) -> dict[str, Any]: """ @@ -2093,9 +2099,9 @@ async def _resolve_seed_groups_by_dataset_async( Args: apply_sampling (bool): When True (default), apply ``max_dataset_size`` sampling. - Resume rebuilds the population from the seed groups stored with the run, so - it calls an overriding implementation only for the state it sets up (such as - scorers built from required datasets), with False, and discards its groups. + Preparation passes False to validate the full assembly. Resume never calls + this; it rebuilds from the stored population, and any state set up here must + also be restored in ``_restore_resume_state_async``. Returns: dict[str, list[AttackSeedGroup]]: Seed groups keyed by dataset name. diff --git a/pyrit/scenario/scenarios/foundry/assert_policy.py b/pyrit/scenario/scenarios/foundry/assert_policy.py index 718919164e..9422fd3c5e 100644 --- a/pyrit/scenario/scenarios/foundry/assert_policy.py +++ b/pyrit/scenario/scenarios/foundry/assert_policy.py @@ -68,7 +68,14 @@ if TYPE_CHECKING: from collections.abc import Sequence - from pyrit.models import ScenarioDatasetSizeEstimate, Scorable, ScorableUnion, Score, ScoringExpectation + from pyrit.models import ( + ScenarioDatasetSizeEstimate, + ScenarioResult, + Scorable, + ScorableUnion, + Score, + ScoringExpectation, + ) from pyrit.prompt_target import PromptTarget from pyrit.scenario.core.scenario_context import ScenarioContext from pyrit.scenario.core.scenario_technique import ScenarioTechnique @@ -618,14 +625,21 @@ def _count_judge_calls(self) -> int: samples: int = self.params["judge_samples"] return len(self._judge_dimensions) * samples + async def _restore_resume_state_async( + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + # Judges and repeated IDs come from the unsampled population, which the stored sample + # doesn't hold, so resume reads the selected datasets again. + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + async def _resolve_seed_groups_by_dataset_async( self, *, apply_sampling: bool = True ) -> dict[str, list[AttackSeedGroup]]: """ Read the selected groups once, build their judges, then sample that same population. - Judges come from the unsampled population because resume reads it unsampled, so the - scenario identity stays the same. + Judges come from the unsampled population, so a run's judges don't depend on its sample. + Resume restores them by reading the selected datasets again (`_restore_resume_state_async`). Returns: dict[str, list[AttackSeedGroup]]: Selected groups keyed by dataset. diff --git a/pyrit/scenario/scenarios/garak/api_key.py b/pyrit/scenario/scenarios/garak/api_key.py index e0c2c3c6ee..62c6ba5865 100644 --- a/pyrit/scenario/scenarios/garak/api_key.py +++ b/pyrit/scenario/scenarios/garak/api_key.py @@ -48,9 +48,14 @@ from collections.abc import Sequence from typing import Literal + from pyrit.models import ScenarioResult from pyrit.scenario.core.scenario_context import ScenarioContext from pyrit.score import TrueFalseScorer +#: Scenario result metadata key for the values the default scorer ignores, so resume doesn't read +#: the partial-key and placeholder datasets again. +_EXCLUDED_VALUES_METADATA_KEY = "api_key_excluded_values" + DATASET_SERVICES = "garak_api_key_services" DATASET_TEMPLATES = "garak_api_key_templates" DATASET_PARTIAL_KEYS = "garak_api_key_partial_keys" @@ -240,6 +245,7 @@ def __init__( scenario_result_id (str | None): Optional existing scenario result to resume. """ self._uses_default_scorer = objective_scorer is None + self._excluded_values: list[str] = [] super().__init__( version=self.VERSION, technique_class=ApiKeyTechnique, @@ -297,15 +303,38 @@ async def _resolve_seed_groups_by_dataset_async( populations = _assemble_requests(corpus=corpus, techniques=config._techniques) groups = config.select_assembled_groups(groups_by_population=populations, apply_sampling=apply_sampling) if self._uses_default_scorer: - excluded_values = [ - seed.value for name in (DATASET_PARTIAL_KEYS, DATASET_SAFE_PLACEHOLDERS) for seed in corpus[name] - ] - self._objective_scorer = CredentialLeakScorer.from_excluded_values( - excluded_values, patterns=CredentialLeakScorer.GARAK_PATTERNS + self._set_default_scorer( + excluded_values=[ + seed.value for name in (DATASET_PARTIAL_KEYS, DATASET_SAFE_PLACEHOLDERS) for seed in corpus[name] + ] ) - self._objective_scorer_identifier = self._objective_scorer.get_identifier() return groups + async def _restore_resume_state_async( + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + if not self._uses_default_scorer: + return + saved = stored_result.metadata.get(_EXCLUDED_VALUES_METADATA_KEY) + if saved is None: + # Runs created before the values were saved read them from the corpus datasets. + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + return + self._set_default_scorer(excluded_values=list(saved)) + + def _build_initial_scenario_metadata(self) -> dict[str, Any]: + metadata = super()._build_initial_scenario_metadata() + if self._uses_default_scorer: + metadata[_EXCLUDED_VALUES_METADATA_KEY] = list(self._excluded_values) + return metadata + + def _set_default_scorer(self, *, excluded_values: list[str]) -> None: + self._excluded_values = excluded_values + self._objective_scorer = CredentialLeakScorer.from_excluded_values( + excluded_values, patterns=CredentialLeakScorer.GARAK_PATTERNS + ) + self._objective_scorer_identifier = self._objective_scorer.get_identifier() + async def _estimate_run_size_async(self, *, budget: BoundedDatasetSize) -> ScenarioRunSizeEstimate: """ Count each synthesized request once rather than crossing techniques again. diff --git a/pyrit/scenario/scenarios/garak/latent_injection.py b/pyrit/scenario/scenarios/garak/latent_injection.py index 2be37cdd88..f094c3fec6 100644 --- a/pyrit/scenario/scenarios/garak/latent_injection.py +++ b/pyrit/scenario/scenarios/garak/latent_injection.py @@ -47,6 +47,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from pyrit.models import ScenarioResult from pyrit.scenario.core.scenario_context import ScenarioContext @@ -436,10 +437,27 @@ async def _resolve_seed_groups_by_dataset_async( groups = config.select_assembled_groups( groups_by_population=config.assemble_groups(ingredients), apply_sampling=apply_sampling ) - scorers = [self._scorer_for_trigger(family=family, trigger=trigger) for family, trigger in config.coverage_keys] + self._set_objective_scorer(coverage_keys=config.coverage_keys) + return groups + + async def _restore_resume_state_async( + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + # Sampling keeps every (family, trigger) pair, so the planned groups carry all of them. + self._set_objective_scorer( + coverage_keys=sorted( + { + LatentInjectionDatasetConfiguration._coverage_key(group) + for groups in seed_groups_by_dataset.values() + for group in groups + } + ) + ) + + def _set_objective_scorer(self, *, coverage_keys: list[tuple[str, str]]) -> None: + scorers = [self._scorer_for_trigger(family=family, trigger=trigger) for family, trigger in coverage_keys] self._objective_scorer = TrueFalseCompositeScorer(aggregator=TrueFalseScoreAggregator.OR, scorers=scorers) self._objective_scorer_identifier = self._objective_scorer.get_identifier() - return groups def _scorer_for_trigger(self, *, family: str, trigger: str) -> TrueFalseScorer: if family == LatentInjectionDatasetConfiguration.HARM_SCORED_FAMILY: diff --git a/pyrit/scenario/scenarios/garak/package_hallucination.py b/pyrit/scenario/scenarios/garak/package_hallucination.py index b4a543ebc7..2f1099908d 100644 --- a/pyrit/scenario/scenarios/garak/package_hallucination.py +++ b/pyrit/scenario/scenarios/garak/package_hallucination.py @@ -35,6 +35,7 @@ ) if TYPE_CHECKING: + from pyrit.models import ScenarioResult from pyrit.scenario.core.scenario_context import ScenarioContext from pyrit.score import TrueFalseScorer @@ -324,6 +325,13 @@ def _build_seed_groups(self, *, spec: _LanguageSpec, prompts: list[str]) -> list for prompt in prompts ] + async def _restore_resume_state_async( + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + # The scorers need the full package registries, which are far too large to save per run, + # so resume reads the corpus datasets again. + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + async def _resolve_seed_groups_by_dataset_async( self, *, apply_sampling: bool = True ) -> dict[str, list[AttackSeedGroup]]: diff --git a/pyrit/scenario/scenarios/garak/prompt_inject.py b/pyrit/scenario/scenarios/garak/prompt_inject.py index 288f969c60..da29669630 100644 --- a/pyrit/scenario/scenarios/garak/prompt_inject.py +++ b/pyrit/scenario/scenarios/garak/prompt_inject.py @@ -49,8 +49,12 @@ if TYPE_CHECKING: from collections.abc import Sequence + from pyrit.models import ScenarioResult from pyrit.scenario.core.scenario_context import ScenarioContext +#: Scenario result metadata key for the technique templates a run selected, so resume doesn't +#: read the technique dataset again. +_TECHNIQUE_TEMPLATES_METADATA_KEY = "prompt_inject_technique_templates" _DEFAULT_GOAL_TEXTS = ( "I hate humans", @@ -318,11 +322,8 @@ async def _resolve_seed_groups_by_dataset_async( Returns: dict[str, list[AttackSeedGroup]]: Sampled context and goal groups. """ - goal_texts = cast("list[str]", self.params["goal_texts"]) config = cast("PromptInjectDatasetConfiguration", self._dataset_config) - if self._use_goal_scorers: - self._objective_scorer = self._build_goal_scorer(goal_texts=goal_texts) - self._objective_scorer_identifier = self._objective_scorer.get_identifier() + self._set_goal_scorer() templates = await cast("ScenarioRequiredData", self._required_data).load_async() groups = config.select_assembled_groups( groups_by_population=config.assemble_groups( @@ -333,6 +334,30 @@ async def _resolve_seed_groups_by_dataset_async( self._technique_templates = self._select_technique_templates(templates[self.TECHNIQUE_DATASET_NAME]) return groups + async def _restore_resume_state_async( + self, *, stored_result: ScenarioResult, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]] + ) -> None: + saved = stored_result.metadata.get(_TECHNIQUE_TEMPLATES_METADATA_KEY) + if saved is None: + # Runs created before templates were saved read them from the technique dataset. + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + return + self._set_goal_scorer() + self._technique_templates = {name: SeedPrompt.model_validate(template) for name, template in saved.items()} + + def _build_initial_scenario_metadata(self) -> dict[str, Any]: + metadata = super()._build_initial_scenario_metadata() + metadata[_TECHNIQUE_TEMPLATES_METADATA_KEY] = { + technique.value: self._technique_templates[technique.value].model_dump(mode="json") + for technique in self._scenario_techniques + } + return metadata + + def _set_goal_scorer(self) -> None: + if self._use_goal_scorers: + self._objective_scorer = self._build_goal_scorer(goal_texts=cast("list[str]", self.params["goal_texts"])) + self._objective_scorer_identifier = self._objective_scorer.get_identifier() + async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: """ Build one prompt-sending attack per sampled technique and goal pair. diff --git a/pyrit/scenario/scenarios/technique/execute.py b/pyrit/scenario/scenarios/technique/execute.py index d4a5dd51ef..a1af29ddc6 100644 --- a/pyrit/scenario/scenarios/technique/execute.py +++ b/pyrit/scenario/scenarios/technique/execute.py @@ -87,7 +87,6 @@ class Execute(Scenario): BASELINE_ATTACK_POLICY: ClassVar[BaselineAttackPolicy] = BaselineAttackPolicy.Disabled USES_DATASET_SIZE_LIMIT: ClassVar[bool] = False MAX_CONCRETE_TECHNIQUES: ClassVar[int | None] = 1 - PREPENDED_CONVERSATION_HASH_KEY: ClassVar[str] = "prepended_conversation_hash" LOCAL_TECHNIQUE_HASH_KEY: ClassVar[str] = "local_technique_configuration_hash" @apply_defaults @@ -95,7 +94,6 @@ def __init__( self, *, objective_scorer: TrueFalseScorer | None = None, scenario_result_id: str | None = None ) -> None: """Initialize the scenario with an optional scorer and resume ID.""" - self._prepended_conversation_hash: str | None = None self._local_technique_hash: str | None = None super().__init__( version=self.VERSION, @@ -234,7 +232,6 @@ async def _resolve_seed_groups_by_dataset_async( return {"objective": [group]} async def _read_history_seeds_async(self) -> list[SeedPrompt]: - self._prepended_conversation_hash = None conversation_id = self.params.get("prepended_conversation_id") if conversation_id is None: return [] @@ -243,26 +240,10 @@ async def _read_history_seeds_async(self) -> list[SeedPrompt]: raise ValueError(f"Prepended conversation '{conversation_id}' is empty or does not exist") if any(message.is_error() for message in messages): raise ValueError(f"Prepended conversation '{conversation_id}' contains blocked or error pieces") - self._prepended_conversation_hash = config_hash( - { - "messages": [ - [ - piece.model_dump( - mode="json", - include={"role", "converted_value", "converted_value_data_type", "prompt_metadata"}, - ) - for piece in message.message_pieces - ] - for message in messages - ] - } - ) return SeedPrompt.from_messages(list(messages)) def _build_initial_scenario_metadata(self) -> dict[str, Any]: metadata = super()._build_initial_scenario_metadata() - if self._prepended_conversation_hash is not None: - metadata[self.PREPENDED_CONVERSATION_HASH_KEY] = self._prepended_conversation_hash if self._local_technique_hash is not None: metadata[self.LOCAL_TECHNIQUE_HASH_KEY] = self._local_technique_hash return metadata @@ -273,11 +254,6 @@ def _validate_stored_scenario( super()._validate_stored_scenario(stored_result=stored_result, current_identifier=current_identifier) if stored_result.metadata.get(self.LOCAL_TECHNIQUE_HASH_KEY) != self._local_technique_hash: raise ValueError("The run-local technique does not match the saved configuration") - if stored_result.metadata.get(self.PREPENDED_CONVERSATION_HASH_KEY) != self._prepended_conversation_hash: - raise ValueError( - f"Prepended conversation '{self.params.get('prepended_conversation_id')}' " - "does not match the saved history. Restore the source history or start a new scenario." - ) async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: local = self.params.get("local_technique_factory") diff --git a/tests/unit/scenario/core/test_atomic_attack.py b/tests/unit/scenario/core/test_atomic_attack.py index 9fe7db8793..c12982b2fc 100644 --- a/tests/unit/scenario/core/test_atomic_attack.py +++ b/tests/unit/scenario/core/test_atomic_attack.py @@ -1010,7 +1010,7 @@ def test_filter_is_stable_across_resampling(self, mock_attack, sample_seed_group @pytest.mark.usefixtures("patch_central_database") -class TestAtomicAttackRestrictSeedGroupsToHashes: +class TestDeprecatedKeepSeedGroupsWithHashes: """Tests for the deprecated ``keep_seed_groups_with_hashes`` keep-set filter.""" def test_keeps_only_listed_hashes(self, mock_attack, sample_seed_groups): diff --git a/tests/unit/scenario/core/test_scenario.py b/tests/unit/scenario/core/test_scenario.py index 1b72bee4b0..fd2870661d 100644 --- a/tests/unit/scenario/core/test_scenario.py +++ b/tests/unit/scenario/core/test_scenario.py @@ -684,8 +684,8 @@ def test_unreconstructable_compatibility_plan_is_rejected(self, *, change: str) ) scenario._atomic_attacks = [current] - with pytest.raises(ValueError, match="cannot resume"): - scenario._apply_persisted_run_plan(stored_plan=stored_plan) + with pytest.raises(ValueError, match="cannot resume: the rebuilt run doesn't match its stored plan"): + scenario._require_rebuilt_plan_matches(stored_plan=stored_plan) @pytest.mark.usefixtures("patch_central_database") @@ -1864,17 +1864,8 @@ def _sample_first_k(population, k): @pytest.mark.usefixtures("patch_central_database") -class TestScenarioResumeDeterministicUnderMaxDatasetSize: - """Phase H regression: resume must reconstruct the persisted objective subset. - - ``max_dataset_size`` applies an unseeded ``random.sample`` on every seed - resolution. Before the fix, resume re-sampled and intersected the persisted - objective hashes against a *fresh* (divergent) draw, so resume aborted with - "persisted objective hash(es) are no longer present in the dataset" whenever - ``max_dataset_size`` was smaller than the dataset. The fix bypasses sampling on - the resume branch: the full deterministic dataset is resolved and the persisted - hashes drive selection, reconstructing exactly the first run's objectives. - """ +class TestScenarioResumeFromStoredPopulation: + """Resume rebuilds the population stored with the run, never resolving or resampling datasets.""" class _StrategyScenario(ConcreteScenarioWithTrueFalseScorer): # Use the base seed resolution, so resume rebuilds only from the stored population. @@ -2015,11 +2006,18 @@ async def test_named_source_preparation_and_resume( lookup.assert_not_awaited() sample.assert_not_called() - async def test_overriding_resolution_still_reads_its_datasets_on_resume(self, mock_objective_target) -> None: + @pytest.mark.parametrize("restore_reads_datasets", [False, True]) + async def test_resume_after_delete_reads_datasets_only_to_restore_state( + self, mock_objective_target, restore_reads_datasets: bool + ) -> None: class _OverridingScenario(self._StrategyScenario): async def _resolve_seed_groups_by_dataset_async(self, *, apply_sampling: bool = True): return await self._dataset_config.get_attack_groups_by_dataset_async(apply_sampling=apply_sampling) + async def _restore_resume_state_async(self, *, stored_result, seed_groups_by_dataset): + if restore_reads_datasets: + await self._resolve_seed_groups_by_dataset_async(apply_sampling=False) + memory = CentralMemory.get_memory_instance() await memory.add_seeds_to_memory_async( seeds=[SeedObjective(value=f"objective-{index}", dataset_name="owned") for index in range(2)], @@ -2032,6 +2030,11 @@ async def _resolve_seed_groups_by_dataset_async(self, *, apply_sampling: bool = await memory.remove_seeds_from_memory_async(dataset_name="owned") resumed = _OverridingScenario(name="Overriding", version=1, scenario_result_id=original._scenario_result_id) resumed.set_params_from_args(args={"objective_target": mock_objective_target, "dataset_config": config}) + if not restore_reads_datasets: + # Resume never runs seed resolution, so an override doesn't need its datasets. + await resumed.initialize_async() + assert resumed._build_run_plan() == original._build_run_plan() + return with pytest.raises(ValueError, match=r"dataset\(s\) 'owned' are no longer in memory") as error: await resumed.initialize_async() assert isinstance(error.value.__cause__, DatasetConstraintError) @@ -2060,7 +2063,7 @@ def _sample_first_k(population, k): "pyrit.scenario.core.dataset_configuration.random.sample", side_effect=_sample_first_k, ): - scenario = self._StrategyScenario(name="Phase H resume", version=1) + scenario = self._StrategyScenario(name="Sampled resume", version=1) scenario.set_params_from_args( args={ "objective_target": mock_objective_target, @@ -2079,8 +2082,7 @@ def _sample_first_k(population, k): persisted_objectives = set(first_strategy.objectives) assert persisted_objectives == {"obj0", "obj1", "obj2"} - # Resume: a *divergent* sample (last 3) would have broken the pre-fix intersection. - # With the fix, resume never samples, so this side_effect must go uncalled. + # Resume rebuilds the stored sample, so a divergent draw (the last 3) must go uncalled. def _sample_last_k(population, k): return list(population)[-k:] @@ -2089,7 +2091,7 @@ def _sample_last_k(population, k): side_effect=_sample_last_k, ) as resume_sample_mock: resumed = self._StrategyScenario( - name="Phase H resume", + name="Sampled resume", version=1, scenario_result_id=original_id, ) @@ -2103,7 +2105,7 @@ def _sample_last_k(population, k): # Must not raise "persisted objective hash(es) are no longer present in the dataset". await resumed.initialize_async() - # Sampling is bypassed on resume — the full dataset is resolved deterministically. + # Resume never samples. assert resume_sample_mock.call_count == 0 assert resumed._scenario_result_id == original_id @@ -2246,7 +2248,7 @@ def _sample_first_k(population, k): "pyrit.scenario.core.dataset_configuration.random.sample", side_effect=_sample_first_k, ) as sample_mock: - scenario = self._StrategyScenario(name="Phase H fresh", version=1) + scenario = self._StrategyScenario(name="Sampled fresh", version=1) scenario.set_params_from_args( args={ "objective_target": mock_objective_target, diff --git a/tests/unit/scenario/garak/test_api_key.py b/tests/unit/scenario/garak/test_api_key.py index f57b1f00fe..952174afb6 100644 --- a/tests/unit/scenario/garak/test_api_key.py +++ b/tests/unit/scenario/garak/test_api_key.py @@ -184,6 +184,24 @@ async def test_resume_replays_sample_after_corpus_order_changes( assert _objectives(resumed) == _objectives(original) + async def test_resume_rebuilds_default_scorer_without_reading_the_corpus( + self, mock_objective_target: PromptTarget, corpus_seeds: dict[str, list[Seed[Any]]] + ) -> None: + original = ApiKey() + await _initialize_async(scenario=original, target=mock_objective_target, corpus_seeds=corpus_seeds) + resumed = ApiKey(scenario_result_id=original._scenario_result_id) + resumed.set_params_from_args(args={"objective_target": mock_objective_target}) + + with patch.object( + _RequiredDatasetConfiguration, + "_collect_named_seeds_async", + side_effect=AssertionError("Resume read the corpus"), + ): + await resumed.initialize_async() + + assert resumed._objective_scorer_identifier == original._objective_scorer_identifier + assert _objectives(resumed) == _objectives(original) + async def test_default_scorer_receives_all_exclusions( self, mock_objective_target: PromptTarget, corpus_seeds: dict[str, list[Seed[Any]]] ) -> None: diff --git a/tests/unit/scenario/garak/test_exploitation.py b/tests/unit/scenario/garak/test_exploitation.py index 4a85a33f1c..7605ac0783 100644 --- a/tests/unit/scenario/garak/test_exploitation.py +++ b/tests/unit/scenario/garak/test_exploitation.py @@ -245,7 +245,7 @@ def changed_converter(*, pattern: str, replace: str) -> SearchReplaceConverter: resumed = Exploitation(scenario_result_id=original._scenario_result_id) with ( patch("pyrit.scenario.scenarios.garak.exploitation.SearchReplaceConverter", side_effect=changed_converter), - pytest.raises(ValueError, match="no longer reconstructable"), + pytest.raises(ValueError, match="rebuilt run doesn't match its stored plan"), ): await _initialize_async(scenario=resumed, corpus=corpus_seeds, target=target) diff --git a/tests/unit/scenario/garak/test_latent_injection.py b/tests/unit/scenario/garak/test_latent_injection.py index 70de6dd72e..126f295cf6 100644 --- a/tests/unit/scenario/garak/test_latent_injection.py +++ b/tests/unit/scenario/garak/test_latent_injection.py @@ -550,3 +550,21 @@ async def test_changed_case_resumes_the_planned_cases_async(self, seeded_memory_ with _read_ingredients(sources): await _initialize_async(resumed, **args) assert [[group.logical_id for group in attack.seed_groups] for attack in resumed._atomic_attacks] == planned + + async def test_resume_rebuilds_scorer_after_ingredients_are_deleted_async( + self, seeded_memory_async: MemoryInterface + ) -> None: + original = LatentInjection() + args = { + "dataset_config": _config(families=["whois", "resume"], max_dataset_size=4), + "scenario_techniques": [LatentInjectionTechnique.Bare], + } + await _initialize_async(original, **args) + for name in LatentInjection.required_datasets(): + await seeded_memory_async.remove_seeds_from_memory_async(dataset_name=name) + + resumed = LatentInjection(scenario_result_id=original._scenario_result_id) + await _initialize_async(resumed, **args) + + assert resumed._objective_scorer_identifier == original._objective_scorer_identifier + assert resumed._build_run_plan() == original._build_run_plan() diff --git a/tests/unit/scenario/garak/test_prompt_inject.py b/tests/unit/scenario/garak/test_prompt_inject.py index 0fee0d1ad6..07eedd8081 100644 --- a/tests/unit/scenario/garak/test_prompt_inject.py +++ b/tests/unit/scenario/garak/test_prompt_inject.py @@ -13,7 +13,7 @@ from pyrit.analytics import compute_technique_stats_async from pyrit.converter import Converter, SearchReplaceConverter -from pyrit.memory import SQLiteMemory +from pyrit.memory import CentralMemory, SQLiteMemory from pyrit.models import AttackSeedGroup, ComponentIdentifier, Message, MessagePiece, SeedObjective, SeedPrompt from pyrit.prompt_target import PromptTarget from pyrit.registry import ScenarioRegistry @@ -347,6 +347,24 @@ async def test_resume_replays_persisted_dataset_sample(self, mock_objective_targ assert _objective_values(resumed) == initial_objectives assert sum(len(attack.seed_groups) for attack in resumed._atomic_attacks) == 60 + async def test_resume_uses_saved_templates_after_datasets_are_deleted( + self, mock_objective_target: PromptTarget + ) -> None: + initial = PromptInject() + await _initialize_async(initial, target=mock_objective_target) + memory = CentralMemory.get_memory_instance() + for name in PromptInject.required_datasets(): + await memory.remove_seeds_from_memory_async(dataset_name=name) + + resumed = PromptInject(scenario_result_id=initial._scenario_result_id) + await _initialize_async(resumed, target=mock_objective_target) + + assert resumed._technique_templates == { + technique.value: initial._technique_templates[technique.value] for technique in initial._scenario_techniques + } + assert resumed._objective_scorer_identifier == initial._objective_scorer_identifier + assert resumed._build_run_plan() == initial._build_run_plan() + async def test_custom_scorer_replaces_goal_scorer( self, mock_objective_target: PromptTarget, mock_objective_scorer: TrueFalseScorer ) -> None: diff --git a/tests/unit/scenario/scenarios/technique/test_execute.py b/tests/unit/scenario/scenarios/technique/test_execute.py index 0442302723..a659fbcfe3 100644 --- a/tests/unit/scenario/scenarios/technique/test_execute.py +++ b/tests/unit/scenario/scenarios/technique/test_execute.py @@ -985,10 +985,7 @@ async def test_gui_resume_restores_only_declared_parameters_async(self, *, score scenario_result_ids=[prepared.scenario._scenario_result_id], ) )[0] - assert Execute.PREPENDED_CONVERSATION_HASH_KEY in stored.metadata - assert Execute.PREPENDED_CONVERSATION_HASH_KEY not in stored.scenario_identifier.params restored = service._restore_launch_request(stored=stored) - assert Execute.PREPENDED_CONVERSATION_HASH_KEY not in restored.scenario_params resumed = await service._prepare_run_async(request=restored) assert resumed.scenario._scenario_result_id == prepared.scenario._scenario_result_id await memory.add_message_to_memory_async( @@ -998,10 +995,9 @@ async def test_gui_resume_restores_only_declared_parameters_async(self, *, score conversation_id=history_id, ).to_message() ) - with pytest.raises( - ValueError, match="does not match the saved history|cannot resume: missing 1 planned seed group" - ): - await service._prepare_run_async(request=restored) + # Resume rebuilds from the planned seeds, so a changed source conversation doesn't matter. + again = await service._prepare_run_async(request=restored) + assert again.scenario._scenario_result_id == prepared.scenario._scenario_result_id finally: await service.close_async() @@ -1164,7 +1160,9 @@ async def test_resume_same_inputs_and_reject_changed_objective_async( await changed.initialize_async() @pytest.mark.parametrize("change", ["append", "metadata"]) - async def test_resume_rejects_changed_source_async(self, *, scorer: MagicMock, change: str) -> None: + async def test_resume_keeps_planned_history_after_source_changes_async( + self, *, scorer: MagicMock, change: str + ) -> None: memory = CentralMemory.get_memory_instance() history_id = await _save_history_async(memory=memory, roles=["user", "assistant"]) target = MockPromptTarget() @@ -1184,8 +1182,8 @@ async def test_resume_rejects_changed_source_async(self, *, scorer: MagicMock, c await memory.update_prompt_metadata_by_conversation_id_async( conversation_id=history_id, prompt_metadata={"custom": "new metadata"} ) - with pytest.raises(ValueError, match="does not match"): - await resumed.initialize_async() + await resumed.initialize_async() + assert resumed._atomic_attacks[0].seed_groups == original._atomic_attacks[0].seed_groups def test_alias_and_dynamic_cache_reset(self) -> None: package = importlib.import_module("pyrit.scenario.technique")