diff --git a/.github/instructions/scenarios.instructions.md b/.github/instructions/scenarios.instructions.md index 9612ab4477..79bd35cd4b 100644 --- a/.github/instructions/scenarios.instructions.md +++ b/.github/instructions/scenarios.instructions.md @@ -217,11 +217,12 @@ Options: - Resume replays the saved launch request with the seed groups stored when the run was planned; later changes to the population do not change the stored seed content. Referenced media files must still be available. Dataset names are checked by the stored identity. -- Resume never prepares or resamples datasets and doesn't call the seed resolver. If your resolver - sets state the atomic attacks need, override `_prepare_resume_state_async(seed_groups_by_dataset=...)` - to restore it. Derive that state from the stored groups when they carry it (see `LatentInjection`). - Otherwise read only the datasets it needs, never the population the stored groups already hold - (see `PromptInject`, which reads its technique templates with `load_async(names=...)`). +- Resume never prepares or resamples datasets and doesn't call the seed resolver. Compute state + that depends on the planned groups, such as a scorer, in `_build_atomic_attacks_async` from + `context.seed_groups`, which runs on new and resumed runs (see `LatentInjection`). Override + `_prepare_resume_state_async(seed_groups_by_dataset=...)` only for state that needs a dataset the + stored groups don't carry, and read only that dataset, never the population the stored groups + already hold (see `PromptInject`, which reads its technique templates with `load_async(names=...)`). - 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/doc/scanner/technique.ipynb b/doc/scanner/technique.ipynb index 22444a2a1e..fe8069a0ed 100644 --- a/doc/scanner/technique.ipynb +++ b/doc/scanner/technique.ipynb @@ -328,9 +328,9 @@ "attempt. Three objective attempts produce two retries, while the planned unit count stays one.\n", "\n", "To resume, pass the saved scenario result ID to `Execute(scenario_result_id=...)` and\n", - "supply the same inputs. A changed objective, source history, or technique configuration\n", - "prevents resume.\n", - "The source-history fingerprint is stored in run metadata, not in launch parameters.\n", + "supply the same inputs. A changed objective or technique configuration prevents resume.\n", + "Resume replays the history stored when the run was planned, so later edits to the source\n", + "conversation, or its deletion, do not change the resumed run.\n", "\n", "For more details, see [Common Scenario Parameters](../code/scenarios/1_common_scenario_parameters.ipynb)." ] diff --git a/doc/scanner/technique.py b/doc/scanner/technique.py index cd8fff1266..90d64e76c6 100644 --- a/doc/scanner/technique.py +++ b/doc/scanner/technique.py @@ -190,8 +190,8 @@ def _validate_request(self, *, normalized_conversation: list[Message]) -> None: # attempt. Three objective attempts produce two retries, while the planned unit count stays one. # # To resume, pass the saved scenario result ID to `Execute(scenario_result_id=...)` and -# supply the same inputs. A changed objective, source history, or technique configuration -# prevents resume. -# The source-history fingerprint is stored in run metadata, not in launch parameters. +# supply the same inputs. A changed objective or technique configuration prevents resume. +# Resume replays the history stored when the run was planned, so later edits to the source +# conversation, or its deletion, do not change the resumed run. # # For more details, see [Common Scenario Parameters](../code/scenarios/1_common_scenario_parameters.ipynb). diff --git a/pyrit/scenario/core/dataset_configuration.py b/pyrit/scenario/core/dataset_configuration.py index c747dcf7fb..32c4f68147 100644 --- a/pyrit/scenario/core/dataset_configuration.py +++ b/pyrit/scenario/core/dataset_configuration.py @@ -1326,8 +1326,7 @@ async def get_attack_seed_groups_async(self, *, apply_sampling: bool = True) -> Args: apply_sampling (bool): When True (default), apply source and total sampling. Pass False to resolve the full, deterministic dataset with no ``random.sample`` - draw -- used on resume so the persisted objective subset can be reconstructed - exactly rather than intersected against a fresh (divergent) sample. + draw, as dataset preparation and compatibility checks do. Returns: list[AttackSeedGroup]: The validated attack groups (sampled when ``apply_sampling`` @@ -1354,8 +1353,7 @@ async def get_attack_groups_by_dataset_async( Args: apply_sampling (bool): When True (default), apply source and total sampling. Pass False to resolve the full, deterministic dataset with no ``random.sample`` - draw -- used on resume so the persisted objective subset can be reconstructed - exactly rather than intersected against a fresh (divergent) sample. + draw, as dataset preparation and compatibility checks do. Returns: dict[str, list[AttackSeedGroup]]: Dataset name -> attack groups (sampled when @@ -1379,7 +1377,7 @@ def select_assembled_groups( Args: groups_by_population (dict[str, list[AttackSeedGroup]]): Assembled groups keyed by population. - apply_sampling (bool): When True (default), apply ``max_total``. Resume passes False. + apply_sampling (bool): When True (default), apply ``max_total``. Returns: dict[str, list[AttackSeedGroup]]: The validated, limited groups. @@ -1706,7 +1704,7 @@ async def get_attack_seed_groups_async(self, *, apply_sampling: bool = True) -> Args: apply_sampling (bool): When True (default), sample both each child and the combined result under ``max_dataset_size``. Pass False to resolve the full, deterministic - dataset with no sampling at any level -- used on resume (propagated to children). + dataset with no sampling at any level (propagated to children). Returns: list[AttackSeedGroup]: The combined, validated attack groups (capped when @@ -1727,7 +1725,7 @@ async def get_attack_groups_by_dataset_async( Args: apply_sampling (bool): When True (default), sample both each child and the merged union under ``max_dataset_size``. Pass False to resolve the full, deterministic - dataset with no sampling at any level -- used on resume (propagated to children). + dataset with no sampling at any level (propagated to children). Returns: dict[str, list[AttackSeedGroup]]: Combined groups keyed by dataset name. diff --git a/pyrit/scenario/core/scenario.py b/pyrit/scenario/core/scenario.py index 7d3b22be52..db285d70b5 100644 --- a/pyrit/scenario/core/scenario.py +++ b/pyrit/scenario/core/scenario.py @@ -2374,7 +2374,7 @@ def _get_stored_run_plan(*, stored_result: ScenarioResult) -> ScenarioRunPlan | def _resume_error_message(self, *, reason: str) -> str: """ - Build the error for a resume refused because its planned seeds can't be found. + Build the error for a resume refused because a dataset its scenario reads is gone or changed. Args: reason (str): What is missing, without a trailing period. @@ -2458,9 +2458,9 @@ async def _prepare_resume_state_async( # noqa: B027 Restore state that a new run's seed resolver sets up. The default does nothing. Resume doesn't call ``_resolve_seed_groups_by_dataset_async``. Override this hook only when - that resolver sets state the atomic attacks need, such as a scorer built from the data. - Derive that state from the stored groups when they carry it, because live datasets may have - changed since the run was planned. + that resolver sets state the atomic attacks need from a dataset the stored groups don't carry, + such as a scorer built from a helper dataset. Compute state the stored groups do carry in + ``_build_atomic_attacks_async`` from ``context.seed_groups``, which runs on new and resumed runs. Args: seed_groups_by_dataset (dict[str, list[AttackSeedGroup]]): The stored planned population. @@ -2468,10 +2468,10 @@ async def _prepare_resume_state_async( # noqa: B027 def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: """ - Validate and replay the exact logical units captured by a stored plan. + Keep the planned atomic groups in plan order, each with exactly the seed groups it planned. Raises: - ValueError: If a planned atomic or seed group cannot be reconstructed. + ValueError: If a planned atomic group is missing or rebuilds different seed groups. """ current_by_id = { self._get_atomic_group_id(atomic_attack=atomic_attack): atomic_attack @@ -2488,16 +2488,14 @@ def _apply_persisted_run_plan(self, *, stored_plan: ScenarioRunPlan) -> None: 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: + # The population is the stored planned groups, so a difference here means the scenario or a + # technique now builds this group differently. Re-importing data can't fix that. + if {seed_group.logical_id for seed_group in atomic_attack.seed_groups} != set(planned_group.seed_group_ids): 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)" - ) + f"Scenario result id '{self._scenario_result_id}' cannot resume: atomic group " + f"'{planned_group.atomic_attack_name}' no longer builds the seed groups it planned. " + "Drop scenario_result_id to start a new run." ) - 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} @@ -2759,8 +2757,8 @@ 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 and - doesn't call this. An override that sets state the atomic attacks need must also - restore that state in ``_prepare_resume_state_async``. + doesn't call this. An override that reads a dataset to set state the atomic attacks + need must also restore that state in ``_prepare_resume_state_async``. Returns: dict[str, list[AttackSeedGroup]]: Seed groups keyed by dataset name. diff --git a/pyrit/scenario/scenarios/garak/exploitation.py b/pyrit/scenario/scenarios/garak/exploitation.py index 0ca39cff8f..ef9dbfecd3 100644 --- a/pyrit/scenario/scenarios/garak/exploitation.py +++ b/pyrit/scenario/scenarios/garak/exploitation.py @@ -273,8 +273,6 @@ async def _resolve_seed_groups_by_dataset_async( Args: apply_sampling (bool): When true, apply the deterministic total prompt cap. - Resume passes false so the base can replay its persisted run plan against - the complete population. Returns: dict[str, list[AttackSeedGroup]]: Raw payload groups keyed by technique. diff --git a/pyrit/scenario/scenarios/garak/latent_injection.py b/pyrit/scenario/scenarios/garak/latent_injection.py index abddc42475..2b09ddf16a 100644 --- a/pyrit/scenario/scenarios/garak/latent_injection.py +++ b/pyrit/scenario/scenarios/garak/latent_injection.py @@ -433,37 +433,9 @@ async def _resolve_seed_groups_by_dataset_async( ) -> dict[str, list[AttackSeedGroup]]: config = cast("LatentInjectionDatasetConfiguration", self._dataset_config) ingredients = await cast("ScenarioRequiredData", self._required_data).load_async() - groups = config.select_assembled_groups( + return config.select_assembled_groups( groups_by_population=config.assemble_groups(ingredients), apply_sampling=apply_sampling ) - self._set_objective_scorer(coverage_keys=config.coverage_keys) - return groups - - async def _prepare_resume_state_async(self, *, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]]) -> None: - """ - Rebuild the trigger scorer from the stored groups, so later trigger edits don't change it. - - Coverage sampling keeps every family/trigger pair, so the stored groups hold the same pairs - the run was planned with. - - Args: - seed_groups_by_dataset (dict[str, list[AttackSeedGroup]]): The stored planned population. - """ - 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: - """Score a response as a success when any planned family/trigger pair succeeds.""" - 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() def _scorer_for_trigger(self, *, family: str, trigger: str) -> TrueFalseScorer: if family == LatentInjectionDatasetConfiguration.HARM_SCORED_FAMILY: @@ -476,6 +448,12 @@ async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list by_pair: dict[tuple[str, str], list[AttackSeedGroup]] = {} for group in context.seed_groups: by_pair.setdefault(LatentInjectionDatasetConfiguration._coverage_key(group), []).append(group) + # The run scores a success when any planned family/trigger pair succeeds. Coverage sampling keeps + # every pair, and resume builds from the stored groups, so later trigger edits don't change it. + self._objective_scorer = TrueFalseCompositeScorer( + aggregator=TrueFalseScoreAggregator.OR, + scorers=[self._scorer_for_trigger(family=family, trigger=trigger) for family, trigger in sorted(by_pair)], + ) attacks: list[AtomicAttack] = [] for technique in context.scenario_techniques: prefix, suffix = self.SEPARATORS[technique.value] diff --git a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py index 9dd4fbea1a..356f6f9143 100644 --- a/pyrit/scenario/scenarios/garak/system_prompt_extraction.py +++ b/pyrit/scenario/scenarios/garak/system_prompt_extraction.py @@ -244,8 +244,7 @@ async def _resolve_seed_groups_by_dataset_async( shared across the atomic attacks. Args: - apply_sampling (bool): Apply the objective limit on fresh runs. Resume resolves - the full population so the stored run plan can restore its selected objectives. + apply_sampling (bool): When true, apply the objective limit. Returns: dict[str, list[AttackSeedGroup]]: Seed groups keyed by technique category value. diff --git a/pyrit/scenario/scenarios/garak/web_injection.py b/pyrit/scenario/scenarios/garak/web_injection.py index 89c6beb7f0..56e9774b8b 100644 --- a/pyrit/scenario/scenarios/garak/web_injection.py +++ b/pyrit/scenario/scenarios/garak/web_injection.py @@ -670,8 +670,7 @@ async def _resolve_seed_groups_by_dataset_async( seed sample used for both the atomic attacks and the baseline. Args: - apply_sampling (bool): Apply finite-source selection caps. False retains the - source groups needed to restore a persisted plan. Random generators always + apply_sampling (bool): Apply finite-source selection caps. Random generators always require a finite generation count. Returns: diff --git a/pyrit/scenario/scenarios/technique/execute.py b/pyrit/scenario/scenarios/technique/execute.py index f48a615f72..c1fe6ce584 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, @@ -211,15 +209,6 @@ async def _estimate_run_size_async(self, *, budget: BoundedDatasetSize) -> Scena note=f"One objective. Up to {attempts} technique attempt(s) run inside one unit; baseline is not retried.", ) - async def _prepare_resume_state_async(self, *, seed_groups_by_dataset: dict[str, list[AttackSeedGroup]]) -> None: - """ - Re-read the prepended conversation, so resume refuses a conversation that changed. - - Args: - seed_groups_by_dataset (dict[str, list[AttackSeedGroup]]): The stored planned population. - """ - 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]]: @@ -243,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 [] @@ -252,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 @@ -282,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/benchmark/test_adversarial_benchmark_cache_reuse.py b/tests/unit/scenario/benchmark/test_adversarial_benchmark_cache_reuse.py index 1067003a9a..da23cd187b 100644 --- a/tests/unit/scenario/benchmark/test_adversarial_benchmark_cache_reuse.py +++ b/tests/unit/scenario/benchmark/test_adversarial_benchmark_cache_reuse.py @@ -71,19 +71,33 @@ def _register_adversarial(*, temperature: float, max_requests_per_minute: int | instances.register(adversarial, name=ADVERSARIAL_NAME) -async def _run_benchmark(*, objective_target: OpenAIChatTarget, use_cached: bool, pending: bool = False) -> list: - scenario = AdversarialBenchmark(objective_scorer=SubStringScorer(substring=MARKER), use_cached=use_cached) +def _benchmark( + *, + objective_target: OpenAIChatTarget, + use_cached: bool, + objectives: tuple[str, ...] = ("placeholder objective",), + scenario_result_id: str | None = None, +) -> AdversarialBenchmark: + scenario = AdversarialBenchmark( + objective_scorer=SubStringScorer(substring=MARKER), use_cached=use_cached, scenario_result_id=scenario_result_id + ) scenario.set_params_from_args( args={ "objective_target": objective_target, "adversarial_targets": [ADVERSARIAL_NAME], "scenario_techniques": [_build_benchmark_technique()("crescendo_simulated")], "dataset_config": DatasetAttackConfiguration( - seed_groups=[AttackSeedGroup(seeds=[SeedObjective(value="placeholder objective")])], max_total=1 + seed_groups=[AttackSeedGroup(seeds=[SeedObjective(value=value)]) for value in objectives], + max_total=len(objectives), ), "use_cached": use_cached, } ) + return scenario + + +async def _run_benchmark(*, objective_target: OpenAIChatTarget, use_cached: bool, pending: bool = False) -> list: + scenario = _benchmark(objective_target=objective_target, use_cached=use_cached) if pending: await scenario.create_pending_run_async() await scenario.initialize_async() @@ -126,6 +140,44 @@ async def test_cache_reuses_results_for_an_identical_adversarial_configuration(p assert adversarial_calls == 0 +@pytest.mark.usefixtures("patch_central_database") +async def test_partially_cached_run_resumes_its_uncached_objective(): + """The plan lists the cached objective last, while resume rebuilds population order; resume still matches.""" + objective_target = _OfflineChatTarget(model_name="objective-model", **_ENDPOINT) + _register_adversarial(temperature=1.2) + first = await _run_benchmark(objective_target=objective_target, use_cached=False) + objectives = ("placeholder objective", "fresh objective") + planned = _benchmark(objective_target=objective_target, use_cached=True, objectives=objectives) + await planned.initialize_async() + # Copy the cached result into the run, then stop before the uncached objective runs. + await planned._prepare_run_async() + [planned_attack] = planned._atomic_attacks + assert [group.objective.value for group in planned._get_planned_seed_groups(atomic_attack=planned_attack)] == [ + "fresh objective", + "placeholder objective", + ] + + resumed = _benchmark( + objective_target=objective_target, + use_cached=True, + objectives=objectives, + scenario_result_id=planned._scenario_result_id, + ) + await resumed.initialize_async() + [resumed_attack] = resumed._atomic_attacks + assert [group.objective.value for group in resumed_attack.seed_groups] == list(objectives) + _OfflineChatTarget.adversarial_calls = 0 + result = await resumed.run_async() + + copied_from = { + attack_result.objective: attack_result.metadata.get("cached_from_attack_result_id") + for results in result.attack_results.values() + for attack_result in results + } + assert copied_from == {"placeholder objective": first[0].attack_result_id, "fresh objective": None} + assert _OfflineChatTarget.adversarial_calls > 0 + + @pytest.mark.usefixtures("patch_central_database") async def test_cache_reuses_results_after_an_operational_only_adversarial_change(): first, second, adversarial_calls = await _cached_rerun(second_temperature=1.2, second_max_requests_per_minute=10) diff --git a/tests/unit/scenario/core/test_scenario.py b/tests/unit/scenario/core/test_scenario.py index 8d6703de6f..3f516883ff 100644 --- a/tests/unit/scenario/core/test_scenario.py +++ b/tests/unit/scenario/core/test_scenario.py @@ -2277,6 +2277,45 @@ async def test_resume_refuses_run_without_stored_planned_seeds(self, mock_object with pytest.raises(ValueError, match="created by an older PyRIT version"): await resumed.initialize_async() + @pytest.mark.parametrize("change", ["missing", "unplanned"]) + async def test_resume_refuses_an_atomic_group_that_builds_other_seed_groups( + self, mock_objective_target, change: str + ) -> None: + def make(scenario_result_id: str | None = None): + scenario = self._StrategyScenario(name="Rebuilt groups", version=1, scenario_result_id=scenario_result_id) + scenario.set_params_from_args( + args={ + "objective_target": mock_objective_target, + "scenario_strategies": None, + "dataset_config": self._make_config(), + } + ) + return scenario + + original = make() + await original.initialize_async() + resumed = make(scenario_result_id=original._scenario_result_id) + build = resumed._build_atomic_attacks_async + + async def build_other_groups(*, context: ScenarioContext) -> list[AtomicAttack]: + *baseline, strategy = await build(context=context) + planned = list(strategy.seed_groups) + unplanned = AttackSeedGroup(seeds=[SeedObjective(value="unplanned objective")]) + groups = planned[1:] if change == "missing" else [*planned, unplanned] + rebuilt = AtomicAttack( + atomic_attack_name=strategy.atomic_attack_name, + attack_technique=strategy.attack_technique, + seed_groups=groups, + ) + return [*baseline, rebuilt] + + with ( + patch.object(resumed, "_build_atomic_attacks_async", side_effect=build_other_groups), + pytest.raises(ValueError, match="'strategy' no longer builds the seed groups it planned") as error, + ): + await resumed.initialize_async() + assert "re-import" not in str(error.value) + async def test_resume_discards_per_objective_attacks_outside_persisted_subset(self, mock_objective_target): def _sample_first_k(population, k): return list(population)[:k] diff --git a/tests/unit/scenario/scenarios/technique/test_execute.py b/tests/unit/scenario/scenarios/technique/test_execute.py index 95290d8de0..b417cc7f87 100644 --- a/tests/unit/scenario/scenarios/technique/test_execute.py +++ b/tests/unit/scenario/scenarios/technique/test_execute.py @@ -1033,23 +1033,11 @@ 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 + assert "prepended_conversation_hash" not in stored.metadata restored = service._restore_launch_request(stored=stored) - assert Execute.PREPENDED_CONVERSATION_HASH_KEY not in restored.scenario_params + assert set(restored.scenario_params) <= {parameter.name for parameter in Execute.supported_parameters()} 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( - request=MessagePiece( - role="user", - original_value="new turn", - 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) finally: await service.close_async() @@ -1211,29 +1199,39 @@ async def test_resume_same_inputs_and_reject_changed_objective_async( with pytest.raises(ValueError, match="does not match the current .Execute. configuration"): await changed.initialize_async() - @pytest.mark.parametrize("change", ["append", "metadata"]) - async def test_resume_rejects_changed_source_async(self, *, scorer: MagicMock, change: str) -> None: + @pytest.mark.parametrize("change", ["append", "metadata", "delete"]) + async def test_resume_uses_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() original = _scenario(scorer=scorer, target=target, prepended_conversation_id=history_id) await original.initialize_async() - resumed = _scenario( - scorer=scorer, target=target, prepended_conversation_id=history_id, resume_id=original._scenario_result_id - ) - await resumed.initialize_async() + planned = original._atomic_attacks[0].seed_groups[0] if change == "append": await memory.add_message_to_memory_async( request=MessagePiece(role="user", original_value="new turn", conversation_id=history_id).to_message() ) - else: - messages = await memory.get_conversation_messages_async(conversation_id=history_id) - messages[0].get_piece().prompt_metadata["custom"] = "new metadata" + elif change == "metadata": 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() + else: + await memory.delete_conversation_pieces_after_sequence_async(conversation_id=history_id, sequence=-1) + assert not await memory.get_conversation_messages_async(conversation_id=history_id) + # Runs planned before the hash was removed still carry the key; resume ignores it. + await memory.update_scenario_metadata_fields_async( + scenario_result_id=original._scenario_result_id, fields={"prepended_conversation_hash": "stale"} + ) + resumed = _scenario( + scorer=scorer, target=target, prepended_conversation_id=history_id, resume_id=original._scenario_result_id + ) + await resumed.initialize_async() + group = resumed._atomic_attacks[0].seed_groups[0] + assert group.logical_id == planned.logical_id + assert [seed.value for seed in group.seeds] == [seed.value for seed in planned.seeds] + assert len(group.prepended_conversation) == 2 def test_alias_and_dynamic_cache_reset(self) -> None: package = importlib.import_module("pyrit.scenario.technique")