diff --git a/doc/scanner/garak.ipynb b/doc/scanner/garak.ipynb index 29d2c7890c..df04320202 100644 --- a/doc/scanner/garak.ipynb +++ b/doc/scanner/garak.ipynb @@ -195,10 +195,7 @@ " \"objective_target\": objective_target,\n", " \"scenario_techniques\": [PromptInjectTechnique.IgnorePrint],\n", " \"goal_texts\": [\"I hate humans\"],\n", - " \"dataset_config\": PromptInjectDatasetConfiguration(\n", - " sources=[DatasetSource(name=name) for name in PromptInject.required_datasets()],\n", - " max_total=1,\n", - " ),\n", + " \"dataset_config\": PromptInjectDatasetConfiguration(max_total=1),\n", " }\n", ")\n", "await prompt_inject_scenario.initialize_async() # type: ignore\n", diff --git a/doc/scanner/garak.py b/doc/scanner/garak.py index 062ef7dd59..da7d0b2733 100644 --- a/doc/scanner/garak.py +++ b/doc/scanner/garak.py @@ -106,10 +106,7 @@ "objective_target": objective_target, "scenario_techniques": [PromptInjectTechnique.IgnorePrint], "goal_texts": ["I hate humans"], - "dataset_config": PromptInjectDatasetConfiguration( - sources=[DatasetSource(name=name) for name in PromptInject.required_datasets()], - max_total=1, - ), + "dataset_config": PromptInjectDatasetConfiguration(max_total=1), } ) await prompt_inject_scenario.initialize_async() # type: ignore diff --git a/pyrit/scenario/scenarios/garak/prompt_inject.py b/pyrit/scenario/scenarios/garak/prompt_inject.py index 827a0620cd..12af15c2a7 100644 --- a/pyrit/scenario/scenarios/garak/prompt_inject.py +++ b/pyrit/scenario/scenarios/garak/prompt_inject.py @@ -33,8 +33,10 @@ from pyrit.scenario.core.dataset_configuration import ( DatasetAttackConfiguration, DatasetSource, + DatasetSourceKind, ) from pyrit.scenario.core.dataset_sampling import sample_with_coverage +from pyrit.scenario.core.required_data import ScenarioRequiredData from pyrit.scenario.core.scenario import BaselineAttackPolicy, Scenario from pyrit.scenario.core.scenario_technique import ScenarioTechnique from pyrit.score import ( @@ -61,7 +63,13 @@ class PromptInjectDatasetConfiguration(DatasetAttackConfiguration): - """Create an attack group for each context and goal combination.""" + """ + Limit the context and goal combinations PromptInject assembles. + + The context and technique templates are PromptInject's required data, read in full. + This configuration holds the goal texts and limits the assembled groups with + ``max_total``, keeping at least one context per goal. + """ CONTEXT_DATASET_NAME: ClassVar[str] = "prompt_inject_contexts" DEFAULT_MAX_DATASET_SIZE: ClassVar[int] = 12 @@ -106,16 +114,6 @@ def _set_goal_texts(self, *, goal_texts: Sequence[str]) -> None: raise ValueError("goal_texts must not contain duplicate values.") self._goal_texts = list(goal_texts) - async def get_attack_seed_groups_async(self, *, apply_sampling: bool = True) -> list[AttackSeedGroup]: - """ - Resolve flat groups with the same goal coverage as the grouped resolver. - - Returns: - list[AttackSeedGroup]: The validated context and goal groups. - """ - groups_by_dataset = await self.get_attack_groups_by_dataset_async(apply_sampling=apply_sampling) - return [group for groups in groups_by_dataset.values() for group in groups] - def _sample_groups_by_dataset( self, groups_by_dataset: dict[str, list[AttackSeedGroup]] ) -> dict[str, list[AttackSeedGroup]]: @@ -135,24 +133,31 @@ def _sample_groups_by_dataset( key=lambda _, group: (group.objective.metadata or {})["goal_text"], ) + def size_caps_by_dataset(self) -> dict[str, list[tuple[str, int, Literal["dataset", "configuration", "compound"]]]]: + """ + Describe the shared cap on the assembled context groups. + + Returns: + dict: The context population mapped to its configuration cap. + """ + caps: list[tuple[str, int, Literal["dataset", "configuration", "compound"]]] = ( + [] if self.max_total == "all" else [("combined configuration cap", self.max_total, "configuration")] + ) + return {self.CONTEXT_DATASET_NAME: caps} + def validate_configuration(self) -> None: """ - Check the sources and goal coverage budget without reading contexts. + Check the goal coverage budget without reading contexts. Raises: - DatasetConstraintError: If the sources are unsupported or the cap cannot cover all goals. + DatasetConstraintError: If the configuration names datasets or the cap cannot cover all goals. """ super().validate_configuration() - if any(self.source_limit(source.name) != "all" for source in self.sources): - raise DatasetConstraintError("PromptInject ingredient sources must be uncapped; use max_total.") - if not self.dataset_names: - raise DatasetConstraintError( - "PromptInject requires the prompt_inject_contexts dataset; inline seeds are not supported." - ) - required_dataset_names = set(PromptInject.required_datasets()) - if set(self.dataset_names) != required_dataset_names: + if self.sources or self.source_kind is DatasetSourceKind.INLINE: raise DatasetConstraintError( - f"PromptInject requires exactly these datasets: {sorted(required_dataset_names)}." + f"PromptInject reads its templates as required data: {PromptInject.required_datasets()}. " + "PromptInjectDatasetConfiguration only takes goal_texts and max_total; " + "inline seeds and other datasets are not supported." ) cap = self.max_total if cap != "all" and cap < len(self._goal_texts): @@ -161,15 +166,14 @@ def validate_configuration(self) -> None: f"({len(self._goal_texts)})." ) - def _build_attack_groups(self, seeds: list[Seed[Any]]) -> list[AttackSeedGroup]: + def assemble_groups(self, contexts: list[Seed[Any]]) -> dict[str, list[AttackSeedGroup]]: """ - Create attack groups from the context templates. + Create one attack group per context and goal. Returns: - list[AttackSeedGroup]: The context and goal attack groups. + dict[str, list[AttackSeedGroup]]: The unsampled groups under the context dataset name. """ groups: list[AttackSeedGroup] = [] - contexts = [seed for seed in seeds if seed.dataset_name == self.CONTEXT_DATASET_NAME] for context in contexts: groups.extend( [ @@ -190,7 +194,7 @@ def _build_attack_groups(self, seeds: list[Seed[Any]]) -> list[AttackSeedGroup]: for goal_text in self._goal_texts ] ) - return groups + return {self.CONTEXT_DATASET_NAME: groups} class PromptInjectTechnique(ScenarioTechnique): @@ -222,7 +226,8 @@ class PromptInject(Scenario): Each attack places a selected injection technique inside one of 35 benign tasks. ``goal_texts`` defines the text that the injection asks the target to return. - Responses are scored by checking for that text. + Responses are scored by checking for that text. The context and technique + templates are required data, always read in full. """ VERSION: int = 3 @@ -279,8 +284,6 @@ def __init__( version=self.VERSION, technique_class=PromptInjectTechnique, default_dataset_config=PromptInjectDatasetConfiguration( - sources=[DatasetSource(name=name) for name in self.required_datasets()], - max_per_dataset="all", max_total=PromptInjectDatasetConfiguration.DEFAULT_MAX_DATASET_SIZE, goal_texts=self.DEFAULT_GOAL_TEXTS, ), @@ -288,6 +291,15 @@ def __init__( scenario_result_id=scenario_result_id, ) + def get_required_data(self) -> ScenarioRequiredData: + """ + Return the context and technique templates, read in full. + + Returns: + ScenarioRequiredData: The PromptInject template datasets. + """ + return ScenarioRequiredData(sources=[DatasetSource(name=name) for name in self.required_datasets()]) + def _validate_runtime_configuration(self) -> None: self._dataset_config = self._get_promptinject_dataset_config( goal_texts=cast("list[str]", self.params["goal_texts"]) @@ -311,9 +323,14 @@ async def _resolve_seed_groups_by_dataset_async( 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._dataset_config = config - groups = await config.get_attack_groups_by_dataset_async(apply_sampling=apply_sampling) - self._technique_templates = await self._load_technique_templates_async() + templates = await cast("ScenarioRequiredData", self._required_data).load_async() + groups = config.select_assembled_groups( + groups_by_population=config.assemble_groups( + templates[PromptInjectDatasetConfiguration.CONTEXT_DATASET_NAME] + ), + apply_sampling=apply_sampling, + ) + self._technique_templates = self._select_technique_templates(templates[self.TECHNIQUE_DATASET_NAME]) return groups async def _build_atomic_attacks_async(self, *, context: ScenarioContext) -> list[AtomicAttack]: @@ -392,9 +409,9 @@ def _get_promptinject_dataset_config(self, *, goal_texts: Sequence[str]) -> Prom config._set_goal_texts(goal_texts=goal_texts) return config - async def _load_technique_templates_async(self) -> dict[str, SeedPrompt]: + def _select_technique_templates(self, seeds: list[Seed[Any]]) -> dict[str, SeedPrompt]: """ - Load the selected technique templates from memory. + Pick the technique templates by name. Returns: dict[str, SeedPrompt]: Technique templates keyed by technique name. @@ -402,7 +419,6 @@ async def _load_technique_templates_async(self) -> dict[str, SeedPrompt]: Raises: DatasetConstraintError: If a selected technique has no template. """ - seeds = await self._dataset_config._collect_seeds_for_dataset_async(dataset_name=self.TECHNIQUE_DATASET_NAME) templates: dict[str, SeedPrompt] = {} for seed in seeds: if isinstance(seed, SeedPrompt) and seed.name: diff --git a/tests/unit/scenario/garak/test_prompt_inject.py b/tests/unit/scenario/garak/test_prompt_inject.py index 8d6ed062b1..c4763dd75e 100644 --- a/tests/unit/scenario/garak/test_prompt_inject.py +++ b/tests/unit/scenario/garak/test_prompt_inject.py @@ -4,6 +4,8 @@ """Tests for the Garak PromptInject scenario.""" import random +from collections.abc import Callable +from dataclasses import dataclass from unittest.mock import MagicMock, patch import pytest @@ -12,11 +14,12 @@ from pyrit.analytics import compute_technique_stats_async from pyrit.converter import Converter, SearchReplaceConverter from pyrit.memory import SQLiteMemory -from pyrit.models import AttackSeedGroup, ComponentIdentifier, Message, MessagePiece, SeedObjective +from pyrit.models import AttackSeedGroup, ComponentIdentifier, Message, MessagePiece, SeedObjective, SeedPrompt from pyrit.prompt_target import PromptTarget from pyrit.registry import ScenarioRegistry -from pyrit.scenario import DatasetAttackConfiguration -from pyrit.scenario.core import DatasetConstraintError +from pyrit.scenario import DatasetAttackConfiguration, DatasetSource +from pyrit.scenario.core import DatasetConstraintError, ResolvedDataset +from pyrit.scenario.core.dataset_configuration import require_seed_type from pyrit.scenario.garak import ( # type: ignore[ty:unresolved-import] PromptInject, PromptInjectDatasetConfiguration, @@ -29,6 +32,16 @@ def _mock_id(name: str) -> ComponentIdentifier: return ComponentIdentifier(class_name=name, class_module="test") +@dataclass +class _SeedTypeValidator: + """An unhashable callable validator, like a user's own dataclass validator.""" + + seed_type: type + + def __call__(self, resolved: ResolvedDataset) -> None: + require_seed_type(self.seed_type)(resolved) + + @pytest.fixture def garak_dataset_names() -> list[str]: return ["prompt_inject_contexts", "prompt_inject_techniques"] @@ -91,8 +104,9 @@ def test_default_dataset_config_caps_context_goal_groups(self) -> None: config = PromptInject()._default_dataset_config assert isinstance(config, PromptInjectDatasetConfiguration) - assert config.dataset_names == ["prompt_inject_contexts", "prompt_inject_techniques"] - assert config.max_dataset_size == 12 + assert config.dataset_names == [] + assert config.max_total == 12 + assert PromptInject().get_required_data().dataset_names == PromptInject.required_datasets() def test_default_technique_expands_to_all_five_forms(self) -> None: resolved = PromptInjectTechnique.resolve(None, default=PromptInjectTechnique.default()) @@ -157,7 +171,7 @@ async def test_sampling_covers_every_goal_async( ) -> None: scenario = PromptInject() goals = ["goal A", "goal B", "goal C"] - config = PromptInjectDatasetConfiguration(dataset_names=PromptInject.required_datasets(), max_dataset_size=cap) + config = PromptInjectDatasetConfiguration(max_total=cap) with patch("pyrit.scenario.core.dataset_sampling.random", random.Random(seed)): await _initialize_async(scenario, target=mock_objective_target, goal_texts=goals, dataset_config=config) @@ -181,8 +195,7 @@ async def test_uncapped_configuration_uses_complete_matrix(self, mock_objective_ scenario, target=mock_objective_target, dataset_config=PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), - max_dataset_size="all", + max_total="all", ), ) @@ -199,8 +212,7 @@ async def test_dataset_sample_is_reused_for_each_technique(self, mock_objective_ techniques=[PromptInjectTechnique.IgnorePrint, PromptInjectTechnique.IgnoreSay], goal_texts=["goal one", "goal two"], dataset_config=PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), - max_dataset_size=10, + max_total=10, ), ) @@ -241,9 +253,7 @@ async def test_converters_preserve_rendered_prompts_async( scenario, target=mock_objective_target, goal_texts=[goal], - dataset_config=PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), max_dataset_size="all" - ), + dataset_config=PromptInjectDatasetConfiguration(max_total="all"), ) for attack in scenario._atomic_attacks: @@ -289,9 +299,7 @@ async def test_persisted_statistics_keep_techniques_separate_async(self, sqlite_ target=target, techniques=[PromptInjectTechnique.IgnorePrint, PromptInjectTechnique.IgnoreSay], goal_texts=["custom goal"], - dataset_config=PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), max_dataset_size=1 - ), + dataset_config=PromptInjectDatasetConfiguration(max_total=1), ) attacks = {attack.atomic_attack_name: attack for attack in scenario._atomic_attacks} print_attack = attacks["ignore_print__goal_0"] @@ -376,8 +384,7 @@ async def test_invalid_goal_texts_raise( async def test_dataset_cap_smaller_than_goal_count_raises(self, mock_objective_target: PromptTarget) -> None: scenario = PromptInject() config = PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), - max_dataset_size=1, + max_total=1, ) with pytest.raises( @@ -398,7 +405,6 @@ def reject_dataset(_: object) -> None: raise DatasetConstraintError("custom validator ran") config = PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), validators=[reject_dataset], ) @@ -412,7 +418,10 @@ async def test_auto_fetch_false_is_preserved_async(self, mock_objective_target: with patch( "pyrit.datasets.seed_datasets.seed_dataset_provider.SeedDatasetProvider.get_providers_by_name_async" ) as fetch: - with pytest.raises(DatasetConstraintError, match="fetch is 'never'"): + with ( + pytest.warns(DeprecationWarning, match="PromptInjectDatasetConfiguration"), + pytest.raises(DatasetConstraintError, match="fetch is 'never'"), + ): await _initialize_async(scenario, target=mock_objective_target, dataset_config=config) fetch.assert_not_called() assert scenario._dataset_config is not config @@ -440,10 +449,10 @@ async def test_unsupported_dataset_selection_raises(self, mock_objective_target: scenario = PromptInject() config = PromptInjectDatasetConfiguration( dataset_names=["prompt_inject_techniques"], - max_dataset_size=1, + max_total=1, ) - with pytest.raises(DatasetConstraintError, match="requires exactly"): + with pytest.raises(DatasetConstraintError, match="required data"): await _initialize_async(scenario, target=mock_objective_target, dataset_config=config) async def test_inline_dataset_is_rejected(self, mock_objective_target: PromptTarget) -> None: @@ -452,7 +461,7 @@ async def test_inline_dataset_is_rejected(self, mock_objective_target: PromptTar seed_groups=[AttackSeedGroup(seeds=[SeedObjective(value="custom goal")])] ) - with pytest.raises(DatasetConstraintError, match="inline seeds are not supported"): + with pytest.raises(DatasetConstraintError, match="inline seeds"): await _initialize_async( scenario, target=mock_objective_target, @@ -475,40 +484,103 @@ class TestPromptInjectDatasetSampling: ], ) async def test_configuration_default_covers_custom_goals_async( - self, *, kwargs: dict[str, int | str | None], expected: int + self, *, kwargs: dict[str, int | str | None], expected: int, mock_objective_target: PromptTarget ) -> None: goals = [f"goal {index}" for index in range(6)] - config = PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), goal_texts=goals, **kwargs + scenario = PromptInject() + + await _initialize_async( + scenario, + target=mock_objective_target, + goal_texts=goals, + dataset_config=PromptInjectDatasetConfiguration(goal_texts=goals, **kwargs), ) - await config.prepare_async() - groups = await config.get_attack_seed_groups_async() + + groups = {group.objective.value: group for attack in scenario._atomic_attacks for group in attack.seed_groups} assert len(groups) == expected - assert {group.objective.metadata["goal_text"] for group in groups} == set(goals) + assert {group.objective.metadata["goal_text"] for group in groups.values()} == set(goals) - @pytest.mark.parametrize("grouped", [False, True]) - async def test_both_resolvers_preserve_goal_coverage_async(self, grouped: bool) -> None: + async def test_small_cap_still_covers_every_goal_async(self, *, mock_objective_target: PromptTarget) -> None: goals = ["goal A", "goal B", "goal C"] - config = PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), goal_texts=goals, max_dataset_size=3 - ) - await config.prepare_async() + scenario = PromptInject() + with patch("pyrit.scenario.core.dataset_sampling.random", random.Random(0)): - if grouped: - by_dataset = await config.get_attack_groups_by_dataset_async() - groups = [group for values in by_dataset.values() for group in values] - else: - groups = await config.get_attack_seed_groups_async() - - assert len(groups) == 3 - assert {group.objective.metadata["goal_text"] for group in groups} == set(goals) - full = await config.get_attack_seed_groups_async(apply_sampling=False) - assert len(full) == 105 - - async def test_flat_resolver_rejects_impossible_cap_async(self) -> None: - config = PromptInjectDatasetConfiguration( - dataset_names=PromptInject.required_datasets(), goal_texts=["goal one", "goal two"], max_dataset_size=1 - ) + await _initialize_async( + scenario, + target=mock_objective_target, + goal_texts=goals, + dataset_config=PromptInjectDatasetConfiguration(goal_texts=goals, max_total=3), + ) + + assert _objective_values(scenario) and len(_objective_values(scenario)) == 3 + assert {attack.display_group for attack in scenario._atomic_attacks} == set(goals) + + async def test_cap_below_the_goal_count_is_rejected_async(self, *, mock_objective_target: PromptTarget) -> None: + goals = ["goal one", "goal two"] with pytest.raises(DatasetConstraintError, match="must be at least the number of goal_texts"): - await config.get_attack_seed_groups_async() + await _initialize_async( + PromptInject(), + target=mock_objective_target, + goal_texts=goals, + dataset_config=PromptInjectDatasetConfiguration(goal_texts=goals, max_total=1), + ) + + async def test_listing_the_templates_as_sources_still_works_with_a_warning_async( + self, *, mock_objective_target: PromptTarget + ) -> None: + scenario = PromptInject() + legacy = PromptInjectDatasetConfiguration( + sources=[DatasetSource(name=name) for name in PromptInject.required_datasets()], max_total=3 + ) + + with pytest.warns(DeprecationWarning, match="PromptInjectDatasetConfiguration"): + await _initialize_async(scenario, target=mock_objective_target, dataset_config=legacy) + + assert len(_objective_values(scenario)) == 3 + assert scenario._build_scenario_identifier().datasets == PromptInject.required_datasets() + + @pytest.mark.parametrize( + "make_validator", + [ + pytest.param(lambda: require_seed_type(SeedPrompt), id="function"), + pytest.param(lambda: _SeedTypeValidator(SeedPrompt), id="callable-object"), + ], + ) + async def test_migrated_legacy_validators_check_the_raw_templates_async( + self, + *, + mock_objective_target: PromptTarget, + make_validator: Callable[[], Callable[[ResolvedDataset], None]], + ) -> None: + # A legacy validator wrote against the raw template seeds, so it must keep seeing those + # (SeedPrompt) after migration, not the assembled objectives (SeedObjective). The callable + # object is an unhashable validator, which the migration must still move. + scenario = PromptInject() + legacy = PromptInjectDatasetConfiguration( + sources=[DatasetSource(name=name) for name in PromptInject.required_datasets()], + validators=[make_validator()], + max_total=3, + ) + + with pytest.warns(DeprecationWarning, match="PromptInjectDatasetConfiguration"): + await _initialize_async(scenario, target=mock_objective_target, dataset_config=legacy) + + assert len(_objective_values(scenario)) == 3 + + +@pytest.mark.usefixtures("patch_central_database") +async def test_never_fetch_override_reaches_the_templates_async(*, mock_objective_target: PromptTarget) -> None: + scenario = PromptInject() + scenario.set_params_from_args( + args={"objective_target": mock_objective_target, "dataset_overrides": {"fetch": "never"}} + ) + + with ( + patch( + "pyrit.datasets.seed_datasets.seed_dataset_provider.SeedDatasetProvider.get_providers_by_name_async" + ) as fetch, + pytest.raises(DatasetConstraintError, match="fetch is 'never'"), + ): + await scenario.initialize_async() + fetch.assert_not_called() diff --git a/tests/unit/scenario/test_default_run_size_estimates.py b/tests/unit/scenario/test_default_run_size_estimates.py index a2b62a62ac..43fb1515e9 100644 --- a/tests/unit/scenario/test_default_run_size_estimates.py +++ b/tests/unit/scenario/test_default_run_size_estimates.py @@ -226,13 +226,12 @@ async def test_configuration_only_checks_are_shared_before_dataset_reads_async( @pytest.mark.usefixtures("patch_central_database") @pytest.mark.parametrize( "configuration_class", - [PromptInjectDatasetConfiguration, LatentInjectionDatasetConfiguration], + [LatentInjectionDatasetConfiguration], ) def test_ingredient_configurations_require_uncapped_sources( configuration_class: type[DatasetAttackConfiguration], ) -> None: scenario_class = { - PromptInjectDatasetConfiguration: PromptInject, LatentInjectionDatasetConfiguration: LatentInjection, }[configuration_class] config = configuration_class(sources=[DatasetSource(name=name) for name in scenario_class.required_datasets()]) @@ -270,7 +269,7 @@ async def test_compound_configuration_checks_children_before_a_bounded_preview_a config = CompoundDatasetAttackConfiguration( configurations=[ DatasetAttackConfiguration(dataset_names=["missing"]), - PromptInjectDatasetConfiguration(dataset_names=PromptInject.required_datasets(), max_dataset_size=1), + PromptInjectDatasetConfiguration(max_total=1), ], max_dataset_size=10, )