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
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.

"""
Flag planned seed groups that reference media.

Dataset media cleanup reads only flagged rows, so existing rows are classified from
their stored seed group before the flag becomes required.

Revision ID: cc714ae17d07
Revises: 3e55dd099e38
Create Date: 2026-11-20 14:00:00.000000
"""

from collections.abc import Generator, Sequence
from contextlib import contextmanager

import sqlalchemy as sa
from alembic import op

from pyrit.memory.memory_models import CustomUUID, planned_media_values

# revision identifiers, used by Alembic.
revision: str = "cc714ae17d07"
down_revision: str | None = "3e55dd099e38"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

_TABLE = "ScenarioPlanSeedGroupEntries"
_INDEX = "ix_ScenarioPlanSeedGroupEntries_has_media"
_BATCH_SIZE = 500
# Created by be3d7027ac91 on SQLite.
_DELETE_TRIGGER = "trg_delete_scenario_plan_seed_groups"


@contextmanager
def _without_sqlite_delete_trigger() -> Generator[None, None, None]:
"""
Drop the SQLite planned-group delete trigger while batch mode rebuilds the table, then restore it.

SQLite checks every trigger when batch mode renames the rebuilt table into place, and this
trigger names the table being replaced, so the rename fails while it exists.

Yields:
None: Control while the table is rebuilt.
"""
sqlite = op.get_context().dialect.name == "sqlite"
if sqlite:
op.execute(f'DROP TRIGGER "{_DELETE_TRIGGER}"')
yield
if sqlite:
op.execute(
f"""
CREATE TRIGGER "{_DELETE_TRIGGER}"
AFTER DELETE ON "ScenarioResultEntries"
BEGIN
DELETE FROM "{_TABLE}" WHERE scenario_result_id = OLD.id;
END
"""
)


def _backfill_has_media(*, connection: sa.Connection) -> None:
"""
Classify every unflagged row from its stored seed group, a bounded page at a time.

Args:
connection (sa.Connection): The Alembic transaction's existing connection.
"""
entries = sa.table(
_TABLE,
sa.column("id", CustomUUID()),
sa.column("seed_group", sa.JSON()),
sa.column("has_media", sa.Boolean()),
)
page = sa.select(entries.c.id, entries.c.seed_group).where(entries.c.has_media.is_(None)).limit(_BATCH_SIZE)
update = (
sa.update(entries)
.where(entries.c.id == sa.bindparam("row_id", type_=CustomUUID()))
.values(has_media=sa.bindparam("flag", type_=sa.Boolean()))
)
while rows := connection.execute(page).all():
connection.execute(
update, [{"row_id": row_id, "flag": bool(planned_media_values(seed_group))} for row_id, seed_group in rows]
)


def upgrade() -> None:
"""Add the media flag, classify existing rows, then require and index it."""
with op.batch_alter_table(_TABLE) as batch_op:
batch_op.add_column(sa.Column("has_media", sa.Boolean(), nullable=True))
_backfill_has_media(connection=op.get_bind())
with _without_sqlite_delete_trigger(), op.batch_alter_table(_TABLE) as batch_op:
batch_op.alter_column("has_media", existing_type=sa.Boolean(), nullable=False)
op.create_index(_INDEX, _TABLE, ["has_media"], unique=False)


def downgrade() -> None:
"""Remove the media flag; stored seed groups are kept."""
op.drop_index(_INDEX, table_name=_TABLE)
with _without_sqlite_delete_trigger(), op.batch_alter_table(_TABLE) as batch_op:
batch_op.drop_column("has_media")
78 changes: 65 additions & 13 deletions pyrit/memory/dataset_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import logging
import os
import uuid
from collections import Counter
from pathlib import Path
from typing import TYPE_CHECKING
from urllib.parse import parse_qs, unquote, urlparse
Expand All @@ -20,15 +21,19 @@

