Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
171 commits
Select commit Hold shift + click to select a range
f36db28
FIX: Reject path parameters by default when building components from …
varunj-msft Oct 26, 2026
291c462
Leave out target types that require a path callers may not set
varunj-msft Oct 26, 2026
797831b
Test a target whose required path is the server upload folder
varunj-msft Oct 26, 2026
214a0fa
Merge origin/main
varunj-msft Nov 2, 2026
521ec7e
TEST: Cover saved converter copies in the server path check
varunj-msft Nov 2, 2026
66fd155
FEAT: Report the documents a storage listing cannot use
varunj-msft Nov 2, 2026
2d8c465
Report non-files and missing containers instead of skipping them
varunj-msft Nov 2, 2026
5dec828
Report an entry that can't be checked instead of failing the whole li…
varunj-msft Nov 2, 2026
bf662b7
FEAT: Read saved registry recipes
varunj-msft Nov 2, 2026
e8b0604
Merge the server path check for API input
varunj-msft Nov 2, 2026
9143ea6
FEAT: Rebuild saved registry entries in dependency order
varunj-msft Nov 2, 2026
c29d812
FEAT: Restore saved registry entries and stay not ready if any fail
varunj-msft Nov 2, 2026
cfa4fc0
Limit technique descriptions like the create request and export the r…
varunj-msft Nov 2, 2026
33735f1
Merge the recipe model limits and exports
varunj-msft Nov 2, 2026
11d0519
Keep restore failure messages safe and complete, and check technique …
varunj-msft Nov 2, 2026
8ab7116
Merge the restore message and credential fixes
varunj-msft Nov 2, 2026
b7bf012
Document the recipes setting in the example config and pin the restor…
varunj-msft Nov 2, 2026
e45865b
Test that a description at the limit is accepted
varunj-msft Nov 3, 2026
b6927a9
Merge the description limit test
varunj-msft Nov 3, 2026
c94ffbd
Show only the error type when a URL in it may carry credentials
varunj-msft Nov 3, 2026
ac849a9
Merge the safer failure messages
varunj-msft Nov 3, 2026
26377ea
Point the restore message at where failures are listed and guard the …
varunj-msft Nov 3, 2026
8663852
Cut failure messages at any URL query or fragment and hide any with u…
varunj-msft Nov 3, 2026
4159905
Merge the stricter failure messages
varunj-msft Nov 3, 2026
9a419b4
Escape text that isn't UTF-8 in restore reports so they can be sent a…
varunj-msft Nov 3, 2026
8fb8095
Merge the report text escaping
varunj-msft Nov 3, 2026
9a67367
Read error text as plain normalized text and say when part of it is h…
varunj-msft Nov 3, 2026
82c957f
Merge the plain, normalized failure text
varunj-msft Nov 3, 2026
274b4ce
Escape entry names in restore reports too
varunj-msft Nov 3, 2026
95f9492
Merge the entry name escaping
varunj-msft Nov 3, 2026
a60323a
Show error text with its original characters
varunj-msft Nov 3, 2026
e7558a4
Test that a reference name that isn't valid text can still be reported
varunj-msft Nov 3, 2026
0e8490c
Merge the original-character error text and escaped entry names
varunj-msft Nov 3, 2026
686d475
Test that the runtime status can report a reference name that isn't v…
varunj-msft Nov 3, 2026
c391b0d
Escape report text only when it is sent as JSON
varunj-msft Nov 3, 2026
0b44db6
Merge the JSON-only report escaping
varunj-msft Nov 3, 2026
f986da5
Check each character on its own so long error messages stay fast
varunj-msft Nov 3, 2026
807a904
Merge the per-character check and JSON-only report escaping
varunj-msft Nov 3, 2026
c86bfe6
Check the exact message for every form of each mark and bound the wor…
varunj-msft Nov 3, 2026
454d05b
Merge the exact look-alike message checks
varunj-msft Nov 3, 2026
9f91282
Test that the runtime status can list a file name that isn't valid text
varunj-msft Nov 3, 2026
a455494
Pass the look-alike check's arguments by keyword
varunj-msft Nov 3, 2026
ce8b684
Test that a technique waits for a saved converter in either list and …
varunj-msft Nov 3, 2026
d48a12c
Merge the converter-list and attack-type tests
varunj-msft Nov 3, 2026
74412fe
Test that restore runs after the startup scripts, at startup and on a…
varunj-msft Nov 3, 2026
784cd45
Keep the offline browser fixture away from saved registry entries
varunj-msft Nov 3, 2026
507567b
Check the opened file before reading it and skip links deleted since …
varunj-msft Nov 3, 2026
9d37ba3
Merge the opened-file check
varunj-msft Nov 3, 2026
ff2c836
Merge the opened-file check
varunj-msft Nov 3, 2026
3afdcaa
Merge origin/main
varunj-msft Nov 3, 2026
de2f4e3
Let restore set the path parameters a target lets callers set, as the…
varunj-msft Nov 3, 2026
e821e7e
Merge the opened-file check, main and the caller path parameters
varunj-msft Nov 3, 2026
a45ac23
Close a file that isn't regular before reporting it and report entrie…
varunj-msft Nov 3, 2026
60477e8
Merge the file handle fix
varunj-msft Nov 3, 2026
28f2262
Merge the file handle fix
varunj-msft Nov 3, 2026
ad21f0c
Give only targets the path parameters their class lets callers set
varunj-msft Nov 3, 2026
3dc4768
Merge the file handle fix and the target-only caller paths
varunj-msft Nov 3, 2026
db245dc
Test a file replaced just before it's opened and stop a blocked read …
varunj-msft Nov 4, 2026
5d3d2d0
Merge the opened-file tests
varunj-msft Nov 4, 2026
07a617f
Merge the opened-file tests
varunj-msft Nov 4, 2026
2b4f1cc
Merge the opened-file tests
varunj-msft Nov 4, 2026
80754a2
Read saved recipes separately from building them
varunj-msft Nov 4, 2026
7965020
Merge the separate recipe read
varunj-msft Nov 4, 2026
bd84ef0
Build restored entries on the runtime loop and read them in a worker …
varunj-msft Nov 4, 2026
1a192f7
Show every signed-in user why saved registry entries couldn't be rest…
varunj-msft Nov 4, 2026
4fb7f35
Retry restoring saved registry entries without a restart
varunj-msft Nov 4, 2026
27ef572
Drop a late retry answer when the runtime failed again between polls
varunj-msft Nov 4, 2026
fa1ae56
Keep Retry in reach and say when the failure list couldn't be loaded
varunj-msft Nov 5, 2026
1af1d00
Stop a scan whose launch scripts would replace a saved entry
varunj-msft Nov 5, 2026
17d6fe0
Report a saved-entry clash when a launch script wraps the refusal
varunj-msft Nov 5, 2026
d1bdd82
List presets, suites, and initializers through the checked listing
varunj-msft Nov 5, 2026
f5ed760
Merge the shared document listing
varunj-msft Nov 5, 2026
4b55b17
Merge the shared document listing
varunj-msft Nov 5, 2026
a1866d5
Merge the shared document listing
varunj-msft Nov 5, 2026
e8dc897
Merge the shared document listing
varunj-msft Nov 5, 2026
09a98af
Merge the shared document listing
varunj-msft Nov 5, 2026
76dbf9c
Report a preset, suite, or initializer folder that can't be read as u…
varunj-msft Nov 5, 2026
f823e4b
Merge the storage error mapping for unreadable folders
varunj-msft Nov 5, 2026
99da684
Merge the storage error mapping for unreadable folders
varunj-msft Nov 5, 2026
2c58145
Merge the storage error mapping for unreadable folders
varunj-msft Nov 5, 2026
5a0afa6
Merge the storage error mapping for unreadable folders
varunj-msft Nov 5, 2026
6bb9aec
Merge the storage error mapping for unreadable folders
varunj-msft Nov 5, 2026
6800d15
Merge origin/main
varunj-msft Nov 6, 2026
74839cd
Merge origin/main
varunj-msft Nov 6, 2026
ee3e64f
Merge origin/main
varunj-msft Nov 6, 2026
15e7a9e
Take out the restore retry changes merged here by mistake
varunj-msft Nov 6, 2026
7d9ac2f
Log why storage is unavailable, without its path or URL
varunj-msft Nov 7, 2026
7b5bfeb
Merge the storage error logging
varunj-msft Nov 7, 2026
22806d8
Merge the storage error logging
varunj-msft Nov 7, 2026
34011c9
Hide a restore message with a percent escape, which can hide a creden…
varunj-msft Nov 7, 2026
8a0113f
Merge the storage error logging and the percent-escape fix
varunj-msft Nov 7, 2026
8d51b6c
Merge the storage error logging and the percent-escape fix
varunj-msft Nov 7, 2026
dc4125c
Stop a launch whose script catches the duplicate-name error for a sav…
varunj-msft Nov 7, 2026
031dc61
Merge origin/main
varunj-msft Nov 8, 2026
7f8ab0d
Merge origin/main
varunj-msft Nov 8, 2026
19205b1
Import the saved recipe models from their package, as main now requires
varunj-msft Nov 8, 2026
0348a0b
Merge origin/main
varunj-msft Nov 8, 2026
bba3afd
Import from public packages, as main now requires
varunj-msft Nov 8, 2026
d4ccd50
Merge origin/main
varunj-msft Nov 8, 2026
ed01798
Merge origin/main
varunj-msft Nov 8, 2026
98766ec
Record a saved entry's name clash wherever a launch script can catch it
varunj-msft Nov 8, 2026
622bbb8
Report storage failures with one error and answer them with 503
varunj-msft Nov 9, 2026
1cae0b9
Merge the single storage error
varunj-msft Nov 9, 2026
eba7bf2
Escape file names once and simplify the saved recipe models
varunj-msft Nov 9, 2026
9f24124
Merge the recipe model simplification
varunj-msft Nov 9, 2026
2bbfc8f
Report restore bugs as build errors and log each failure once
varunj-msft Nov 9, 2026
3735dbc
Merge the restore logging and build error fixes
varunj-msft Nov 9, 2026
ca7563d
Stay ready when a saved entry can't be restored, and hold its name
varunj-msft Nov 9, 2026
a9dfc86
Merge the stay-ready restore
varunj-msft Nov 10, 2026
67416f1
Reset the registries between runtime tests, as a real startup does
varunj-msft Nov 10, 2026
e6e419e
Merge the runtime test isolation
varunj-msft Nov 10, 2026
81c0317
Stop a launch whose script takes the name of a saved entry that failed
varunj-msft Nov 10, 2026
6ee84f0
Merge origin/main
varunj-msft Nov 10, 2026
d43a7e8
Merge origin/main
varunj-msft Nov 10, 2026
0664063
Merge origin/main
varunj-msft Nov 10, 2026
3b3ac59
Merge origin/main
varunj-msft Nov 10, 2026
04fe60f
Merge origin/main
varunj-msft Nov 10, 2026
8614025
Use one recipe format version, keep the auth mode, and escape failure…
varunj-msft Nov 10, 2026
5a3f18b
Merge the recipe format changes
varunj-msft Nov 10, 2026
b3c7847
Build restored entries with a builder the caller supplies
varunj-msft Nov 10, 2026
af4075f
Merge the restore builder changes
varunj-msft Nov 10, 2026
061807a
Warn that writing saved entries is administrator authority, and test …
varunj-msft Nov 10, 2026
1740964
Merge the restore builder changes
varunj-msft Nov 10, 2026
986cc90
Test the parser's depth limit without depending on the stack size
varunj-msft Nov 10, 2026
1096925
Merge the parser depth test fix
varunj-msft Nov 10, 2026
f25b520
Merge the parser depth test fix
varunj-msft Nov 10, 2026
1845b64
Merge the parser depth test fix
varunj-msft Nov 10, 2026
fb90af8
Read saved entries in a worker thread when restore isn't given what w…
varunj-msft Nov 10, 2026
c44d2ce
Merge the worker-thread read
varunj-msft Nov 10, 2026
abd116a
Stay not ready when a saved entry can't be restored, and let apply retry
varunj-msft Nov 10, 2026
0bfa6cc
Drop the refusal of held names from launches
varunj-msft Nov 10, 2026
c62118f
Merge the not-ready restore
varunj-msft Nov 10, 2026
f59306e
Read saved recipes off the event loop by default, and harden URL reda…
richlundeen Nov 10, 2026
f1ff143
Keep an "@" in a URL's path when redacting URLs in text
richlundeen Nov 10, 2026
009e761
Merge the restore read and redaction fixes
varunj-msft Nov 10, 2026
21f22a4
Merge the restore read and redaction fixes
varunj-msft Nov 10, 2026
cc4ae4d
Merge main
varunj-msft Nov 10, 2026
9f4c71e
Merge main
varunj-msft Nov 10, 2026
187191c
Answer suite readiness storage failures through the shared storage ha…
varunj-msft Nov 11, 2026
bb2a620
Merge the readiness and save test fixes
varunj-msft Nov 11, 2026
374c620
Merge main
varunj-msft Nov 11, 2026
7ac059c
Answer suite readiness storage failures through the shared storage ha…
varunj-msft Nov 11, 2026
e08b67a
Merge main
varunj-msft Nov 11, 2026
7fa4ca4
Expect storage errors from main's version-checked delete tests the wa…
varunj-msft Nov 11, 2026
9bf5886
Merge main
varunj-msft Nov 11, 2026
626d2d4
Merge main
varunj-msft Nov 11, 2026
c506195
Merge main
varunj-msft Nov 11, 2026
1ba526f
Merge main
varunj-msft Nov 11, 2026
9cdf7e7
Merge main
varunj-msft Nov 11, 2026
40d36ed
Merge main
varunj-msft Nov 11, 2026
6a52054
Merge main
varunj-msft Nov 11, 2026
0e7a21f
Exempt the storage error handler from the keyword-only check
varunj-msft Nov 11, 2026
c35fa01
Merge keyword-only fixes
varunj-msft Nov 11, 2026
953dcce
Merge keyword-only fixes
varunj-msft Nov 11, 2026
d6079a1
Merge keyword-only fixes
varunj-msft Nov 11, 2026
21556ed
Merge keyword-only fixes
varunj-msft Nov 11, 2026
bf97225
Log every problem with a saved file that isn't valid
varunj-msft Nov 11, 2026
5e6faed
Merge the full schema-validation log
varunj-msft Nov 11, 2026
35199cc
Leave the error behind a storage failure out of the logs
varunj-msft Nov 12, 2026
efcdfa9
Test a blob upload that fails with a transport or authentication error
varunj-msft Nov 12, 2026
0fdebdc
Merge the storage log and restore report fixes
varunj-msft Nov 12, 2026
c413994
Merge the storage log and restore report fixes
varunj-msft Nov 12, 2026
c057e30
Merge the storage log and restore report fixes
varunj-msft Nov 12, 2026
dc97ec7
Merge the storage log and restore report fixes
varunj-msft Nov 12, 2026
c9b795a
Merge main
varunj-msft Nov 12, 2026
38c981c
Merge main
varunj-msft Nov 12, 2026
eb71448
Merge main
varunj-msft Nov 12, 2026
1be067e
Merge main
varunj-msft Nov 12, 2026
162fc2a
Merge main
varunj-msft Nov 12, 2026
4e8d9c2
Return 409 when a suite's launch scripts would replace a saved entry
varunj-msft Nov 12, 2026
46e5fb4
Merge main
varunj-msft Nov 12, 2026
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
8 changes: 6 additions & 2 deletions pyrit/backend/routes/scenario_suites.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
)
from pyrit.backend.models.common import IdentifierStr
from pyrit.backend.services import get_scenario_suite_execution_service, get_scenario_suite_service
from pyrit.backend.services.scenario_run_service import SavedEntryLaunchConflictError
from pyrit.backend.services.scenario_suite_execution_service import ScenarioSuiteExecutionCapacityError
from pyrit.models import (
LaunchScenarioSuiteRequest,
Expand Down Expand Up @@ -152,7 +153,10 @@ async def cancel_scenario_suite_execution( # pyrit-async-suffix-exempt
responses={
400: {"model": ProblemDetail, "description": "The suite has unresolved or invalid entries"},
404: {"model": ProblemDetail, "description": "Scenario suite not found"},
409: {"model": ProblemDetail, "description": "The suite or a referenced preset changed"},
409: {
"model": ProblemDetail,
"description": "The suite or a referenced preset changed, or a launch script would replace a saved entry",
},
429: {"model": ProblemDetail, "description": "Active suite execution capacity is full"},
503: {"model": ProblemDetail, "description": "Runtime or definition storage unavailable"},
},
Expand All @@ -179,7 +183,7 @@ async def launch_scenario_suite( # pyrit-async-suffix-exempt
return await get_scenario_suite_execution_service().launch_async(name=name, request=body)
except ScenarioSuiteExecutionNotFoundError as exc:
raise _not_found(name) from exc
except ScenarioSuiteLaunchConflictError as exc:
except (ScenarioSuiteLaunchConflictError, SavedEntryLaunchConflictError) as exc:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(exc)) from None
except ScenarioSuiteConflictError as exc:
raise HTTPException(
Expand Down
5 changes: 4 additions & 1 deletion pyrit/backend/routes/scenarios.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,10 @@ async def load_scenario_datasets_async(
responses={
400: {"model": ProblemDetail, "description": "Invalid request (bad scenario/target/technique)"},
404: {"model": ProblemDetail, "description": "Saved run not found"},
409: {"model": ProblemDetail, "description": "Saved run cannot be resumed"},
409: {
"model": ProblemDetail,
"description": "Saved run cannot be resumed, or a launch script would replace a saved entry",
},
},
)
async def start_scenario_run( # pyrit-async-suffix-exempt
Expand Down
43 changes: 42 additions & 1 deletion pyrit/backend/services/scenario_run_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@
from pyrit.models.scenario_readiness import ScenarioConfigurationError
from pyrit.prompt_target import PromptTarget
from pyrit.registry import InitializerRegistry, ScenarioRegistry
from pyrit.registry.instance_registry import SavedEntryReplacementError, record_saved_entry_refusals
from pyrit.registry.resolution import reject_non_external_params, resolve_declared_params
from pyrit.scenario import IncompatibleTechniquePolicy, Scenario
from pyrit.scenario.core import get_default_adversarial_target, override_default_adversarial_target
Expand Down Expand Up @@ -192,6 +193,10 @@ class ScenarioRunConflictError(ValueError):
"""A saved run cannot be admitted to the scheduler in its current state."""


class SavedEntryLaunchConflictError(ScenarioRunConflictError):
"""A launch script would replace an entry rebuilt from a saved recipe."""


class ScenarioRunNotFoundError(ValueError):
"""The requested saved run is not in the active memory database."""

Expand Down Expand Up @@ -1657,6 +1662,7 @@ async def _run_initializers_async(self, *, request: RunScenarioRequest) -> None:

Raises:
ValueError: If an initializer name is not found in the registry.
SavedEntryLaunchConflictError: If an initializer would replace a saved entry.
"""
if not request.initializers:
return
Expand All @@ -1670,7 +1676,42 @@ async def _run_initializers_async(self, *, request: RunScenarioRequest) -> None:
)
except KeyError as e:
raise ValueError(f"Initializer not found: {e}") from None
await instance.initialize_async()
# The registries refuse to replace a saved entry; the record also catches a refusal
# that the script itself caught, which would leave the saved entry in its place.
with record_saved_entry_refusals() as refusals:
try:
await instance.initialize_async()
except SavedEntryReplacementError as error:
refusals.append((error.kind, error.name))
except Exception as error:
# A script can wrap the refusal in an error of its own; the clash is still why it stopped.
if refusals:
raise self._saved_entry_conflict(
initializer_name=initializer_name, refusals=refusals
) from error
raise
if refusals:
raise self._saved_entry_conflict(initializer_name=initializer_name, refusals=refusals)

@staticmethod
def _saved_entry_conflict(
*, initializer_name: str, refusals: list[tuple[str, str]]
) -> SavedEntryLaunchConflictError:
"""
Describe the saved entries a launch script would have replaced.

Args:
initializer_name (str): The launch script's name.
refusals (list[tuple[str, str]]): The kind and name of each saved entry that was refused.

Returns:
SavedEntryLaunchConflictError: The error to raise.
"""
entries = ", ".join(f"{kind.removesuffix('s')} '{name}'" for kind, name in dict.fromkeys(refusals))
return SavedEntryLaunchConflictError(
f"The launch script '{initializer_name}' would replace the saved {entries}. "
"Leave that script out of the launch."
)

async def _initialize_scenario_async(
self,
Expand Down
22 changes: 19 additions & 3 deletions pyrit/registry/components/attack_technique_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@

from pyrit.models import AttackIdentifier, ComponentType
from pyrit.models.component_spec import SourceInstanceSpec
from pyrit.registry.instance_registry import DefaultInstanceRegistry, RegistryNameTakenError
from pyrit.registry.instance_registry import (
DefaultInstanceRegistry,
RegistryNameTakenError,
_record_saved_entry_refusal,
refuse_saved_entry,
)
from pyrit.registry.registry import Registry
from pyrit.registry.registry_metadata import RegistryMetadata

Expand Down Expand Up @@ -143,10 +148,14 @@ class TechniqueAdmissionError(ValueError):
class TechniqueInstanceRegistry(DefaultInstanceRegistry["AttackTechniqueFactory"]):
"""Factory storage with an atomic runtime-admission path."""

def register_runtime(self, factory: AttackTechniqueFactory) -> None:
def register_runtime(self, factory: AttackTechniqueFactory, *, metadata: dict[str, Any] | None = None) -> None:
"""
Check selector collisions while holding the same lock as registration.

Args:
factory (AttackTechniqueFactory): The technique to register.
metadata (dict[str, Any] | None): Optional per-entry metadata. Defaults to None.

Raises:
TechniqueSelectorConflictError: If the name or a tag conflicts with another technique's name or tag.
TechniqueAdmissionError: If a tag repeats the technique's own name, a selector can't become a scenario
Expand All @@ -162,6 +171,8 @@ def register_runtime(self, factory: AttackTechniqueFactory) -> None:
tags = {tag.casefold(): tag for entry in entries for tag in entry.instance.technique_tags}
folded_name = factory.name.casefold()
if folded_name in names:
# Code that catches this error would leave a saved technique standing in, so the clash is recorded.
_record_saved_entry_refusal(self.get_entry(names[folded_name]))
raise TechniqueSelectorConflictError(
f"Technique '{factory.name}' already exists (names are case-insensitive)"
)
Expand All @@ -186,7 +197,7 @@ def register_runtime(self, factory: AttackTechniqueFactory) -> None:
)
except ValueError as error:
raise TechniqueAdmissionError(str(error)) from error
self.register(factory, name=factory.name, tags=factory.technique_tags)
self.register(factory, name=factory.name, tags=factory.technique_tags, metadata=metadata)


class AttackTechniqueRegistry(Registry["AttackTechniqueFactory", AttackTechniqueMetadata]):
Expand Down Expand Up @@ -769,8 +780,13 @@ def register_from_factories(
factories (list[AttackTechniqueFactory]): Self-describing factories to
register. Each factory's ``name`` and ``technique_tags`` properties are
used directly.

Raises:
SavedEntryReplacementError: If a factory's name belongs to a technique rebuilt
from a saved recipe, which skipping would quietly use in its place.
"""
for factory in factories:
refuse_saved_entry(self.instances.get_entry(factory.name))
if factory.name not in self.instances:
tags: dict[str, str] = dict.fromkeys(factory.technique_tags, "")
self.register_technique(
Expand Down
116 changes: 114 additions & 2 deletions pyrit/registry/instance_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,13 @@
from __future__ import annotations

import threading
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Generic, Protocol, TypeVar, runtime_checkable

if TYPE_CHECKING:
from collections.abc import Callable, Iterator
from collections.abc import Callable, Generator, Iterator

from pyrit.models import ComponentIdentifier
from pyrit.registry.tag_query import TagQuery
Expand All @@ -43,6 +45,14 @@ def get_identifier(self) -> ComponentIdentifier:

T = TypeVar("T", bound=SupportsIdentifier) # The type of items stored

#: Entry metadata naming the kind of saved recipe an entry was rebuilt from, such as ``"targets"``.
SAVED_ENTRY_METADATA_KEY = "saved_recipe_kind"

_saved_entry_refusals: ContextVar[list[tuple[str, str]] | None] = ContextVar("_saved_entry_refusals", default=None)

# The kind and name of the saved entry being rebuilt in this context, so registering that name marks the entry.
_saved_entry_registration: ContextVar[tuple[str, str] | None] = ContextVar("_saved_entry_registration", default=None)


class RegistryNameTakenError(ValueError):
"""A name is already registered, so another entry can't take it."""
Expand Down Expand Up @@ -70,6 +80,98 @@ class RegistryEntry(Generic[T]):
metadata: dict[str, Any] = field(default_factory=dict)


class SavedEntryReplacementError(RuntimeError):
"""
Raised when code registers an entry under the name of an entry rebuilt from a saved recipe.

It isn't a ``ValueError``, so a startup script that skips the entries it can't build doesn't
swallow it.
"""

def __init__(self, *, kind: str, name: str) -> None:
"""
Describe the saved entry that would have been replaced.

Args:
kind (str): The saved recipe kind, such as ``"targets"``.
name (str): The entry's name.
"""
super().__init__(f"Saved {kind.removesuffix('s')} '{name}' can't be replaced.")
self.kind = kind
self.name = name


def refuse_saved_entry(entry: RegistryEntry[Any] | None) -> None:
"""
Refuse to replace, or stand in for, an entry rebuilt from a saved recipe.

Args:
entry (RegistryEntry[Any] | None): The entry registered under the name, if any.

Raises:
SavedEntryReplacementError: If the entry was rebuilt from a saved recipe.
"""
kind = _record_saved_entry_refusal(entry)
if entry is not None and kind is not None:
raise SavedEntryReplacementError(kind=kind, name=entry.name)


def _record_saved_entry_refusal(entry: RegistryEntry[Any] | None) -> str | None:
"""
Record a refused use of an entry rebuilt from a saved recipe, when refusals are being recorded.

Args:
entry (RegistryEntry[Any] | None): The entry registered under the name, if any.

Returns:
str | None: The entry's saved recipe kind, or None when it wasn't rebuilt from a saved recipe.
"""
if entry is None or SAVED_ENTRY_METADATA_KEY not in entry.metadata:
return None
kind = str(entry.metadata[SAVED_ENTRY_METADATA_KEY])
refusals = _saved_entry_refusals.get()
if refusals is not None:
refusals.append((kind, entry.name))
return kind


@contextmanager
def record_saved_entry_refusals() -> Generator[list[tuple[str, str]], None, None]:
"""
Collect the saved entries that code run in this context tried to replace.

The list holds every refusal, including ones the code caught itself.

Yields:
list[tuple[str, str]]: The kind and name of each saved entry that was refused.
"""
refusals: list[tuple[str, str]] = []
token = _saved_entry_refusals.set(refusals)
try:
yield refusals
finally:
_saved_entry_refusals.reset(token)


@contextmanager
def saved_entry_registration(*, kind: str, name: str) -> Generator[None, None, None]:
"""
Mark the entry registered under ``name`` in this context as rebuilt from a saved recipe.

Args:
kind (str): The saved recipe kind, such as ``"targets"``.
name (str): The saved entry's name.

Yields:
None: Control returns to the caller while the mark applies.
"""
token = _saved_entry_registration.set((kind, name))
try:
yield
finally:
_saved_entry_registration.reset(token)


@runtime_checkable
class InstanceRegistry(Protocol[T]):
"""
Expand Down Expand Up @@ -292,6 +394,8 @@ def register(
``instance`` is not of that type.
ValueError: If the name is reserved.
RegistryNameTakenError: If the name is already registered and ``replace`` is False.
SavedEntryReplacementError: If ``replace`` would replace an entry rebuilt
from a saved recipe.
"""
expected_type = self._resolve_instance_type()
if expected_type is not None and not isinstance(instance, expected_type):
Expand All @@ -302,17 +406,23 @@ def register(

if name is None:
name = instance.get_identifier().unique_name
entry_metadata = dict(metadata or {})
restoring = _saved_entry_registration.get()
if restoring is not None and restoring[1] == name:
entry_metadata[SAVED_ENTRY_METADATA_KEY] = restoring[0]
entry = RegistryEntry(
name=name,
instance=instance,
tags=self._normalize_tags(tags),
metadata=metadata or {},
metadata=entry_metadata,
)
with self._lock:
if name in self._reserved_names:
raise ValueError(f"Instance name '{name}' is reserved")
if not replace:
self.validate_name_available(name)
else:
refuse_saved_entry(self._registry_items.get(name))
self._registry_items[name] = entry
self._metadata_cache = None
self._instance_version += 1
Expand Down Expand Up @@ -345,6 +455,8 @@ def validate_name_available(self, name: str) -> None:
if name in self._reserved_names:
raise ValueError(f"Instance name '{name}' is reserved")
if name in self._registry_items:
# Code that catches this error would leave a saved entry standing in, so the clash is recorded.
_record_saved_entry_refusal(self._registry_items[name])
raise RegistryNameTakenError(f"Instance '{name}' already exists")

def unregister(self, name: str, *, expected_entry: RegistryEntry[T] | None = None) -> T | None:
Expand Down
5 changes: 3 additions & 2 deletions pyrit/registry/registry_recipe_restore.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
TechniqueRecipe,
)
from pyrit.registry.file_document_storage import DocumentStorageUnavailableError
from pyrit.registry.instance_registry import RegistryNameTakenError
from pyrit.registry.instance_registry import RegistryNameTakenError, saved_entry_registration
from pyrit.registry.registry_recipe_storage import RecipeListing, RegistryRecipeStorage, safe_failure_text

if TYPE_CHECKING:
Expand Down Expand Up @@ -518,7 +518,8 @@ async def _build_async(
from pyrit.registry.components.attack_technique_registry import TechniqueAdmissionError

try:
await build_async(stored)
with saved_entry_registration(kind=stored.ref.kind.value, name=stored.ref.name):
await build_async(stored)
except RecipeRejectedError as rejection:
return self._failure(stored=stored, reason=rejection.reason, message=str(rejection))
except RegistryNameTakenError as error:
Expand Down
8 changes: 7 additions & 1 deletion pyrit/setup/initializers/scorers.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from pyrit.common.async_compatibility import run_legacy_sync_async
from pyrit.models import Parameter, SeedPrompt
from pyrit.registry import ScorerRegistry, TargetRegistry
from pyrit.registry.instance_registry import refuse_saved_entry
from pyrit.score import (
AzureContentFilterScorer,
DecisionScorer,
Expand Down Expand Up @@ -513,6 +514,8 @@ def _tag_best_per_category(self) -> None:
for best_tag, (preferred_name, category_tag) in self._PREFERRED_BEST.items():
entry = scorer_registry.instances.get_entry(preferred_name)
if entry is not None:
# A saved scorer under this name would stand in for the one this script couldn't build.
refuse_saved_entry(entry)
scorer_registry.instances.add_tags(name=preferred_name, tags=[best_tag])
logger.info(f"Tagged {preferred_name} as {best_tag}")
continue
Expand Down Expand Up @@ -635,7 +638,10 @@ def _tag_best_objective(self) -> None:

# Fall back: prefer scale_and_refusal, then first composite
best_tags: list[str] = [ScorerInitializerTags.BEST_OBJECTIVE, ScorerInitializerTags.DEFAULT_OBJECTIVE_SCORER]
if scorer_registry.instances.get_entry(self.SCALE_AND_REFUSAL):
scale_and_refusal = scorer_registry.instances.get_entry(self.SCALE_AND_REFUSAL)
if scale_and_refusal is not None:
# A saved scorer under this name would stand in for the one this script couldn't build.
refuse_saved_entry(scale_and_refusal)
fallback_name = self.SCALE_AND_REFUSAL
else:
composites = scorer_registry.instances.get_by_tag(tag=ScorerInitializerTags.OBJECTIVE_COMPOSITE)
Expand Down
Loading
Loading