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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions .github/instructions/scenarios.instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 3 additions & 3 deletions doc/scanner/technique.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -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)."
]
Expand Down
6 changes: 3 additions & 3 deletions doc/scanner/technique.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
12 changes: 5 additions & 7 deletions pyrit/scenario/core/dataset_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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``
Expand All @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down
30 changes: 14 additions & 16 deletions pyrit/scenario/core/scenario.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -2458,20 +2458,20 @@ 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.
"""

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
Expand All @@ -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}
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 0 additions & 2 deletions pyrit/scenario/scenarios/garak/exploitation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
36 changes: 7 additions & 29 deletions pyrit/scenario/scenarios/garak/latent_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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]
Expand Down
3 changes: 1 addition & 2 deletions pyrit/scenario/scenarios/garak/system_prompt_extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
3 changes: 1 addition & 2 deletions pyrit/scenario/scenarios/garak/web_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
33 changes: 0 additions & 33 deletions pyrit/scenario/scenarios/technique/execute.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,13 @@ 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
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,
Expand Down Expand Up @@ -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]]:
Expand All @@ -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 []
Expand All @@ -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
Expand All @@ -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")
Expand Down
Loading
Loading