from pyrit.memory.dataset_upload_lease import try_upload_lease_async
from pyrit.memory.memory_models import (
SIMULATED_CONVERSATION_PROMPT_FIELDS,
DatasetLifecycleEntry,
DatasetLifecycleLock,
DatasetMediaEntry,
PromptGenerationEntry,
PromptMemoryEntry,
ScenarioPlanSeedGroupEntry,
ScenarioResultEntry,
ScorableContentEntry,
SeedEntry,
planned_media_values,
)
from pyrit.models import DATASET_NAME_RELEASING_STATUSES, MEDIA_PATH_DATA_TYPES
from pyrit.models import DATASET_NAME_RELEASING_STATUSES, MEDIA_PATH_DATA_TYPES, ScenarioRunState

if TYPE_CHECKING:
from collections.abc import Awaitable, Callable, Sequence
Expand Down Expand Up @@ -110,15 +115,19 @@ def media_key(value: str, *, storage: StorageIO | None = None) -> str:
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def _media_keys(session: Session, values: Sequence[str]) -> set[str]:
def canonicalize() -> set[str]:
return {media_key(value, storage=session.info.get("dataset_storage_io")) for value in values}
def _media_key_map(session: Session, *, values: Sequence[str]) -> dict[str, str]:
def canonicalize() -> dict[str, str]:
return {value: media_key(value, storage=session.info.get("dataset_storage_io")) for value in values}

if session.get_bind().dialect.is_async:
return await_only(asyncio.to_thread(canonicalize))
return canonicalize()


def _media_keys(session: Session, values: Sequence[str]) -> set[str]:
return set(_media_key_map(session, values=values).values())


def lock_dataset_lifecycle(session: Session) -> None:
"""
Hold the same database lock for lifecycle decisions and every reference change.
Expand Down Expand Up @@ -169,6 +178,8 @@ def _entry_media_values(entry: object) -> list[str]:
return []
if isinstance(entry, ScorableContentEntry):
return [entry.value] if entry.data_type in MEDIA_PATH_DATA_TYPES else []
if isinstance(entry, ScenarioPlanSeedGroupEntry):
return planned_media_values(entry.seed_group)
if isinstance(entry, PromptMemoryEntry):
return [
value
Expand All @@ -190,7 +201,7 @@ def _seed_media_values(*, seed_type: str, value: str, data_type: str) -> list[st
if not isinstance(config, dict):
raise ValueError("A simulated conversation requires a stored configuration object.")
values = []
for field in ("adversarial_chat_system_prompt", "simulated_target_system_prompt", "next_message_system_prompt"):
for field in SIMULATED_CONVERSATION_PROMPT_FIELDS:
prompt = config.get(field)
if isinstance(prompt, dict) and prompt.get("data_type") in MEDIA_PATH_DATA_TYPES:
path = prompt.get("value")
Expand Down Expand Up @@ -242,10 +253,17 @@ def _validate_dataset_references(*, session: Session, dataset_names: set[str | N
raise ValueError("Media has been removed or is reserved for dataset cleanup.")


def stored_media_keys(session: Session) -> set[str]:
def stored_media_keys(session: Session, *, include_planned: bool = True) -> set[str]:
"""
Read all live seed, original/converted message, and loose scorer-media references.

Media planned by a scenario run that hasn't completed counts too, so deleting a dataset
doesn't remove files a paused run still needs to resume.

Args:
session (Session): The session to read in.
include_planned (bool): Whether to include media planned by runs that haven't completed.

Returns:
set[str]: Canonical identities of the referenced media.
"""
Expand All @@ -266,7 +284,32 @@ def stored_media_keys(session: Session) -> set[str]:
(PromptMemoryEntry.converted_value, PromptMemoryEntry.converted_value_data_type),
):
values.extend(session.scalars(select(value_column).where(type_column.in_(MEDIA_PATH_DATA_TYPES))).all())
return _media_keys(session, [value for value in values if value])
keys = _media_keys(session, [value for value in values if value])
return keys | set(planned_media_key_counts(session)) if include_planned else keys


def planned_media_key_counts(session: Session) -> Counter[str]:
"""
Count the planned seed groups of runs that haven't completed that reference each media key.

Args:
session (Session): The session to read in.

