diff --git a/doc/api.rst b/doc/api.rst index 8cc7a73ce..48de65a5e 100644 --- a/doc/api.rst +++ b/doc/api.rst @@ -338,6 +338,7 @@ API Reference ChatMessageListDictContent construct_response_from_request ConversationReference + ConversationStats ConversationType DataTypeSerializer data_serializer_factory diff --git a/pyrit/backend/models/attacks.py b/pyrit/backend/models/attacks.py index 9183d933c..fb40e0656 100644 --- a/pyrit/backend/models/attacks.py +++ b/pyrit/backend/models/attacks.py @@ -117,18 +117,16 @@ class AttackListResponse(BaseModel): class AttackOptionsResponse(BaseModel): - """Response containing unique attack class names used across attacks.""" + """Response containing unique attack type names used across attacks.""" - attack_classes: list[str] = Field( - ..., description="Sorted list of unique attack class names found in attack results" - ) + attack_types: list[str] = Field(..., description="Sorted list of unique attack type names found in attack results") class ConverterOptionsResponse(BaseModel): - """Response containing unique converter class names used across attacks.""" + """Response containing unique converter type names used across attacks.""" - converter_classes: list[str] = Field( - ..., description="Sorted list of unique converter class names found in attack results" + converter_types: list[str] = Field( + ..., description="Sorted list of unique converter type names found in attack results" ) diff --git a/pyrit/backend/routes/attacks.py b/pyrit/backend/routes/attacks.py index ed6fc4c02..6c08400e4 100644 --- a/pyrit/backend/routes/attacks.py +++ b/pyrit/backend/routes/attacks.py @@ -52,10 +52,10 @@ def _parse_labels(label_params: Optional[list[str]]) -> Optional[dict[str, str]] response_model=AttackListResponse, ) async def list_attacks( - attack_class: Optional[str] = Query(None, description="Filter by exact attack class name"), - converter_classes: Optional[list[str]] = Query( + attack_type: Optional[str] = Query(None, description="Filter by exact attack type name"), + converter_types: Optional[list[str]] = Query( None, - description="Filter by converter class names (repeatable, AND logic). Pass empty to match no-converter attacks.", + description="Filter by converter type names (repeatable, AND logic). Pass empty to match no-converter attacks.", ), outcome: Optional[Literal["undetermined", "success", "failure"]] = Query(None, description="Filter by outcome"), label: Optional[list[str]] = Query(None, description="Filter by labels (format: key:value, repeatable)"), @@ -76,8 +76,8 @@ async def list_attacks( service = get_attack_service() labels = _parse_labels(label) return await service.list_attacks_async( - attack_class=attack_class, - converter_classes=converter_classes, + attack_type=attack_type, + converter_types=converter_types, outcome=outcome, labels=labels, min_turns=min_turns, @@ -93,17 +93,17 @@ async def list_attacks( ) async def get_attack_options() -> AttackOptionsResponse: """ - Get unique attack class names used across all attacks. + Get unique attack type names used across all attacks. - Returns all attack class names found in stored attack results. + Returns all attack type names found in stored attack results. Useful for populating attack type filter dropdowns in the GUI. Returns: - AttackOptionsResponse: Sorted list of unique attack class names. + AttackOptionsResponse: Sorted list of unique attack type names. """ service = get_attack_service() class_names = await service.get_attack_options_async() - return AttackOptionsResponse(attack_classes=class_names) + return AttackOptionsResponse(attack_types=class_names) @router.get( @@ -112,17 +112,17 @@ async def get_attack_options() -> AttackOptionsResponse: ) async def get_converter_options() -> ConverterOptionsResponse: """ - Get unique converter class names used across all attacks. + Get unique converter type names used across all attacks. - Returns all converter class names found in stored attack results. + Returns all converter type names found in stored attack results. Useful for populating converter filter dropdowns in the GUI. Returns: - ConverterOptionsResponse: Sorted list of unique converter class names. + ConverterOptionsResponse: Sorted list of unique converter type names. """ service = get_attack_service() class_names = await service.get_converter_options_async() - return ConverterOptionsResponse(converter_classes=class_names) + return ConverterOptionsResponse(converter_types=class_names) @router.post( diff --git a/pyrit/backend/services/attack_service.py b/pyrit/backend/services/attack_service.py index 652cafee5..badc3ffe0 100644 --- a/pyrit/backend/services/attack_service.py +++ b/pyrit/backend/services/attack_service.py @@ -63,8 +63,8 @@ def __init__(self) -> None: async def list_attacks_async( self, *, - attack_class: Optional[str] = None, - converter_classes: Optional[list[str]] = None, + attack_type: Optional[str] = None, + converter_types: Optional[list[str]] = None, outcome: Optional[Literal["undetermined", "success", "failure"]] = None, labels: Optional[dict[str, str]] = None, min_turns: Optional[int] = None, @@ -78,8 +78,8 @@ async def list_attacks_async( Queries AttackResult entries from the database. Args: - attack_class: Filter by exact attack class_name (case-sensitive). - converter_classes: Filter by converter usage. + attack_type: Filter by exact attack class_name (case-sensitive). + converter_types: Filter by converter usage. None = no filter, [] = only attacks with no converters, ["A", "B"] = only attacks using ALL specified converters (AND logic, case-insensitive). outcome: Filter by attack outcome. @@ -96,8 +96,8 @@ async def list_attacks_async( attack_results = self._memory.get_attack_results( outcome=outcome, labels=labels, - attack_class=attack_class, - converter_classes=converter_classes, + attack_class=attack_type, + converter_classes=converter_types, ) filtered: list[AttackResult] = [] diff --git a/pyrit/memory/azure_sql_memory.py b/pyrit/memory/azure_sql_memory.py index 6702f2240..c7e6235ee 100644 --- a/pyrit/memory/azure_sql_memory.py +++ b/pyrit/memory/azure_sql_memory.py @@ -1,10 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import json import logging import struct from collections.abc import MutableSequence, Sequence -from contextlib import closing +from contextlib import closing, suppress from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Optional, TypeVar, Union @@ -27,6 +28,7 @@ ) from pyrit.models import ( AzureBlobStorageIO, + ConversationStats, MessagePiece, ) @@ -388,7 +390,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: """ - Azure SQL implementation for filtering AttackResults by attack type. + Azure SQL implementation for filtering AttackResults by attack class. Uses JSON_VALUE() to match class_name in the attack_identifier JSON column. Args: @@ -402,7 +404,7 @@ def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any AND JSON_VALUE("AttackResultEntries".attack_identifier, '$.class_name') = :attack_class""" ).bindparams(attack_class=attack_class) - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_classes_condition(self, *, converter_classes: Sequence[str]) -> Any: """ Azure SQL implementation for filtering AttackResults by converter classes. @@ -481,6 +483,86 @@ def get_unique_converter_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: + """ + Azure SQL implementation: lightweight aggregate stats per conversation. + + Executes a single SQL query that returns message count (distinct + sequences), a truncated last-message preview, the first non-empty + labels dict, and the earliest timestamp for each conversation_id. + + Args: + conversation_ids (Sequence[str]): The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + """ + if not conversation_ids: + return {} + + placeholders = ", ".join(f":cid{i}" for i in range(len(conversation_ids))) + params = {f"cid{i}": cid for i, cid in enumerate(conversation_ids)} + + max_len = ConversationStats.PREVIEW_MAX_LEN + sql = text( + f""" + SELECT + pme.conversation_id, + COUNT(DISTINCT pme.sequence) AS msg_count, + ( + SELECT TOP 1 LEFT(p2.converted_value, {max_len + 3}) + FROM "PromptMemoryEntries" p2 + WHERE p2.conversation_id = pme.conversation_id + ORDER BY p2.sequence DESC, p2.id DESC + ) AS last_preview, + ( + SELECT TOP 1 p3.labels + FROM "PromptMemoryEntries" p3 + WHERE p3.conversation_id = pme.conversation_id + AND p3.labels IS NOT NULL + AND p3.labels != '{{}}' + AND p3.labels != 'null' + ORDER BY p3.sequence ASC, p3.id ASC + ) AS first_labels, + MIN(pme.timestamp) AS created_at + FROM "PromptMemoryEntries" pme + WHERE pme.conversation_id IN ({placeholders}) + GROUP BY pme.conversation_id + """ + ) + + with closing(self.get_session()) as session: + rows = session.execute(sql, params).fetchall() + + result: dict[str, ConversationStats] = {} + for row in rows: + conv_id, msg_count, last_preview, raw_labels, raw_created_at = row + + preview = None + if last_preview: + preview = last_preview[:max_len] + "..." if len(last_preview) > max_len else last_preview + + labels: dict[str, str] = {} + if raw_labels and raw_labels not in ("null", "{}"): + with suppress(ValueError, TypeError): + labels = json.loads(raw_labels) + + created_at = None + if raw_created_at is not None: + if isinstance(raw_created_at, str): + created_at = datetime.fromisoformat(raw_created_at) + else: + created_at = raw_created_at + + result[conv_id] = ConversationStats( + message_count=msg_count, + last_message_preview=preview, + labels=labels, + created_at=created_at, + ) + + return result + def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ Get the SQL Azure implementation for filtering ScenarioResults by labels. @@ -673,8 +755,14 @@ def _update_entries(self, *, entries: MutableSequence[Base], update_fields: dict with closing(self.get_session()) as session: try: for entry in entries: - # Ensure the entry is attached to the session. If it's detached, merge it. - entry_in_session = session.merge(entry) if not session.is_modified(entry) else entry + # Load a fresh copy by primary key so we only touch the + # requested fields. Using merge() would copy ALL + # attributes from the (potentially stale) detached object + # and silently overwrite concurrent updates to columns + # that are NOT in update_fields. + entry_in_session = session.get(type(entry), entry.id) # type: ignore[attr-defined] + if entry_in_session is None: + entry_in_session = session.merge(entry) for field, value in update_fields.items(): if field in vars(entry_in_session): setattr(entry_in_session, field, value) diff --git a/pyrit/memory/memory_interface.py b/pyrit/memory/memory_interface.py index 67e6dcfb6..e66e239e8 100644 --- a/pyrit/memory/memory_interface.py +++ b/pyrit/memory/memory_interface.py @@ -15,6 +15,7 @@ from sqlalchemy import MetaData, and_, or_ from sqlalchemy.engine.base import Engine +from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm.attributes import InstrumentedAttribute from pyrit.common.path import DB_DATA_PATH @@ -34,6 +35,7 @@ ) from pyrit.models import ( AttackResult, + ConversationStats, DataTypeSerializer, Message, MessagePiece, @@ -242,8 +244,6 @@ def _update_entry(self, entry: Base) -> None: Raises: SQLAlchemyError: If there's an error during the database operation. """ - from sqlalchemy.exc import SQLAlchemyError - with closing(self.get_session()) as session: try: session.merge(entry) @@ -292,7 +292,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: @abc.abstractmethod def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: """ - Return a database-specific condition for filtering AttackResults by attack type + Return a database-specific condition for filtering AttackResults by attack class (class_name in the attack_identifier JSON column). Args: @@ -303,7 +303,7 @@ def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any """ @abc.abstractmethod - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_classes_condition(self, *, converter_classes: Sequence[str]) -> Any: """ Return a database-specific condition for filtering AttackResults by converter classes in the request_converter_identifiers array within attack_identifier JSON column. @@ -347,6 +347,24 @@ def get_unique_converter_class_names(self) -> list[str]: Sorted list of unique converter class name strings. """ + @abc.abstractmethod + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, "ConversationStats"]: + """ + Return lightweight aggregate statistics for one or more conversations. + + Computes per-conversation message count (distinct sequence numbers), + a truncated last-message preview, the first non-empty labels dict, + and the earliest message timestamp using efficient SQL aggregation + instead of loading full pieces. + + Args: + conversation_ids: The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + Conversations with no pieces are omitted from the result. + """ + @abc.abstractmethod def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ @@ -631,15 +649,18 @@ def get_message_pieces( logger.exception(f"Failed to retrieve prompts with error {e}") raise - def _duplicate_conversation(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: + def duplicate_messages(self, *, messages: Sequence[Message]) -> tuple[str, Sequence[MessagePiece]]: """ - Duplicate messages with new conversation ID. + Duplicate messages with a new conversation ID. + + Each duplicated piece gets a fresh ``id`` and ``timestamp`` while + preserving ``original_prompt_id`` for tracking lineage. Args: - messages (Sequence[Message]): The messages to duplicate. + messages: The messages to duplicate. Returns: - tuple[str, Sequence[MessagePiece]]: The new conversation ID and the duplicated message pieces. + Tuple of (new_conversation_id, duplicated_message_pieces). """ new_conversation_id = str(uuid.uuid4()) @@ -669,7 +690,7 @@ def duplicate_conversation(self, *, conversation_id: str) -> str: The uuid for the new conversation. """ messages = self.get_conversation(conversation_id=conversation_id) - new_conversation_id, all_pieces = self._duplicate_conversation(messages=messages) + new_conversation_id, all_pieces = self.duplicate_messages(messages=messages) self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id @@ -702,7 +723,7 @@ def duplicate_conversation_excluding_last_turn(self, *, conversation_id: str) -> message for message in messages if message.sequence <= last_message.sequence - length_of_sequence_to_remove ] - new_conversation_id, all_pieces = self._duplicate_conversation(messages=messages_to_duplicate) + new_conversation_id, all_pieces = self.duplicate_messages(messages=messages_to_duplicate) self.add_message_pieces_to_memory(message_pieces=all_pieces) return new_conversation_id @@ -1256,8 +1277,86 @@ def add_attack_results_to_memory(self, *, attack_results: Sequence[AttackResult] """ Insert a list of attack results into the memory storage. The database model automatically calculates objective_sha256 for consistency. + + Raises: + SQLAlchemyError: If the database transaction fails. + """ + entries = [AttackResultEntry(entry=attack_result) for attack_result in attack_results] + with closing(self.get_session()) as session: + try: + session.add_all(entries) + session.commit() + # Populate the attack_result_id back onto the domain objects so callers + # can reference the DB-assigned ID immediately after insert. + for ar, entry in zip(attack_results, entries, strict=False): + ar.attack_result_id = str(entry.id) + except SQLAlchemyError: + session.rollback() + raise + + def update_attack_result(self, *, conversation_id: str, update_fields: dict[str, Any]) -> bool: """ - self._insert_entries(entries=[AttackResultEntry(entry=attack_result) for attack_result in attack_results]) + Update specific fields of an existing AttackResultEntry identified by conversation_id. + + This method queries for the raw database entry by conversation_id and updates + the specified fields in place, avoiding the creation of duplicate rows. + + Args: + conversation_id (str): The conversation ID of the attack result to update. + update_fields (dict[str, Any]): A dictionary of column names to new values. + Valid fields include 'adversarial_chat_conversation_ids', + 'pruned_conversation_ids', 'outcome', 'attack_metadata', etc. + + Returns: + bool: True if the update was successful, False if the entry was not found. + + Raises: + ValueError: If update_fields is empty. + """ + if not update_fields: + raise ValueError("update_fields must not be empty") + + entries: MutableSequence[AttackResultEntry] = self._query_entries( + AttackResultEntry, + conditions=AttackResultEntry.conversation_id == conversation_id, + ) + if not entries: + return False + + # When duplicate rows exist for the same conversation_id (legacy bug), + # pick the newest entry — it has the most up-to-date data. + target_entry = max(entries, key=lambda e: e.timestamp) + self._update_entries(entries=[target_entry], update_fields=update_fields) + return True + + def update_attack_result_by_id(self, *, attack_result_id: str, update_fields: dict[str, Any]) -> bool: + """ + Update specific fields of an existing AttackResultEntry identified by its primary key. + + Args: + attack_result_id: The UUID primary key of the AttackResultEntry. + update_fields: Column names to new values. + + Returns: + True if the update was successful, False if the entry was not found. + """ + try: + attack_result_uuid = uuid.UUID(attack_result_id) + except (ValueError, TypeError): + logger.warning( + "Invalid attack_result_id '%s' passed to update_attack_result_by_id", + attack_result_id, + ) + return False + + entries: MutableSequence[AttackResultEntry] = self._query_entries( + AttackResultEntry, + conditions=AttackResultEntry.id == attack_result_uuid, + ) + if not entries: + return False + self._update_entries(entries=[entries[0]], update_fields=update_fields) + return True def get_attack_results( self, @@ -1326,7 +1425,7 @@ def get_attack_results( if converter_classes is not None: # converter_classes=[] means "only attacks with no converters" # converter_classes=["A","B"] means "must have all listed converters" - conditions.append(self._get_attack_result_converter_condition(converter_classes=converter_classes)) + conditions.append(self._get_attack_result_converter_classes_condition(converter_classes=converter_classes)) if targeted_harm_categories: # Use database-specific JSON query method @@ -1342,7 +1441,14 @@ def get_attack_results( entries: Sequence[AttackResultEntry] = self._query_entries( AttackResultEntry, conditions=and_(*conditions) if conditions else None ) - return [entry.get_attack_result() for entry in entries] + # Deduplicate by conversation_id — when duplicate rows exist + # (legacy bug), keep only the newest entry per conversation_id. + seen: dict[str, AttackResultEntry] = {} + for entry in entries: + prev = seen.get(entry.conversation_id) + if prev is None or entry.timestamp > prev.timestamp: + seen[entry.conversation_id] = entry + return [entry.get_attack_result() for entry in seen.values()] except Exception as e: logger.exception(f"Failed to retrieve attack results with error {e}") raise diff --git a/pyrit/memory/memory_models.py b/pyrit/memory/memory_models.py index 04be633df..50ed0fb87 100644 --- a/pyrit/memory/memory_models.py +++ b/pyrit/memory/memory_models.py @@ -852,6 +852,7 @@ def get_attack_result(self) -> AttackResult: return AttackResult( conversation_id=self.conversation_id, + attack_result_id=str(self.id), objective=self.objective, attack_identifier=ComponentIdentifier.from_dict(self.attack_identifier) if self.attack_identifier else None, last_response=self.last_response.get_message_piece() if self.last_response else None, diff --git a/pyrit/memory/sqlite_memory.py b/pyrit/memory/sqlite_memory.py index cfce238fd..552953771 100644 --- a/pyrit/memory/sqlite_memory.py +++ b/pyrit/memory/sqlite_memory.py @@ -1,10 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. +import json import logging import uuid from collections.abc import MutableSequence, Sequence -from contextlib import closing +from contextlib import closing, suppress from datetime import datetime from pathlib import Path from typing import Any, Optional, TypeVar, Union @@ -24,8 +25,9 @@ Base, EmbeddingDataEntry, PromptMemoryEntry, + ScenarioResultEntry, ) -from pyrit.models import DiskStorageIO, MessagePiece +from pyrit.models import ConversationStats, DiskStorageIO, MessagePiece logger = logging.getLogger(__name__) @@ -298,8 +300,14 @@ def _update_entries(self, *, entries: MutableSequence[Base], update_fields: dict with closing(self.get_session()) as session: try: for entry in entries: - # Ensure the entry is attached to the session. If it's detached, merge it. - entry_in_session = session.merge(entry) if not session.is_modified(entry) else entry + # Load a fresh copy by primary key so we only touch the + # requested fields. Using merge() would copy ALL + # attributes from the (potentially stale) detached object + # and silently overwrite concurrent updates to columns + # that are NOT in update_fields. + entry_in_session = session.get(type(entry), entry.id) # type: ignore[attr-defined] + if entry_in_session is None: + entry_in_session = session.merge(entry) for field, value in update_fields.items(): if field in vars(entry_in_session): setattr(entry_in_session, field, value) @@ -412,8 +420,6 @@ def export_conversations( # Export to JSON manually since the exporter expects objects but we have dicts with open(file_path, "w") as f: - import json - json.dump(merged_data, f, indent=4) return file_path @@ -462,7 +468,7 @@ def _get_attack_result_harm_category_condition(self, *, targeted_harm_categories from pyrit.memory.memory_models import AttackResultEntry, PromptMemoryEntry - return exists().where( + targeted_harm_categories_subquery = exists().where( and_( PromptMemoryEntry.conversation_id == AttackResultEntry.conversation_id, # Exclude empty strings, None, and empty lists @@ -477,6 +483,7 @@ def _get_attack_result_harm_category_condition(self, *, targeted_harm_categories ), ) ) + return targeted_harm_categories_subquery # noqa: RET504 def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ @@ -490,7 +497,7 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: from pyrit.memory.memory_models import AttackResultEntry, PromptMemoryEntry - return exists().where( + labels_subquery = exists().where( and_( PromptMemoryEntry.conversation_id == AttackResultEntry.conversation_id, PromptMemoryEntry.labels.isnot(None), @@ -499,18 +506,19 @@ def _get_attack_result_label_condition(self, *, labels: dict[str, str]) -> Any: ), ) ) + return labels_subquery # noqa: RET504 def _get_attack_result_attack_class_condition(self, *, attack_class: str) -> Any: """ - SQLite implementation for filtering AttackResults by attack type. + SQLite implementation for filtering AttackResults by attack class. Uses json_extract() to match class_name in the attack_identifier JSON column. Returns: - Any: A SQLAlchemy condition for filtering by attack type. + Any: A SQLAlchemy condition for filtering by attack class. """ return func.json_extract(AttackResultEntry.attack_identifier, "$.class_name") == attack_class - def _get_attack_result_converter_condition(self, *, converter_classes: Sequence[str]) -> Any: + def _get_attack_result_converter_classes_condition(self, *, converter_classes: Sequence[str]) -> Any: """ SQLite implementation for filtering AttackResults by converter classes. @@ -581,6 +589,88 @@ def get_unique_converter_class_names(self) -> list[str]: ).fetchall() return sorted(row[0] for row in rows) + def get_conversation_stats(self, *, conversation_ids: Sequence[str]) -> dict[str, ConversationStats]: + """ + SQLite implementation: lightweight aggregate stats per conversation. + + Executes a single SQL query that returns message count (distinct + sequences), a truncated last-message preview, the first non-empty + labels dict, and the earliest timestamp for each conversation_id. + + Args: + conversation_ids: The conversation IDs to query. + + Returns: + Mapping from conversation_id to ConversationStats. + """ + if not conversation_ids: + return {} + + placeholders = ", ".join(f":cid{i}" for i in range(len(conversation_ids))) + params = {f"cid{i}": cid for i, cid in enumerate(conversation_ids)} + + max_len = ConversationStats.PREVIEW_MAX_LEN + sql = text( + f""" + SELECT + pme.conversation_id, + COUNT(DISTINCT pme.sequence) AS msg_count, + ( + SELECT SUBSTR(p2.converted_value, 1, {max_len + 3}) + FROM "PromptMemoryEntries" p2 + WHERE p2.conversation_id = pme.conversation_id + ORDER BY p2.sequence DESC, p2.id DESC + LIMIT 1 + ) AS last_preview, + ( + SELECT p3.labels + FROM "PromptMemoryEntries" p3 + WHERE p3.conversation_id = pme.conversation_id + AND p3.labels IS NOT NULL + AND p3.labels != '{{}}' + AND p3.labels != 'null' + ORDER BY p3.sequence ASC, p3.id ASC + LIMIT 1 + ) AS first_labels, + MIN(pme.timestamp) AS created_at + FROM "PromptMemoryEntries" pme + WHERE pme.conversation_id IN ({placeholders}) + GROUP BY pme.conversation_id + """ + ) + + with closing(self.get_session()) as session: + rows = session.execute(sql, params).fetchall() + + result: dict[str, ConversationStats] = {} + for row in rows: + conv_id, msg_count, last_preview, raw_labels, raw_created_at = row + + preview = None + if last_preview: + preview = last_preview[:max_len] + "..." if len(last_preview) > max_len else last_preview + + labels: dict[str, str] = {} + if raw_labels and raw_labels not in ("null", "{}"): + with suppress(ValueError, TypeError): + labels = json.loads(raw_labels) + + created_at = None + if raw_created_at is not None: + if isinstance(raw_created_at, str): + created_at = datetime.fromisoformat(raw_created_at) + else: + created_at = raw_created_at + + result[conv_id] = ConversationStats( + message_count=msg_count, + last_message_preview=preview, + labels=labels, + created_at=created_at, + ) + + return result + def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any: """ SQLite implementation for filtering ScenarioResults by labels. @@ -589,11 +679,6 @@ def _get_scenario_result_label_condition(self, *, labels: dict[str, str]) -> Any Returns: Any: A SQLAlchemy exists subquery condition. """ - from sqlalchemy import and_, func - - from pyrit.memory.memory_models import ScenarioResultEntry - - # Return a combined condition that checks ALL labels must be present return and_( *[func.json_extract(ScenarioResultEntry.labels, f"$.{key}") == value for key, value in labels.items()] ) @@ -606,10 +691,6 @@ def _get_scenario_result_target_endpoint_condition(self, *, endpoint: str) -> An Returns: Any: A SQLAlchemy subquery for filtering by target endpoint. """ - from sqlalchemy import func - - from pyrit.memory.memory_models import ScenarioResultEntry - return func.lower(func.json_extract(ScenarioResultEntry.objective_target_identifier, "$.endpoint")).like( f"%{endpoint.lower()}%" ) @@ -622,10 +703,6 @@ def _get_scenario_result_target_model_condition(self, *, model_name: str) -> Any Returns: Any: A SQLAlchemy subquery for filtering by target model name. """ - from sqlalchemy import func - - from pyrit.memory.memory_models import ScenarioResultEntry - return func.lower(func.json_extract(ScenarioResultEntry.objective_target_identifier, "$.model_name")).like( f"%{model_name.lower()}%" ) diff --git a/pyrit/models/__init__.py b/pyrit/models/__init__.py index 6f6734cb8..26eeae2d1 100644 --- a/pyrit/models/__init__.py +++ b/pyrit/models/__init__.py @@ -11,6 +11,7 @@ ChatMessagesDataset, ) from pyrit.models.conversation_reference import ConversationReference, ConversationType +from pyrit.models.conversation_stats import ConversationStats from pyrit.models.data_type_serializer import ( AllowedCategories, AudioPathDataTypeSerializer, @@ -70,6 +71,7 @@ "ChatMessageRole", "ChatMessageListDictContent", "ConversationReference", + "ConversationStats", "ConversationType", "construct_response_from_request", "DataTypeSerializer", diff --git a/pyrit/models/attack_result.py b/pyrit/models/attack_result.py index cd9efff5c..499e3f6de 100644 --- a/pyrit/models/attack_result.py +++ b/pyrit/models/attack_result.py @@ -47,6 +47,10 @@ class AttackResult(StrategyResult): # Natural-language description of the attacker's objective objective: str + # Database-assigned unique ID for this AttackResult row. + # ``None`` for newly-constructed results that haven't been persisted yet. + attack_result_id: Optional[str] = None + # Identifier of the attack strategy that produced this result attack_identifier: Optional[ComponentIdentifier] = None diff --git a/pyrit/models/conversation_stats.py b/pyrit/models/conversation_stats.py new file mode 100644 index 000000000..bb8283fcc --- /dev/null +++ b/pyrit/models/conversation_stats.py @@ -0,0 +1,26 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, ClassVar, Optional + +if TYPE_CHECKING: + from datetime import datetime + + +@dataclass(frozen=True) +class ConversationStats: + """ + Lightweight aggregate statistics for a conversation. + + Used to build attack summaries without loading full message pieces. + """ + + PREVIEW_MAX_LEN: ClassVar[int] = 100 + + message_count: int = 0 + last_message_preview: Optional[str] = None + labels: dict[str, str] = field(default_factory=dict) + created_at: Optional[datetime] = None diff --git a/pyrit/prompt_target/openai/openai_image_target.py b/pyrit/prompt_target/openai/openai_image_target.py index 1c65ed603..ebdbdfe1a 100644 --- a/pyrit/prompt_target/openai/openai_image_target.py +++ b/pyrit/prompt_target/openai/openai_image_target.py @@ -314,6 +314,16 @@ def _validate_request(self, *, message: Message) -> None: other_types = [p.converted_value_data_type for p in other_pieces] raise ValueError(f"The message contains unsupported piece types. Unsupported types: {other_types}.") + request = text_pieces[0] + messages = self._memory.get_conversation(conversation_id=request.conversation_id) + + n_messages = len(messages) + if n_messages > 0: + raise ValueError( + "This target only supports a single turn conversation. " + f"Received: {n_messages} messages which indicates a prior turn." + ) + def is_json_response_supported(self) -> bool: """ Check if the target supports JSON as a response format. diff --git a/pyrit/prompt_target/openai/openai_realtime_target.py b/pyrit/prompt_target/openai/openai_realtime_target.py index 774eeb773..c57de2156 100644 --- a/pyrit/prompt_target/openai/openai_realtime_target.py +++ b/pyrit/prompt_target/openai/openai_realtime_target.py @@ -21,6 +21,7 @@ construct_response_from_request, data_serializer_factory, ) +from pyrit.prompt_target.common.prompt_chat_target import PromptChatTarget from pyrit.prompt_target.common.utils import limit_requests_per_minute from pyrit.prompt_target.openai.openai_target import OpenAITarget @@ -55,7 +56,7 @@ def flatten_transcripts(self) -> str: return "".join(self.transcripts) -class RealtimeTarget(OpenAITarget): +class RealtimeTarget(OpenAITarget, PromptChatTarget): """ A prompt target for Azure OpenAI Realtime API. diff --git a/pyrit/prompt_target/openai/openai_response_target.py b/pyrit/prompt_target/openai/openai_response_target.py index 34ff23b70..01584989e 100644 --- a/pyrit/prompt_target/openai/openai_response_target.py +++ b/pyrit/prompt_target/openai/openai_response_target.py @@ -178,6 +178,7 @@ def _build_identifier(self) -> ComponentIdentifier: "max_output_tokens": self._max_output_tokens, "reasoning_effort": self._reasoning_effort, "reasoning_summary": self._reasoning_summary, + "extra_body_parameters": self._extra_body_parameters, }, ) diff --git a/pyrit/prompt_target/openai/openai_target.py b/pyrit/prompt_target/openai/openai_target.py index bf9c46bf6..e4fb8ecdd 100644 --- a/pyrit/prompt_target/openai/openai_target.py +++ b/pyrit/prompt_target/openai/openai_target.py @@ -29,7 +29,7 @@ handle_bad_request_exception, ) from pyrit.models import Message, MessagePiece -from pyrit.prompt_target.common.prompt_chat_target import PromptChatTarget +from pyrit.prompt_target.common.prompt_target import PromptTarget from pyrit.prompt_target.openai.openai_error_handling import ( _extract_error_payload, _extract_request_id_from_exception, @@ -78,7 +78,7 @@ async def async_token_provider() -> str: return async_token_provider -class OpenAITarget(PromptChatTarget): +class OpenAITarget(PromptTarget): """ Abstract base class for OpenAI-based prompt targets. @@ -159,7 +159,7 @@ def __init__( ) # Initialize parent with endpoint and model_name - PromptChatTarget.__init__( + PromptTarget.__init__( self, max_requests_per_minute=max_requests_per_minute, endpoint=endpoint_value, diff --git a/pyrit/prompt_target/openai/openai_video_target.py b/pyrit/prompt_target/openai/openai_video_target.py index 276bbfc2c..77e3510cf 100644 --- a/pyrit/prompt_target/openai/openai_video_target.py +++ b/pyrit/prompt_target/openai/openai_video_target.py @@ -476,6 +476,15 @@ def _validate_request(self, *, message: Message) -> None: if remix_video_id and image_pieces: raise ValueError("Cannot use image input in remix mode. Remix uses existing video as reference.") + messages = self._memory.get_conversation(conversation_id=text_piece.conversation_id) + + n_messages = len(messages) + if n_messages > 0: + raise ValueError( + "This target only supports a single turn conversation. " + f"Received: {n_messages} messages which indicates a prior turn." + ) + def is_json_response_supported(self) -> bool: """ Check if the target supports JSON response data. diff --git a/tests/unit/backend/test_api_routes.py b/tests/unit/backend/test_api_routes.py index 44ad3f34b..3725dc21c 100644 --- a/tests/unit/backend/test_api_routes.py +++ b/tests/unit/backend/test_api_routes.py @@ -86,13 +86,13 @@ def test_list_attacks_with_filters(self, client: TestClient) -> None: response = client.get( "/api/attacks", - params={"attack_class": "CrescendoAttack", "outcome": "success", "limit": 10}, + params={"attack_type": "CrescendoAttack", "outcome": "success", "limit": 10}, ) assert response.status_code == status.HTTP_200_OK mock_service.list_attacks_async.assert_called_once_with( - attack_class="CrescendoAttack", - converter_classes=None, + attack_type="CrescendoAttack", + converter_types=None, outcome="success", labels=None, min_turns=None, @@ -416,7 +416,7 @@ def test_get_attack_options(self, client: TestClient) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["attack_classes"] == ["CrescendoAttack", "ManualAttack"] + assert data["attack_types"] == ["CrescendoAttack", "ManualAttack"] def test_get_converter_options(self, client: TestClient) -> None: """Test getting converter options from attack results.""" @@ -429,7 +429,7 @@ def test_get_converter_options(self, client: TestClient) -> None: assert response.status_code == status.HTTP_200_OK data = response.json() - assert data["converter_classes"] == ["Base64Converter", "ROT13Converter"] + assert data["converter_types"] == ["Base64Converter", "ROT13Converter"] def test_parse_labels_skips_param_without_colon(self, client: TestClient) -> None: """Test that _parse_labels skips label params that have no colon.""" @@ -486,8 +486,8 @@ def test_parse_labels_value_with_extra_colons(self, client: TestClient) -> None: call_kwargs = mock_service.list_attacks_async.call_args[1] assert call_kwargs["labels"] == {"url": "http://example.com:8080"} - def test_list_attacks_forwards_converter_classes_param(self, client: TestClient) -> None: - """Test that converter_classes query params are forwarded to service.""" + def test_list_attacks_forwards_converter_types_param(self, client: TestClient) -> None: + """Test that converter_types query params are forwarded to service.""" with patch("pyrit.backend.routes.attacks.get_attack_service") as mock_get_service: mock_service = MagicMock() mock_service.list_attacks_async = AsyncMock( @@ -498,11 +498,11 @@ def test_list_attacks_forwards_converter_classes_param(self, client: TestClient) ) mock_get_service.return_value = mock_service - response = client.get("/api/attacks?converter_classes=Base64&converter_classes=ROT13") + response = client.get("/api/attacks?converter_types=Base64&converter_types=ROT13") assert response.status_code == status.HTTP_200_OK call_kwargs = mock_service.list_attacks_async.call_args[1] - assert call_kwargs["converter_classes"] == ["Base64", "ROT13"] + assert call_kwargs["converter_types"] == ["Base64", "ROT13"] # ============================================================================ diff --git a/tests/unit/backend/test_attack_service.py b/tests/unit/backend/test_attack_service.py index e184f8ad4..7ed17497e 100644 --- a/tests/unit/backend/test_attack_service.py +++ b/tests/unit/backend/test_attack_service.py @@ -173,45 +173,45 @@ async def test_list_attacks_returns_attacks(self, attack_service, mock_memory) - assert result.items[0].attack_type == "Test Attack" @pytest.mark.asyncio - async def test_list_attacks_filters_by_attack_class_exact(self, attack_service, mock_memory) -> None: - """Test that list_attacks passes attack_class to memory layer.""" + async def test_list_attacks_filters_by_attack_type_exact(self, attack_service, mock_memory) -> None: + """Test that list_attacks passes attack_type to memory layer as attack_class.""" ar1 = make_attack_result(conversation_id="attack-1", name="CrescendoAttack") mock_memory.get_attack_results.return_value = [ar1] mock_memory.get_message_pieces.return_value = [] - result = await attack_service.list_attacks_async(attack_class="CrescendoAttack") + result = await attack_service.list_attacks_async(attack_type="CrescendoAttack") assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" - # Verify attack_class was forwarded to the memory layer + # Verify attack_type was forwarded to the memory layer as attack_class call_kwargs = mock_memory.get_attack_results.call_args[1] assert call_kwargs["attack_class"] == "CrescendoAttack" @pytest.mark.asyncio - async def test_list_attacks_attack_class_passed_to_memory(self, attack_service, mock_memory) -> None: - """Test that attack_class is forwarded to memory for DB-level filtering.""" + async def test_list_attacks_attack_type_passed_to_memory(self, attack_service, mock_memory) -> None: + """Test that attack_type is forwarded to memory as attack_class for DB-level filtering.""" mock_memory.get_attack_results.return_value = [] mock_memory.get_message_pieces.return_value = [] - await attack_service.list_attacks_async(attack_class="Crescendo") + await attack_service.list_attacks_async(attack_type="Crescendo") call_kwargs = mock_memory.get_attack_results.call_args[1] assert call_kwargs["attack_class"] == "Crescendo" @pytest.mark.asyncio async def test_list_attacks_filters_by_no_converters(self, attack_service, mock_memory) -> None: - """Test that converter_classes=[] is forwarded to memory for DB-level filtering.""" + """Test that converter_types=[] is forwarded to memory for DB-level filtering.""" mock_memory.get_attack_results.return_value = [] mock_memory.get_message_pieces.return_value = [] - await attack_service.list_attacks_async(converter_classes=[]) + await attack_service.list_attacks_async(converter_types=[]) call_kwargs = mock_memory.get_attack_results.call_args[1] assert call_kwargs["converter_classes"] == [] @pytest.mark.asyncio - async def test_list_attacks_filters_by_converter_classes_and_logic(self, attack_service, mock_memory) -> None: - """Test that list_attacks passes converter_classes to memory layer.""" + async def test_list_attacks_filters_by_converter_types_and_logic(self, attack_service, mock_memory) -> None: + """Test that list_attacks passes converter_types to memory layer.""" ar1 = make_attack_result(conversation_id="attack-1", name="Attack One") ar1.attack_identifier = ComponentIdentifier( class_name="Attack One", @@ -240,11 +240,11 @@ async def test_list_attacks_filters_by_converter_classes_and_logic(self, attack_ mock_memory.get_attack_results.return_value = [ar1] mock_memory.get_message_pieces.return_value = [] - result = await attack_service.list_attacks_async(converter_classes=["Base64Converter", "ROT13Converter"]) + result = await attack_service.list_attacks_async(converter_types=["Base64Converter", "ROT13Converter"]) assert len(result.items) == 1 assert result.items[0].conversation_id == "attack-1" - # Verify converter_classes was forwarded to the memory layer + # Verify converter_types was forwarded to the memory layer as converter_classes call_kwargs = mock_memory.get_attack_results.call_args[1] assert call_kwargs["converter_classes"] == ["Base64Converter", "ROT13Converter"] diff --git a/tests/unit/memory/memory_interface/test_interface_attack_results.py b/tests/unit/memory/memory_interface/test_interface_attack_results.py index 3106409fd..fe560d429 100644 --- a/tests/unit/memory/memory_interface/test_interface_attack_results.py +++ b/tests/unit/memory/memory_interface/test_interface_attack_results.py @@ -126,7 +126,11 @@ def test_get_attack_results_by_ids(sqlite_instance: MemoryInterface): def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface): - """Test retrieving attack results by conversation ID.""" + """Test retrieving attack results by conversation ID. + + When duplicate rows exist for the same conversation_id (legacy bug), + get_attack_results deduplicates and returns only the newest entry. + """ # Create and add attack results attack_result1 = AttackResult( conversation_id="conv_1", @@ -137,7 +141,7 @@ def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface) ) attack_result2 = AttackResult( - conversation_id="conv_1", # Same conversation ID + conversation_id="conv_1", # Same conversation ID (simulates legacy duplicate) objective="Test objective 2", executed_turns=3, execution_time_ms=500, @@ -155,13 +159,11 @@ def test_get_attack_results_by_conversation_id(sqlite_instance: MemoryInterface) # Add all attack results to memory sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result1, attack_result2, attack_result3]) - # Retrieve attack results by conversation ID + # Retrieve attack results by conversation ID — deduplication keeps only the newest retrieved_results = sqlite_instance.get_attack_results(conversation_id="conv_1") - # Verify correct results were retrieved - assert len(retrieved_results) == 2 - for result in retrieved_results: - assert result.conversation_id == "conv_1" + assert len(retrieved_results) == 1 + assert retrieved_results[0].conversation_id == "conv_1" def test_get_attack_results_by_objective(sqlite_instance: MemoryInterface): @@ -593,6 +595,128 @@ def test_attack_result_without_attack_generation_conversation_ids(sqlite_instanc assert not retrieved_result.get_conversations_by_type(ConversationType.ADVERSARIAL) +def test_update_attack_result_adversarial_chat_conversation_ids_round_trip(sqlite_instance: MemoryInterface): + """Test that updating adversarial_chat_conversation_ids is reflected when reading back. + + This catches a regression where the conversation count in the attack history + was always showing 1 instead of the actual number of conversations. + """ + # Create attack with no related conversations + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test conversation count", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Verify initial state: no related conversations + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results) == 1 + assert len(results[0].related_conversations) == 0 + + # Add first related conversation + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) + + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 1 + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1"} + + # Add second related conversation (preserving the first) + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1", "branch-2"]}, + ) + + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 2 + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1", "branch-2"} + + # Verify they are all ADVERSARIAL type + for ref in results[0].related_conversations: + assert ref.conversation_type == ConversationType.ADVERSARIAL + + +def test_update_attack_result_metadata_does_not_clobber_conversation_ids(sqlite_instance: MemoryInterface): + """Regression test: updating only attack_metadata must not erase adversarial_chat_conversation_ids. + + This was the root cause of the conversation-count bug. The old _update_entries + used session.merge() which copied ALL attributes from the (potentially stale) + detached entry, silently overwriting JSON columns that were not in update_fields. + """ + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test metadata update preserves conversation ids", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Step 1: add related conversations + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1", "branch-2"]}, + ) + + # Step 2: update ONLY metadata (this is what add_message_async does) + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"attack_metadata": {"created_at": "2026-01-01T00:00:00", "updated_at": "2026-01-02T00:00:00"}}, + ) + + # Verify conversation ids are still present + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 2, ( + "Updating attack_metadata must not erase adversarial_chat_conversation_ids" + ) + assert {r.conversation_id for r in results[0].related_conversations} == {"branch-1", "branch-2"} + + +def test_update_attack_result_stale_entry_does_not_overwrite(sqlite_instance: MemoryInterface): + """Regression test: merging a stale entry must not overwrite concurrent updates. + + Simulates the race condition where entry is loaded, then another update modifies + the DB, and finally the stale entry is used for an unrelated update. + """ + from pyrit.memory.memory_models import AttackResultEntry + + attack_result = AttackResult( + conversation_id="conv_1", + objective="Test stale merge", + outcome=AttackOutcome.UNDETERMINED, + metadata={"created_at": "2026-01-01T00:00:00"}, + ) + sqlite_instance.add_attack_results_to_memory(attack_results=[attack_result]) + + # Load entry (will become stale) + stale_entries = sqlite_instance._query_entries( + AttackResultEntry, conditions=AttackResultEntry.conversation_id == "conv_1" + ) + assert stale_entries[0].adversarial_chat_conversation_ids is None + + # Concurrent update adds conversation ids + sqlite_instance.update_attack_result( + conversation_id="conv_1", + update_fields={"adversarial_chat_conversation_ids": ["branch-1"]}, + ) + + # Now update with the stale entry (only metadata) + sqlite_instance._update_entries( + entries=[stale_entries[0]], + update_fields={"attack_metadata": {"updated_at": "2026-01-02T00:00:00"}}, + ) + + # Verify the concurrent update was NOT lost + results = sqlite_instance.get_attack_results(conversation_id="conv_1") + assert len(results[0].related_conversations) == 1, ( + "Stale entry merge must not overwrite concurrent adversarial_chat_conversation_ids update" + ) + assert results[0].related_conversations.pop().conversation_id == "branch-1" + + def test_get_attack_results_by_harm_category_single(sqlite_instance: MemoryInterface): """Test filtering attack results by a single harm category.""" diff --git a/tests/unit/memory/test_sqlite_memory.py b/tests/unit/memory/test_sqlite_memory.py index f99b72525..de404d233 100644 --- a/tests/unit/memory/test_sqlite_memory.py +++ b/tests/unit/memory/test_sqlite_memory.py @@ -547,3 +547,123 @@ def test_update_prompt_metadata_by_conversation_id(sqlite_instance, sample_conve # Verify that the entry with a different conversation_id was not updated other_entry = session.query(PromptMemoryEntry).filter_by(conversation_id="other_id").first() assert other_entry.prompt_metadata == original_metadata # Metadata should remain unchanged + + +def test_get_conversation_stats_returns_empty_for_no_ids(sqlite_instance): + """Test that get_conversation_stats returns empty dict for empty input.""" + result = sqlite_instance.get_conversation_stats(conversation_ids=[]) + assert result == {} + + +def test_get_conversation_stats_returns_empty_for_unknown_ids(sqlite_instance): + """Test that get_conversation_stats omits unknown conversation IDs.""" + result = sqlite_instance.get_conversation_stats(conversation_ids=["nonexistent"]) + assert result == {} + + +def test_get_conversation_stats_counts_distinct_sequences(sqlite_instance, sample_conversation_entries): + """Test that message_count reflects distinct sequence numbers, not raw rows.""" + # Extract conversation IDs and sequences before inserting (entries get detached after commit) + from pyrit.models import Message + from unit.mocks import get_sample_conversations + + conversations = get_sample_conversations() + pieces = Message.flatten_to_message_pieces(conversations) + expected: dict[str, set[int]] = {} + for p in pieces: + expected.setdefault(p.conversation_id, set()).add(p.sequence) + + sqlite_instance._insert_entries(entries=sample_conversation_entries) + + conv_ids = list(expected.keys()) + result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + + for conv_id in conv_ids: + if conv_id in result: + assert result[conv_id].message_count == len(expected[conv_id]), ( + f"Conv {conv_id}: expected {len(expected[conv_id])}, got {result[conv_id].message_count}" + ) + + +def test_get_conversation_stats_returns_labels(sqlite_instance): + """Test that labels from the first piece with non-empty labels are returned.""" + import uuid + + from pyrit.models import MessagePiece + + conv_id = str(uuid.uuid4()) + piece = MessagePiece( + role="user", + original_value="hello", + original_value_data_type="text", + converted_value="hello", + converted_value_data_type="text", + conversation_id=conv_id, + sequence=0, + labels={"env": "prod", "source": "gui"}, + ) + entry = PromptMemoryEntry(entry=piece) + sqlite_instance._insert_entry(entry) + + result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + assert conv_id in result + assert result[conv_id].labels == {"env": "prod", "source": "gui"} + + +def test_get_conversation_stats_preview_truncates(sqlite_instance): + """Test that last_message_preview is truncated to 100 chars + ellipsis.""" + import uuid + + from pyrit.models import MessagePiece + + conv_id = str(uuid.uuid4()) + long_text = "x" * 200 + piece = MessagePiece( + role="assistant", + original_value=long_text, + original_value_data_type="text", + converted_value=long_text, + converted_value_data_type="text", + conversation_id=conv_id, + sequence=0, + ) + entry = PromptMemoryEntry(entry=piece) + sqlite_instance._insert_entry(entry) + + result = sqlite_instance.get_conversation_stats(conversation_ids=[conv_id]) + assert conv_id in result + preview = result[conv_id].last_message_preview + assert preview is not None + assert len(preview) == 103 # 100 chars + "..." + assert preview.endswith("...") + + +def test_get_conversation_stats_batches_multiple_conversations(sqlite_instance): + """Test that a single call returns stats for multiple conversations.""" + import uuid + + from pyrit.models import MessagePiece + + conv_ids = [str(uuid.uuid4()) for _ in range(3)] + entries = [] + for i, cid in enumerate(conv_ids): + for seq in range(i + 1): # conv 0: 1 msg, conv 1: 2 msgs, conv 2: 3 msgs + piece = MessagePiece( + role="user", + original_value=f"msg-{seq}", + original_value_data_type="text", + converted_value=f"msg-{seq}", + converted_value_data_type="text", + conversation_id=cid, + sequence=seq, + ) + entries.append(PromptMemoryEntry(entry=piece)) + + sqlite_instance._insert_entries(entries=entries) + + result = sqlite_instance.get_conversation_stats(conversation_ids=conv_ids) + + assert len(result) == 3 + assert result[conv_ids[0]].message_count == 1 + assert result[conv_ids[1]].message_count == 2 + assert result[conv_ids[2]].message_count == 3 diff --git a/tests/unit/target/test_image_target.py b/tests/unit/target/test_image_target.py index ffba3a756..4c5056e24 100644 --- a/tests/unit/target/test_image_target.py +++ b/tests/unit/target/test_image_target.py @@ -504,3 +504,21 @@ async def test_validate_piece_type(image_target: OpenAIImageTarget): finally: if os.path.isfile(audio_piece.original_value): os.remove(audio_piece.original_value) + + +@pytest.mark.asyncio +async def test_validate_previous_conversations( + image_target: OpenAIImageTarget, sample_conversations: MutableSequence[MessagePiece] +): + message_piece = sample_conversations[0] + + mock_memory = MagicMock() + mock_memory.get_conversation.return_value = sample_conversations + mock_memory.add_message_to_memory = AsyncMock() + + image_target._memory = mock_memory + + request = Message(message_pieces=[message_piece]) + + with pytest.raises(ValueError, match="This target only supports a single turn conversation."): + await image_target.send_prompt_async(message=request) diff --git a/tests/unit/target/test_video_target.py b/tests/unit/target/test_video_target.py index eab0d81ac..877bce7d6 100644 --- a/tests/unit/target/test_video_target.py +++ b/tests/unit/target/test_video_target.py @@ -910,3 +910,20 @@ def test_supported_durations(self, video_target: OpenAIVideoTarget): n_seconds=duration, ) assert target._n_seconds == duration + + +def test_video_validate_previous_conversations( + video_target: OpenAIVideoTarget, sample_conversations: MutableSequence[MessagePiece] +): + message_piece = sample_conversations[0] + + mock_memory = MagicMock() + mock_memory.get_conversation.return_value = sample_conversations + mock_memory.add_message_to_memory = AsyncMock() + + video_target._memory = mock_memory + + request = Message(message_pieces=[message_piece]) + + with pytest.raises(ValueError, match="This target only supports a single turn conversation."): + video_target._validate_request(message=request)