Returns:
Counter[str]: The number of planned groups referencing each canonical media identity.
"""
planned = (
select(ScenarioPlanSeedGroupEntry.seed_group)
.join(ScenarioResultEntry, ScenarioResultEntry.id == ScenarioPlanSeedGroupEntry.scenario_result_id)
.where(
ScenarioPlanSeedGroupEntry.has_media,
ScenarioResultEntry.scenario_run_state != ScenarioRunState.COMPLETED.value,
)
)
with session.no_autoflush:
groups = [{value for value in planned_media_values(group) if value} for group in session.scalars(planned)]
keys = _media_key_map(session, values=sorted(set().union(*groups)))
return Counter(key for values in groups for key in {keys[value] for value in values})


def reserved_seed_state(session: Session) -> dict[uuid.UUID, tuple[object, ...]]:
Expand All @@ -288,22 +331,31 @@ def reserved_seed_state(session: Session) -> dict[uuid.UUID, tuple[object, ...]]


def validate_stored_dataset_references(
session: Session, *, reserved_seeds: dict[uuid.UUID, tuple[object, ...]] | None = None
session: Session,
*,
reserved_seeds: dict[uuid.UUID, tuple[object, ...]] | None = None,
planned_before: Counter[str] | None = None,
) -> None:
"""
Validate bulk writes without refreshing or discarding pending ORM changes.

Args:
session (Session): The session that ran the bulk write.
reserved_seeds (dict[uuid.UUID, tuple[object, ...]] | None): Protected seed rows read before the write.
planned_before (Counter[str] | None): Planned media references read before a planned seed group
write. Only references the write added are checked; a run's older plan can name media
deleted while it was completed, and that must not block other writes.

Raises:
DatasetNameConflictError: If bulk DML changed a protected seed population.
"""
with session.no_autoflush:
if reserved_seeds is not None and reserved_seed_state(session) != reserved_seeds:
raise DatasetNameConflictError("The dataset name is reserved by an upload.")
_validate_dataset_references(
session=session,
dataset_names=set(),
keys=stored_media_keys(session),
)
keys = stored_media_keys(session, include_planned=False)
if planned_before is not None:
keys |= {key for key, count in planned_media_key_counts(session).items() if count > planned_before[key]}
_validate_dataset_references(session=session, dataset_names=set(), keys=keys)


async def _finish_storage_write_async(write: Awaitable[None]) -> None:
Expand Down
5 changes: 5 additions & 0 deletions pyrit/memory/memory_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -8171,8 +8171,13 @@ def _execute_add_scenario_results_to_memory(
(name, group) for name, groups in population.items() for group in groups
)
]
from pyrit.memory.dataset_lifecycle import entry_references_dataset_assets, lock_dataset_lifecycle

with closing(self._get_session()) as session:
try:
if any(entry_references_dataset_assets(entry) for entry in plan_entries):
# Cleanup holds this lock while it reads runs, so take it before inserting one.
lock_dataset_lifecycle(session)
for scenario_result in scenario_results:
self._persist_scenario_identifier(
session=session,
Expand Down
35 changes: 35 additions & 0 deletions pyrit/memory/memory_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
from pyrit.memory.analytics_identity_v1 import ObjectiveTargetAnalyticsIdentityV1
from pyrit.memory.analytics_sql import ResolvedAttackIdentifierHash
from pyrit.models import (
MEDIA_PATH_DATA_TYPES,
SEED_RESPONSE_JSON_SCHEMA_METADATA_KEY,
AtomicAttackEvaluationIdentifier,
AtomicAttackIdentifier,
Expand Down Expand Up @@ -2825,6 +2826,36 @@ def __str__(self) -> str:
return f"ScenarioResultEntry: {self.scenario_name} (version {self.scenario_version})"


SIMULATED_CONVERSATION_PROMPT_FIELDS = (
"adversarial_chat_system_prompt",
"simulated_target_system_prompt",
"next_message_system_prompt",
)


def planned_media_values(seed_group: dict[str, Any]) -> list[str]:
"""
Return the media paths a stored planned seed group references.

Args:
seed_group (dict[str, Any]): A ``ScenarioPlanSeedGroupEntry.seed_group`` value.

Returns:
list[str]: The media paths, in seed order.
"""
values: list[str] = []
for seed in seed_group.get("seeds", []):
prompts = [seed]
if seed.get("seed_type") == "simulated_conversation":
prompts = [seed.get(field) for field in SIMULATED_CONVERSATION_PROMPT_FIELDS]
values.extend(
prompt["value"]
for prompt in prompts
if isinstance(prompt, dict) and prompt.get("data_type") in MEDIA_PATH_DATA_TYPES
)
return values


class ScenarioPlanSeedGroupEntry(Base):
"""
One seed group a scenario run planned, stored when the run is created.
Expand All @@ -2837,6 +2868,7 @@ class ScenarioPlanSeedGroupEntry(Base):
__tablename__ = "ScenarioPlanSeedGroupEntries"
__table_args__ = (
Index("ix_ScenarioPlanSeedGroupEntries_scenario_result_id_position", "scenario_result_id", "position"),
Index("ix_ScenarioPlanSeedGroupEntries_has_media", "has_media"),
)

id: Mapped[uuid.UUID] = mapped_column(CustomUUID, primary_key=True)
Expand All @@ -2849,6 +2881,8 @@ class ScenarioPlanSeedGroupEntry(Base):
position: Mapped[int] = mapped_column(INTEGER, nullable=False)
#: The ``AttackSeedGroup`` as JSON.
seed_group: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
#: Whether ``seed_group`` references media files, so media cleanup reads only these rows.
has_media: Mapped[bool] = mapped_column(Boolean, nullable=False)

def __init__(
self, *, scenario_result_id: uuid.UUID, dataset_name: str, position: int, seed_group: AttackSeedGroup
Expand All @@ -2867,6 +2901,7 @@ def __init__(
self.dataset_name = dataset_name
self.position = position
self.seed_group = seed_group.model_dump(mode="json")
self.has_media = bool(planned_media_values(self.seed_group))

def get_seed_group(self) -> AttackSeedGroup:
"""
Expand Down
14 changes: 10 additions & 4 deletions pyrit/memory/memory_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
ObservationEntry,
ObservationMessagePieceEntry,
PromptMemoryEntry,
ScenarioPlanSeedGroupEntry,
ScorableContentEntry,
ScoreEntry,
ScoreObservationEntry,
Expand Down Expand Up @@ -78,7 +79,7 @@ def flush(self, objects: Sequence[Any] | None = None) -> None:
writes = [
entry
for entry in self.new | self.dirty | self.deleted
if isinstance(entry, (SeedEntry, PromptMemoryEntry, ScorableContentEntry))
if isinstance(entry, (SeedEntry, PromptMemoryEntry, ScorableContentEntry, ScenarioPlanSeedGroupEntry))
]
if writes:
from pyrit.memory.dataset_lifecycle import (
Expand All @@ -87,8 +88,8 @@ def flush(self, objects: Sequence[Any] | None = None) -> None:
validate_dataset_reference_writes,
)

# Only seeds and media-bearing rows can reference dataset assets. Text-only message
# writes skip the global lifecycle lock so concurrent conversations are not serialized.
# Only seeds and media-bearing rows, including planned seed groups, can reference dataset assets.
# Text-only message writes skip the global lifecycle lock so concurrent conversations are not serialized.
references = [entry for entry in writes if entry_references_dataset_assets(entry)]
if references:
lock_dataset_lifecycle(self)
Expand Down Expand Up @@ -194,10 +195,12 @@ def _guard_bulk_media_writes(state: ORMExecuteState) -> Any:
SeedEntry.__tablename__,
PromptMemoryEntry.__tablename__,
ScorableContentEntry.__tablename__,
ScenarioPlanSeedGroupEntry.__tablename__,
}:
return state.invoke_statement()
from pyrit.memory.dataset_lifecycle import (
lock_dataset_lifecycle,
planned_media_key_counts,
reserved_seed_state,
validate_stored_dataset_references,
)
Expand All @@ -207,6 +210,9 @@ def _guard_bulk_media_writes(state: ORMExecuteState) -> Any:
return state.invoke_statement()
with state.session.begin_nested():
reserved_seeds = reserved_seed_state(state.session) if table_name == SeedEntry.__tablename__ else None
planned_before = (
planned_media_key_counts(state.session) if table_name == ScenarioPlanSeedGroupEntry.__tablename__ else None
)
result = state.invoke_statement()
validate_stored_dataset_references(state.session, reserved_seeds=reserved_seeds)
validate_stored_dataset_references(state.session, reserved_seeds=reserved_seeds, planned_before=planned_before)
return result
Loading
Loading